跳到内容

Python SDK 参考

LangGraph 客户端实现连接到 LangGraph API。

此模块提供异步(get_client(url="https://:2024"))LangGraphClient) 和同步(get_sync_client(url="https://:2024"))SyncLanggraphClient) 客户端,用于与 LangGraph API 的核心资源(如助手、线程、运行和定时任务)及其持久文档存储进行交互。

名称 描述
LangGraphClient

LangGraph API 的顶级客户端。

HttpClient

处理 LangGraph API 的异步请求。

AssistantsClient

用于在 LangGraph 中管理助手的客户端。

ThreadsClient

用于在 LangGraph 中管理线程的客户端。

RunsClient

用于在 LangGraph 中管理运行的客户端。

CronClient

用于在 LangGraph 中管理循环运行(定时任务)的客户端。

StoreClient

用于与图的共享存储交互的客户端。

SyncLangGraphClient

用于与 LangGraph API 交互的同步客户端。

SyncHttpClient

处理 LangGraph API 的同步请求。

SyncAssistantsClient

用于在 LangGraph 中同步管理助手的客户端。

SyncThreadsClient

用于在 LangGraph 中管理线程的同步客户端。

SyncRunsClient

用于在 LangGraph 中管理运行的同步客户端。

SyncCronClient

用于在 LangGraph 中管理定时任务的同步客户端。

SyncStoreClient

用于键值存储同步操作的客户端。

函数

名称 描述
get_client

获取 LangGraphClient 实例。

get_sync_client

获取同步 LangGraphClient 实例。

LangGraphClient

LangGraph API 的顶级客户端。

属性

名称 类型 描述
assistants

管理图的版本化配置。

threads

处理(可能)多轮交互,例如会话线程。

runs

控制图的单个调用。

crons

管理计划操作。

store

与持久共享数据存储接口。

HttpClient

处理 LangGraph API 的异步请求。

在提供的 httpx 客户端之上添加额外的错误消息和内容处理。

属性

名称 类型 描述
client AsyncClient

底层 HTTPX 异步客户端。

方法

名称 描述
获取

发送 GET 请求。

post

发送 POST 请求。

放置

发送 PUT 请求。

patch

发送 PATCH 请求。

delete

发送 DELETE 请求。

stream

使用 SSE 流式传输结果。

get async

