Skip to content
LangSmith 文档版本 跟随上游 源快照 a27317e7 更新于 2026-10-18

无状态运行

大多数情况下,你在运行 graph 时会向客户端提供一个 thread_id,以便借助 LangSmith Deployment 内置的持久化状态跟踪此前的运行。但如果你不需要持久化运行,就不必使用内置的持久化状态,可以直接创建无状态运行。

设置

先设置客户端:

python
from langgraph_sdk import get_client

client = get_client(url=<DEPLOYMENT_URL>)
# Using the graph deployed with the name "agent"
assistant_id = "agent"

无状态流式输出

无状态运行的流式输出方式,与带状态属性的运行几乎完全相同,区别在于不给 thread_id 参数传值,而是传 None:

python
input = {
    "messages": [
        {"role": "user", "content": "Hello! My name is Bagatur and I am 26 years old."}
    ]
}

async for chunk in client.runs.stream(
    # Don't pass in a thread_id and the stream will be stateless
    None,
    assistant_id,
    input=input,
    stream_mode="updates",
):
    if chunk.data and "run_id" not in chunk.data:
        print(chunk.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 函数等待无状态结果,如下所示:

python
stateless_run_result = await client.runs.wait(
    None,
    assistant_id,
    input=input,
)
print(stateless_run_result)

输出:

{
    'messages': [
        {
            'content': 'Hello! My name is Bagatur and I am 26 years old.',
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'human',
            'name': None,
            'id': '5e088543-62c2-43de-9d95-6086ad7f8b48',
            'example': False
        },
        {
            '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'd like to explore.',
            '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
        }
    ]
}

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。