跳到主要內容
Open In ColabOpen on GitHub

如何建立自訂回呼處理器

先決條件

本指南假設您熟悉以下概念

LangChain 具有一些內建的回呼處理器,但您通常會想要使用自訂邏輯建立自己的處理器。

若要建立自訂回呼處理器,我們需要確定我們想要處理的事件,以及當事件觸發時,我們希望回呼處理器執行的動作。然後,我們只需要將回呼處理器附加到物件,例如透過建構子在執行時

在以下範例中,我們將使用自訂處理器實作串流。

在我們的自訂回呼處理器 MyCustomHandler 中,我們實作了 on_llm_new_token 處理器以列印我們剛收到的 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。

下一步

您現在已學習如何建立自己的自訂回呼處理器。

接下來,查看本節中的其他操作指南,例如如何將回呼附加到 runnable


此頁面是否對您有幫助?