get(
    path: str,
    *,
    params: QueryParamTypes | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 GET 请求。

post async

post(
    path: str,
    *,
    json: dict | None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 POST 请求。

put async

put(
    path: str,
    *,
    json: dict,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 PUT 请求。

patch async

patch(
    path: str,
    *,
    json: dict,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 PATCH 请求。

delete async

delete(
    path: str,
    *,
    json: Any | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> None

发送 DELETE 请求。

stream async

stream(
    path: str,
    method: str,
    *,
    json: dict | None = None,
    params: QueryParamTypes | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> AsyncIterator[StreamPart]

使用 SSE 流式传输结果。

AssistantsClient

用于在 LangGraph 中管理助手的客户端。

此类提供与助手交互的方法,助手是图的版本化配置。

示例
client = get_client(url="https://:2024")
assistant = await client.assistants.get("assistant_id_123")

方法

名称 描述
获取

通过 ID 获取助手。

get_graph

按 ID 获取助手的图。

get_schemas

通过 ID 获取助手的 schema。

get_subgraphs

通过 ID 获取助手的 schema。

create

创建一个新助手。

更新

更新助手。

delete

删除助手。

search

搜索助手。

get_versions

列出助手的全部版本。

set_latest

更改助手的版本。

get async

get(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> Assistant

通过 ID 获取助手。

参数

名称 类型 描述 默认值
assistant_id str

要获取的助手的 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Assistant Assistant

助手对象。

示例用法
assistant = await client.assistants.get(
    assistant_id="my_assistant_id"
)
print(assistant)
----------------------------------------------------

{
    'assistant_id': 'my_assistant_id',
    'graph_id': 'agent',
    'created_at': '2024-06-25T17:10:33.109781+00:00',
    'updated_at': '2024-06-25T17:10:33.109781+00:00',
    'config': {},
    'metadata': {'created_by': 'system'},
    'version': 1,
    'name': 'my_assistant'
}

get_graph async

get_graph(
    assistant_id: str,
    *,
    xray: int | bool = False,
    headers: dict[str, str] | None = None
) -> dict[str, list[dict[str, Any]]]

按 ID 获取助手的图。

参数

名称 类型 描述 默认值
assistant_id str

要获取图的助手的 ID。

必填
xray int | bool

包含子图的图表示。如果提供了整数值,则只包含深度小于或等于该值的子图。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
dict[str, list[dict[str, Any]]]

助手的图信息,JSON 格式。

示例用法
client = get_client(url="https://:2024")
graph_info = await client.assistants.get_graph(
    assistant_id="my_assistant_id"
)
print(graph_info)
--------------------------------------------------------------------------------------------------------------------------

{
    'nodes':
        [
            {'id': '__start__', 'type': 'schema', 'data': '__start__'},
            {'id': '__end__', 'type': 'schema', 'data': '__end__'},
            {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
        ],
    'edges':
        [
            {'source': '__start__', 'target': 'agent'},
            {'source': 'agent','target': '__end__'}
        ]
}

get_schemas async

get_schemas(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> GraphSchema

通过 ID 获取助手的 schema。

参数

名称 类型 描述 默认值
assistant_id str

要获取其 schema 的助手的 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
GraphSchema GraphSchema

助手的图模式。

示例用法
client = get_client(url="https://:2024")
schema = await client.assistants.get_schemas(
    assistant_id="my_assistant_id"
)
print(schema)
----------------------------------------------------------------------------------------------------------------------------

{
    'graph_id': 'agent',
    'state_schema':
        {
            'title': 'LangGraphInput',
            '$ref': '#/definitions/AgentState',
            'definitions':
                {
                    'BaseMessage':
                        {
                            'title': 'BaseMessage',
                            'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                            'type': 'object',
                            'properties':
                                {
                                 'content':
                                    {
                                        'title': 'Content',
                                        'anyOf': [
                                            {'type': 'string'},
                                            {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                        ]
                                    },
                                'additional_kwargs':
                                    {
                                        'title': 'Additional Kwargs',
                                        'type': 'object'
                                    },
                                'response_metadata':
                                    {
                                        'title': 'Response Metadata',
                                        'type': 'object'
                                    },
                                'type':
                                    {
                                        'title': 'Type',
                                        'type': 'string'
                                    },
                                'name':
                                    {
                                        'title': 'Name',
                                        'type': 'string'
                                    },
                                'id':
                                    {
                                        'title': 'Id',
                                        'type': 'string'
                                    }
                                },
                            'required': ['content', 'type']
                        },
                    'AgentState':
                        {
                            'title': 'AgentState',
                            'type': 'object',
                            'properties':
                                {
                                    'messages':
                                        {
                                            'title': 'Messages',
                                            'type': 'array',
                                            'items': {'$ref': '#/definitions/BaseMessage'}
                                        }
                                },
                            'required': ['messages']
                        }
                }
        },
    'config_schema':
        {
            'title': 'Configurable',
            'type': 'object',
            'properties':
                {
                    'model_name':
                        {
                            'title': 'Model Name',
                            'enum': ['anthropic', 'openai'],
                            'type': 'string'
                        }
                }
        }
}

get_subgraphs async

get_subgraphs(
    assistant_id: str,
    namespace: str | None = None,
    recurse: bool = False,
    *,
    headers: dict[str, str] | None = None
) -> Subgraphs

通过 ID 获取助手的 schema。

参数

名称 类型 描述 默认值
assistant_id str

要获取其 schema 的助手的 ID。

必填
namespace str | None

按命名空间过滤的可选命名空间。

None
recurse bool

是否递归获取子图。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
子图 子图

助手的图模式。

create async

create(
    graph_id: str | None,
    config: Config | None = None,
    *,
    metadata: Json = None,
    assistant_id: str | None = None,
    if_exists: OnConflictBehavior | None = None,
    name: str | None = None,
    headers: dict[str, str] | None = None,
    description: str | None = None
) -> Assistant

创建一个新助手。

当图可配置且您想根据不同配置创建不同助手时很有用。

参数

名称 类型 描述 默认值
graph_id str | None

助手应使用的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。

必填
config Config | None

用于图的配置。

None
metadata Json

要添加到助手的元数据。

None
assistant_id str | None

要使用的助手 ID,如果未提供,将默认为随机 UUID。

None
if_exists OnConflictBehavior | None

如何处理重复创建。默认为“raise”。必须是“raise”(如果重复则引发错误)或“do_nothing”(返回现有助手)。

None
name str | None

助手的名称。默认为“Untitled”。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api server 版本 >= 0.0.45

None

返回

名称 类型 描述
Assistant Assistant

创建的助手。

示例用法
client = get_client(url="https://:2024")
assistant = await client.assistants.create(
    graph_id="agent",
    config={"configurable": {"model_name": "openai"}},
    metadata={"number":1},
    assistant_id="my-assistant-id",
    if_exists="do_nothing",
    name="my_name"
)

update async

update(
    assistant_id: str,
    *,
    graph_id: str | None = None,
    config: Config | None = None,
    metadata: Json = None,
    name: str | None = None,
    headers: dict[str, str] | None = None,
    description: str | None = None
) -> Assistant

更新助手。

使用此功能指向不同的图,更新配置,或更改助手的元数据。

参数

名称 类型 描述 默认值
assistant_id str

要更新的助手。

必填
graph_id str | None

助手应使用的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。如果为 None,助手将继续指向相同的图。

None
config Config | None

用于图的配置。

None
metadata Json

要与现有助手元数据合并的元数据。

None
name str | None

助手的新名称。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api server 版本 >= 0.0.45

None

返回

名称 类型 描述
Assistant Assistant

更新后的助手。

示例用法
client = get_client(url="https://:2024")
assistant = await client.assistants.update(
    assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
    graph_id="other-graph",
    config={"configurable": {"model_name": "anthropic"}},
    metadata={"number":2}
)

delete async

delete(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> None

删除助手。

参数

名称 类型 描述 默认值
assistant_id str

要删除的助手 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.assistants.delete(
    assistant_id="my_assistant_id"
)

search async

search(
    *,
    metadata: Json = None,
    graph_id: str | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: AssistantSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Assistant]

搜索助手。

参数

名称 类型 描述 默认值
metadata Json

要过滤的元数据。每个键值对的精确匹配过滤器。

None
graph_id str | None

要过滤的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。

None
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
sort_by AssistantSortBy | None

要排序的字段。

None
sort_order SortOrder | None

排序顺序。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Assistant]

list[Assistant]: 助手列表。

示例用法
client = get_client(url="https://:2024")
assistants = await client.assistants.search(
    metadata = {"name":"my_name"},
    graph_id="my_graph_id",
    limit=5,
    offset=5
)

get_versions async

get_versions(
    assistant_id: str,
    metadata: Json = None,
    limit: int = 10,
    offset: int = 0,
    *,
    headers: dict[str, str] | None = None
) -> list[AssistantVersion]

列出助手的全部版本。

参数

名称 类型 描述 默认值
assistant_id str

要获取版本的助手 ID。

必填
metadata Json

用于过滤版本的元数据。每个键值对的精确匹配过滤器。

None
限制 整数

要返回的最大版本数。

10
offset 整数

要跳过的版本数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[AssistantVersion]

list[AssistantVersion]: 助手版本列表。

示例用法
client = get_client(url="https://:2024")
assistant_versions = await client.assistants.get_versions(
    assistant_id="my_assistant_id"
)

set_latest async

set_latest(
    assistant_id: str,
    version: int,
    *,
    headers: dict[str, str] | None = None
) -> Assistant

更改助手的版本。

参数

名称 类型 描述 默认值
assistant_id str

要删除的助手 ID。

必填
version 整数

要更改为的版本。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Assistant Assistant

助手对象。

示例用法
client = get_client(url="https://:2024")
new_version_assistant = await client.assistants.set_latest(
    assistant_id="my_assistant_id",
    version=3
)

ThreadsClient

用于在 LangGraph 中管理线程的客户端。

线程在多次交互/调用(即运行)中保持图的状态。它累积并持久化图的状态,允许图的独立调用之间保持连续性。

示例
client = get_client(url="https://:2024"))
new_thread = await client.threads.create(metadata={"user_id": "123"})

方法

名称 描述
获取

通过 ID 获取会话。

create

创建新会话。

更新

更新会话。

delete

删除会话。

search

搜索线程。

copy

复制线程。

get_state

获取线程的状态。

update_state

更新线程的状态。

get_history

获取线程的状态历史。

get async

get(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> Thread

通过 ID 获取会话。

参数

名称 类型 描述 默认值
thread_id str

要获取的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

线程对象。

示例用法
client = get_client(url="https://:2024")
thread = await client.threads.get(
    thread_id="my_thread_id"
)
print(thread)
-----------------------------------------------------

{
    'thread_id': 'my_thread_id',
    'created_at': '2024-07-18T18:35:15.540834+00:00',
    'updated_at': '2024-07-18T18:35:15.540834+00:00',
    'metadata': {'graph_id': 'agent'}
}

create async

create(
    *,
    metadata: Json = None,
    thread_id: str | None = None,
    if_exists: OnConflictBehavior | None = None,
    supersteps: (
        Sequence[dict[str, Sequence[dict[str, Any]]]] | None
    ) = None,
    graph_id: str | None = None,
    headers: dict[str, str] | None = None
) -> Thread

创建新会话。

参数

名称 类型 描述 默认值
metadata Json

要添加到线程的元数据。

None
thread_id str | None

线程 ID。如果为 None,ID 将是随机生成的 UUID。

None
if_exists OnConflictBehavior | None

如何处理重复创建。默认为“raise”。必须是“raise”(如果重复则引发错误)或“do_nothing”(返回现有线程)。

None
supersteps Sequence[dict[str, Sequence[dict[str, Any]]]] | None

创建线程时应用一系列超级步骤,每个步骤包含一系列更新。每次更新都有 `values` 或 `command` 和 `as_node`。用于在部署之间复制线程。

None
graph_id str | None

与线程关联的可选图 ID。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

创建的会话。

示例用法
client = get_client(url="https://:2024")
thread = await client.threads.create(
    metadata={"number":1},
    thread_id="my-thread-id",
    if_exists="raise"
)

update async

update(
    thread_id: str,
    *,
    metadata: dict[str, Any],
    headers: dict[str, str] | None = None
) -> Thread

更新会话。

参数

名称 类型 描述 默认值
thread_id str

要更新的线程 ID。

必填
metadata dict[str, Any]

要与现有线程元数据合并的元数据。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

创建的会话。

示例用法
client = get_client(url="https://:2024")
thread = await client.threads.update(
    thread_id="my-thread-id",
    metadata={"number":1},
)

delete async

delete(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> None

删除会话。

参数

名称 类型 描述 默认值
thread_id str

要删除的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://2024)
await client.threads.delete(
    thread_id="my_thread_id"
)

search async

search(
    *,
    metadata: Json = None,
    values: Json = None,
    status: ThreadStatus | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: ThreadSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Thread]

搜索线程。

参数

名称 类型 描述 默认值
metadata Json

要过滤的线程元数据。

None
values Json

要过滤的状态值。

None
status ThreadStatus | None

要过滤的会话状态。必须是 'idle'、'busy'、'interrupted' 或 'error' 之一。

None
限制 整数

要返回的线程数限制。

10
offset 整数

从线程表中开始搜索的偏移量。

0
sort_by ThreadSortBy | None

按字段排序。

None
sort_order SortOrder | None

排序顺序。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Thread]

list[Thread]: 匹配搜索参数的线程列表。

示例用法
client = get_client(url="https://:2024")
threads = await client.threads.search(
    metadata={"number":1},
    status="interrupted",
    limit=15,
    offset=5
)

copy async

copy(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> None

复制线程。

参数

名称 类型 描述 默认值
thread_id str

要复制的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024)
await client.threads.copy(
    thread_id="my_thread_id"
)

get_state async

get_state(
    thread_id: str,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    *,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None
) -> ThreadState

获取线程的状态。

参数

名称 类型 描述 默认值
thread_id str

要获取状态的线程 ID。

必填
checkpoint Checkpoint | None

要获取状态的检查点。

None
checkpoint_id str | None

(已弃用)要获取状态的检查点 ID。

None
subgraphs bool

包括子图状态。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
ThreadState ThreadState

状态的线程。

示例用法
client = get_client(url="https://:2024)
thread_state = await client.threads.get_state(
    thread_id="my_thread_id",
    checkpoint_id="my_checkpoint_id"
)
print(thread_state)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'values': {
        'messages': [
            {
                'content': 'how are you?',
                'additional_kwargs': {},
                'response_metadata': {},
                'type': 'human',
                'name': None,
                'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
                'example': False
            },
            {
                'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                'additional_kwargs': {},
                'response_metadata': {},
                'type': 'ai',
                'name': None,
                'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                'example': False,
                'tool_calls': [],
                'invalid_tool_calls': [],
                'usage_metadata': None
            }
        ]
    },
    'next': [],
    'checkpoint':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
        }
    'metadata':
        {
            'step': 1,
            'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
            'source': 'loop',
            'writes':
                {
                    'agent':
                        {
                            'messages': [
                                {
                                    'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                    'name': None,
                                    'type': 'ai',
                                    'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                    'example': False,
                                    'tool_calls': [],
                                    'usage_metadata': None,
                                    'additional_kwargs': {},
                                    'response_metadata': {},
                                    'invalid_tool_calls': []
                                }
                            ]
                        }
                },
    'user_id': None,
    'graph_id': 'agent',
    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
    'created_by': 'system',
    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
    'created_at': '2024-07-25T15:35:44.184703+00:00',
    'parent_config':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
        }
}

update_state async

update_state(
    thread_id: str,
    values: dict | Sequence[dict] | None,
    *,
    as_node: str | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    headers: dict[str, str] | None = None
) -> ThreadUpdateStateResponse

更新线程的状态。

参数

名称 类型 描述 默认值
thread_id str

要更新的线程 ID。

必填
values dict | Sequence[dict] | None

用于更新状态的值。

必填
as_node str | None

更新状态,就好像这个节点刚刚执行一样。

None
checkpoint Checkpoint | None

要更新状态的检查点。

None
checkpoint_id str | None

(已弃用)要更新状态的检查点 ID。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
ThreadUpdateStateResponse ThreadUpdateStateResponse

更新线程状态后的响应。

示例用法

client = get_client(url="https://:2024)
response = await client.threads.update_state(
    thread_id="my_thread_id",
    values={"messages":[{"role": "user", "content": "hello!"}]},
    as_node="my_node",
)
print(response)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'checkpoint': {
        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
        'checkpoint_ns': '',
        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
        'checkpoint_map': {}
    }
}

get_history async

get_history(
    thread_id: str,
    *,
    limit: int = 10,
    before: str | Checkpoint | None = None,
    metadata: dict | None = None,
    checkpoint: Checkpoint | None = None,
    headers: dict[str, str] | None = None
) -> list[ThreadState]

获取线程的状态历史。

参数

名称 类型 描述 默认值
thread_id str

要获取状态历史的线程 ID。

必填
checkpoint Checkpoint | None

返回此子图的状态。如果为空,则默认为根。

None
限制 整数

要返回的最大状态数。

10
before str | Checkpoint | None

返回此检查点之前的状态。

None
metadata dict | None

按元数据键值对过滤状态。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[ThreadState]

list[ThreadState]: 线程的状态历史。

示例用法
client = get_client(url="https://:2024)
thread_state = await client.threads.get_history(
    thread_id="my_thread_id",
    limit=5,
)

RunsClient

用于在 LangGraph 中管理运行的客户端。

运行是单个助手调用,包含可选的输入、配置和元数据。此客户端管理运行,运行可以是状态化的(在线程上)或无状态的。

示例
client = get_client(url="https://:2024")
run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})

方法

名称 描述
stream

创建运行并流式传输结果。

create

创建后台运行。

create_batch

创建一批无状态后台运行。

wait

创建一个运行,等待它完成并返回最终状态。

list

列出运行。

获取

获取一个运行。

cancel

获取一个运行。

join

阻塞直到运行完成。返回线程的最终状态。

join_stream

实时流式传输运行的输出,直到运行完成。

delete

删除运行。

stream

stream(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    stream_mode: (
        StreamMode | Sequence[StreamMode]
    ) = "values",
    stream_subgraphs: bool = False,
    stream_resumable: bool = False,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    feedback_keys: Sequence[str] | None = None,
    on_disconnect: DisconnectMode | None = None,
    on_completion: OnCompletionBehavior | None = None,
    webhook: str | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    if_not_exists: IfNotExists | None = None,
    after_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> AsyncIterator[StreamPart]

创建运行并流式传输结果。

参数

名称 类型 描述 默认值
thread_id str | None

要分配给线程的线程 ID。如果为 None,将创建一个无状态运行。

必填
assistant_id str

要从中流式传输的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。不能与输入结合使用。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否流式传输子图的输出。

False
stream_resumable bool

流是否被认为是可恢复的。如果为 true,即使在断开连接后,也可以完全恢复和重播流。

False
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
feedback_keys Sequence[str] | None

要分配给运行的反馈键。

None
on_disconnect DisconnectMode | None

要使用的断开连接模式。必须是“cancel”或“continue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的回调函数。

None

返回

类型 描述
AsyncIterator[StreamPart]

AsyncIterator[StreamPart]: 流结果的异步迭代器。

示例用法
client = get_client(url="https://:2024)
async for chunk in client.runs.stream(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    stream_mode=["values","debug"],
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
):
    print(chunk)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
StreamPart(event='end', data=None)

create async

create(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    stream_mode: (
        StreamMode | Sequence[StreamMode]
    ) = "values",
    stream_subgraphs: bool = False,
    stream_resumable: bool = False,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    if_not_exists: IfNotExists | None = None,
    on_completion: OnCompletionBehavior | None = None,
    after_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> Run

创建后台运行。

参数

名称 类型 描述 默认值
thread_id str | None

要分配给线程的线程 ID。如果为 None,将创建一个无状态运行。

必填
assistant_id str

要从中流式传输的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。不能与输入结合使用。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否流式传输子图的输出。

False
stream_resumable bool

流是否被认为是可恢复的。如果为 true,即使在断开连接后,也可以完全恢复和重播流。

False
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的可选回调函数。

None

返回

名称 类型 描述
Run Run

创建的后台运行。

示例用法
background_run = await client.runs.create(
    thread_id="my_thread_id",
    assistant_id="my_assistant_id",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(background_run)
--------------------------------------------------------------------------------

{
    'run_id': 'my_run_id',
    'thread_id': 'my_thread_id',
    'assistant_id': 'my_assistant_id',
    'created_at': '2024-07-25T15:35:42.598503+00:00',
    'updated_at': '2024-07-25T15:35:42.598503+00:00',
    'metadata': {},
    'status': 'pending',
    'kwargs':
        {
            'input':
                {
                    'messages': [
                        {
                            'role': 'user',
                            'content': 'how are you?'
                        }
                    ]
                },
            'config':
                {
                    'metadata':
                        {
                            'created_by': 'system'
                        },
                    'configurable':
                        {
                            'run_id': 'my_run_id',
                            'user_id': None,
                            'graph_id': 'agent',
                            'thread_id': 'my_thread_id',
                            'checkpoint_id': None,
                            'model_name': "openai",
                            'assistant_id': 'my_assistant_id'
                        }
                },
            'webhook': "https://my.fake.webhook.com",
            'temporary': False,
            'stream_mode': ['values'],
            'feedback_keys': None,
            'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
            'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
        },
    'multitask_strategy': 'interrupt'
}

create_batch async

create_batch(payloads: list[RunCreate]) -> list[Run]

创建一批无状态后台运行。

wait async

wait(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    webhook: str | None = None,
    on_disconnect: DisconnectMode | None = None,
    on_completion: OnCompletionBehavior | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    if_not_exists: IfNotExists | None = None,
    after_seconds: int | None = None,
    raise_error: bool = True,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> list[dict] | dict[str, Any]

创建一个运行,等待它完成并返回最终状态。

参数

名称 类型 描述 默认值
thread_id str | None

创建运行的线程 ID。如果为 None,将创建无状态运行。

必填
assistant_id str

要运行的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。不能与输入结合使用。

None
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
on_disconnect DisconnectMode | None

要使用的断开连接模式。必须是“cancel”或“continue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的可选回调函数。

None

返回

类型 描述
list[dict] | dict[str, Any]

Union[list[dict], dict[str, Any]]: 运行的输出。

示例用法
client = get_client(url="https://:2024")
final_state_of_run = await client.runs.wait(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(final_state_of_run)
-------------------------------------------------------------------------------------------------------------------------------------------

{
    'messages': [
        {
            'content': 'how are you?',
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'human',
            'name': None,
            'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
            'example': False
        },
        {
            'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'ai',
            'name': None,
            'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
            'example': False,
            'tool_calls': [],
            'invalid_tool_calls': [],
            'usage_metadata': None
        }
    ]
}

list async

list(
    thread_id: str,
    *,
    limit: int = 10,
    offset: int = 0,
    status: RunStatus | None = None,
    headers: dict[str, str] | None = None
) -> list[Run]

列出运行。

参数

名称 类型 描述 默认值
thread_id str

要列出运行的线程 ID。

必填
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
status RunStatus | None

要过滤的运行状态。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Run]

list[Run]: 线程的运行。

示例用法
client = get_client(url="https://:2024")
await client.runs.list(
    thread_id="thread_id",
    limit=5,
    offset=5,
)

get async

get(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> Run

获取一个运行。

参数

名称 类型 描述 默认值
thread_id str

要获取的线程 ID。

必填
run_id str

要获取的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

运行对象。

示例用法
client = get_client(url="https://:2024")
run = await client.runs.get(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete",
)

cancel async

cancel(
    thread_id: str,
    run_id: str,
    *,
    wait: bool = False,
    action: CancelAction = "interrupt",
    headers: dict[str, str] | None = None
) -> None

获取一个运行。

参数

名称 类型 描述 默认值
thread_id str

要取消的线程 ID。

必填
run_id str

要取消的运行 ID。

必填
wait bool

是否等待运行完成。

False
action CancelAction

取消运行时要采取的操作。可能的值为 interruptrollback。默认为 interrupt

'interrupt'
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.runs.cancel(
    thread_id="thread_id_to_cancel",
    run_id="run_id_to_cancel",
    wait=True,
    action="interrupt"
)

join async

join(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> dict

阻塞直到运行完成。返回线程的最终状态。

参数

名称 类型 描述 默认值
thread_id str

要加入的线程 ID。

必填
run_id str

要加入的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
dict

None

示例用法
client = get_client(url="https://:2024")
result =await client.runs.join(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)

join_stream

join_stream(
    thread_id: str,
    run_id: str,
    *,
    cancel_on_disconnect: bool = False,
    stream_mode: (
        StreamMode | Sequence[StreamMode] | None
    ) = None,
    headers: dict[str, str] | None = None,
    last_event_id: str | None = None
) -> AsyncIterator[StreamPart]

实时流式传输运行的输出,直到运行完成。输出不进行缓冲,因此在此调用之前产生的任何输出将不会在此处收到。

参数

名称 类型 描述 默认值
thread_id str

要加入的线程 ID。

必填
run_id str

要加入的运行 ID。

必填
cancel_on_disconnect bool

断开流时是否取消运行。

False
stream_mode StreamMode | Sequence[StreamMode] | None

要使用的流模式。必须是创建运行时传递的流模式的子集。后台运行默认为所有流模式的并集。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
AsyncIterator[StreamPart]

None

示例用法
client = get_client(url="https://:2024")
async for part in client.runs.join_stream(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join",
    stream_mode=["values", "debug"]
):
    print(part)

delete async

delete(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> None

删除运行。

参数

名称 类型 描述 默认值
thread_id str

要删除的线程 ID。

必填
run_id str

要删除的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.runs.delete(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete"
)

CronClient

用于在 LangGraph 中管理循环运行(定时任务)的客户端。

运行是对助手进行的单个调用,包含可选的输入和配置。此客户端允许安排定期运行自动发生。

示例用法
client = get_client(url="https://:2024"))
cron_job = await client.crons.create_for_thread(
    thread_id="thread_123",
    assistant_id="asst_456",
    schedule="0 9 * * *",
    input={"message": "Daily update"}
)

功能可用性

cron 客户端功能并非所有许可证都支持。请查看相关许可证文档,了解最新的功能可用性详细信息。

方法

名称 描述
create_for_thread

为线程创建定时任务。

create

创建定时运行。

delete

删除定时任务。

search

获取定时任务列表。

create_for_thread async

create_for_thread(
    thread_id: str,
    assistant_id: str,
    *,
    schedule: str,
    input: dict | None = None,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | list[str] | None = None,
    interrupt_after: All | list[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: str | None = None,
    headers: dict[str, str] | None = None
) -> Run

为线程创建定时任务。

参数

名称 类型 描述 默认值
thread_id str

运行定时任务的线程 ID。

必填
assistant_id str

用于定时任务的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此任务的定时计划。

必填
input dict | None

图的输入。

None
metadata dict | None

要分配给定时任务运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | list[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | list[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy str | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

定时运行。

示例用法
client = get_client(url="https://:2024")
cron_run = await client.crons.create_for_thread(
    thread_id="my-thread-id",
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)

create async

create(
    assistant_id: str,
    *,
    schedule: str,
    input: dict | None = None,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | list[str] | None = None,
    interrupt_after: All | list[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: str | None = None,
    headers: dict[str, str] | None = None
) -> Run

创建定时运行。

参数

名称 类型 描述 默认值
assistant_id str

用于定时任务的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此任务的定时计划。

必填
input dict | None

图的输入。

None
metadata dict | None

要分配给定时任务运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | list[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | list[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy str | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

定时运行。

示例用法
client = get_client(url="https://:2024")
cron_run = client.crons.create(
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)

delete async

delete(
    cron_id: str, headers: dict[str, str] | None = None
) -> None

删除定时任务。

参数

名称 类型 描述 默认值
cron_id str

要删除的定时任务 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.crons.delete(
    cron_id="cron_to_delete"
)

search async

search(
    *,
    assistant_id: str | None = None,
    thread_id: str | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: CronSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Cron]

获取定时任务列表。

参数

名称 类型 描述 默认值
assistant_id str | None

要搜索的助手 ID 或图名称。

None
thread_id str | None

要搜索的线程 ID。

None
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Cron]

list[Cron]: 搜索返回的定时任务列表。

示例用法

client = get_client(url="https://:2024")
cron_jobs = await client.crons.search(
    assistant_id="my_assistant_id",
    thread_id="my_thread_id",
    limit=5,
    offset=5,
)
print(cron_jobs)
----------------------------------------------------------

[
    {
        'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
        'assistant_id': 'my_assistant_id',
        'thread_id': 'my_thread_id',
        'user_id': None,
        'payload':
            {
                'input': {'start_time': ''},
                'schedule': '4 * * * *',
                'assistant_id': 'my_assistant_id'
            },
        'schedule': '4 * * * *',
        'next_run_date': '2024-07-25T17:04:00+00:00',
        'end_time': None,
        'created_at': '2024-07-08T06:02:23.073257+00:00',
        'updated_at': '2024-07-08T06:02:23.073257+00:00'
    }
]

StoreClient

用于与图的共享存储交互的客户端。

Store 提供了一个键值存储系统,用于在图执行之间持久化数据,从而实现状态操作和跨线程数据共享。

示例
client = get_client(url="https://:2024")
await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})

方法

名称 描述
put_item

存储或更新项目。

get_item

检索单个项。

delete_item

删除项。

search_items

在命名空间前缀内搜索项。

list_namespaces

列出带可选匹配条件的命名空间。

put_item async

put_item(
    namespace: Sequence[str],
    /,
    key: str,
    value: dict[str, Any],
    index: Literal[False] | list[str] | None = None,
    ttl: int | None = None,
    headers: dict[str, str] | None = None,
) -> None

存储或更新项目。

参数

名称 类型 描述 默认值
namespace Sequence[str]

表示命名空间路径的字符串列表。

必填
str

命名空间内项目的唯一标识符。

必填
dict[str, Any]

包含项目数据的字典。

必填
index Literal[False] | list[str] | None

控制搜索索引 - None(使用默认值)、False(禁用)或要索引的字段路径列表。

None
生存时间 int | None

项目的可选生存时间(分钟),或 None 表示永不失效。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.store.put_item(
    ["documents", "user123"],
    key="item456",
    value={"title": "My Document", "content": "Hello World"}
)

get_item async

get_item(
    namespace: Sequence[str],
    /,
    key: str,
    *,
    refresh_ttl: bool | None = None,
    headers: dict[str, str] | None = None,
) -> Item

检索单个项。

参数

名称 类型 描述 默认值
str

项目的唯一标识符。

必填
namespace Sequence[str]

表示命名空间路径的可选字符串列表。

必填
refresh_ttl bool | None

在此读取操作上是否刷新 TTL。如果为 None,则使用存储的默认行为。

None

返回

名称 类型 描述

检索到的项目。

headers

请求中包含的可选自定义头。

示例用法

client = get_client(url="https://:2024")
item = await client.store.get_item(
    ["documents", "user123"],
    key="item456",
)
print(item)
----------------------------------------------------------------

{
    'namespace': ['documents', 'user123'],
    'key': 'item456',
    'value': {'title': 'My Document', 'content': 'Hello World'},
    'created_at': '2024-07-30T12:00:00Z',
    'updated_at': '2024-07-30T12:00:00Z'
}

delete_item async

delete_item(
    namespace: Sequence[str],
    /,
    key: str,
    headers: dict[str, str] | None = None,
) -> None

删除项。

参数

名称 类型 描述 默认值
str

项目的唯一标识符。

必填
namespace Sequence[str]

表示命名空间路径的可选字符串列表。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_client(url="https://:2024")
await client.store.delete_item(
    ["documents", "user123"],
    key="item456",
)

search_items async

search_items(
    namespace_prefix: Sequence[str],
    /,
    filter: dict[str, Any] | None = None,
    limit: int = 10,
    offset: int = 0,
    query: str | None = None,
    refresh_ttl: bool | None = None,
    headers: dict[str, str] | None = None,
) -> SearchItemsResponse

在命名空间前缀内搜索项。

参数

名称 类型 描述 默认值
namespace_prefix Sequence[str]

表示命名空间前缀的字符串列表。

必填
过滤器 dict[str, Any] | None

可选的键值对字典,用于过滤结果。

None
限制 整数

要返回的最大项目数(默认值为 10)。

10
offset 整数

在返回结果之前要跳过的项目数(默认值为 0)。

0
查询 str | None

自然语言搜索的可选查询。

None
refresh_ttl bool | None

是否刷新此搜索返回项目的 TTL。如果为 None,则使用存储的默认行为。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
SearchItemsResponse

list[Item]: 匹配搜索条件的项目列表。

示例用法

client = get_client(url="https://:2024")
items = await client.store.search_items(
    ["documents"],
    filter={"author": "John Doe"},
    limit=5,
    offset=0
)
print(items)
----------------------------------------------------------------

{
    "items": [
        {
            "namespace": ["documents", "user123"],
            "key": "item789",
            "value": {
                "title": "Another Document",
                "author": "John Doe"
            },
            "created_at": "2024-07-30T12:00:00Z",
            "updated_at": "2024-07-30T12:00:00Z"
        },
        # ... additional items ...
    ]
}

list_namespaces async

list_namespaces(
    prefix: list[str] | None = None,
    suffix: list[str] | None = None,
    max_depth: int | None = None,
    limit: int = 100,
    offset: int = 0,
    headers: dict[str, str] | None = None,
) -> ListNamespaceResponse

列出带可选匹配条件的命名空间。

参数

名称 类型 描述 默认值
prefix list[str] | None

表示命名空间前缀的可选字符串列表,用于过滤命名空间。

None
suffix list[str] | None

表示命名空间后缀的可选字符串列表,用于过滤命名空间。

None
max_depth int | None

可选整数,指定要返回的命名空间的最大深度。

None
限制 整数

要返回的最大命名空间数(默认值为 100)。

100
offset 整数

在返回结果之前要跳过的命名空间数(默认值为 0)。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
ListNamespaceResponse

list[list[str]]: 匹配条件的命名空间列表。

示例用法
client = get_client(url="https://:2024")
namespaces = await client.store.list_namespaces(
    prefix=["documents"],
    max_depth=3,
    limit=10,
    offset=0
)
print(namespaces)

----------------------------------------------------------------

[
    ["documents", "user123", "reports"],
    ["documents", "user456", "invoices"],
    ...
]

SyncLangGraphClient

用于与 LangGraph API 交互的同步客户端。

此类提供同步访问 LangGraph API 端点,用于管理助手、线程、运行、定时任务和数据存储。

示例
client = get_sync_client(url="https://:2024")
assistant = client.assistants.get("asst_123")

SyncHttpClient

处理 LangGraph API 的同步请求。

在底层 httpx 客户端之上提供错误消息和内容处理增强功能,镜像 HttpClient 的接口,但用于同步用法。

属性

名称 类型 描述
client Client

底层 HTTPX 同步客户端。

方法

名称 描述
获取

发送 GET 请求。

post

发送 POST 请求。

放置

发送 PUT 请求。

patch

发送 PATCH 请求。

delete

发送 DELETE 请求。

stream

使用 SSE 流式传输请求结果。

get

get(
    path: str,
    *,
    params: QueryParamTypes | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 GET 请求。

post

post(
    path: str,
    *,
    json: dict | None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 POST 请求。

put

put(
    path: str,
    *,
    json: dict,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 PUT 请求。

patch

patch(
    path: str,
    *,
    json: dict,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Any

发送 PATCH 请求。

delete

delete(
    path: str,
    *,
    json: Any | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> None

发送 DELETE 请求。

stream

stream(
    path: str,
    method: str,
    *,
    json: dict | None = None,
    params: QueryParamTypes | None = None,
    headers: dict[str, str] | None = None,
    on_response: Callable[[Response], None] | None = None
) -> Iterator[StreamPart]

使用 SSE 流式传输请求结果。

SyncAssistantsClient

用于在 LangGraph 中同步管理助手的客户端。

此类提供与助手交互的方法,助手是图的版本化配置。

示例
client = get_sync_client(url="https://:2024")
assistant = client.assistants.get("assistant_id_123")

方法

名称 描述
获取

通过 ID 获取助手。

get_graph

按 ID 获取助手的图。

get_schemas

通过 ID 获取助手的 schema。

get_subgraphs

通过 ID 获取助手的 schema。

create

创建一个新助手。

更新

更新助手。

delete

删除助手。

search

搜索助手。

get_versions

列出助手的全部版本。

set_latest

更改助手的版本。

get

get(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> Assistant

通过 ID 获取助手。

参数

名称 类型 描述 默认值
assistant_id str

要获取的助手 ID 或图的名称(用于默认助手)。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Assistant Assistant

助手对象。

示例用法
assistant = client.assistants.get(
    assistant_id="my_assistant_id"
)
print(assistant)
----------------------------------------------------

{
    'assistant_id': 'my_assistant_id',
    'graph_id': 'agent',
    'created_at': '2024-06-25T17:10:33.109781+00:00',
    'updated_at': '2024-06-25T17:10:33.109781+00:00',
    'config': {},
    'metadata': {'created_by': 'system'}
}

get_graph

get_graph(
    assistant_id: str,
    *,
    xray: int | bool = False,
    headers: dict[str, str] | None = None
) -> dict[str, list[dict[str, Any]]]

按 ID 获取助手的图。

参数

名称 类型 描述 默认值
assistant_id str

要获取图的助手的 ID。

必填
xray int | bool

包含子图的图表示。如果提供了整数值,则只包含深度小于或等于该值的子图。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
dict[str, list[dict[str, Any]]]

助手的图信息,JSON 格式。

示例用法
client = get_sync_client(url="https://:2024")
graph_info = client.assistants.get_graph(
    assistant_id="my_assistant_id"
)
print(graph_info)

--------------------------------------------------------------------------------------------------------------------------

{
    'nodes':
        [
            {'id': '__start__', 'type': 'schema', 'data': '__start__'},
            {'id': '__end__', 'type': 'schema', 'data': '__end__'},
            {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
        ],
    'edges':
        [
            {'source': '__start__', 'target': 'agent'},
            {'source': 'agent','target': '__end__'}
        ]
}

get_schemas

get_schemas(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> GraphSchema

通过 ID 获取助手的 schema。

参数

名称 类型 描述 默认值
assistant_id str

要获取其 schema 的助手的 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
GraphSchema GraphSchema

助手的图模式。

示例用法

client = get_sync_client(url="https://:2024")
schema = client.assistants.get_schemas(
    assistant_id="my_assistant_id"
)
print(schema)
----------------------------------------------------------------------------------------------------------------------------

{
    'graph_id': 'agent',
    'state_schema':
        {
            'title': 'LangGraphInput',
            '$ref': '#/definitions/AgentState',
            'definitions':
                {
                    'BaseMessage':
                        {
                            'title': 'BaseMessage',
                            'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
                            'type': 'object',
                            'properties':
                                {
                                 'content':
                                    {
                                        'title': 'Content',
                                        'anyOf': [
                                            {'type': 'string'},
                                            {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
                                        ]
                                    },
                                'additional_kwargs':
                                    {
                                        'title': 'Additional Kwargs',
                                        'type': 'object'
                                    },
                                'response_metadata':
                                    {
                                        'title': 'Response Metadata',
                                        'type': 'object'
                                    },
                                'type':
                                    {
                                        'title': 'Type',
                                        'type': 'string'
                                    },
                                'name':
                                    {
                                        'title': 'Name',
                                        'type': 'string'
                                    },
                                'id':
                                    {
                                        'title': 'Id',
                                        'type': 'string'
                                    }
                                },
                            'required': ['content', 'type']
                        },
                    'AgentState':
                        {
                            'title': 'AgentState',
                            'type': 'object',
                            'properties':
                                {
                                    'messages':
                                        {
                                            'title': 'Messages',
                                            'type': 'array',
                                            'items': {'$ref': '#/definitions/BaseMessage'}
                                        }
                                },
                            'required': ['messages']
                        }
                }
        },
    'config_schema':
        {
            'title': 'Configurable',
            'type': 'object',
            'properties':
                {
                    'model_name':
                        {
                            'title': 'Model Name',
                            'enum': ['anthropic', 'openai'],
                            'type': 'string'
                        }
                }
        }
}

get_subgraphs

get_subgraphs(
    assistant_id: str,
    namespace: str | None = None,
    recurse: bool = False,
    *,
    headers: dict[str, str] | None = None
) -> Subgraphs

通过 ID 获取助手的 schema。

参数

名称 类型 描述 默认值
assistant_id str

要获取其 schema 的助手的 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
子图 子图

助手的图模式。

create

create(
    graph_id: str | None,
    config: Config | None = None,
    *,
    metadata: Json = None,
    assistant_id: str | None = None,
    if_exists: OnConflictBehavior | None = None,
    name: str | None = None,
    headers: dict[str, str] | None = None,
    description: str | None = None
) -> Assistant

创建一个新助手。

当图可配置且您想根据不同配置创建不同助手时很有用。

参数

名称 类型 描述 默认值
graph_id str | None

助手应使用的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。

必填
config Config | None

用于图的配置。

None
metadata Json

要添加到助手的元数据。

None
assistant_id str | None

要使用的助手 ID,如果未提供,将默认为随机 UUID。

None
if_exists OnConflictBehavior | None

如何处理重复创建。默认为“raise”。必须是“raise”(如果重复则引发错误)或“do_nothing”(返回现有助手)。

None
name str | None

助手的名称。默认为“Untitled”。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api server 版本 >= 0.0.45

None

返回

名称 类型 描述
Assistant Assistant

创建的助手。

示例用法
client = get_sync_client(url="https://:2024")
assistant = client.assistants.create(
    graph_id="agent",
    config={"configurable": {"model_name": "openai"}},
    metadata={"number":1},
    assistant_id="my-assistant-id",
    if_exists="do_nothing",
    name="my_name"
)

update

update(
    assistant_id: str,
    *,
    graph_id: str | None = None,
    config: Config | None = None,
    metadata: Json = None,
    name: str | None = None,
    headers: dict[str, str] | None = None,
    description: str | None = None
) -> Assistant

更新助手。

使用此功能指向不同的图,更新配置,或更改助手的元数据。

参数

名称 类型 描述 默认值
assistant_id str

要更新的助手。

必填
graph_id str | None

助手应使用的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。如果为 None,助手将继续指向相同的图。

None
config Config | None

用于图的配置。

None
metadata Json

要与现有助手元数据合并的元数据。

None
name str | None

助手的新名称。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api server 版本 >= 0.0.45

None

返回

名称 类型 描述
Assistant Assistant

更新后的助手。

示例用法
client = get_sync_client(url="https://:2024")
assistant = client.assistants.update(
    assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
    graph_id="other-graph",
    config={"configurable": {"model_name": "anthropic"}},
    metadata={"number":2}
)

delete

delete(
    assistant_id: str,
    *,
    headers: dict[str, str] | None = None
) -> None

删除助手。

参数

名称 类型 描述 默认值
assistant_id str

要删除的助手 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:2024")
client.assistants.delete(
    assistant_id="my_assistant_id"
)

search

search(
    *,
    metadata: Json = None,
    graph_id: str | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: AssistantSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Assistant]

搜索助手。

参数

名称 类型 描述 默认值
metadata Json

要过滤的元数据。每个键值对的精确匹配过滤器。

None
graph_id str | None

要过滤的图 ID。图 ID 通常在您的 langgraph.json 配置中设置。

None
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Assistant]

list[Assistant]: 助手列表。

示例用法
client = get_sync_client(url="https://:2024")
assistants = client.assistants.search(
    metadata = {"name":"my_name"},
    graph_id="my_graph_id",
    limit=5,
    offset=5
)

get_versions

get_versions(
    assistant_id: str,
    metadata: Json = None,
    limit: int = 10,
    offset: int = 0,
    *,
    headers: dict[str, str] | None = None
) -> list[AssistantVersion]

列出助手的全部版本。

参数

名称 类型 描述 默认值
assistant_id str

要获取版本的助手 ID。

必填
metadata Json

用于过滤版本的元数据。每个键值对的精确匹配过滤器。

None
限制 整数

要返回的最大版本数。

10
offset 整数

要跳过的版本数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[AssistantVersion]

list[Assistant]: 助手列表。

示例用法
client = get_sync_client(url="https://:2024")
assistant_versions = client.assistants.get_versions(
    assistant_id="my_assistant_id"
)

set_latest

set_latest(
    assistant_id: str,
    version: int,
    *,
    headers: dict[str, str] | None = None
) -> Assistant

更改助手的版本。

参数

名称 类型 描述 默认值
assistant_id str

要删除的助手 ID。

必填
version 整数

要更改为的版本。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Assistant Assistant

助手对象。

示例用法
client = get_sync_client(url="https://:2024")
new_version_assistant = client.assistants.set_latest(
    assistant_id="my_assistant_id",
    version=3
)

SyncThreadsClient

用于在 LangGraph 中管理线程的同步客户端。

此类提供创建、检索和管理线程的方法,线程表示对话或有状态交互。

示例
client = get_sync_client(url="https://:2024")
thread = client.threads.create(metadata={"user_id": "123"})

方法

名称 描述
获取

通过 ID 获取会话。

create

创建新会话。

更新

更新会话。

delete

删除会话。

search

搜索线程。

copy

复制线程。

get_state

获取线程的状态。

update_state

更新线程的状态。

get_history

获取线程的状态历史。

get

get(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> Thread

通过 ID 获取会话。

参数

名称 类型 描述 默认值
thread_id str

要获取的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

线程对象。

示例用法

client = get_sync_client(url="https://:2024")
thread = client.threads.get(
    thread_id="my_thread_id"
)
print(thread)
-----------------------------------------------------

{
    'thread_id': 'my_thread_id',
    'created_at': '2024-07-18T18:35:15.540834+00:00',
    'updated_at': '2024-07-18T18:35:15.540834+00:00',
    'metadata': {'graph_id': 'agent'}
}

create

create(
    *,
    metadata: Json = None,
    thread_id: str | None = None,
    if_exists: OnConflictBehavior | None = None,
    supersteps: (
        Sequence[dict[str, Sequence[dict[str, Any]]]] | None
    ) = None,
    graph_id: str | None = None,
    headers: dict[str, str] | None = None
) -> Thread

创建新会话。

参数

名称 类型 描述 默认值
metadata Json

要添加到线程的元数据。

None
thread_id str | None

线程 ID。如果为 None,ID 将是随机生成的 UUID。

None
if_exists OnConflictBehavior | None

如何处理重复创建。默认为“raise”。必须是“raise”(如果重复则引发错误)或“do_nothing”(返回现有线程)。

None
supersteps Sequence[dict[str, Sequence[dict[str, Any]]]] | None

创建线程时应用一系列超级步骤,每个步骤包含一系列更新。每次更新都有 `values` 或 `command` 和 `as_node`。用于在部署之间复制线程。

None
graph_id str | None

与线程关联的可选图 ID。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

创建的会话。

示例用法

client = get_sync_client(url="https://:2024")
thread = client.threads.create(
    metadata={"number":1},
    thread_id="my-thread-id",
    if_exists="raise"
)
)

update

update(
    thread_id: str,
    *,
    metadata: dict[str, Any],
    headers: dict[str, str] | None = None
) -> Thread

更新会话。

参数

名称 类型 描述 默认值
thread_id str

要更新的线程 ID。

必填
metadata dict[str, Any]

要与现有线程元数据合并的元数据。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Thread Thread

创建的会话。

示例用法
client = get_sync_client(url="https://:2024")
thread = client.threads.update(
    thread_id="my-thread-id",
    metadata={"number":1},
)

delete

delete(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> None

删除会话。

参数

名称 类型 描述 默认值
thread_id str

要删除的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client.threads.delete(
    thread_id="my_thread_id"
)

search

search(
    *,
    metadata: Json = None,
    values: Json = None,
    status: ThreadStatus | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: ThreadSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Thread]

搜索线程。

参数

名称 类型 描述 默认值
metadata Json

要过滤的线程元数据。

None
values Json

要过滤的状态值。

None
status ThreadStatus | None

要过滤的会话状态。必须是 'idle'、'busy'、'interrupted' 或 'error' 之一。

None
限制 整数

要返回的线程数限制。

10
offset 整数

从线程表中开始搜索的偏移量。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Thread]

list[Thread]: 匹配搜索参数的线程列表。

示例用法
client = get_sync_client(url="https://:2024")
threads = client.threads.search(
    metadata={"number":1},
    status="interrupted",
    limit=15,
    offset=5
)

copy

copy(
    thread_id: str, *, headers: dict[str, str] | None = None
) -> None

复制线程。

参数

名称 类型 描述 默认值
thread_id str

要复制的线程 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:2024")
client.threads.copy(
    thread_id="my_thread_id"
)

get_state

get_state(
    thread_id: str,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    *,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None
) -> ThreadState

获取线程的状态。

参数

名称 类型 描述 默认值
thread_id str

要获取状态的线程 ID。

必填
checkpoint Checkpoint | None

要获取状态的检查点。

None
subgraphs bool

包括子图状态。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
ThreadState ThreadState

状态的线程。

示例用法
client = get_sync_client(url="https://:2024")
thread_state = client.threads.get_state(
    thread_id="my_thread_id",
    checkpoint_id="my_checkpoint_id"
)
print(thread_state)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'values': {
        'messages': [
            {
                'content': 'how are you?',
                'additional_kwargs': {},
                'response_metadata': {},
                'type': 'human',
                'name': None,
                'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
                'example': False
            },
            {
                'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                'additional_kwargs': {},
                'response_metadata': {},
                'type': 'ai',
                'name': None,
                'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                'example': False,
                'tool_calls': [],
                'invalid_tool_calls': [],
                'usage_metadata': None
            }
        ]
    },
    'next': [],
    'checkpoint':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
        }
    'metadata':
        {
            'step': 1,
            'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
            'source': 'loop',
            'writes':
                {
                    'agent':
                        {
                            'messages': [
                                {
                                    'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                    'name': None,
                                    'type': 'ai',
                                    'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                    'example': False,
                                    'tool_calls': [],
                                    'usage_metadata': None,
                                    'additional_kwargs': {},
                                    'response_metadata': {},
                                    'invalid_tool_calls': []
                                }
                            ]
                        }
                },
    'user_id': None,
    'graph_id': 'agent',
    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
    'created_by': 'system',
    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
    'created_at': '2024-07-25T15:35:44.184703+00:00',
    'parent_config':
        {
            'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
            'checkpoint_ns': '',
            'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
        }
}

update_state

update_state(
    thread_id: str,
    values: dict | Sequence[dict] | None,
    *,
    as_node: str | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    headers: dict[str, str] | None = None
) -> ThreadUpdateStateResponse

更新线程的状态。

参数

名称 类型 描述 默认值
thread_id str

要更新的线程 ID。

必填
values dict | Sequence[dict] | None

用于更新状态的值。

必填
as_node str | None

更新状态,就好像这个节点刚刚执行一样。

None
checkpoint Checkpoint | None

要更新状态的检查点。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
ThreadUpdateStateResponse ThreadUpdateStateResponse

更新线程状态后的响应。

示例用法
response = await client.threads.update_state(
    thread_id="my_thread_id",
    values={"messages":[{"role": "user", "content": "hello!"}]},
    as_node="my_node",
)
print(response)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

{
    'checkpoint': {
        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
        'checkpoint_ns': '',
        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
        'checkpoint_map': {}
    }
}

get_history

get_history(
    thread_id: str,
    *,
    limit: int = 10,
    before: str | Checkpoint | None = None,
    metadata: dict | None = None,
    checkpoint: Checkpoint | None = None,
    headers: dict[str, str] | None = None
) -> list[ThreadState]

获取线程的状态历史。

参数

名称 类型 描述 默认值
thread_id str

要获取状态历史的线程 ID。

必填
checkpoint Checkpoint | None

返回此子图的状态。如果为空,则默认为根。

None
限制 整数

要返回的最大状态数。

10
before str | Checkpoint | None

返回此检查点之前的状态。

None
metadata dict | None

按元数据键值对过滤状态。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[ThreadState]

list[ThreadState]: 线程的状态历史。

示例用法
thread_state = client.threads.get_history(
    thread_id="my_thread_id",
    limit=5,
    before="my_timestamp",
    metadata={"name":"my_name"}
)

SyncRunsClient

用于在 LangGraph 中管理运行的同步客户端。

此类提供创建、检索和管理运行的方法,运行表示图的单个执行。

示例
client = get_sync_client(url="https://:2024")
run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")

方法

名称 描述
stream

创建运行并流式传输结果。

create

创建后台运行。

create_batch

创建一批无状态后台运行。

wait

创建一个运行,等待它完成并返回最终状态。

list

列出运行。

获取

获取一个运行。

cancel

获取一个运行。

join

阻塞直到运行完成。返回线程的最终状态。

join_stream

实时流式传输运行的输出,直到运行完成。

delete

删除运行。

stream

stream(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    stream_mode: (
        StreamMode | Sequence[StreamMode]
    ) = "values",
    stream_subgraphs: bool = False,
    stream_resumable: bool = False,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    feedback_keys: Sequence[str] | None = None,
    on_disconnect: DisconnectMode | None = None,
    on_completion: OnCompletionBehavior | None = None,
    webhook: str | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    if_not_exists: IfNotExists | None = None,
    after_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> Iterator[StreamPart]

创建运行并流式传输结果。

参数

名称 类型 描述 默认值
thread_id str | None

要分配给线程的线程 ID。如果为 None,将创建一个无状态运行。

必填
assistant_id str

要从中流式传输的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否流式传输子图的输出。

False
stream_resumable bool

流是否被认为是可恢复的。如果为 true,即使在断开连接后,也可以完全恢复和重播流。

False
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
feedback_keys Sequence[str] | None

要分配给运行的反馈键。

None
on_disconnect DisconnectMode | None

要使用的断开连接模式。必须是“cancel”或“continue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的可选回调函数。

None

返回

类型 描述
Iterator[StreamPart]

Iterator[StreamPart]: 流结果的迭代器。

示例用法

client = get_sync_client(url="https://:2024")
async for chunk in client.runs.stream(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    stream_mode=["values","debug"],
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
):
    print(chunk)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
StreamPart(event='end', data=None)

create

create(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    stream_mode: (
        StreamMode | Sequence[StreamMode]
    ) = "values",
    stream_subgraphs: bool = False,
    stream_resumable: bool = False,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    on_completion: OnCompletionBehavior | None = None,
    if_not_exists: IfNotExists | None = None,
    after_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> Run

创建后台运行。

参数

名称 类型 描述 默认值
thread_id str | None

要分配给线程的线程 ID。如果为 None,将创建一个无状态运行。

必填
assistant_id str

要从中流式传输的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否流式传输子图的输出。

False
stream_resumable bool

流是否被认为是可恢复的。如果为 true,即使在断开连接后,也可以完全恢复和重播流。

False
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的可选回调函数。

None

返回

名称 类型 描述
Run Run

创建的后台运行。

示例用法
client = get_sync_client(url="https://:2024")
background_run = client.runs.create(
    thread_id="my_thread_id",
    assistant_id="my_assistant_id",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(background_run)
--------------------------------------------------------------------------------

{
    'run_id': 'my_run_id',
    'thread_id': 'my_thread_id',
    'assistant_id': 'my_assistant_id',
    'created_at': '2024-07-25T15:35:42.598503+00:00',
    'updated_at': '2024-07-25T15:35:42.598503+00:00',
    'metadata': {},
    'status': 'pending',
    'kwargs':
        {
            'input':
                {
                    'messages': [
                        {
                            'role': 'user',
                            'content': 'how are you?'
                        }
                    ]
                },
            'config':
                {
                    'metadata':
                        {
                            'created_by': 'system'
                        },
                    'configurable':
                        {
                            'run_id': 'my_run_id',
                            'user_id': None,
                            'graph_id': 'agent',
                            'thread_id': 'my_thread_id',
                            'checkpoint_id': None,
                            'model_name': "openai",
                            'assistant_id': 'my_assistant_id'
                        }
                },
            'webhook': "https://my.fake.webhook.com",
            'temporary': False,
            'stream_mode': ['values'],
            'feedback_keys': None,
            'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
            'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
        },
    'multitask_strategy': 'interrupt'
}

create_batch

create_batch(
    payloads: list[RunCreate],
    *,
    headers: dict[str, str] | None = None
) -> list[Run]

创建一批无状态后台运行。

wait

wait(
    thread_id: str | None,
    assistant_id: str,
    *,
    input: dict | None = None,
    command: Command | None = None,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint_during: bool | None = None,
    checkpoint: Checkpoint | None = None,
    checkpoint_id: str | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    webhook: str | None = None,
    on_disconnect: DisconnectMode | None = None,
    on_completion: OnCompletionBehavior | None = None,
    multitask_strategy: MultitaskStrategy | None = None,
    if_not_exists: IfNotExists | None = None,
    after_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    on_run_created: (
        Callable[[RunCreateMetadata], None] | None
    ) = None
) -> list[dict] | dict[str, Any]

创建一个运行,等待它完成并返回最终状态。

参数

名称 类型 描述 默认值
thread_id str | None

创建运行的线程 ID。如果为 None,将创建无状态运行。

必填
assistant_id str

要运行的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
input dict | None

图的输入。

None
command Command | None

要执行的命令。

None
metadata dict | None

要分配给运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint Checkpoint | None

要从其恢复的检查点。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | Sequence[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | Sequence[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
on_disconnect DisconnectMode | None

要使用的断开连接模式。必须是“cancel”或“continue”之一。

None
on_completion OnCompletionBehavior | None

是否删除或保留为无状态运行创建的线程。必须是“delete”或“keep”之一。

None
multitask_strategy MultitaskStrategy | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
if_not_exists IfNotExists | None

如何处理丢失的线程。默认为“reject”。必须是“reject”(如果丢失则引发错误)或“create”(创建新线程)。

None
after_seconds int | None

开始运行前等待的秒数。用于安排未来的运行。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None
on_run_created Callable[[RunCreateMetadata], None] | None

创建运行时的可选回调函数。

None

返回

类型 描述
list[dict] | dict[str, Any]

Union[list[dict], dict[str, Any]]: 运行的输出。

示例用法
final_state_of_run = client.runs.wait(
    thread_id=None,
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "how are you?"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "anthropic"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)
print(final_state_of_run)
-------------------------------------------------------------------------------------------------------------------------------------------

{
    'messages': [
        {
            'content': 'how are you?',
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'human',
            'name': None,
            'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
            'example': False
        },
        {
            'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
            'additional_kwargs': {},
            'response_metadata': {},
            'type': 'ai',
            'name': None,
            'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
            'example': False,
            'tool_calls': [],
            'invalid_tool_calls': [],
            'usage_metadata': None
        }
    ]
}

list

list(
    thread_id: str,
    *,
    limit: int = 10,
    offset: int = 0,
    headers: dict[str, str] | None = None
) -> list[Run]

列出运行。

参数

名称 类型 描述 默认值
thread_id str

要列出运行的线程 ID。

必填
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Run]

list[Run]: 线程的运行。

示例用法
client = get_sync_client(url="https://:2024")
client.runs.list(
    thread_id="thread_id",
    limit=5,
    offset=5,
)

get

get(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> Run

获取一个运行。

参数

名称 类型 描述 默认值
thread_id str

要获取的线程 ID。

必填
run_id str

要获取的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

运行对象。

示例用法
run = client.runs.get(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete",
)

cancel

cancel(
    thread_id: str,
    run_id: str,
    *,
    wait: bool = False,
    action: CancelAction = "interrupt",
    headers: dict[str, str] | None = None
) -> None

获取一个运行。

参数

名称 类型 描述 默认值
thread_id str

要取消的线程 ID。

必填
run_id str

要取消的运行 ID。

必填
wait bool

是否等待运行完成。

False
action CancelAction

取消运行时要采取的操作。可能的值为 interruptrollback。默认为 interrupt

'interrupt'
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:2024")
client.runs.cancel(
    thread_id="thread_id_to_cancel",
    run_id="run_id_to_cancel",
    wait=True,
    action="interrupt"
)

join

join(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> dict

阻塞直到运行完成。返回线程的最终状态。

参数

名称 类型 描述 默认值
thread_id str

要加入的线程 ID。

必填
run_id str

要加入的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
dict

None

示例用法
client = get_sync_client(url="https://:2024")
client.runs.join(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join"
)

join_stream

join_stream(
    thread_id: str,
    run_id: str,
    *,
    stream_mode: (
        StreamMode | Sequence[StreamMode] | None
    ) = None,
    cancel_on_disconnect: bool = False,
    headers: dict[str, str] | None = None,
    last_event_id: str | None = None
) -> Iterator[StreamPart]

实时流式传输运行的输出,直到运行完成。输出不进行缓冲,因此在此调用之前产生的任何输出将不会在此处收到。

参数

名称 类型 描述 默认值
thread_id str

要加入的线程 ID。

必填
run_id str

要加入的运行 ID。

必填
stream_mode StreamMode | Sequence[StreamMode] | None

要使用的流模式。必须是创建运行时传递的流模式的子集。后台运行默认为所有流模式的并集。

None
cancel_on_disconnect bool

断开流时是否取消运行。

False
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
Iterator[StreamPart]

None

示例用法
client = get_sync_client(url="https://:2024")
client.runs.join_stream(
    thread_id="thread_id_to_join",
    run_id="run_id_to_join",
    stream_mode=["values", "debug"]
)

delete

delete(
    thread_id: str,
    run_id: str,
    *,
    headers: dict[str, str] | None = None
) -> None

删除运行。

参数

名称 类型 描述 默认值
thread_id str

要删除的线程 ID。

必填
run_id str

要删除的运行 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:2024")
client.runs.delete(
    thread_id="thread_id_to_delete",
    run_id="run_id_to_delete"
)

SyncCronClient

用于在 LangGraph 中管理定时任务的同步客户端。

此类提供创建和管理计划任务(定时任务)以实现自动化图执行的方法。

示例
client = get_sync_client(url="https://:8123")
cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")

功能可用性

cron 客户端功能并非所有许可证都支持。请查看相关许可证文档,了解最新的功能可用性详细信息。

方法

名称 描述
create_for_thread

为线程创建定时任务。

create

创建定时运行。

delete

删除定时任务。

search

获取定时任务列表。

create_for_thread

create_for_thread(
    thread_id: str,
    assistant_id: str,
    *,
    schedule: str,
    input: dict | None = None,
    metadata: dict | None = None,
    checkpoint_during: bool | None = None,
    config: Config | None = None,
    interrupt_before: All | list[str] | None = None,
    interrupt_after: All | list[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: str | None = None,
    headers: dict[str, str] | None = None
) -> Run

为线程创建定时任务。

参数

名称 类型 描述 默认值
thread_id str

运行定时任务的线程 ID。

必填
assistant_id str

用于定时任务的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此任务的定时计划。

必填
input dict | None

图的输入。

None
metadata dict | None

要分配给定时任务运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | list[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | list[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy str | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

定时运行。

示例用法
client = get_sync_client(url="https://:8123")
cron_run = client.crons.create_for_thread(
    thread_id="my-thread-id",
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)

create

create(
    assistant_id: str,
    *,
    schedule: str,
    input: dict | None = None,
    metadata: dict | None = None,
    config: Config | None = None,
    checkpoint_during: bool | None = None,
    interrupt_before: All | list[str] | None = None,
    interrupt_after: All | list[str] | None = None,
    webhook: str | None = None,
    multitask_strategy: str | None = None,
    headers: dict[str, str] | None = None
) -> Run

创建定时运行。

参数

名称 类型 描述 默认值
assistant_id str

用于定时任务的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此任务的定时计划。

必填
input dict | None

图的输入。

None
metadata dict | None

要分配给定时任务运行的元数据。

None
config Config | None

助手的配置。

None
checkpoint_during bool | None

是否在运行期间(或仅在结束/中断时)进行检查点。

None
interrupt_before All | list[str] | None

在节点执行前立即中断它们。

None
interrupt_after All | list[str] | None

在节点执行后立即中断它们。

None
webhook str | None

LangGraph API 调用完成后要调用的 webhook。

None
multitask_strategy str | None

要使用的多任务策略。必须是“reject”、“interrupt”、“rollback”或“enqueue”之一。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述
Run Run

定时运行。

示例用法
client = get_sync_client(url="https://:8123")
cron_run = client.crons.create(
    assistant_id="agent",
    schedule="27 15 * * *",
    input={"messages": [{"role": "user", "content": "hello!"}]},
    metadata={"name":"my_run"},
    config={"configurable": {"model_name": "openai"}},
    checkpoint_during=True,
    interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
    interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
    webhook="https://my.fake.webhook.com",
    multitask_strategy="interrupt"
)

delete

delete(
    cron_id: str, *, headers: dict[str, str] | None = None
) -> None

删除定时任务。

参数

名称 类型 描述 默认值
cron_id str

要删除的定时任务 ID。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:8123")
client.crons.delete(
    cron_id="cron_to_delete"
)

search

search(
    *,
    assistant_id: str | None = None,
    thread_id: str | None = None,
    limit: int = 10,
    offset: int = 0,
    sort_by: CronSortBy | None = None,
    sort_order: SortOrder | None = None,
    headers: dict[str, str] | None = None
) -> list[Cron]

获取定时任务列表。

参数

名称 类型 描述 默认值
assistant_id str | None

要搜索的助手 ID 或图名称。

None
thread_id str | None

要搜索的线程 ID。

None
限制 整数

要返回的最大结果数。

10
offset 整数

要跳过的结果数。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
list[Cron]

list[Cron]: 搜索返回的定时任务列表。

示例用法
client = get_sync_client(url="https://:8123")
cron_jobs = client.crons.search(
    assistant_id="my_assistant_id",
    thread_id="my_thread_id",
    limit=5,
    offset=5,
)
print(cron_jobs)
----------------------------------------------------------

[
    {
        'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
        'assistant_id': 'my_assistant_id',
        'thread_id': 'my_thread_id',
        'user_id': None,
        'payload':
            {
                'input': {'start_time': ''},
                'schedule': '4 * * * *',
                'assistant_id': 'my_assistant_id'
            },
        'schedule': '4 * * * *',
        'next_run_date': '2024-07-25T17:04:00+00:00',
        'end_time': None,
        'created_at': '2024-07-08T06:02:23.073257+00:00',
        'updated_at': '2024-07-08T06:02:23.073257+00:00'
    }
]

SyncStoreClient

用于键值存储同步操作的客户端。

提供与远程键值存储交互的方法,允许在命名空间层次结构中存储和检索项目。

示例
client = get_sync_client(url="https://:2024"))
client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})

方法

名称 描述
put_item

存储或更新项目。

get_item

检索单个项。

delete_item

删除项。

search_items

在命名空间前缀内搜索项。

list_namespaces

列出带可选匹配条件的命名空间。

put_item

put_item(
    namespace: Sequence[str],
    /,
    key: str,
    value: dict[str, Any],
    index: Literal[False] | list[str] | None = None,
    ttl: int | None = None,
    headers: dict[str, str] | None = None,
) -> None

存储或更新项目。

参数

名称 类型 描述 默认值
namespace Sequence[str]

表示命名空间路径的字符串列表。

必填
str

命名空间内项目的唯一标识符。

必填
dict[str, Any]

包含项目数据的字典。

必填
index Literal[False] | list[str] | None

控制搜索索引 - None(使用默认值)、False(禁用)或要索引的字段路径列表。

None
生存时间 int | None

项目的可选生存时间(分钟),或 None 表示永不失效。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:8123")
client.store.put_item(
    ["documents", "user123"],
    key="item456",
    value={"title": "My Document", "content": "Hello World"}
)

get_item

get_item(
    namespace: Sequence[str],
    /,
    key: str,
    *,
    refresh_ttl: bool | None = None,
    headers: dict[str, str] | None = None,
) -> Item

检索单个项。

参数

名称 类型 描述 默认值
str

项目的唯一标识符。

必填
namespace Sequence[str]

表示命名空间路径的可选字符串列表。

必填
refresh_ttl bool | None

在此读取操作上是否刷新 TTL。如果为 None,则使用存储的默认行为。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

名称 类型 描述

检索到的项目。

示例用法
client = get_sync_client(url="https://:8123")
item = client.store.get_item(
    ["documents", "user123"],
    key="item456",
)
print(item)
----------------------------------------------------------------

{
    'namespace': ['documents', 'user123'],
    'key': 'item456',
    'value': {'title': 'My Document', 'content': 'Hello World'},
    'created_at': '2024-07-30T12:00:00Z',
    'updated_at': '2024-07-30T12:00:00Z'
}

delete_item

delete_item(
    namespace: Sequence[str],
    /,
    key: str,
    headers: dict[str, str] | None = None,
) -> None

删除项。

参数

名称 类型 描述 默认值
str

项目的唯一标识符。

必填
namespace Sequence[str]

表示命名空间路径的可选字符串列表。

必填
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
None

None

示例用法
client = get_sync_client(url="https://:8123")
client.store.delete_item(
    ["documents", "user123"],
    key="item456",
)

search_items

search_items(
    namespace_prefix: Sequence[str],
    /,
    filter: dict[str, Any] | None = None,
    limit: int = 10,
    offset: int = 0,
    query: str | None = None,
    refresh_ttl: bool | None = None,
    headers: dict[str, str] | None = None,
) -> SearchItemsResponse

在命名空间前缀内搜索项。

参数

名称 类型 描述 默认值
namespace_prefix Sequence[str]

表示命名空间前缀的字符串列表。

必填
过滤器 dict[str, Any] | None

可选的键值对字典,用于过滤结果。

None
限制 整数

要返回的最大项目数(默认值为 10)。

10
offset 整数

在返回结果之前要跳过的项目数(默认值为 0)。

0
查询 str | None

自然语言搜索的可选查询。

None
refresh_ttl bool | None

是否刷新此搜索返回项目的 TTL。如果为 None,则使用存储的默认行为。

None
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
SearchItemsResponse

list[Item]: 匹配搜索条件的项目列表。

示例用法

client = get_sync_client(url="https://:8123")
items = client.store.search_items(
    ["documents"],
    filter={"author": "John Doe"},
    limit=5,
    offset=0
)
print(items)
----------------------------------------------------------------

{
    "items": [
        {
            "namespace": ["documents", "user123"],
            "key": "item789",
            "value": {
                "title": "Another Document",
                "author": "John Doe"
            },
            "created_at": "2024-07-30T12:00:00Z",
            "updated_at": "2024-07-30T12:00:00Z"
        },
        # ... additional items ...
    ]
}

list_namespaces

list_namespaces(
    prefix: list[str] | None = None,
    suffix: list[str] | None = None,
    max_depth: int | None = None,
    limit: int = 100,
    offset: int = 0,
    headers: dict[str, str] | None = None,
) -> ListNamespaceResponse

列出带可选匹配条件的命名空间。

参数

名称 类型 描述 默认值
prefix list[str] | None

表示命名空间前缀的可选字符串列表,用于过滤命名空间。

None
suffix list[str] | None

表示命名空间后缀的可选字符串列表,用于过滤命名空间。

None
max_depth int | None

可选整数,指定要返回的命名空间的最大深度。

None
限制 整数

要返回的最大命名空间数(默认值为 100)。

100
offset 整数

在返回结果之前要跳过的命名空间数(默认值为 0)。

0
headers dict[str, str] | None

请求中包含的可选自定义头。

None

返回

类型 描述
ListNamespaceResponse

list[list[str]]: 匹配条件的命名空间列表。

示例用法
client = get_sync_client(url="https://:8123")
namespaces = client.store.list_namespaces(
    prefix=["documents"],
    max_depth=3,
    limit=10,
    offset=0
)
print(namespaces)
----------------------------------------------------------------

[
    ["documents", "user123", "reports"],
    ["documents", "user456", "invoices"],
    ...
]

get_client

get_client(
    *,
    url: str | None = None,
    api_key: str | None = None,
    headers: dict[str, str] | None = None,
    timeout: TimeoutTypes | None = None
) -> LangGraphClient

获取 LangGraphClient 实例。

参数

名称 类型 描述 默认值
url str | None

LangGraph API 的 URL。

None
api_key str | None

API 密钥。如果未提供,将从环境中读取。优先级:1. 显式参数 2. LANGGRAPH_API_KEY 3. LANGSMITH_API_KEY 4. LANGCHAIN_API_KEY

None
headers dict[str, str] | None

可选的自定义头部

None
timeout TimeoutTypes | None

HTTP 客户端的可选超时配置。接受 httpx.Timeout 实例、浮点数(秒)或超时元组。元组格式为 (connect, read, write, pool)。如果未提供,默认为 connect=5s, read=300s, write=300s, pool=5s。

None

返回

名称 类型 描述
LangGraphClient LangGraphClient

用于访问 AssistantsClient、

LangGraphClient

ThreadsClient、RunsClient 和 CronClient 的顶级客户端。

示例
from langgraph_sdk import get_client

# get top-level LangGraphClient
client = get_client(url="https://:8123")

# example usage: client.<model>.<method_name>()
assistants = await client.assistants.get(assistant_id="some_uuid")

get_sync_client

get_sync_client(
    *,
    url: str | None = None,
    api_key: str | None = None,
    headers: dict[str, str] | None = None,
    timeout: TimeoutTypes | None = None
) -> SyncLangGraphClient

获取同步 LangGraphClient 实例。

参数

名称 类型 描述 默认值
url str | None

LangGraph API 的 URL。

None
api_key str | None

API 密钥。如果未提供,将从环境中读取。优先级:1. 显式参数 2. LANGGRAPH_API_KEY 3. LANGSMITH_API_KEY 4. LANGCHAIN_API_KEY

None
headers dict[str, str] | None

可选的自定义头部

None
timeout TimeoutTypes | None

HTTP 客户端的可选超时配置。接受 httpx.Timeout 实例、浮点数(秒)或超时元组。元组格式为 (connect, read, write, pool)。如果未提供,默认为 connect=5s, read=300s, write=300s, pool=5s。

None

返回:SyncLangGraphClient:用于访问 AssistantsClient、ThreadsClient、RunsClient 和 CronClient 的顶级同步客户端。

示例
from langgraph_sdk import get_sync_client

# get top-level synchronous LangGraphClient
client = get_sync_client(url="https://:8123")

# example usage: client.<model>.<method_name>()
assistant = client.assistants.get(assistant_id="some_uuid")

用于与 LangGraph API 交互的数据模型。

名称 描述
配置

调用的配置选项。

检查点

表示执行过程中的一个检查点。

GraphSchema

定义图的结构和属性。

AssistantBase

助手的基本模型。

AssistantVersion

表示助手的特定版本。

Assistant

表示具有附加属性的助手。

中断

表示执行流中的中断。

Thread

表示一个对话线程。

ThreadTask

表示线程中的一个任务。

ThreadState

表示线程的状态。

ThreadUpdateStateResponse

表示更新线程状态的响应。

Run

表示单个执行运行。

Cron

表示一个计划任务。

RunCreate

定义启动后台运行的参数。

表示图的存储中的单个文档或数据条目。

ListNamespaceResponse

列出命名空间的响应结构。

SearchItem

搜索操作中具有可选相关性分数项。

SearchItemsResponse

搜索项的响应结构。

StreamPart

表示流响应的一部分。

Send

表示要发送到图中特定节点的消息。

Command

表示一个或多个用于控制图执行流和状态的命令。

RunCreateMetadata

运行创建请求的元数据。

属性

名称 类型 描述
Json

表示一个类似 JSON 的结构,可以是 None 或带有字符串键和任意值的字典。

RunStatus

表示运行的状态

ThreadStatus

表示线程的状态

StreamMode

定义流模式

DisconnectMode

指定断开连接时的行为

MultitaskStrategy

定义如何处理多个任务

OnConflictBehavior

指定冲突时的行为

OnCompletionBehavior

定义完成后的操作

所有

表示通配符或“全部”选择器。

IfNotExists

指定线程不存在时的行为

CancelAction

取消运行时的操作。

AssistantSortBy

要排序的字段。

ThreadSortBy

要排序的字段。

CronSortBy

要排序的字段。

SortOrder

排序顺序。

Json module-attribute

Json = Optional[dict[str, Any]]

表示一个类似 JSON 的结构,可以是 None 或带有字符串键和任意值的字典。

RunStatus module-attribute

RunStatus = Literal[
    "pending",
    "running",
    "error",
    "success",
    "timeout",
    "interrupted",
]

表示运行状态:- "pending":运行正在等待开始。- "running":运行当前正在执行。- "error":运行遇到错误并停止。- "success":运行成功完成。- "timeout":运行超出其时间限制。- "interrupted":运行被手动停止或中断。

ThreadStatus module-attribute

ThreadStatus = Literal[
    "idle", "busy", "interrupted", "error"
]

表示线程状态:- "idle":线程当前未处理任何任务。- "busy":线程正在积极处理任务。- "interrupted":线程的执行被中断。- "error":任务处理期间发生异常。

StreamMode module-attribute

StreamMode = Literal[
    "values",
    "messages",
    "updates",
    "events",
    "tasks",
    "checkpoints",
    "debug",
    "custom",
    "messages-tuple",
]

定义流模式:- "values":仅流式传输值。- "messages":流式传输完整消息。- "updates":流式传输状态更新。- "events":流式传输执行期间发生的事件。- "checkpoints":流式传输创建的检查点。- "tasks":流式传输任务开始和结束事件。- "debug":流式传输详细调试信息。- "custom":流式传输自定义事件。

DisconnectMode module-attribute

DisconnectMode = Literal['cancel', 'continue']

指定断开连接时的行为:- "cancel":断开连接时取消操作。- "continue":即使断开连接也继续操作。

MultitaskStrategy module-attribute

MultitaskStrategy = Literal[
    "reject", "interrupt", "rollback", "enqueue"
]

定义如何处理多个任务:- "reject":繁忙时拒绝新任务。- "interrupt":中断当前任务以处理新任务。- "rollback":回滚当前任务并启动新任务。- "enqueue":将新任务排队等待后续执行。

OnConflictBehavior module-attribute

OnConflictBehavior = Literal['raise', 'do_nothing']

指定冲突时的行为:- "raise":发生冲突时引发异常。- "do_nothing":忽略冲突并继续。

OnCompletionBehavior module-attribute

OnCompletionBehavior = Literal['delete', 'keep']

定义完成后的操作:- "delete":完成后删除资源。- "keep":完成后保留资源。

All module-attribute

All = Literal['*']

表示通配符或“全部”选择器。

IfNotExists module-attribute

IfNotExists = Literal['create', 'reject']

指定线程不存在时的行为:- "create":如果线程不存在则创建新线程。- "reject":如果线程不存在则拒绝操作。

CancelAction module-attribute

CancelAction = Literal['interrupt', 'rollback']

取消运行时的操作。- "interrupt":仅取消运行。- "rollback":取消运行。然后删除运行和关联的检查点。

AssistantSortBy module-attribute

AssistantSortBy = Literal[
    "assistant_id",
    "graph_id",
    "name",
    "created_at",
    "updated_at",
]

要排序的字段。

ThreadSortBy module-attribute

ThreadSortBy = Literal[
    "thread_id", "status", "created_at", "updated_at"
]

要排序的字段。

CronSortBy module-attribute

CronSortBy = Literal[
    "cron_id",
    "assistant_id",
    "thread_id",
    "created_at",
    "updated_at",
    "next_run_date",
]

要排序的字段。

SortOrder module-attribute

SortOrder = Literal['asc', 'desc']

排序顺序。

Config

基础类: TypedDict

调用的配置选项。

属性

名称 类型 描述
tags list[str]

此调用和任何子调用(例如,调用 LLM 的链)的标签。

recursion_limit 整数

调用可以递归的最大次数。如果未提供,默认为 25。

configurable dict[str, Any]

此 Runnable 上先前可配置的属性的运行时值,

tags instance-attribute

tags: list[str]

此调用及任何子调用(例如,链调用 LLM)的标签。您可以使用这些标签来过滤调用。

recursion_limit instance-attribute

recursion_limit: int

调用可以递归的最大次数。如果未提供,默认为 25。

configurable instance-attribute

configurable: dict[str, Any]

通过 .configurable_fields() 或 .configurable_alternatives() 在此 Runnable 或子 Runnable 上先前可配置的属性的运行时值。有关已配置的属性的说明,请查看 .output_schema()。

Checkpoint

基础类: TypedDict

表示执行过程中的一个检查点。

属性

名称 类型 描述
thread_id str

与此检查点关联的线程的唯一标识符。

checkpoint_ns str

检查点的命名空间;内部用于管理子图状态。

checkpoint_id str | None

检查点本身的唯一可选标识符。

checkpoint_map dict[str, Any] | None

包含检查点特定数据的可选字典。

thread_id instance-attribute

thread_id: str

与此检查点关联的线程的唯一标识符。

checkpoint_ns instance-attribute

checkpoint_ns: str

检查点的命名空间;内部用于管理子图状态。

checkpoint_id instance-attribute

checkpoint_id: str | None

检查点本身的唯一可选标识符。

checkpoint_map instance-attribute

checkpoint_map: dict[str, Any] | None

包含检查点特定数据的可选字典。

GraphSchema

基础类: TypedDict

定义图的结构和属性。

属性

名称 类型 描述
graph_id str

图的 ID。

input_schema dict | None

图输入的 schema。

output_schema dict | None

图输出的 schema。

state_schema dict | None

图状态的 schema。

config_schema dict | None

图配置的 schema。

graph_id instance-attribute

graph_id: str

图的 ID。

input_schema instance-attribute

input_schema: dict | None

图输入的 schema。如果无法从图中生成 JSON schema 则缺失。

output_schema instance-attribute

output_schema: dict | None

图输出的 schema。如果无法从图中生成 JSON schema 则缺失。

state_schema instance-attribute

state_schema: dict | None

图状态的 schema。如果无法从图中生成 JSON schema 则缺失。

config_schema instance-attribute

config_schema: dict | None

图配置的 schema。如果无法从图中生成 JSON schema 则缺失。

AssistantBase

基础类: TypedDict

助手的基本模型。

属性

名称 类型 描述
assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

assistant_id instance-attribute

assistant_id: str

助手的 ID。

graph_id instance-attribute

graph_id: str

图的 ID。

config instance-attribute

config: Config

助手配置。

created_at instance-attribute

created_at: datetime

助手创建的时间。

metadata instance-attribute

metadata: Json

助手元数据。

version instance-attribute

version: int

助手的版本

name instance-attribute

name: str

助手的名称

description instance-attribute

description: str | None

助手的描述

AssistantVersion

继承自:AssistantBase

表示助手的特定版本。

属性

名称 类型 描述
assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

assistant_id instance-attribute

assistant_id: str

助手的 ID。

graph_id instance-attribute

graph_id: str

图的 ID。

config instance-attribute

config: Config

助手配置。

created_at instance-attribute

created_at: datetime

助手创建的时间。

metadata instance-attribute

metadata: Json

助手元数据。

version instance-attribute

version: int

助手的版本

name instance-attribute

name: str

助手的名称

description instance-attribute

description: str | None

助手的描述

Assistant

继承自:AssistantBase

表示具有附加属性的助手。

属性

名称 类型 描述
updated_at datetime

助手最后一次更新的时间。

assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

updated_at instance-attribute

updated_at: datetime

助手最后一次更新的时间。

assistant_id instance-attribute

assistant_id: str

助手的 ID。

graph_id instance-attribute

graph_id: str

图的 ID。

config instance-attribute

config: Config

助手配置。

created_at instance-attribute

created_at: datetime

助手创建的时间。

metadata instance-attribute

metadata: Json

助手元数据。

version instance-attribute

version: int

助手的版本

name instance-attribute

name: str

助手的名称

description instance-attribute

description: str | None

助手的描述

Interrupt

基础类: TypedDict

表示执行流中的中断。

属性

名称 类型 描述
Any

与中断关联的值。

when Literal['during']

中断发生的时间。

resumable bool

中断是否可以恢复。

ns list[str] | None

中断的可选命名空间。

value instance-attribute

value: Any

与中断关联的值。

when instance-attribute

when: Literal['during']

中断发生的时间。

resumable instance-attribute

resumable: bool

中断是否可以恢复。

ns instance-attribute

ns: list[str] | None

中断的可选命名空间。

Thread

基础类: TypedDict

表示一个对话线程。

属性

名称 类型 描述
thread_id str

线程的 ID。

创建时间 datetime

线程创建的时间。

updated_at datetime

线程最后一次更新的时间。

metadata Json

线程元数据。

status ThreadStatus

线程状态,'idle'、'busy'、'interrupted' 之一。

values Json

线程的当前状态。

interrupts dict[str, list[Interrupt]]

在此线程中抛出的中断

thread_id instance-attribute

thread_id: str

线程的 ID。

created_at instance-attribute

created_at: datetime

线程创建的时间。

updated_at instance-attribute

updated_at: datetime

线程最后一次更新的时间。

metadata instance-attribute

metadata: Json

线程元数据。

status instance-attribute

status: ThreadStatus

线程状态,'idle'、'busy'、'interrupted' 之一。

values instance-attribute

values: Json

线程的当前状态。

interrupts instance-attribute

interrupts: dict[str, list[Interrupt]]

在此线程中抛出的中断

ThreadTask

基础类: TypedDict

表示线程中的一个任务。

ThreadState

基础类: TypedDict

表示线程的状态。

属性

名称 类型 描述
values list[dict] | dict[str, Any]

状态值。

下一个 Sequence[str]

要执行的下一个节点。如果为空,则线程完成,直到有新的输入。

checkpoint 检查点

检查点的 ID。

metadata Json

此状态的元数据

创建时间 str | None

状态创建的时间戳

parent_checkpoint Checkpoint | None

父检查点的 ID。如果缺失,则表示这是根检查点。

tasks Sequence[ThreadTask]

此步骤中要执行的任务。如果已尝试,可能包含错误。

values instance-attribute

values: list[dict] | dict[str, Any]

状态值。

next instance-attribute

next: Sequence[str]

要执行的下一个节点。如果为空,则线程在收到新输入之前完成。

checkpoint instance-attribute

checkpoint: Checkpoint

检查点的 ID。

metadata instance-attribute

metadata: Json

此状态的元数据

created_at instance-attribute

created_at: str | None

状态创建的时间戳

parent_checkpoint instance-attribute

parent_checkpoint: Checkpoint | None

父检查点的 ID。如果缺失,则表示这是根检查点。

tasks instance-attribute

此步骤中要执行的任务。如果已尝试,可能包含错误。

ThreadUpdateStateResponse

基础类: TypedDict

表示更新线程状态的响应。

属性

名称 类型 描述
checkpoint 检查点

最新状态的检查点。

checkpoint instance-attribute

checkpoint: Checkpoint

最新状态的检查点。

Run

基础类: TypedDict

表示单个执行运行。

属性

名称 类型 描述
run_id str

运行的 ID。

thread_id str

线程的 ID。

assistant_id str

此运行使用的助手。

创建时间 datetime

运行创建的时间。

updated_at datetime

运行最后一次更新的时间。

status RunStatus

运行状态。'pending'、'running'、"error"、'success'、"timeout"、"interrupted" 之一。

metadata Json

运行元数据。

multitask_strategy MultitaskStrategy

处理同一线程上并发运行的策略。

run_id instance-attribute

run_id: str

运行的 ID。

thread_id instance-attribute

thread_id: str

线程的 ID。

assistant_id instance-attribute

assistant_id: str

此运行使用的助手。

created_at instance-attribute

created_at: datetime

运行创建的时间。

updated_at instance-attribute

updated_at: datetime

运行最后一次更新的时间。

status instance-attribute

status: RunStatus

运行状态。'pending'、'running'、"error"、'success'、"timeout"、"interrupted" 之一。

metadata instance-attribute

metadata: Json

运行元数据。

multitask_strategy instance-attribute

multitask_strategy: MultitaskStrategy

处理同一线程上并发运行的策略。

Cron

基础类: TypedDict

表示一个计划任务。

属性

名称 类型 描述
cron_id str

Cron 的 ID。

assistant_id str

助手的 ID。

thread_id str | None

线程的 ID。

end_time datetime | None

停止运行 cron 的结束日期。

schedule str

要运行的计划,cron 格式。

创建时间 datetime

cron 创建的时间。

updated_at datetime

cron 最后一次更新的时间。

payload dict

用于创建新运行的运行载荷。

user_id str | None

cron 的用户 ID。

next_run_date datetime | None

cron 的下一次运行日期。

metadata dict

cron 的元数据。

cron_id instance-attribute

cron_id: str

Cron 的 ID。

assistant_id instance-attribute

assistant_id: str

助手的 ID。

thread_id instance-attribute

thread_id: str | None

线程的 ID。

end_time instance-attribute

end_time: datetime | None

停止运行 cron 的结束日期。

schedule instance-attribute

schedule: str

要运行的计划,cron 格式。

created_at instance-attribute

created_at: datetime

cron 创建的时间。

updated_at instance-attribute

updated_at: datetime

cron 最后一次更新的时间。

payload instance-attribute

payload: dict

用于创建新运行的运行载荷。

user_id instance-attribute

user_id: str | None

cron 的用户 ID。

next_run_date instance-attribute

next_run_date: datetime | None

cron 的下一次运行日期。

metadata instance-attribute

metadata: dict

cron 的元数据。

RunCreate

基础类: TypedDict

定义启动后台运行的参数。

属性

名称 类型 描述
thread_id str | None

要运行的线程标识符。如果未提供,则运行是无状态的。

assistant_id str

此运行要使用的助手的标识符。

input dict | None

运行的初始输入数据。

metadata dict | None

与运行关联的附加元数据。

config Config | None

运行的配置选项。

checkpoint_id str | None

要从其恢复的检查点的标识符。

interrupt_before list[str] | None

中断执行前要停止的节点名称列表。

interrupt_after list[str] | None

中断执行后要停止的节点名称列表。

webhook str | None

发送有关运行进度的 webhook 通知 URL。

multitask_strategy MultitaskStrategy | None

处理同一线程上并发运行的策略。

thread_id instance-attribute

thread_id: str | None

要运行的线程标识符。如果未提供,则运行是无状态的。

assistant_id instance-attribute

assistant_id: str

此运行要使用的助手的标识符。

input instance-attribute

input: dict | None

运行的初始输入数据。

metadata instance-attribute

metadata: dict | None

与运行关联的附加元数据。

config instance-attribute

config: Config | None

运行的配置选项。

checkpoint_id instance-attribute

checkpoint_id: str | None

要从其恢复的检查点的标识符。

interrupt_before instance-attribute

interrupt_before: list[str] | None

中断执行前要停止的节点名称列表。

interrupt_after instance-attribute

interrupt_after: list[str] | None

中断执行后要停止的节点名称列表。

webhook instance-attribute

webhook: str | None

发送有关运行进度的 webhook 通知 URL。

multitask_strategy instance-attribute

multitask_strategy: MultitaskStrategy | None

处理同一线程上并发运行的策略。

Item

基础类: TypedDict

表示图的存储中的单个文档或数据条目。

项目用于存储跨线程的记忆。

属性

名称 类型 描述
namespace list[str]

项目的命名空间。命名空间类似于文档的目录。

str

项目在其命名空间内的唯一标识符。

dict[str, Any]

项目中存储的值。这是文档本身。

创建时间 datetime

项目创建时的时间戳。

updated_at datetime

项目最后一次更新时的时间戳。

namespace instance-attribute

namespace: list[str]

项目的命名空间。命名空间类似于文档的目录。

key instance-attribute

key: str

项目在其命名空间内的唯一标识符。

通常,键不需要是全局唯一的。

value instance-attribute

value: dict[str, Any]

项目中存储的值。这是文档本身。

created_at instance-attribute

created_at: datetime

项目创建时的时间戳。

updated_at instance-attribute

updated_at: datetime

项目最后一次更新时的时间戳。

ListNamespaceResponse

基础类: TypedDict

列出命名空间的响应结构。

属性

名称 类型 描述
namespaces list[list[str]]

命名空间路径列表,其中每个路径都是字符串列表。

namespaces instance-attribute

namespaces: list[list[str]]

命名空间路径列表,其中每个路径都是字符串列表。

SearchItem

继承自:Item

搜索操作中具有可选相关性分数项。

属性

名称 类型 描述
score Optional[float]

相关性/相似性得分。在兼容存储中使用自然语言查询进行搜索时包含此项。

namespace instance-attribute

namespace: list[str]

项目的命名空间。命名空间类似于文档的目录。

key instance-attribute

key: str

项目在其命名空间内的唯一标识符。

通常,键不需要是全局唯一的。

value instance-attribute

value: dict[str, Any]

项目中存储的值。这是文档本身。

created_at instance-attribute

created_at: datetime

项目创建时的时间戳。

updated_at instance-attribute

updated_at: datetime

项目最后一次更新时的时间戳。

SearchItemsResponse

基础类: TypedDict

搜索项的响应结构。

属性

名称 类型 描述
items list[SearchItem]

匹配搜索条件的项目列表。

items instance-attribute

items: list[SearchItem]

匹配搜索条件的项目列表。

StreamPart

基类:NamedTuple

表示流响应的一部分。

属性

名称 类型 描述
event str

此流部分的事件类型。

data dict

与事件关联的数据负载。

event instance-attribute

event: str

此流部分的事件类型。

data instance-attribute

data: dict

与事件关联的数据负载。

Send

基础类: TypedDict

表示要发送到图中特定节点的消息。

此类型用于明确向图中的节点发送消息,通常在 Command 对象中使用以控制图执行流。

属性

名称 类型 描述
node str

要发送消息的目标节点的名称。

input dict[str, Any] | None

包含要传递给节点的输入数据的可选字典。

node instance-attribute

node: str

要发送消息的目标节点的名称。

input instance-attribute

input: dict[str, Any] | None

包含要传递给节点的输入数据的可选字典。

如果为 None,则节点将不带输入调用。

Command

基础类: TypedDict

表示一个或多个用于控制图执行流和状态的命令。

此类型定义了节点可以返回的控制命令,以影响图执行。它允许您导航到其他节点、更新图状态并从中断中恢复。

属性

名称 类型 描述
goto Send | str | Sequence[Send | str]

指定执行应在何处继续。可以是

更新 dict[str, Any] | Sequence[tuple[str, Any]]

应用于图状态的更新。可以是

resume Any

中断后恢复执行的值。

goto instance-attribute

goto: Send | str | Sequence[Send | str]

指定执行应在何处继续。可以是

  • 要导航到的字符串节点名称
  • 一个 Send 对象,用于执行带有特定输入的节点
  • 要按顺序执行的节点名称或 Send 对象的序列

update instance-attribute

update: dict[str, Any] | Sequence[tuple[str, Any]]

应用于图状态的更新。可以是

  • 要合并的状态更新字典
  • 用于有序更新的 (key, value) 元组序列

resume instance-attribute

resume: Any

中断后恢复执行的值。与 interrupt() 结合使用以实现控制流。

RunCreateMetadata

基础类: TypedDict

运行创建请求的元数据。

属性

名称 类型 描述
run_id str

运行的 ID。

thread_id str | None

线程的 ID。

run_id instance-attribute

run_id: str

运行的 ID。

thread_id instance-attribute

thread_id: str | None

线程的 ID。

模块

名称 描述
exceptions

身份验证系统中使用的异常。

types

LangGraph 的身份验证和授权类型。

名称 描述
Auth

为您的 LangGraph 应用程序添加自定义身份验证和授权管理。

Auth

为您的 LangGraph 应用程序添加自定义身份验证和授权管理。

Auth 类提供了一个统一的系统,用于处理 LangGraph 应用程序中的身份验证和授权。它支持自定义用户身份验证协议以及针对不同资源和操作的细粒度授权规则。

要使用,请创建一个单独的 python 文件,并将该文件的路径添加到您的 LangGraph API 配置文件 (langgraph.json) 中。在该文件中,创建一个 Auth 类的实例,并根据需要注册身份验证和授权处理程序。

langgraph.json 文件示例

{
  "dependencies": ["."],
  "graphs": {
    "agent": "./my_agent/agent.py:graph"
  },
  "env": ".env",
  "auth": {
    "path": "./auth.py:my_auth"
  }

然后 LangGraph 服务器将加载您的身份验证文件,并在每次请求到来时在服务器端运行它。

基本用法
from langgraph_sdk import Auth

my_auth = Auth()

async def verify_token(token: str) -> str:
    # Verify token and return user_id
    # This would typically be a call to your auth server
    return "user_id"

@auth.authenticate
async def authenticate(authorization: str) -> str:
    # Verify token and return user_id
    result = await verify_token(authorization)
    if result != "user_id":
        raise Auth.exceptions.HTTPException(
            status_code=401, detail="Unauthorized"
        )
    return result

# Global fallback handler
@auth.on
async def authorize_default(params: Auth.on.value):
    return False # Reject all requests (default behavior)

@auth.on.threads.create
async def authorize_thread_create(params: Auth.on.threads.create.value):
    # Allow the allowed user to create a thread
    assert params.get("metadata", {}).get("owner") == "allowed_user"

@auth.on.store
async def authorize_store(ctx: Auth.types.AuthContext, value: Auth.types.on):
    assert ctx.user.identity in value["namespace"], "Not authorized"
请求处理流程
  1. 身份验证(您的 @auth.authenticate 处理程序)首先在每个请求上执行
  2. 对于授权,调用最具体的匹配处理程序
    • 如果存在针对确切资源和操作的处理程序,则使用该处理程序(例如,@auth.on.threads.create
    • 否则,如果存在针对资源的任何操作的处理程序,则使用该处理程序(例如,@auth.on.threads
    • 最后,如果没有特定的处理程序匹配,则使用全局处理程序(例如,@auth.on
    • 如果未设置全局处理程序,则接受请求

这允许您使用全局处理程序设置默认行为,同时根据需要覆盖特定路由。

方法

名称 描述
authenticate

注册一个身份验证处理程序函数。

属性

名称 类型 描述
types

引用身份验证类型定义。

exceptions

引用身份验证异常定义。

on

授权处理程序的入口点,用于控制对特定资源的访问。

types class-attribute instance-attribute

types = types

引用身份验证类型定义。

提供对身份验证系统中使用的所有类型定义的访问,例如 ThreadsCreate、AssistantsRead 等。

exceptions class-attribute instance-attribute

exceptions = exceptions

引用身份验证异常定义。

提供对身份验证系统中使用的所有异常定义的访问,例如 HTTPException 等。

on instance-attribute

on = _On(self)

授权处理程序的入口点,用于控制对特定资源的访问。

on 类提供了一种灵活的方式来定义应用程序中不同资源和操作的授权规则。它支持三种主要用法模式

  1. 适用于所有资源和操作的全局处理程序
  2. 适用于资源上所有操作的资源特定处理程序
  3. 用于细粒度控制的资源和操作特定处理程序
每个处理程序必须是接受两个参数的异步函数
  • ctx (AuthContext):包含请求上下文和已认证的用户信息
  • value:正在授权的数据(类型因端点而异)

处理程序应返回其中之一

- None or True: Accept the request
- False: Reject with 403 error
- FilterType: Apply filtering rules to the response
示例

所有请求的全局处理程序

@auth.on
async def reject_unhandled_requests(ctx: AuthContext, value: Any) -> None:
    print(f"Request to {ctx.path} by {ctx.user.identity}")
    return False

资源特定处理程序。这将在 threads 资源上的所有操作中优先于全局处理程序

@auth.on.threads
async def check_thread_access(ctx: AuthContext, value: Any) -> bool:
    # Allow access only to threads created by the user
    return value.get("created_by") == ctx.user.identity

资源和操作特定处理程序

@auth.on.threads.delete
async def prevent_thread_deletion(ctx: AuthContext, value: Any) -> bool:
    # Only admins can delete threads
    return "admin" in ctx.user.permissions

多个资源或操作

@auth.on(resources=["threads", "runs"], actions=["create", "update"])
async def rate_limit_writes(ctx: AuthContext, value: Any) -> bool:
    # Implement rate limiting for write operations
    return await check_rate_limit(ctx.user.identity)

store 资源的身份验证有点不同,因为它的结构由开发人员定义。您通常希望在命名空间中强制执行用户凭据。您

@auth.on.store
async def check_store_access(ctx: AuthContext, value: Auth.types.on) -> bool:
    # Assuming you structure your store like (store.aput((user_id, application_context), key, value))
    assert value["namespace"][0] == ctx.user.identity

authenticate

authenticate(fn: AH) -> AH

注册一个身份验证处理程序函数。

身份验证处理程序负责验证凭据并返回用户范围。它可以通过名称接受以下任何参数

- request (Request): The raw ASGI request object
- body (dict): The parsed request body
- path (str): The request path, e.g., "/threads/abcd-1234-abcd-1234/runs/abcd-1234-abcd-1234/stream"
- method (str): The HTTP method, e.g., "GET"
- path_params (dict[str, str]): URL path parameters, e.g., {"thread_id": "abcd-1234-abcd-1234", "run_id": "abcd-1234-abcd-1234"}
- query_params (dict[str, str]): URL query parameters, e.g., {"stream": "true"}
- headers (dict[bytes, bytes]): Request headers
- authorization (str | None): The Authorization header value (e.g., "Bearer <token>")

参数

名称 类型 描述 默认值
fn AH

要注册的身份验证处理程序函数。必须返回用户的表示。这可以是:- 字符串(用户 ID)- 包含 {"identity": str, "permissions": list[str]} 的字典 - 或具有身份和权限属性的对象 权限可由您的下游处理程序选择性使用。

必填

返回

类型 描述
AH

已注册的处理程序函数。

抛出

类型 描述
ValueError

如果已注册身份验证处理程序。

示例

基本令牌身份验证

@auth.authenticate
async def authenticate(authorization: str) -> str:
    user_id = verify_token(authorization)
    return user_id

接受完整的请求上下文

@auth.authenticate
async def authenticate(
    method: str,
    path: str,
    headers: dict[str, bytes]
) -> str:
    user = await verify_request(method, path, headers)
    return user

返回用户名和权限

@auth.authenticate
async def authenticate(
    method: str,
    path: str,
    headers: dict[str, bytes]
) -> Auth.types.MinimalUserDict:
    permissions, user = await verify_request(method, path, headers)
    # Permissions could be things like ["runs:read", "runs:write", "threads:read", "threads:write"]
    return {
        "identity": user["id"],
        "permissions": permissions,
        "display_name": user["name"],
    }

LangGraph 的身份验证和授权类型。

此模块定义了 LangGraph 中用于身份验证、授权和请求处理的核心类型。它包括用户协议、身份验证上下文以及各种 API 操作的类型化字典。

注意

所有 typing.TypedDict 类都使用 total=False,使所有字段默认为 typing.Optional。

名称 描述
ThreadsCreate

用于创建新线程的参数。

ThreadsRead

用于读取线程状态或运行信息的参数。

ThreadsUpdate

用于更新线程或运行的参数。

ThreadsDelete

用于删除线程的参数。

ThreadsSearch

用于搜索线程的参数。

RunsCreate

创建运行的有效载荷。

AssistantsCreate

创建助手的有效载荷。

AssistantsRead

读取助手的有效载荷。

AssistantsUpdate

更新助手的有效载荷。

AssistantsDelete

删除助手的有效载荷。

AssistantsSearch

搜索助手的有效载荷。

StoreGet

按命名空间和键检索特定项的操作。

StoreSearch

在指定命名空间层次结构中搜索项的操作。

StoreListNamespaces

列出和过滤存储中命名空间的操作。

StorePut

在存储中存储、更新或删除项的操作。

StoreDelete

从存储中删除项的操作。

on

不同 API 操作的类型定义命名空间。

属性

名称 类型 描述
MetadataInput

附加到实体任意元数据的类型。

RunStatus module-attribute

RunStatus = Literal[
    "pending", "error", "success", "timeout", "interrupted"
]

运行执行的状态。

  • pending:运行已排队或正在进行中
  • error:运行失败并出现错误
  • success:运行成功完成
  • timeout:运行超出时间限制
  • interrupted:运行被手动中断

MultitaskStrategy module-attribute

MultitaskStrategy = Literal[
    "reject", "rollback", "interrupt", "enqueue"
]

处理多个并发任务的策略。

  • reject:当一个任务正在进行时拒绝新任务
  • rollback:取消当前任务并开始新任务
  • interrupt:中断当前任务并开始新任务
  • enqueue:将新任务排队,在当前任务之后运行

OnConflictBehavior module-attribute

OnConflictBehavior = Literal['raise', 'do_nothing']

遇到冲突时的行为。

  • raise:冲突时引发异常
  • do_nothing:静默忽略冲突

IfNotExists module-attribute

IfNotExists = Literal['create', 'reject']

实体不存在时的行为。

  • create:创建实体
  • reject:拒绝操作

FilterType module-attribute

FilterType = Union[
    dict[
        str,
        Union[str, dict[Literal["$eq", "$contains"], str]],
    ],
    dict[str, str],
]

授权处理程序的响应类型。

支持精确匹配和运算符
  • 精确匹配简写:{"field": "value"}
  • 精确匹配:{"field": {"$eq": "value"}}
  • 包含:{"field": {"$contains": "value"}}
示例

资源所有者的简单精确匹配过滤器

filter = {"owner": "user-abcd123"}

精确匹配过滤器的显式版本

filter = {"owner": {"$eq": "user-abcd123"}}

包含

filter = {"participants": {"$contains": "user-abcd123"}}

组合过滤器(视为逻辑 AND

filter = {"owner": "user-abcd123", "participants": {"$contains": "user-efgh456"}}

ThreadStatus module-attribute

ThreadStatus = Literal[
    "idle", "busy", "interrupted", "error"
]

线程的状态。

  • idle:线程可用于工作
  • busy:线程当前正在处理
  • interrupted:线程被中断
  • error:线程遇到错误

MetadataInput module-attribute

MetadataInput = dict[str, Any]

附加到实体任意元数据的类型。

允许与任何实体存储自定义键值对。键必须是字符串,值可以是任何 JSON 可序列化类型。

示例
metadata = {
    "created_by": "user123",
    "priority": 1,
    "tags": ["important", "urgent"]
}

HandlerResult module-attribute

HandlerResult = Union[None, bool, FilterType]

处理程序的结果可以是:* None | True:接受请求。* False:以 403 错误拒绝请求。* FilterType:要应用的过滤器

Authenticator module-attribute

Authenticator = Callable[
    ...,
    Awaitable[
        Union[
            MinimalUser,
            str,
            BaseUser,
            MinimalUserDict,
            Mapping[str, Any],
        ],
    ],
]

认证函数的类型。

认证器可以返回以下之一:1. 一个字符串 (user_id) 2. 一个包含 {"identity": str, "permissions": list[str]} 的字典 3. 一个具有 identity 和 permissions 属性的对象

权限可以由您的授权逻辑在下游使用,以确定对不同资源的访问权限。

如果您的函数签名中包含以下任何参数,`authenticate` 装饰器将自动按名称注入它们

参数

名称 类型 描述 默认值
请求 请求

原始 ASGI 请求对象

必填
请求体 dict

解析后的请求体

必填
路径 str

请求路径

必填
方法 str

HTTP 方法 (GET, POST 等)

必填
路径参数 dict[str, str] | None

URL 路径参数

必填
查询参数 dict[str, str] | None

URL 查询参数

必填
headers dict[str, bytes] | None

请求头

必填
授权 str | None

Authorization 头部值 (例如 "Bearer"")

必填
示例

带令牌的基本认证

from langgraph_sdk import Auth

auth = Auth()

@auth.authenticate
async def authenticate1(authorization: str) -> Auth.types.MinimalUserDict:
    return await get_user(authorization)

多参数认证

@auth.authenticate
async def authenticate2(
    method: str,
    path: str,
    headers: dict[str, bytes]
) -> Auth.types.MinimalUserDict:
    # Custom auth logic using method, path and headers
    user = verify_request(method, path, headers)
    return user

接受原始 ASGI 请求

MY_SECRET = "my-secret-key"
@auth.authenticate
async def get_current_user(request: Request) -> Auth.types.MinimalUserDict:
    try:
        token = (request.headers.get("authorization") or "").split(" ", 1)[1]
        payload = jwt.decode(token, MY_SECRET, algorithms=["HS256"])
    except (IndexError, InvalidTokenError):
        raise HTTPException(
            status_code=401,
            detail="Invalid token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://api.myauth-provider.com/auth/v1/user",
            headers={"Authorization": f"Bearer {MY_SECRET}"}
        )
        if response.status_code != 200:
            raise HTTPException(status_code=401, detail="User not found")

        user_data = response.json()
        return {
            "identity": user_data["id"],
            "display_name": user_data.get("name"),
            "permissions": user_data.get("permissions", []),
            "is_authenticated": True,
        }

MinimalUser

基类: Protocol

用户对象必须至少暴露 identity 属性。

属性

名称 类型 描述
身份标识 str

用户的唯一标识符。

identity property

identity: str

用户的唯一标识符。

这可以是一个用户名、电子邮件或任何其他用于区分系统中不同用户的唯一标识符。

MinimalUserDict

基础类: TypedDict

用户的字典表示。

属性

名称 类型 描述
身份标识 Required[str]

用户的必需唯一标识符。

显示名称 str

用户的可选显示名称。

已认证 bool

用户是否已认证。默认为 True。

权限 Sequence[str]

与用户关联的权限列表。

identity instance-attribute

identity: Required[str]

用户的必需唯一标识符。

display_name instance-attribute

display_name: str

用户的可选显示名称。

is_authenticated instance-attribute

is_authenticated: bool

用户是否已认证。默认为 True。

permissions instance-attribute

permissions: Sequence[str]

与用户关联的权限列表。

您可以在您的 @auth.on 授权逻辑中使用这些来确定对不同资源的访问权限。

BaseUser

基类: Protocol

基础 ASGI 用户协议

方法

名称 描述
__getitem__

从您的最小用户字典中获取一个键。

__contains__

检查属性是否存在。

__iter__

迭代用户的键。

属性

名称 类型 描述
已认证 bool

用户是否已认证。

显示名称 str

用户的显示名称。

身份标识 str

用户的唯一标识符。

权限 Sequence[str]

与用户关联的权限。

is_authenticated property

is_authenticated: bool

用户是否已认证。

display_name property

display_name: str

用户的显示名称。

identity property

identity: str

用户的唯一标识符。

permissions property

permissions: Sequence[str]

与用户关联的权限。

__getitem__

__getitem__(key)

从您的最小用户字典中获取一个键。

__contains__

__contains__(key)

检查属性是否存在。

__iter__

__iter__()

迭代用户的键。

StudioUser

一个用户对象,通过 LangGraph studio 的认证请求填充。

注意:Studio 认证可以在您的 langgraph.json 配置中禁用。

{
  "auth": {
    "disable_studio_auth": true
  }
}

您可以在授权处理程序 (@auth.on) 中使用 isinstance 检查,以专门控制从 LangGraph Studio UI 访问实例的开发人员的访问权限。

示例
@auth.on
async def allow_developers(ctx: Auth.types.AuthContext, value: Any) -> None:
    if isinstance(ctx.user, Auth.types.StudioUser):
        return None
    ...
    return False

BaseAuthContext

认证上下文的基类。

提供授权决策所需的基本认证信息。

属性

名称 类型 描述
权限 Sequence[str]

授予已认证用户的权限。

用户 BaseUser

已认证用户。

permissions instance-attribute

permissions: Sequence[str]

授予已认证用户的权限。

user instance-attribute

user: BaseUser

已认证用户。

AuthContext

基类: BaseAuthContext

包含资源和操作信息的完整认证上下文。

扩展 BaseAuthContext,包含正在访问的特定资源和操作,从而实现细粒度访问控制决策。

属性

名称 类型 描述
资源 Literal['runs', 'threads', 'crons', 'assistants', 'store']

正在访问的资源。

action Literal['create', 'read', 'update', 'delete', 'search', 'create_run', 'put', 'get', 'list_namespaces']

对资源执行的操作。

权限 Sequence[str]

授予已认证用户的权限。

用户 BaseUser

已认证用户。

resource instance-attribute

resource: Literal[
    "runs", "threads", "crons", "assistants", "store"
]

正在访问的资源。

action instance-attribute

action: Literal[
    "create",
    "read",
    "update",
    "delete",
    "search",
    "create_run",
    "put",
    "get",
    "list_namespaces",
]

对资源执行的操作。

大多数资源支持以下操作:- create: 创建新资源 - read: 读取资源信息 - update: 更新现有资源 - delete: 删除资源 - search: 搜索资源

存储支持以下操作:- put: 在存储中添加或更新文档 - get: 从存储中获取文档 - list_namespaces: 列出存储中的命名空间

permissions instance-attribute

permissions: Sequence[str]

授予已认证用户的权限。

user instance-attribute

user: BaseUser

已认证用户。

ThreadsCreate

基础类: TypedDict

用于创建新线程的参数。

示例
create_params = {
    "thread_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "metadata": {"owner": "user123"},
    "if_exists": "do_nothing"
}

属性

名称 类型 描述
thread_id UUID

线程的唯一标识符。

metadata MetadataInput

可选的附加到线程的元数据。

if_exists OnConflictBehavior

当具有相同 ID 的线程已存在时的行为。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

可选的附加到线程的元数据。

if_exists instance-attribute

if_exists: OnConflictBehavior

当具有相同 ID 的线程已存在时的行为。

ThreadsRead

基础类: TypedDict

用于读取线程状态或运行信息的参数。

此类型用于三种上下文:1. 读取线程、线程版本或线程状态信息:仅提供 `thread_id` 2. 读取运行信息:同时提供 `thread_id` 和 `run_id`

属性

名称 类型 描述
thread_id UUID

线程的唯一标识符。

run_id UUID | None

用于过滤的运行 ID。仅在读取线程内的运行信息时使用。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

run_id instance-attribute

run_id: UUID | None

用于过滤的运行 ID。仅在读取线程内的运行信息时使用。

ThreadsUpdate

基础类: TypedDict

用于更新线程或运行的参数。

用于更新线程、线程版本或取消运行。

属性

名称 类型 描述
thread_id UUID

线程的唯一标识符。

metadata MetadataInput

可选的要更新的元数据。

action Literal['interrupt', 'rollback'] | None

可选的对线程执行的操作。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

可选的要更新的元数据。

action instance-attribute

action: Literal['interrupt', 'rollback'] | None

可选的对线程执行的操作。

ThreadsDelete

基础类: TypedDict

用于删除线程的参数。

用于删除线程、线程版本或运行

属性

名称 类型 描述
thread_id UUID

线程的唯一标识符。

run_id UUID | None

可选的用于过滤的运行 ID。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

run_id instance-attribute

run_id: UUID | None

可选的用于过滤的运行 ID。

ThreadsSearch

基础类: TypedDict

用于搜索线程的参数。

用于搜索线程或运行。

属性

名称 类型 描述
metadata MetadataInput

可选的用于过滤的元数据。

values MetadataInput

可选的用于过滤的值。

status ThreadStatus | None

可选的用于过滤的状态。

限制 整数

返回结果的最大数量。

offset 整数

分页偏移量。

thread_id UUID | None

可选的用于过滤的线程 ID。

metadata instance-attribute

metadata: MetadataInput

可选的用于过滤的元数据。

values instance-attribute

values: MetadataInput

可选的用于过滤的值。

status instance-attribute

status: ThreadStatus | None

可选的用于过滤的状态。

limit instance-attribute

limit: int

返回结果的最大数量。

offset instance-attribute

offset: int

分页偏移量。

thread_id instance-attribute

thread_id: UUID | None

可选的用于过滤的线程 ID。

RunsCreate

基础类: TypedDict

创建运行的有效载荷。

示例
create_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
    "run_id": UUID("123e4567-e89b-12d3-a456-426614174002"),
    "status": "pending",
    "metadata": {"owner": "user123"},
    "prevent_insert_if_inflight": True,
    "multitask_strategy": "reject",
    "if_not_exists": "create",
    "after_seconds": 10,
    "kwargs": {"key": "value"},
    "action": "interrupt"
}

属性

名称 类型 描述
assistant_id UUID | None

此运行要使用的可选助手 ID。

thread_id UUID | None

此运行要使用的可选线程 ID。

run_id UUID | None

此运行要使用的可选运行 ID。

status RunStatus | None

此运行的可选状态。

metadata MetadataInput

此运行的可选元数据。

防止在运行中插入 bool

如果已有运行正在进行,则阻止插入新运行。

multitask_strategy MultitaskStrategy

此运行的多任务策略。

if_not_exists IfNotExists

此运行的 IfNotExists。

after_seconds 整数

在创建运行前等待的秒数。

关键字参数 dict[str, Any]

传递给运行的关键字参数。

action Literal['interrupt', 'rollback'] | None

如果更新现有运行,要采取的操作。

assistant_id instance-attribute

assistant_id: UUID | None

此运行要使用的可选助手 ID。

thread_id instance-attribute

thread_id: UUID | None

此运行要使用的可选线程 ID。

run_id instance-attribute

run_id: UUID | None

此运行要使用的可选运行 ID。

status instance-attribute

status: RunStatus | None

此运行的可选状态。

metadata instance-attribute

metadata: MetadataInput

此运行的可选元数据。

prevent_insert_if_inflight instance-attribute

prevent_insert_if_inflight: bool

如果已有运行正在进行,则阻止插入新运行。

multitask_strategy instance-attribute

multitask_strategy: MultitaskStrategy

此运行的多任务策略。

if_not_exists instance-attribute

if_not_exists: IfNotExists

此运行的 IfNotExists。

after_seconds instance-attribute

after_seconds: int

在创建运行前等待的秒数。

kwargs instance-attribute

kwargs: dict[str, Any]

传递给运行的关键字参数。

action instance-attribute

action: Literal['interrupt', 'rollback'] | None

如果更新现有运行,要采取的操作。

AssistantsCreate

基础类: TypedDict

创建助手的有效载荷。

示例
create_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "graph_id": "graph123",
    "config": {"key": "value"},
    "metadata": {"owner": "user123"},
    "if_exists": "do_nothing",
    "name": "Assistant 1"
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

graph_id str

此助手要使用的图 ID。

config dict[str, Any] | Any | None

助手的可选配置。

metadata MetadataInput

可选的附加到助手的元数据。

if_exists OnConflictBehavior

当具有相同 ID 的助手已存在时的行为。

name str

助手的名称。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

graph_id instance-attribute

graph_id: str

此助手要使用的图 ID。

config instance-attribute

config: dict[str, Any] | Any | None

助手的可选配置。

metadata instance-attribute

metadata: MetadataInput

可选的附加到助手的元数据。

if_exists instance-attribute

if_exists: OnConflictBehavior

当具有相同 ID 的助手已存在时的行为。

name instance-attribute

name: str

助手的名称。

AssistantsRead

基础类: TypedDict

读取助手的有效载荷。

示例
read_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "metadata": {"owner": "user123"}
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

metadata MetadataInput

可选的用于过滤的元数据。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

可选的用于过滤的元数据。

AssistantsUpdate

基础类: TypedDict

更新助手的有效载荷。

示例
update_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "graph_id": "graph123",
    "config": {"key": "value"},
    "metadata": {"owner": "user123"},
    "name": "Assistant 1",
    "version": 1
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

graph_id str | None

可选的要更新的图 ID。

config dict[str, Any] | Any | None

可选的要更新的配置。

metadata MetadataInput

可选的要更新的元数据。

name str | None

可选的要更新的名称。

version int | None

可选的要更新的版本。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

graph_id instance-attribute

graph_id: str | None

可选的要更新的图 ID。

config instance-attribute

config: dict[str, Any] | Any | None

可选的要更新的配置。

metadata instance-attribute

metadata: MetadataInput

可选的要更新的元数据。

name instance-attribute

name: str | None

可选的要更新的名称。

version instance-attribute

version: int | None

可选的要更新的版本。

AssistantsDelete

基础类: TypedDict

删除助手的有效载荷。

示例
delete_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000")
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

AssistantsSearch

基础类: TypedDict

搜索助手的有效载荷。

示例
search_params = {
    "graph_id": "graph123",
    "metadata": {"owner": "user123"},
    "limit": 10,
    "offset": 0
}

属性

名称 类型 描述
graph_id str | None

可选的用于过滤的图 ID。

metadata MetadataInput

可选的用于过滤的元数据。

限制 整数

返回结果的最大数量。

offset 整数

分页偏移量。

graph_id instance-attribute

graph_id: str | None

可选的用于过滤的图 ID。

metadata instance-attribute

metadata: MetadataInput

可选的用于过滤的元数据。

limit instance-attribute

limit: int

返回结果的最大数量。

offset instance-attribute

offset: int

分页偏移量。

CronsCreate

基础类: TypedDict

用于创建 cron 作业的有效负载。

示例
create_params = {
    "payload": {"key": "value"},
    "schedule": "0 0 * * *",
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
    "user_id": "user123",
    "end_time": datetime(2024, 3, 16, 10, 0, 0)
}

属性

名称 类型 描述
payload dict[str, Any]

cron 作业的有效负载。

schedule str

cron 作业的计划。

cron_id UUID | None

cron 作业的可选唯一标识符。

thread_id UUID | None

此 cron 作业要使用的可选线程 ID。

user_id str | None

此 cron 作业要使用的可选用户 ID。

end_time datetime | None

cron 作业的可选结束时间。

payload instance-attribute

payload: dict[str, Any]

cron 作业的有效负载。

schedule instance-attribute

schedule: str

cron 作业的计划。

cron_id instance-attribute

cron_id: UUID | None

cron 作业的可选唯一标识符。

thread_id instance-attribute

thread_id: UUID | None

此 cron 作业要使用的可选线程 ID。

user_id instance-attribute

user_id: str | None

此 cron 作业要使用的可选用户 ID。

end_time instance-attribute

end_time: datetime | None

cron 作业的可选结束时间。

CronsDelete

基础类: TypedDict

用于删除 cron 作业的有效负载。

示例
delete_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
}

属性

名称 类型 描述
cron_id UUID

cron 作业的唯一标识符。

cron_id instance-attribute

cron_id: UUID

cron 作业的唯一标识符。

CronsRead

基础类: TypedDict

用于读取 cron 作业的有效负载。

示例
read_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
}

属性

名称 类型 描述
cron_id UUID

cron 作业的唯一标识符。

cron_id instance-attribute

cron_id: UUID

cron 作业的唯一标识符。

CronsUpdate

基础类: TypedDict

用于更新 cron 作业的有效负载。

示例
update_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "payload": {"key": "value"},
    "schedule": "0 0 * * *"
}

属性

名称 类型 描述
cron_id UUID

cron 作业的唯一标识符。

payload dict[str, Any] | None

可选的要更新的有效负载。

schedule str | None

可选的要更新的计划。

cron_id instance-attribute

cron_id: UUID

cron 作业的唯一标识符。

payload instance-attribute

payload: dict[str, Any] | None

可选的要更新的有效负载。

schedule instance-attribute

schedule: str | None

可选的要更新的计划。

CronsSearch

基础类: TypedDict

用于搜索 cron 作业的有效负载。

示例
search_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
    "limit": 10,
    "offset": 0
}

属性

名称 类型 描述
assistant_id UUID | None

可选的用于过滤的助手 ID。

thread_id UUID | None

可选的用于过滤的线程 ID。

限制 整数

返回结果的最大数量。

offset 整数

分页偏移量。

assistant_id instance-attribute

assistant_id: UUID | None

可选的用于过滤的助手 ID。

thread_id instance-attribute

thread_id: UUID | None

可选的用于过滤的线程 ID。

limit instance-attribute

limit: int

返回结果的最大数量。

offset instance-attribute

offset: int

分页偏移量。

StoreGet

基础类: TypedDict

按命名空间和键检索特定项的操作。

属性

名称 类型 描述
namespace tuple[str, ...]

唯一标识项目位置的层次路径。

str

项目在其特定命名空间内的唯一标识符。

namespace instance-attribute

namespace: tuple[str, ...]

唯一标识项目位置的层次路径。

key instance-attribute

key: str

项目在其特定命名空间内的唯一标识符。

StoreSearch

基础类: TypedDict

在指定命名空间层次结构中搜索项的操作。

属性

名称 类型 描述
namespace tuple[str, ...]

用于定义搜索范围的前缀过滤器。

过滤器 dict[str, Any] | None

用于根据精确匹配或比较运算符过滤结果的键值对。

限制 整数

搜索结果中返回的最大项目数。

offset 整数

分页时跳过的匹配项目数。

查询 str | None

用于语义搜索功能的自然语言搜索查询。

namespace instance-attribute

namespace: tuple[str, ...]

用于定义搜索范围的前缀过滤器。

filter instance-attribute

filter: dict[str, Any] | None

用于根据精确匹配或比较运算符过滤结果的键值对。

limit instance-attribute

limit: int

搜索结果中返回的最大项目数。

offset instance-attribute

offset: int

分页时跳过的匹配项目数。

query instance-attribute

query: str | None

用于语义搜索功能的自然语言搜索查询。

StoreListNamespaces

基础类: TypedDict

列出和过滤存储中命名空间的操作。

属性

名称 类型 描述
namespace tuple[str, ...] | None

前缀过滤命名空间。

suffix tuple[str, ...] | None

过滤命名空间的可选条件。

max_depth int | None

返回命名空间层次结构的最大深度。

限制 整数

返回的最大命名空间数量。

offset 整数

分页时跳过的命名空间数量。

namespace instance-attribute

namespace: tuple[str, ...] | None

前缀过滤命名空间。

suffix instance-attribute

suffix: tuple[str, ...] | None

过滤命名空间的可选条件。

max_depth instance-attribute

max_depth: int | None

返回命名空间层次结构的最大深度。

注意

深度超过此级别的命名空间将被截断。

limit instance-attribute

limit: int

返回的最大命名空间数量。

offset instance-attribute

offset: int

分页时跳过的命名空间数量。

StorePut

基础类: TypedDict

在存储中存储、更新或删除项的操作。

属性

名称 类型 描述
namespace tuple[str, ...]

标识项目位置的层次路径。

str

项目在其命名空间内的唯一标识符。

dict[str, Any] | None

要存储的数据,或 None 表示要删除的项目。

index Literal[False] | list[str] | None

用于全文搜索的可选索引配置。

namespace instance-attribute

namespace: tuple[str, ...]

标识项目位置的层次路径。

key instance-attribute

key: str

项目在其命名空间内的唯一标识符。

value instance-attribute

value: dict[str, Any] | None

要存储的数据,或 None 表示要删除的项目。

index instance-attribute

index: Literal[False] | list[str] | None

用于全文搜索的可选索引配置。

StoreDelete

基础类: TypedDict

从存储中删除项的操作。

属性

名称 类型 描述
namespace tuple[str, ...]

唯一标识项目位置的层次路径。

str

项目在其特定命名空间内的唯一标识符。

namespace instance-attribute

namespace: tuple[str, ...]

唯一标识项目位置的层次路径。

key instance-attribute

key: str

项目在其特定命名空间内的唯一标识符。

on

不同 API 操作的类型定义命名空间。

此类组织了不同资源(线程、助手、cron 作业)的创建、读取、更新、删除和搜索操作的类型定义。

用量
from langgraph_sdk import Auth

auth = Auth()

@auth.on
def handle_all(params: Auth.on.value):
    raise Exception("Not authorized")

@auth.on.threads.create
def handle_thread_create(params: Auth.on.threads.create.value):
    # Handle thread creation
    pass

@auth.on.assistants.search
def handle_assistant_search(params: Auth.on.assistants.search.value):
    # Handle assistant search
    pass

名称 描述
threads

线程相关操作的类型。

assistants

助手相关操作的类型。

crons

Cron 作业相关操作的类型。

store

存储相关操作的类型。

threads

线程相关操作的类型。

名称 描述
create

线程创建参数的类型。

创建运行

用于创建或流式传输运行的类型。

读取

线程读取参数的类型。

更新

线程更新参数的类型。

delete

线程删除参数的类型。

search

线程搜索参数的类型。

create

线程创建参数的类型。

create_run

用于创建或流式传输运行的类型。

read

线程读取参数的类型。

update

线程更新参数的类型。

delete

线程删除参数的类型。

search

线程搜索参数的类型。

assistants

助手相关操作的类型。

名称 描述
create

助手创建参数的类型。

读取

助手读取参数的类型。

更新

助手更新参数的类型。

delete

助手删除参数的类型。

search

助手搜索参数的类型。

create

助手创建参数的类型。

read

助手读取参数的类型。

update

助手更新参数的类型。

delete

助手删除参数的类型。

search

助手搜索参数的类型。

crons

Cron 作业相关操作的类型。

名称 描述
create

Cron 创建参数的类型。

读取

Cron 读取参数的类型。

更新

Cron 更新参数的类型。

delete

Cron 删除参数的类型。

search

Cron 搜索参数的类型。

create

Cron 创建参数的类型。

read

Cron 读取参数的类型。

update

Cron 更新参数的类型。

delete

Cron 删除参数的类型。

search

Cron 搜索参数的类型。

store

存储相关操作的类型。

名称 描述
放置

存储放入参数的类型。

获取

存储获取参数的类型。

search

存储搜索参数的类型。

delete

存储删除参数的类型。

list_namespaces

存储列出命名空间参数的类型。

put

存储放入参数的类型。

get

存储获取参数的类型。

search

存储搜索参数的类型。

delete

存储删除参数的类型。

list_namespaces

存储列出命名空间参数的类型。

身份验证系统中使用的异常。

名称 描述
HTTP异常

您可以抛出的 HTTP 异常,用于返回特定的 HTTP 错误响应。

HTTPException

基类: Exception

您可以抛出的 HTTP 异常,用于返回特定的 HTTP 错误响应。

由于此异常在 auth 模块中定义,我们默认状态码为 401。

参数

名称 类型 描述 默认值
状态码 整数

错误的 HTTP 状态码。默认为 401 "未授权"。

401
详细信息 str | None

详细错误消息。如果为 None,则根据状态码使用默认消息。

None
headers Mapping[str, str] | None

错误响应中包含的额外 HTTP 头部。

None
示例

默认值

raise HTTPException()
# HTTPException(status_code=401, detail='Unauthorized')

添加头部

raise HTTPException(headers={"X-Custom-Header": "Custom Value"})
# HTTPException(status_code=401, detail='Unauthorized', headers={"WWW-Authenticate": "Bearer"})

自定义错误

raise HTTPException(status_code=404, detail="Not found")