无状态运行¶
大多数情况下,当你运行图时,会提供一个 thread_id
给你的客户端,以便通过 LangGraph Cloud 中实现的持久状态来跟踪之前的运行。然而,如果你不需要持久化这些运行,你就不必使用内置的持久状态,可以创建无状态运行。
设置¶
首先,让我们设置我们的客户端:
curl --request POST \
--url <DEPLOYMENT_URL>/assistants/search \
--header 'Content-Type: application/json' \
--data '{
"limit": 10,
"offset": 0
}' | jq -c 'map(select(.config == null or .config == {})) | .[0].graph_id' && \
curl --request POST \
--url <DEPLOYMENT_URL>/threads \
--header 'Content-Type: application/json' \
--data '{}'
无状态流式处理¶
我们可以以几乎相同的方式流式处理无状态运行的结果,就像从带有状态属性的运行中流式处理一样,但是我们不需要传递 thread_id
参数的值,而是传递 None
:
let input = {
messages: [
{ role: "user", content: "Hello! My name is Bagatur and I am 26 years old." }
]
};
const streamResponse = client.runs.stream(
// 不传递 thread_id 参数,流式处理将变为无状态
null,
assistantId,
{
input,
streamMode: "updates"
}
);
for await (const chunk of streamResponse) {
if (chunk.data && !("run_id" in chunk.data)) {
console.log(chunk.data);
}
}
curl --request POST \
--url <DEPLOYMENT_URL>/runs/stream \
--header 'Content-Type: application/json' \
--data "{
\"assistant_id\": \"agent\",
\"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"Hello! My name is Bagatur and I am 26 years old.\"}]},
\"stream_mode\": [
\"updates\"
]
}" | jq -c 'select(.data and (.data | has("run_id") | not)) | .data'
输出:
{'agent': {'messages': [{'content': "Hello Bagatur! It's nice to meet you. Thank you for introducing yourself and sharing your age. Is there anything specific you'd like to know or discuss? I'm here to help with any questions or topics you're interested in.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-489ec573-1645-4ce2-a3b8-91b391d50a71', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]}}
等待无状态结果¶
除了流式处理外,你还可以通过使用.wait
函数来等待无状态的结果,如下所示:
输出:
{
'messages': [
{
'content': '你好!我的名字是巴加图尔,我26岁。',
'additional_kwargs': {},
'response_metadata': {},
'type': 'human',
'name': None,
'id': '5e088543-62c2-43de-9d95-6086ad7f8b48',
'example': False
},
{
'content': "你好巴加图尔!很高兴见到你。感谢你介绍自己并分享你的年龄。你是否有任何具体的问题或话题想要讨论?我在这里帮助你解答任何问题或探索任何话题。",
'additional_kwargs': {},
'response_metadata': {},
'type': 'ai',
'name': None,
'id': 'run-d6361e8d-4d4c-45bd-ba47-39520257f773',
'example': False,
'tool_calls': [],
'invalid_tool_calls': [],
'usage_metadata': None
}
]
}