interrupt 选项。该选项会中断图的先前运行,并使用双重输入启动新的运行。此选项不会删除第一次运行,而是将其保留在数据库中,并将其状态设置为 interrupted。下面是使用 interrupt 选项的简单示例。
设置
首先,我们定义一个简单的辅助函数,用于输出 JS 和 cURL 模型的结果(如果使用 Python,可以跳过此步骤):- Javascript
- cURL
function prettyPrint(m) {
const padded = " " + m['type'] + " ";
const sepLen = Math.floor((80 - padded.length) / 2);
const sep = "=".repeat(sepLen);
const secondSep = sep + (padded.length % 2 ? "=" : "");
console.log(`${sep}${padded}${secondSep}`);
console.log("\n\n");
console.log(m.content);
}
# 将此内容放入名为 pretty_print.sh 的文件中
pretty_print() {
local type="$1"
local content="$2"
local padded=" $type "
local total_width=80
local sep_len=$(( (total_width - ${#padded}) / 2 ))
local sep=$(printf '=%.0s' $(eval "echo {1.."${sep_len}"}"))
local second_sep=$sep
if (( (total_width - ${#padded}) % 2 )); then
second_sep="${second_sep}="
fi
echo "${sep}${padded}${second_sep}"
echo
echo "$content"
}
- Python
- Javascript
- cURL
import asyncio
from langchain_core.messages import convert_to_messages
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>)
# 使用以 "agent" 名称部署的图
assistant_id = "agent"
thread = await client.threads.create()
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// 使用以 "agent" 名称部署的图
const assistantId = "agent";
const thread = await client.threads.create();
curl --request POST \
--url <DEPLOYMENT_URL>/threads \
--header 'Content-Type: application/json' \
--data '{}'
创建运行
现在,我们可以启动两次运行,并等待第二次运行完成:- Python
- Javascript
- cURL
# 第一次运行将被中断
interrupted_run = await client.runs.create(
thread["thread_id"],
assistant_id,
input={"messages": [{"role": "user", "content": "旧金山的天气怎么样?"}]},
)
# 稍微等待一段时间,以获取第一次运行的部分输出
await asyncio.sleep(2)
run = await client.runs.create(
thread["thread_id"],
assistant_id,
input={"messages": [{"role": "user", "content": "纽约的天气怎么样?"}]},
multitask_strategy="interrupt",
)
# 等待第二次运行完成
await client.runs.join(thread["thread_id"], run["run_id"])
// 第一次运行将被中断
let interruptedRun = await client.runs.create(
thread["thread_id"],
assistantId,
{ input: { messages: [{ role: "human", content: "旧金山的天气怎么样?" }] } }
);
// 稍微等待一段时间,以获取第一次运行的部分输出
await new Promise(resolve => setTimeout(resolve, 2000));
let run = await client.runs.create(
thread["thread_id"],
assistantId,
{
input: { messages: [{ role: "human", content: "纽约的天气怎么样?" }] },
multitaskStrategy: "interrupt"
}
);
// 等待第二次运行完成
await client.runs.join(thread["thread_id"], run["run_id"]);
curl --request POST \
--url <DEPLOY<ENT_URL>>/threads/<THREAD_ID>/runs \
--header 'Content-Type: application/json' \
--data "{
\"assistant_id\": \"agent\",
\"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"旧金山的天气怎么样?\"}]},
}" && sleep 2 && curl --request POST \
--url <DEPLOY<ENT_URL>>/threads/<THREAD_ID>/runs \
--header 'Content-Type: application/json' \
--data "{
\"assistant_id\": \"agent\",
\"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"纽约的天气怎么样?\"}]},
\"multitask_strategy\": \"interrupt\"
}" && curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/runs/<RUN_ID>/join
查看运行结果
我们可以看到,线程中包含第一次运行的部分数据,以及第二次运行的数据。- Python
- Javascript
- cURL
state = await client.threads.get_state(thread["thread_id"])
for m in convert_to_messages(state["values"]["messages"]):
m.pretty_print()
const state = await client.threads.getState(thread["thread_id"]);
for (const m of state['values']['messages']) {
prettyPrint(m);
}
source pretty_print.sh && curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/state | \
jq -c '.values.messages[]' | while read -r element; do
type=$(echo "$element" | jq -r '.type')
content=$(echo "$element" | jq -r '.content | if type == "array" then tostring else . end')
pretty_print "$type" "$content"
done
================================ Human Message =================================
旧金山的天气怎么样?
================================== Ai Message ==================================
[{'id': 'toolu_01MjNtVJwEcpujRGrf3x6Pih', 'input': {'query': '旧金山的天气'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01MjNtVJwEcpujRGrf3x6Pih)
Call ID: toolu_01MjNtVJwEcpujRGrf3x6Pih
Args:
query: 旧金山的天气
================================= Tool Message =================================
Name: tavily_search_results_json
[{"url": "https://www.wunderground.com/hourly/us/ca/san-francisco/KCASANFR2002/date/2024-6-18", "content": "最高气温 64°F。西风 10 至 20 英里/小时。天气时有少量云层。最低气温 49°F。西风 10 至 20 英里/小时。气温。旧金山天气预报。Weather Underground 提供本地及长期天气预报……"}]
================================ Human Message =================================
纽约的天气怎么样?
================================== Ai Message ==================================
[{'id': 'toolu_01KtE1m1ifPLQAx4fQLyZL9Q', 'input': {'query': '纽约市的天气'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01KtE1m1ifPLQAx4fQLyZL9Q)
Call ID: toolu_01KtE1m1ifPLQAx4fQLyZL9Q
Args:
query: 纽约市的天气
================================= Tool Message =================================
Name: tavily_search_results_json
[{"url": "https://www.accuweather.com/en/us/new-york/10021/june-weather/349727", "content": "获取纽约州纽约市的月度天气预报,包括每日最高/最低气温和历史平均值,帮助你提前做好计划。"}]
================================== Ai Message ==================================
搜索结果提供了纽约市的天气预报和相关信息。根据 AccuWeather 的首条结果,纽约市的天气有以下几个要点:
* 这是纽约市六月的月度天气预报。
* 其中包含每日最高和最低气温,可用于提前规划。
* 同时提供纽约市六月的历史平均值,作为参考。
* 如需了解降水概率、湿度、风力等更详细的每日或每小时预报,可以访问 AccuWeather 页面。
总的来说,该搜索结果方便地概述了纽约市未来一个月的预期天气状况,便于你在前往当地旅行或制定计划时做好准备。如果你还需要其他详细信息,请告诉我!
- Python
- Javascript
print((await client.runs.get(thread["thread_id"], interrupted_run["run_id"]))["status"])
console.log((await client.runs.get(thread['thread_id'], interruptedRun["run_id"]))["status"])
'interrupted'
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

