Skip to main content
Open In Colab在 GitHub 上打开

如何创建自定义回调处理程序

先决条件

本指南假定您熟悉以下概念:

LangChain 有一些内置的回调处理程序,但您经常需要使用自定义逻辑创建自己的处理程序。

要创建自定义回调处理程序,我们需要确定我们希望回调处理程序处理的事件,以及我们希望回调处理程序在事件触发时做什么。然后,我们需要做的就是将回调处理程序附加到对象上,例如通过构造函数或在运行时

在下面的示例中,我们将使用自定义处理程序实现流式处理。

在我们的自定义回调处理程序中MyCustomHandler,我们实现on_llm_new_tokenhandler 来打印我们刚刚收到的 token。然后,我们将自定义处理程序作为构造函数回调附加到模型对象。

from langchain_anthropic import ChatAnthropic
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.prompts import ChatPromptTemplate


class MyCustomHandler(BaseCallbackHandler):
def on_llm_new_token(self, token: str, **kwargs) -> None:
print(f"My custom handler, token: {token}")


prompt = ChatPromptTemplate.from_messages(["Tell me a joke about {animal}"])

# To enable streaming, we pass in `streaming=True` to the ChatModel constructor
# Additionally, we pass in our custom handler as a list to the callbacks parameter
model = ChatAnthropic(
model="claude-3-sonnet-20240229", streaming=True, callbacks=[MyCustomHandler()]
)

chain = prompt | model

response = chain.invoke({"animal": "bears"})
My custom handler, token: Here
My custom handler, token: 's
My custom handler, token: a
My custom handler, token: bear
My custom handler, token: joke
My custom handler, token: for
My custom handler, token: you
My custom handler, token: :
My custom handler, token:

Why
My custom handler, token: di
My custom handler, token: d the
My custom handler, token: bear
My custom handler, token: dissol
My custom handler, token: ve
My custom handler, token: in
My custom handler, token: water
My custom handler, token: ?
My custom handler, token:
Because
My custom handler, token: it
My custom handler, token: was
My custom handler, token: a
My custom handler, token: polar
My custom handler, token: bear
My custom handler, token: !

您可以查看此参考页面,了解您可以处理的事件列表。请注意,handle_chain_*事件为大多数 LCEL 可运行程序运行。

后续步骤

您现在已经学习了如何创建自己的自定义回调处理程序。

接下来,查看本节中的其他操作指南,例如如何将回调附加到 runnable