如何创建自定义回调处理器
前置条件
本指南假定您熟悉以下概念:
LangChain 有一些内置的回调处理器,但通常您会希望创建带有自定义逻辑的处理器。
要创建自定义回调处理器,我们需要确定我们希望回调处理器处理的事件,以及在触发事件时我们希望回调处理器执行的操作。然后,我们只需将该回调处理器附加到对象上,例如通过构造函数或在运行时。
构建自定义回调处理器的一种简便方法是将其初始化为一个对象,其键是函数,函数名与我们要处理的事件相匹配。以下是一个仅处理聊天模型开始运行和模型运行期间流式传输令牌的示例:
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { ChatAnthropic } from "@langchain/anthropic";
const prompt = ChatPromptTemplate.fromTemplate(`What is 1 + {number}?`);
const model = new ChatAnthropic({
model: "claude-3-sonnet-20240229",
});
const chain = prompt.pipe(model);
const customHandler = {
handleChatModelStart: async (llm, inputMessages, runId) => {
console.log("Chat model start:", llm, inputMessages, runId);
},
handleLLMNewToken: async (token) => {
console.log("Chat model new token", token);
},
};
const stream = await chain.stream(
{ number: "2" },
{ callbacks: [customHandler] }
);
for await (const _ of stream) {
// Just consume the stream so the callbacks run
}
Chat model start: {
lc: 1,
type: "constructor",
id: [ "langchain", "chat_models", "anthropic", "ChatAnthropic" ],
kwargs: {
callbacks: undefined,
model: "claude-3-sonnet-20240229",
verbose: undefined,
anthropic_api_key: { lc: 1, type: "secret", id: [ "ANTHROPIC_API_KEY" ] },
api_key: { lc: 1, type: "secret", id: [ "ANTHROPIC_API_KEY" ] }
}
} [
[
HumanMessage {
lc_serializable: true,
lc_kwargs: {
content: "What is 1 + 2?",
additional_kwargs: {},
response_metadata: {}
},
lc_namespace: [ "langchain_core", "messages" ],
content: "What is 1 + 2?",
name: undefined,
additional_kwargs: {},
response_metadata: {}
}
]
] b6e3b7ad-c602-4cef-9652-d51781a657b7
Chat model new token The
Chat model new token sum
Chat model new token of
Chat model new token
Chat model new token 1
Chat model new token
Chat model new token an
Chat model new token d
Chat model new token 2
Chat model new token
Chat model new token is
Chat model new token
Chat model new token 3
Chat model new token .
你可以查看此参考页面,了解你可以处理的事件列表。请注意,handleChain*
事件会在大多数 LCEL 可运行对象中执行。
下一步
你现在已学会了如何创建自己的自定义回调处理器。
接下来,请查看本节中的其他操作指南,例如如何在无服务器环境中等待回调。