跳至主要内容

如何在模块构造函数中传递回调

先决条件

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

大多数 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: []
}

您可以看到,我们只看到了来自聊天模型运行的事件 - 没有来自提示或更广泛链的事件。

下一步

您现在已经了解了如何在构造函数中传递回调。

接下来,查看本节中的其他操作指南,例如如何创建您自己的 自定义回调处理程序


本页是否有用?


您也可以留下详细的反馈 在 GitHub 上.