如何将回调传递到模块构造函数中
先决条件
本指南假设你熟悉以下概念
大多数 LangChain 模块允许你将 回调函数
直接传递到构造函数中。在这种情况下,回调函数只会针对该实例(以及任何嵌套运行)被调用。
以下是一个使用 LangChain 的内置 ConsoleCallbackHandler
的示例
import { ConsoleCallbackHandler } from "@langchain/core/tracers/console";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { ChatAnthropic } from "@langchain/anthropic";
const handler = new ConsoleCallbackHandler();
const prompt = ChatPromptTemplate.fromTemplate(`What is 1 + {number}?`);
const model = new ChatAnthropic({
model: "claude-3-sonnet-20240229",
callbacks: [handler],
});
const chain = prompt.pipe(model);
await chain.invoke({ number: "2" });
[llm/start] [1:llm:ChatAnthropic] Entering LLM run with input: {
"messages": [
[
{
"lc": 1,
"type": "constructor",
"id": [
"langchain_core",
"messages",
"HumanMessage"
],
"kwargs": {
"content": "What is 1 + 2?",
"additional_kwargs": {},
"response_metadata": {}
}
}
]
]
}
[llm/end] [1:llm:ChatAnthropic] [1.00s] Exiting LLM run with output: {
"generations": [
[
{
"text": "1 + 2 = 3",
"message": {
"lc": 1,
"type": "constructor",
"id": [
"langchain_core",
"messages",
"AIMessage"
],
"kwargs": {
"content": "1 + 2 = 3",
"tool_calls": [],
"invalid_tool_calls": [],
"additional_kwargs": {
"id": "msg_011Z1cgi3gyNGxT55wnRNkXq",
"type": "message",
"role": "assistant",
"model": "claude-3-sonnet-20240229",
"stop_sequence": null,
"usage": {
"input_tokens": 16,
"output_tokens": 13
},
"stop_reason": "end_turn"
},
"response_metadata": {
"id": "msg_011Z1cgi3gyNGxT55wnRNkXq",
"model": "claude-3-sonnet-20240229",
"stop_sequence": null,
"usage": {
"input_tokens": 16,
"output_tokens": 13
},
"stop_reason": "end_turn"
}
}
}
}
]
],
"llmOutput": {
"id": "msg_011Z1cgi3gyNGxT55wnRNkXq",
"model": "claude-3-sonnet-20240229",
"stop_sequence": null,
"usage": {
"input_tokens": 16,
"output_tokens": 13
},
"stop_reason": "end_turn"
}
}
AIMessage {
lc_serializable: true,
lc_kwargs: {
content: "1 + 2 = 3",
tool_calls: [],
invalid_tool_calls: [],
additional_kwargs: {
id: "msg_011Z1cgi3gyNGxT55wnRNkXq",
type: "message",
role: "assistant",
model: "claude-3-sonnet-20240229",
stop_sequence: null,
usage: { input_tokens: 16, output_tokens: 13 },
stop_reason: "end_turn"
},
response_metadata: {}
},
lc_namespace: [ "langchain_core", "messages" ],
content: "1 + 2 = 3",
name: undefined,
additional_kwargs: {
id: "msg_011Z1cgi3gyNGxT55wnRNkXq",
type: "message",
role: "assistant",
model: "claude-3-sonnet-20240229",
stop_sequence: null,
usage: { input_tokens: 16, output_tokens: 13 },
stop_reason: "end_turn"
},
response_metadata: {
id: "msg_011Z1cgi3gyNGxT55wnRNkXq",
model: "claude-3-sonnet-20240229",
stop_sequence: null,
usage: { input_tokens: 16, output_tokens: 13 },
stop_reason: "end_turn"
},
tool_calls: [],
invalid_tool_calls: []
}
你可以看到,我们只看到了来自聊天模型运行的事件 - 没有来自提示或更广泛的链的事件。
下一步
现在你已经了解了如何将回调函数传递到构造函数中。
接下来,查看本节中的其他操作指南,例如如何创建自己的 自定义回调处理程序。