langchain_core.callbacks.manager.adispatch_custom_event

async langchain_core.callbacks.manager.adispatch_custom_event(name: str, data: Any, *, config: Optional[RunnableConfig] = None) None[source]

向处理器派发即兴事件。

参数
  • name (str) – 即兴事件的名称。

  • data (Any) – 即兴事件的数据。自由形式数据。理想情况下应该可被JSON序列化以避免下行序列化问题,但此要求并不强制。

  • config (Optional[RunnableConfig]) – 可选的配置对象。与异步API相匹配,但不是必需的。

返回类型

None

示例

from langchain_core.callbacks import (
    AsyncCallbackHandler,
    adispatch_custom_event
)
from langchain_core.runnable import RunnableLambda

class CustomCallbackManager(AsyncCallbackHandler):
    async def on_custom_event(
        self,
        name: str,
        data: Any,
        *,
        run_id: UUID,
        tags: Optional[List[str]] = None,
        metadata: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> None:
        print(f"Received custom event: {name} with data: {data}")

callback = CustomCallbackManager()

async def foo(inputs):
    await adispatch_custom_event("my_event", {"bar": "buzz})
    return inputs

foo_ = RunnableLambda(foo)
await foo_.ainvoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})

示例:与astream事件一起使用

from langchain_core.callbacks import (
    AsyncCallbackHandler,
    adispatch_custom_event
)
from langchain_core.runnable import RunnableLambda

class CustomCallbackManager(AsyncCallbackHandler):
    async def on_custom_event(
        self,
        name: str,
        data: Any,
        *,
        run_id: UUID,
        tags: Optional[List[str]] = None,
        metadata: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> None:
        print(f"Received custom event: {name} with data: {data}")

callback = CustomCallbackManager()

async def foo(inputs):
    await adispatch_custom_event("event_type_1", {"bar": "buzz})
    await adispatch_custom_event("event_type_2", 5)
    return inputs

foo_ = RunnableLambda(foo)

async for event in foo_.ainvoke_stream(
    {"a": "1"},
    version="v2",
    config={"callbacks": [CustomCallbackManager()]}
):
    print(event)

新增于版本 0.2.15。