跳到内容

Python SDK 参考

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

该模块提供异步 (get_client(url="https://:2024"))LangGraphClient) 和同步 (get_sync_client(url="https://:2024"))SyncLanggraphClient) 客户端,用于与 LangGraph API 的核心资源(如 Assistants、Threads、Runs 和 Cron 作业)以及其持久化文档存储(Store)进行交互。

名称 描述
LangGraphClient

LangGraph API 的顶级客户端。

HttpClient

处理对 LangGraph API 的异步请求。

AssistantsClient

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

ThreadsClient

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

RunsClient

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

CronClient

用于在 LangGraph 中管理周期性运行(cron 作业)的客户端。

StoreClient

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

SyncLangGraphClient

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

SyncHttpClient

处理对 LangGraph API 的同步请求。

SyncAssistantsClient

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

SyncThreadsClient

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

SyncRunsClient

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

SyncCronClient

用于在 LangGraph 中同步管理 cron 作业的客户端。

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 中管理助手的客户端。

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

示例
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']
                        }
                }
        },
    'context_schema':
        {
            'title': 'Context',
            '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,
    *,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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 服务器版本 >=0.0.45。

None

返回

名称 类型 描述
Assistant Assistant

创建的助手。

用法示例
client = get_client(url="https://:2024")
assistant = await client.assistants.create(
    graph_id="agent",
    context={"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,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

None
metadata Json

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

None
name str | None

助手的新名称。

None
headers dict[str, str] | None

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

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api 服务器版本 >=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",
    context={"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 中管理线程的客户端。

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

示例
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

在创建线程时应用一系列超步骤(superstep),每个超步骤包含一系列更新。每个更新都有 `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 中管理运行的客户端。

运行(run)是一次助手的调用,可以带有可选的输入、配置、上下文和元数据。此客户端管理运行,运行可以是有状态的(在线程上)或无状态的。

示例
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,
    context: Context | 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

要执行的命令。不能与 input 一起使用。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否从子图中流式传输输出。

False
stream_resumable bool

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

False
metadata dict | None

分配给运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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"},
    context={"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,
    context: Context | 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

要执行的命令。不能与 input 一起使用。

None
stream_mode StreamMode | Sequence[StreamMode]

要使用的流模式。

'values'
stream_subgraphs bool

是否从子图中流式传输输出。

False
stream_resumable bool

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

False
metadata dict | None

分配给运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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"},
    context={"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,
                            'assistant_id': 'my_assistant_id'
                        },
                },
            'context':
                {
                    'model_name': 'openai'
                }
            '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,
    context: Context | 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

要执行的命令。不能与 input 一起使用。

None
metadata dict | None

分配给运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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"},
    context={"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 中管理周期性运行(cron 作业)的客户端。

运行是助手的单次调用,可以带有可选的输入、配置和上下文。此客户端允许调度周期性运行以自动发生。

用法示例
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"}
)

功能可用性

crons 客户端功能并非在所有许可证上都受支持。请查看相关许可证文档,以获取有关功能可用性的最新详细信息。

方法

名称 描述
create_for_thread

为线程创建 cron 作业。

create

创建一个 cron 运行。

delete

删除一个 cron。

search

获取 cron 作业列表。

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,
    context: Context | 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

为线程创建 cron 作业。

参数

名称 类型 描述 默认值
thread_id str

要在其上运行 cron 作业的线程 ID。

必填
assistant_id str

用于 cron 作业的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此作业的 cron 计划。

必填
input dict | None

图的输入。

None
metadata dict | None

分配给 cron 作业运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

cron 运行。

用法示例
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"},
    context={"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,
    context: Context | 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

创建一个 cron 运行。

参数

名称 类型 描述 默认值
assistant_id str

用于 cron 作业的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此作业的 cron 计划。

必填
input dict | None

图的输入。

None
metadata dict | None

分配给 cron 作业运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

cron 运行。

用法示例
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"},
    context={"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。

参数

名称 类型 描述 默认值
cron_id str

要删除的 cron 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]

获取 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]:搜索返回的 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 端点的同步访问,用于管理助手、线程、运行、cron 作业和数据存储。

示例
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 中同步管理助手的客户端。

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

示例
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': {},
    'context': {},
    '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'
                        }
                }
        },
    'context_schema':
        {
            'title': 'Context',
            '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,
    *,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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 服务器版本 >=0.0.45。

None

返回

名称 类型 描述
Assistant Assistant

创建的助手。

用法示例
client = get_sync_client(url="https://:2024")
assistant = client.assistants.create(
    graph_id="agent",
    context={"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,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

None
metadata Json

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

None
name str | None

助手的新名称。

None
headers dict[str, str] | None

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

None
description str | None

助手的可选描述。description 字段适用于 langgraph-api 服务器版本 >=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",
    context={"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

在创建线程时应用一系列超步骤(superstep),每个超步骤包含一系列更新。每个更新都有 `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,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

返回

类型 描述
迭代器[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"},
    context={"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,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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"},
    context={"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,
                            'assistant_id': 'my_assistant_id'
                        }
                },
            'context':
                {
                    'model_name': 'openai'
                },
            '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,
    context: Context | 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
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

返回

类型 描述
列表[字典] | 字典[字符串, 任意]

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"},
    context={"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

返回

类型 描述
列表[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

返回

类型 描述
迭代器[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 中同步管理 cron 作业的客户端。

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

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

功能可用性

crons 客户端功能并非在所有许可证上都受支持。请查看相关许可证文档,以获取有关功能可用性的最新详细信息。

方法

名称 描述
create_for_thread

为线程创建 cron 作业。

create

创建一个 cron 运行。

delete

删除一个 cron。

search

获取 cron 作业列表。

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,
    context: Context | 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

为线程创建 cron 作业。

参数

名称 类型 描述 默认值
thread_id str

要在其上运行 cron 作业的线程 ID。

必填
assistant_id str

用于 cron 作业的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此作业的 cron 计划。

必填
input dict | None

图的输入。

None
metadata dict | None

分配给 cron 作业运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

cron 运行。

用法示例
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"},
    context={"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,
    context: Context | 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

创建一个 cron 运行。

参数

名称 类型 描述 默认值
assistant_id str

用于 cron 作业的助手 ID 或图名称。如果使用图名称,将默认为从该图创建的第一个助手。

必填
schedule str

执行此作业的 cron 计划。

必填
input dict | None

图的输入。

None
metadata dict | None

分配给 cron 作业运行的元数据。

None
config Config | None

助手的配置。

None
context Context | None

要添加到助手的静态上下文。

langgraph>=0.6.0 版本支持

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

cron 运行。

用法示例
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"},
    context={"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。

参数

名称 类型 描述 默认值
cron_id str

要删除的 cron 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]

获取 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]:搜索返回的 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 超时类型 | 无

HTTP 客户端的可选超时配置。接受 httpx.Timeout 实例、浮点数(秒)或超时元组。元组格式为 (connect, read, write, pool) 如果未提供,则默认为 connect=5s, read=300s, write=300s, and 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 超时类型 | 无

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

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

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

ListNamespaceResponse

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

SearchItem

来自搜索操作的带有可选相关性分数的项目。

SearchItemsResponse

用于搜索项目的响应结构。

StreamPart

表示流响应的一部分。

Send

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

Command

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

RunCreateMetadata

运行创建请求的元数据。

属性

名称 类型 描述
Json

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

RunStatus

表示运行的状态

ThreadStatus

表示线程的状态

StreamMode

定义流媒体模式

DisconnectMode

指定断开连接时的行为

MultitaskStrategy

定义如何处理多个任务

OnConflictBehavior

指定冲突时的行为

OnCompletionBehavior

定义完成后的操作

所有

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

IfNotExists

指定如果线程不存在时的行为

CancelAction

取消运行时要采取的操作。

AssistantSortBy

用于排序的字段。

ThreadSortBy

用于排序的字段。

CronSortBy

用于排序的字段。

SortOrder

排序的顺序。

Json 模块属性

Json = Optional[dict[str, Any]]

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

RunStatus 模块属性

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

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

ThreadStatus 模块属性

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

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

StreamMode 模块属性

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

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

DisconnectMode 模块属性

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

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

MultitaskStrategy 模块属性

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

定义如何处理多个任务: - “reject”:当繁忙时拒绝新任务。 - “interrupt”:为新任务中断当前任务。 - “rollback”:回滚当前任务并开始新任务。 - “enqueue”:将新任务排队以供稍后执行。

OnConflictBehavior 模块属性

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

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

OnCompletionBehavior 模块属性

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

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

All 模块属性

All = Literal['*']

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

IfNotExists 模块属性

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

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

CancelAction 模块属性

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

取消运行时要采取的操作。- “interrupt”:仅取消运行。- “rollback”:取消运行。然后删除运行和相关的检查点。

AssistantSortBy 模块属性

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

用于排序的字段。

ThreadSortBy 模块属性

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

用于排序的字段。

CronSortBy 模块属性

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

用于排序的字段。

SortOrder 模块属性

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

排序的顺序。

Config

基础类: TypedDict

调用的配置选项。

属性

名称 类型 描述
tags 列表[字符串]

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

recursion_limit 整数

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

configurable dict[str, Any]

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

tags 实例属性

tags: list[str]

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

recursion_limit 实例属性

recursion_limit: int

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

configurable 实例属性

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 实例属性

thread_id: str

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

checkpoint_ns 实例属性

checkpoint_ns: str

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

checkpoint_id 实例属性

checkpoint_id: str | None

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

checkpoint_map 实例属性

checkpoint_map: dict[str, Any] | None

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

GraphSchema

基础类: TypedDict

定义图的结构和属性。

属性

名称 类型 描述
graph_id str

图的 ID。

input_schema dict | None

图输入的模式。

output_schema dict | None

图输出的模式。

state_schema dict | None

图状态的模式。

config_schema dict | None

图配置的模式。

context_schema dict | None

图上下文的模式。

graph_id 实例属性

graph_id: str

图的 ID。

input_schema 实例属性

input_schema: dict | None

图输入的模式。如果无法从图生成 JSON 模式,则缺失。

output_schema 实例属性

output_schema: dict | None

图输出的模式。如果无法从图生成 JSON 模式,则缺失。

state_schema 实例属性

state_schema: dict | None

图状态的模式。如果无法从图生成 JSON 模式,则缺失。

config_schema 实例属性

config_schema: dict | None

图配置的模式。如果无法从图生成 JSON 模式,则缺失。

context_schema 实例属性

context_schema: dict | None

图上下文的模式。如果无法从图生成 JSON 模式,则缺失。

AssistantBase

基础类: TypedDict

助手的基本模型。

属性

名称 类型 描述
assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

context 上下文

助手的静态上下文。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

assistant_id 实例属性

assistant_id: str

助手的 ID。

graph_id 实例属性

graph_id: str

图的 ID。

config 实例属性

config: Config

助手配置。

context 实例属性

context: Context

助手的静态上下文。

created_at 实例属性

created_at: datetime

助手创建的时间。

metadata 实例属性

metadata: Json

助手元数据。

version 实例属性

version: int

助手的版本

name 实例属性

name: str

助手的名称

description 实例属性

description: str | None

助手的描述

AssistantVersion

基类:AssistantBase

表示助手的特定版本。

属性

名称 类型 描述
assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

context 上下文

助手的静态上下文。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

assistant_id 实例属性

assistant_id: str

助手的 ID。

graph_id 实例属性

graph_id: str

图的 ID。

config 实例属性

config: Config

助手配置。

context 实例属性

context: Context

助手的静态上下文。

created_at 实例属性

created_at: datetime

助手创建的时间。

metadata 实例属性

metadata: Json

助手元数据。

version 实例属性

version: int

助手的版本

name 实例属性

name: str

助手的名称

description 实例属性

description: str | None

助手的描述

Assistant

基类:AssistantBase

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

属性

名称 类型 描述
updated_at datetime

助手上次更新的时间。

assistant_id str

助手的 ID。

graph_id str

图的 ID。

config 配置

助手配置。

context 上下文

助手的静态上下文。

创建时间 datetime

助手创建的时间。

metadata Json

助手元数据。

version 整数

助手的版本

name str

助手的名称

description str | None

助手的描述

updated_at 实例属性

updated_at: datetime

助手上次更新的时间。

assistant_id 实例属性

assistant_id: str

助手的 ID。

graph_id 实例属性

graph_id: str

图的 ID。

config 实例属性

config: Config

助手配置。

context 实例属性

context: Context

助手的静态上下文。

created_at 实例属性

created_at: datetime

助手创建的时间。

metadata 实例属性

metadata: Json

助手元数据。

version 实例属性

version: int

助手的版本

name 实例属性

name: str

助手的名称

description 实例属性

description: str | None

助手的描述

Interrupt

基础类: TypedDict

表示执行流中的中断。

属性

名称 类型 描述
任何

与中断关联的值。

id str

中断的 ID。可用于恢复中断。

value 实例属性

value: Any

与中断关联的值。

id 实例属性

id: str

中断的 ID。可用于恢复中断。

Thread

基础类: TypedDict

表示一个对话线程。

属性

名称 类型 描述
thread_id str

线程的 ID。

创建时间 datetime

线程创建的时间。

updated_at datetime

线程上次更新的时间。

metadata Json

线程元数据。

status ThreadStatus

线程的状态,可以是“idle”、“busy”、“interrupted”之一。

values Json

线程的当前状态。

interrupts 字典[字符串, 列表[Interrupt]]

任务 ID 到在该任务中引发的中断的映射。

thread_id 实例属性

thread_id: str

线程的 ID。

created_at 实例属性

created_at: datetime

线程创建的时间。

updated_at 实例属性

updated_at: datetime

线程上次更新的时间。

metadata 实例属性

metadata: Json

线程元数据。

status 实例属性

status: ThreadStatus

线程的状态,可以是“idle”、“busy”、“interrupted”之一。

values 实例属性

values: Json

线程的当前状态。

interrupts 实例属性

interrupts: dict[str, list[Interrupt]]

任务 ID 到在该任务中引发的中断的映射。

ThreadTask

基础类: TypedDict

表示线程中的一个任务。

ThreadState

基础类: TypedDict

表示线程的状态。

属性

名称 类型 描述
values 列表[字典] | 字典[字符串, 任意]

状态值。

下一个 Sequence[str]

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

checkpoint 检查点

检查点的 ID。

metadata Json

此状态的元数据

创建时间 str | None

状态创建的时间戳

parent_checkpoint Checkpoint | None

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

tasks 序列[ThreadTask]

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

interrupts 列表[Interrupt]

在此线程中抛出的中断。

values 实例属性

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

状态值。

next 实例属性

next: Sequence[str]

接下来要执行的节点。如果为空,则线程完成,直到接收到新输入。

checkpoint 实例属性

checkpoint: Checkpoint

检查点的 ID。

metadata 实例属性

metadata: Json

此状态的元数据

created_at 实例属性

created_at: str | None

状态创建的时间戳

parent_checkpoint 实例属性

parent_checkpoint: Checkpoint | None

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

tasks 实例属性

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

interrupts 实例属性

interrupts: list[Interrupt]

在此线程中抛出的中断。

ThreadUpdateStateResponse

基础类: TypedDict

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

属性

名称 类型 描述
checkpoint 检查点

最新状态的检查点。

checkpoint 实例属性

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 实例属性

run_id: str

运行的 ID。

thread_id 实例属性

thread_id: str

线程的 ID。

assistant_id 实例属性

assistant_id: str

用于此运行的助手。

created_at 实例属性

created_at: datetime

运行创建的时间。

updated_at 实例属性

updated_at: datetime

运行上次更新的时间。

status 实例属性

status: RunStatus

运行的状态。可以是“pending”、“running”、“error”、“success”、“timeout”、“interrupted”之一。

metadata 实例属性

metadata: Json

运行元数据。

multitask_strategy 实例属性

multitask_strategy: MultitaskStrategy

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

Cron

基础类: TypedDict

表示一个计划任务。

属性

名称 类型 描述
cron_id str

cron 的 ID。

assistant_id str

助手的 ID。

thread_id str | None

线程的 ID。

end_time 日期时间 | 无

停止运行 cron 的结束日期。

schedule str

运行的计划,cron 格式。

创建时间 datetime

cron 创建的时间。

updated_at datetime

cron 上次更新的时间。

payload dict

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

user_id str | None

cron 的用户 ID。

next_run_date 日期时间 | 无

cron 的下一次运行日期。

metadata dict

cron 的元数据。

cron_id 实例属性

cron_id: str

cron 的 ID。

assistant_id 实例属性

assistant_id: str

助手的 ID。

thread_id 实例属性

thread_id: str | None

线程的 ID。

end_time 实例属性

end_time: datetime | None

停止运行 cron 的结束日期。

schedule 实例属性

schedule: str

运行的计划,cron 格式。

created_at 实例属性

created_at: datetime

cron 创建的时间。

updated_at 实例属性

updated_at: datetime

cron 上次更新的时间。

payload 实例属性

payload: dict

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

user_id 实例属性

user_id: str | None

cron 的用户 ID。

next_run_date 实例属性

next_run_date: datetime | None

cron 的下一次运行日期。

metadata 实例属性

metadata: dict

cron 的元数据。

RunCreate

基础类: TypedDict

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

属性

名称 类型 描述
thread_id str | None

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

assistant_id str

用于此运行的助手的标识符。

input dict | None

运行的初始输入数据。

metadata dict | None

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

config Config | None

运行的配置选项。

context Context | 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 实例属性

thread_id: str | None

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

assistant_id 实例属性

assistant_id: str

用于此运行的助手的标识符。

input 实例属性

input: dict | None

运行的初始输入数据。

metadata 实例属性

metadata: dict | None

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

config 实例属性

config: Config | None

运行的配置选项。

context 实例属性

context: Context | None

运行的静态上下文。

checkpoint_id 实例属性

checkpoint_id: str | None

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

interrupt_before 实例属性

interrupt_before: list[str] | None

在执行前中断的节点名称列表。

interrupt_after 实例属性

interrupt_after: list[str] | None

在执行后中断的节点名称列表。

webhook 实例属性

webhook: str | None

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

multitask_strategy 实例属性

multitask_strategy: MultitaskStrategy | None

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

Item

基础类: TypedDict

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

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

属性

名称 类型 描述
namespace 列表[字符串]

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

str

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

dict[str, Any]

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

创建时间 datetime

项目创建时的时间戳。

updated_at datetime

项目上次更新时的时间戳。

namespace 实例属性

namespace: list[str]

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

key 实例属性

key: str

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

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

value 实例属性

value: dict[str, Any]

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

created_at 实例属性

created_at: datetime

项目创建时的时间戳。

updated_at 实例属性

updated_at: datetime

项目上次更新时的时间戳。

ListNamespaceResponse

基础类: TypedDict

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

属性

名称 类型 描述
namespaces 列表[列表[字符串]]

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

namespaces 实例属性

namespaces: list[list[str]]

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

SearchItem

基类:Item

来自搜索操作的带有可选相关性分数的项目。

属性

名称 类型 描述
score 可选[浮点数]

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

namespace 实例属性

namespace: list[str]

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

key 实例属性

key: str

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

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

value 实例属性

value: dict[str, Any]

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

created_at 实例属性

created_at: datetime

项目创建时的时间戳。

updated_at 实例属性

updated_at: datetime

项目上次更新时的时间戳。

SearchItemsResponse

基础类: TypedDict

用于搜索项目的响应结构。

属性

名称 类型 描述
items 列表[SearchItem]

一个匹配搜索条件的项列表。

items 实例属性

items: list[SearchItem]

一个匹配搜索条件的项列表。

StreamPart

基类:NamedTuple

表示流响应的一部分。

属性

名称 类型 描述
event str

此流部分的事件类型。

data dict

与事件关联的数据负载。

event 实例属性

event: str

此流部分的事件类型。

data 实例属性

data: dict

与事件关联的数据负载。

Send

基础类: TypedDict

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

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

属性

名称 类型 描述
node str

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

input dict[str, Any] | None

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

node 实例属性

node: str

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

input 实例属性

input: dict[str, Any] | None

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

如果为 None,则将以无输入的方式调用该节点。

Command

基础类: TypedDict

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

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

属性

名称 类型 描述
goto Send | 字符串 | 序列[Send | 字符串]

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

更新 字典[字符串, 任意] | 序列[元组[字符串, 任意]]

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

resume 任何

中断后用于恢复执行的值。

goto 实例属性

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

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

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

update 实例属性

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

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

  • 要合并的状态更新字典
  • 一个用于有序更新的(键,值)元组序列

resume 实例属性

resume: Any

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

RunCreateMetadata

基础类: TypedDict

运行创建请求的元数据。

属性

名称 类型 描述
run_id str

运行的 ID。

thread_id str | None

线程的 ID。

run_id 实例属性

run_id: str

运行的 ID。

thread_id 实例属性

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 类属性 实例属性

types = types

引用认证类型定义。

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

exceptions 类属性 实例属性

exceptions = exceptions

引用认证异常定义。

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

on 实例属性

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]} 的字典 - 或具有 identity 和 permissions 属性的对象 权限可以由您的下游处理程序选择性使用。

必填

返回

类型 描述
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 模块属性

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

运行执行的状态。

  • pending: 运行已排队或正在进行中
  • error: 运行因错误而失败
  • success: 运行成功完成
  • timeout: 运行超出时间限制
  • 已中断:运行被人为中断

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` 装饰器将按名称自动注入它们

参数

名称 类型 描述 默认值
request Request

原始 ASGI 请求对象

必填
body dict

已解析的请求体

必填
path str

请求路径

必填
method str

HTTP 方法(GET, POST 等)

必填
path_params dict[str, str] | None

URL 路径参数

必填
query_params dict[str, str] | None

URL 查询参数

必填
headers dict[str, bytes] | None

请求头

必填
authorization 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

Bases: Protocol

用户对象必须至少暴露 identity 属性。

属性

名称 类型 描述
identity str

用户的唯一标识符。

identity property

identity: str

用户的唯一标识符。

这可以是用户名、电子邮件或用于区分系统中不同用户的任何其他唯一标识符。

MinimalUserDict

基础类: TypedDict

用户的字典表示。

属性

名称 类型 描述
identity Required[str]

用户的必需唯一标识符。

display_name str

用户的 typing.Optional 显示名称。

is_authenticated bool

用户是否已通过身份验证。默认为 True。

permissions Sequence[str]

与用户关联的权限列表。

identity instance-attribute

identity: Required[str]

用户的必需唯一标识符。

display_name instance-attribute

display_name: str

用户的 typing.Optional 显示名称。

is_authenticated instance-attribute

is_authenticated: bool

用户是否已通过身份验证。默认为 True。

permissions instance-attribute

permissions: Sequence[str]

与用户关联的权限列表。

您可以在 @auth.on 授权逻辑中使用这些来确定对不同资源的访问权限。

BaseUser

Bases: Protocol

基础 ASGI 用户协议

方法

名称 描述
__getitem__

从您的最小用户字典中获取一个键。

__contains__

检查属性是否存在。

__iter__

迭代用户的键。

属性

名称 类型 描述
is_authenticated bool

用户是否已通过身份验证。

display_name str

用户的显示名称。

identity str

用户的唯一标识符。

permissions 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 发出的已验证请求中填充的用户对象。

注意:可以在您的 `langgraph.json` 配置中禁用 Studio 身份验证。

{
  "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

身份验证上下文的基类。

提供授权决策所需的基本身份验证信息。

属性

名称 类型 描述
permissions Sequence[str]

授予已验证用户的权限。

user BaseUser

已通过身份验证的用户。

permissions instance-attribute

permissions: Sequence[str]

授予已验证用户的权限。

user instance-attribute

user: BaseUser

已通过身份验证的用户。

AuthContext

Bases: BaseAuthContext

包含资源和操作信息的完整身份验证上下文。

通过指定正在访问的特定资源和操作来扩展 BaseAuthContext,从而实现细粒度的访问控制决策。

属性

名称 类型 描述
resource Literal['runs', 'threads', 'crons', 'assistants', 'store']

正在访问的资源。

action Literal['create', 'read', 'update', 'delete', 'search', 'create_run', 'put', 'get', 'list_namespaces']

正在对资源执行的操作。

permissions Sequence[str]

授予已验证用户的权限。

user 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

typing.Optional 附加到线程的元数据。

if_exists OnConflictBehavior

当具有相同 ID 的线程已存在时的行为。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 附加到线程的元数据。

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

typing.Optional 要更新的元数据。

action Literal['interrupt', 'rollback'] | None

typing.Optional 要在线程上执行的操作。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 要更新的元数据。

action instance-attribute

action: Literal['interrupt', 'rollback'] | None

typing.Optional 要在线程上执行的操作。

ThreadsDelete

基础类: TypedDict

删除线程的参数。

用于删除线程、线程版本或运行

属性

名称 类型 描述
thread_id UUID

线程的唯一标识符。

run_id UUID | None

typing.Optional 用于筛选的运行 ID。

thread_id instance-attribute

thread_id: UUID

线程的唯一标识符。

run_id instance-attribute

run_id: UUID | None

typing.Optional 用于筛选的运行 ID。

ThreadsSearch

基础类: TypedDict

用于搜索线程的参数。

用于搜索线程或运行。

属性

名称 类型 描述
metadata MetadataInput

typing.Optional 用于筛选的元数据。

values MetadataInput

typing.Optional 用于筛选的值。

status ThreadStatus | None

typing.Optional 用于筛选的状态。

限制 整数

返回结果的最大数量。

offset 整数

用于分页的偏移量。

thread_id UUID | None

typing.Optional 用于筛选的线程 ID。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 用于筛选的元数据。

values instance-attribute

values: MetadataInput

typing.Optional 用于筛选的值。

status instance-attribute

status: ThreadStatus | None

typing.Optional 用于筛选的状态。

limit instance-attribute

limit: int

返回结果的最大数量。

offset instance-attribute

offset: int

用于分页的偏移量。

thread_id instance-attribute

thread_id: UUID | None

typing.Optional 用于筛选的线程 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

typing.Optional 用于此运行的助手 ID。

thread_id UUID | None

typing.Optional 用于此运行的线程 ID。

run_id UUID | None

typing.Optional 用于此运行的运行 ID。

status RunStatus | None

typing.Optional 此运行的状态。

metadata MetadataInput

typing.Optional 运行的元数据。

prevent_insert_if_inflight bool

如果已有运行正在进行,则阻止插入新运行。

multitask_strategy MultitaskStrategy

此运行的多任务策略。

if_not_exists IfNotExists

此运行的 IfNotExists。

after_seconds 整数

创建运行前等待的秒数。

kwargs dict[str, Any]

传递给运行的关键字参数。

action Literal['interrupt', 'rollback'] | None

更新现有运行时要执行的操作。

assistant_id instance-attribute

assistant_id: UUID | None

typing.Optional 用于此运行的助手 ID。

thread_id instance-attribute

thread_id: UUID | None

typing.Optional 用于此运行的线程 ID。

run_id instance-attribute

run_id: UUID | None

typing.Optional 用于此运行的运行 ID。

status instance-attribute

status: RunStatus | None

typing.Optional 此运行的状态。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 运行的元数据。

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": {"tags": ["tag1", "tag2"]},
    "context": {"key": "value"},
    "metadata": {"owner": "user123"},
    "if_exists": "do_nothing",
    "name": "Assistant 1"
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

graph_id str

用于此助手的图 ID。

config dict[str, Any]

typing.Optional 助手的配置。

metadata MetadataInput

typing.Optional 附加到助手的元数据。

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]

typing.Optional 助手的配置。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 附加到助手的元数据。

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

typing.Optional 用于筛选的元数据。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 用于筛选的元数据。

AssistantsUpdate

基础类: TypedDict

更新助手的有效负载。

示例
update_params = {
    "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "graph_id": "graph123",
    "config": {"tags": ["tag1", "tag2"]},
    "context": {"key": "value"},
    "metadata": {"owner": "user123"},
    "name": "Assistant 1",
    "version": 1
}

属性

名称 类型 描述
assistant_id UUID

助手的唯一标识符。

graph_id str | None

typing.Optional 要更新的图 ID。

config dict[str, Any]

typing.Optional 要更新的配置。

context dict[str, Any]

助手的静态上下文。

metadata MetadataInput

typing.Optional 要更新的元数据。

name str | None

typing.Optional 要更新的名称。

version int | None

typing.Optional 要更新的版本。

assistant_id instance-attribute

assistant_id: UUID

助手的唯一标识符。

graph_id instance-attribute

graph_id: str | None

typing.Optional 要更新的图 ID。

config instance-attribute

config: dict[str, Any]

typing.Optional 要更新的配置。

context instance-attribute

context: dict[str, Any]

助手的静态上下文。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 要更新的元数据。

name instance-attribute

name: str | None

typing.Optional 要更新的名称。

version instance-attribute

version: int | None

typing.Optional 要更新的版本。

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

typing.Optional 用于筛选的图 ID。

metadata MetadataInput

typing.Optional 用于筛选的元数据。

限制 整数

返回结果的最大数量。

offset 整数

用于分页的偏移量。

graph_id instance-attribute

graph_id: str | None

typing.Optional 用于筛选的图 ID。

metadata instance-attribute

metadata: MetadataInput

typing.Optional 用于筛选的元数据。

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]

定时任务的有效负载。

schedule str

定时任务的调度计划。

cron_id UUID | None

typing.Optional 定时任务的唯一标识符。

thread_id UUID | None

typing.Optional 用于此定时任务的线程 ID。

user_id str | None

typing.Optional 用于此定时任务的用户 ID。

end_time 日期时间 | 无

typing.Optional 定时任务的结束时间。

payload instance-attribute

payload: dict[str, Any]

定时任务的有效负载。

schedule instance-attribute

schedule: str

定时任务的调度计划。

cron_id instance-attribute

cron_id: UUID | None

typing.Optional 定时任务的唯一标识符。

thread_id instance-attribute

thread_id: UUID | None

typing.Optional 用于此定时任务的线程 ID。

user_id instance-attribute

user_id: str | None

typing.Optional 用于此定时任务的用户 ID。

end_time instance-attribute

end_time: datetime | None

typing.Optional 定时任务的结束时间。

CronsDelete

基础类: TypedDict

删除定时任务的有效负载。

示例
delete_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
}

属性

名称 类型 描述
cron_id UUID

定时任务的唯一标识符。

cron_id instance-attribute

cron_id: UUID

定时任务的唯一标识符。

CronsRead

基础类: TypedDict

读取定时任务的有效负载。

示例
read_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
}

属性

名称 类型 描述
cron_id UUID

定时任务的唯一标识符。

cron_id instance-attribute

cron_id: UUID

定时任务的唯一标识符。

CronsUpdate

基础类: TypedDict

更新定时任务的有效负载。

示例
update_params = {
    "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
    "payload": {"key": "value"},
    "schedule": "0 0 * * *"
}

属性

名称 类型 描述
cron_id UUID

定时任务的唯一标识符。

payload dict[str, Any] | None

typing.Optional 要更新的有效负载。

schedule str | None

typing.Optional 要更新的调度计划。

cron_id instance-attribute

cron_id: UUID

定时任务的唯一标识符。

payload instance-attribute

payload: dict[str, Any] | None

typing.Optional 要更新的有效负载。

schedule instance-attribute

schedule: str | None

typing.Optional 要更新的调度计划。

CronsSearch

基础类: TypedDict

搜索定时任务的有效负载。

示例
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

typing.Optional 用于筛选的助手 ID。

thread_id UUID | None

typing.Optional 用于筛选的线程 ID。

限制 整数

返回结果的最大数量。

offset 整数

用于分页的偏移量。

assistant_id instance-attribute

assistant_id: UUID | None

typing.Optional 用于筛选的助手 ID。

thread_id instance-attribute

thread_id: UUID | None

typing.Optional 用于筛选的线程 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 操作的类型定义的命名空间。

此类组织了跨不同资源(线程、助手、定时任务)的创建、读取、更新、删除和搜索操作的类型定义。

用量
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

与定时任务相关的操作的类型。

store

与存储相关的操作的类型。

threads

与线程相关的操作的类型。

名称 描述
create

线程创建参数的类型。

create_run

创建或流式传输运行的类型。

read

线程读取参数的类型。

更新

线程更新参数的类型。

delete

线程删除参数的类型。

search

线程搜索参数的类型。

create

线程创建参数的类型。

create_run

创建或流式传输运行的类型。

read

线程读取参数的类型。

update

线程更新参数的类型。

delete

线程删除参数的类型。

search

线程搜索参数的类型。

assistants

与助手相关的操作的类型。

名称 描述
create

助手创建参数的类型。

read

助手读取参数的类型。

更新

助手更新参数的类型。

delete

助手删除参数的类型。

search

助手搜索参数的类型。

create

助手创建参数的类型。

read

助手读取参数的类型。

update

助手更新参数的类型。

delete

助手删除参数的类型。

search

助手搜索参数的类型。

crons

与定时任务相关的操作的类型。

名称 描述
create

定时任务创建参数的类型。

read

定时任务读取参数的类型。

更新

定时任务更新参数的类型。

delete

定时任务删除参数的类型。

search

定时任务搜索参数的类型。

create

定时任务创建参数的类型。

read

定时任务读取参数的类型。

update

定时任务更新参数的类型。

delete

定时任务删除参数的类型。

search

定时任务搜索参数的类型。

store

与存储相关的操作的类型。

名称 描述
放置

存储 put 参数的类型。

获取

存储 get 参数的类型。

search

存储搜索参数的类型。

delete

存储删除参数的类型。

list_namespaces

存储列出命名空间参数的类型。

put

存储 put 参数的类型。

get

存储 get 参数的类型。

search

存储搜索参数的类型。

delete

存储删除参数的类型。

list_namespaces

存储列出命名空间参数的类型。

在认证系统中使用到的异常。

名称 描述
HTTPException

您可以引发的 HTTP 异常,以返回特定的 HTTP 错误响应。

HTTPException

Bases: Exception

您可以引发的 HTTP 异常,以返回特定的 HTTP 错误响应。

由于这在 auth 模块中定义,我们默认使用 401 状态码。

参数

名称 类型 描述 默认值
status_code 整数

错误的 HTTP 状态码。默认为 401 "Unauthorized"。

401
detail 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")