如何添加断点¶
在创建LangGraph代理时,通常希望添加一个人机交互组件。 这在赋予它们工具访问权限时可能很有帮助。 在这种情况下,您可能希望在执行某个操作之前手动批准。
这可以通过多种方式实现,但主要支持的方式是在某个节点执行之前添加一个“中断”。 这会在该节点处中断执行。 然后您可以从该位置继续执行。
设置¶
图表代码¶
在此指南中,我们使用一个简单的ReAct风格的托管图表(你可以在这里查看其完整代码here)。重要的是,它有两个节点(一个名为agent
的节点调用LLM,另一个名为action
的节点调用工具),以及从agent
到action
的路由函数,该函数确定是否调用action
节点或结束图表运行(action
节点在执行后总是调用agent
节点)。
SDK 初始化¶
添加断点¶
我们现在希望在图形运行中添加一个断点,这个断点将设置在调用工具之前。
我们可以通过添加 interrupt_before=["action"]
来实现这一点,这表示在调用动作节点之前中断。
我们可以在编译图形时或启动运行时添加断点。
这里我们将在启动运行时添加断点,如果你想在编译时添加断点,你需要编辑定义图形的 Python 文件,并在调用 .compile
时添加 interrupt_before
参数。
首先,让我们通过 SDK 访问托管的 LangGraph 实例:
然后,我们现在在工具节点之前编译它并添加断点:
input = {"messages": [{"role": "user", "content": "what's the weather in sf"}]}
async for chunk in client.runs.stream(
thread["thread_id"],
assistant_id,
input=input,
stream_mode="updates",
interrupt_before=["action"],
):
print(f"Receiving new event of type: {chunk.event}...")
print(chunk.data)
print("\n\n")
const input = { messages: [{ role: "human", content: "what's the weather in sf" }] };
const streamResponse = client.runs.stream(
thread["thread_id"],
assistantId,
{
input: input,
streamMode: "updates",
interruptBefore: ["action"]
}
);
for await (const chunk of streamResponse) {
console.log(`Receiving new event of type: ${chunk.event}...`);
console.log(chunk.data);
console.log("\n\n");
}
curl --request POST \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/runs/stream \
--header 'Content-Type: application/json' \
--data "{
\"assistant_id\": \"agent\",
\"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"what's the weather in sf\"}]},
\"interrupt_before\": [\"action\"],
\"stream_mode\": [
\"messages\"
]
}" | \
sed 's/\r$//' | \
awk '
/^event:/ {
if (data_content != "") {
print data_content "\n"
}
sub(/^event: /, "Receiving event of type: ", $0)
printf "%s...\n", $0
data_content = ""
}
/^data:/ {
sub(/^data: /, "", $0)
data_content = $0
}
END {
if (data_content != "") {
print data_content "\n"
}
}
'
输出:
Receiving new event of type: metadata...
{'run_id': '3b77ef83-687a-4840-8858-0371f91a92c3'}
Receiving new event of type: data...
{'agent': {'messages': [{'content': [{'id': 'toolu_01HwZqM1ptX6E15A5LAmyZTB', 'input': {'query': 'weather in san francisco'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}], 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-e5d17791-4d37-4ad2-815f-a0c4cba62585', 'example': False, 'tool_calls': [{'name': 'tavily_search_results_json', 'args': {'query': 'weather in san francisco'}, 'id': 'toolu_01HwZqM1ptX6E15A5LAmyZTB'}], 'invalid_tool_calls': []}]}}
Receiving new event of type: end...
None