Skip to content

使用线程

前提条件

在本指南中,我们将展示如何创建、查看和检查线程。

创建线程

要运行你的图并持久化状态,你必须首先创建一个线程。

空线程

要创建一个新的线程,请使用 LangGraph SDKcreate 方法。有关更多信息,请参阅 PythonJS SDK 参考文档。

from langgraph_sdk import get_client

client = get_client(url=<DEPLOYMENT_URL>)
thread = await client.threads.create()

print(thread)
import { Client } from "@langchain/langgraph-sdk";

const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
const thread = await client.threads.create();

console.log(thread);
curl --request POST \
    --url <DEPLOYMENT_URL>/threads \
    --header 'Content-Type: application/json' \
    --data '{}'

输出:

{
  "thread_id": "123e4567-e89b-12d3-a456-426614174000",
  "created_at": "2025-05-12T14:04:08.268Z",
  "updated_at": "2025-05-12T14:04:08.268Z",
  "metadata": {},
  "status": "idle",
  "values": {}
}

复制线程

或者,如果你已经在应用程序中有一个线程,并希望复制其状态,你可以使用 copy 方法。这将创建一个独立的线程,其历史与操作时的原始线程相同。有关更多信息,请参阅 PythonJS SDK 参考文档。

copied_thread = await client.threads.copy(<THREAD_ID>)
const copiedThread = await client.threads.copy(<THREAD_ID>);
curl --request POST --url <DEPLOYMENT_URL>/threads/<THREAD_ID>/copy \
--header 'Content-Type: application/json'

预填充状态

最后,你可以通过在 create 方法中提供一组 supersteps 来创建具有任意预定义状态的线程。supersteps 描述了一组状态更新序列。例如:

from langgraph_sdk import get_client

client = get_client(url=<DEPLOYMENT_URL>)
thread = await client.threads.create(
  graph_id="agent",
  supersteps=[
    {
      updates: [
        {
          values: {},
          as_node: '__input__',
        },
      ],
    },
    {
      updates: [
        {
          values: {
            messages: [
              {
                type: 'human',
                content: 'hello',
              },
            ],
          },
          as_node: '__start__',
        },
      ],
    },
    {
      updates: [
        {
          values: {
            messages: [
              {
                content: 'Hello! How can I assist you today?',
                type: 'ai',
              },
            ],
          },
          as_node: 'call_model',
        },
      ],
    },
  ])

print(thread)
import { Client } from "@langchain/langgraph-sdk";

const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
const thread = await client.threads.create({
    graphId: 'agent',
    supersteps: [
    {
      updates: [
        {
          values: {},
          asNode: '__input__',
        },
      ],
    },
    {
      updates: [
        {
          values: {
            messages: [
              {
                type: 'human',
                content: 'hello',
              },
            ],
          },
          asNode: '__start__',
        },
      ],
    },
    {
      updates: [
        {
          values: {
            messages: [
              {
                content: 'Hello! How can I assist you today?',
                type: 'ai',
              },
            ],
          },
          asNode: 'call_model',
        },
      ],
    },
  ],
});

console.log(thread);
curl --request POST \
    --url <DEPLOYMENT_URL>/threads \
    --header 'Content-Type: application/json' \
    --data '{"metadata":{"graph_id":"agent"},"supersteps":[{"updates":[{"values":{},"as_node":"__input__"}]},{"updates":[{"values":{"messages":[{"type":"human","content":"hello"}]},"as_node":"__start__"}]},{"updates":[{"values":{"messages":[{"content":"Hello\u0021 How can I assist you today?","type":"ai"}]},"as_node":"call_model"}]}]}'

输出:

{
    "thread_id": "f15d70a1-27d4-4793-a897-de5609920b7d",
    "created_at": "2025-05-12T15:37:08.935038+00:00",
    "updated_at": "2025-05-12T15:37:08.935046+00:00",
    "metadata": {"graph_id": "agent"},
    "status": "idle",
    "config": {},
    "values": {
        "messages": [
            {
                "content": "hello",
                "additional_kwargs": {},
                "response_metadata": {},
                "type": "human",
                "name": null,
                "id": "8701f3be-959c-4b7c-852f-c2160699b4ab",
                "example": false
            },
            {
                "content": "Hello! How can I assist you today?",
                "additional_kwargs": {},
                "response_metadata": {},
                "type": "ai",
                "name": null,
                "id": "4d8ea561-7ca1-409a-99f7-6b67af3e1aa3",
                "example": false,
                "tool_calls": [],
                "invalid_tool_calls": [],
                "usage_metadata": null
            }
        ]
    }
}

列出线程

LangGraph SDK

要列出线程,请使用 LangGraph SDKsearch 方法。这将列出与提供的筛选条件匹配的应用程序中的线程。有关更多信息,请参阅 PythonJS SDK 参考文档。

按线程状态筛选

使用 status 字段根据线程的状态进行筛选。支持的值包括 idlebusyinterruptederror。有关每个状态的信息,请参见 此处。例如,查看 idle 状态的线程:

print(await client.threads.search(status="idle",limit=1))
console.log(await client.threads.search({ status: "idle", limit: 1 }));
curl --request POST \
--url <DEPLOYMENT_URL>/threads/search \
--header 'Content-Type: application/json' \
--data '{"status": "idle", "limit": 1}'

输出:

[
  {
    'thread_id': 'cacf79bb-4248-4d01-aabc-938dbd60ed2c',
    'created_at': '2024-08-14T17:36:38.921660+00:00',
    'updated_at': '2024-08-14T17:36:38.921660+00:00',
    'metadata': {'graph_id': 'agent'},
    'status': 'idle',
    'config': {'configurable': {}}
  }
]

按元数据筛选

search 方法允许您按元数据进行筛选:

print((await client.threads.search(metadata={"graph_id":"agent"},limit=1)))
console.log((await client.threads.search({ metadata: { "graph_id": "agent" }, limit: 1 })));
curl --request POST \
--url <DEPLOYMENT_URL>/threads/search \
--header 'Content-Type: application/json' \
--data '{"metadata": {"graph_id":"agent"}, "limit": 1}'

输出:

[
  {
    'thread_id': 'cacf79bb-4248-4d01-aabc-938dbd60ed2c',
    'created_at': '2024-08-14T17:36:38.921660+00:00',
    'updated_at': '2024-08-14T17:36:38.921660+00:00',
    'metadata': {'graph_id': 'agent'},
    'status': 'idle',
    'config': {'configurable': {}}
  }
]

排序

SDK 还支持通过 thread_idstatuscreated_atupdated_at 对线程进行排序,使用 sort_bysort_order 参数。

LangGraph 平台 UI

您还可以通过 LangGraph 平台 UI 查看部署中的线程。

在您的部署中,选择“线程”标签页。这将加载您部署中的所有线程表。

要按线程状态筛选,请在顶部栏选择一个状态。要按支持的属性排序,请点击所需列的箭头图标。

查看线程

LangGraph SDK

获取线程

要根据给定的 thread_id 查看特定线程,使用 get 方法:

print((await client.threads.get(<THREAD_ID>)))
console.log((await client.threads.get(<THREAD_ID>)));
curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID> \
--header 'Content-Type: application/json'

输出:

{
  'thread_id': 'cacf79bb-4248-4d01-aabc-938dbd60ed2c',
  'created_at': '2024-08-14T17:36:38.921660+00:00',
  'updated_at': '2024-08-14T17:36:38.921660+00:00',
  'metadata': {'graph_id': 'agent'},
  'status': 'idle',
  'config': {'configurable': {}}
}

查看线程状态

要查看给定线程的当前状态,请使用 get_state 方法:

print((await client.threads.get_state(<THREAD_ID>)))
console.log((await client.threads.getState(<THREAD_ID>)));
curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/state \
--header 'Content-Type: application/json'

输出:

{
    "values": {
        "messages": [
            {
                "content": "hello",
                "additional_kwargs": {},
                "response_metadata": {},
                "type": "human",
                "name": null,
                "id": "8701f3be-959c-4b7c-852f-c2160699b4ab",
                "example": false
            },
            {
                "content": "Hello! How can I assist you today?",
                "additional_kwargs": {},
                "response_metadata": {},
                "type": "ai",
                "name": null,
                "id": "4d8ea561-7ca1-409a-99f7-6b67af3e1aa3",
                "example": false,
                "tool_calls": [],
                "invalid_tool_calls": [],
                "usage_metadata": null
            }
        ]
    },
    "next": [],
    "tasks": [],
    "metadata": {
        "thread_id": "f15d70a1-27d4-4793-a897-de5609920b7d",
        "checkpoint_id": "1f02f46f-7308-616c-8000-1b158a9a6955",
        "graph_id": "agent_with_quite_a_long_name",
        "source": "update",
        "step": 1,
        "writes": {
            "call_model": {
                "messages": [
                    {
                        "content": "Hello! How can I assist you today?",
                        "type": "ai"
                    }
                ]
            }
        },
        "parents": {}
    },
    "created_at": "2025-05-12T15:37:09.008055+00:00",
    "checkpoint": {
        "checkpoint_id": "1f02f46f-733f-6b58-8001-ea90dcabb1bd",
        "thread_id": "f15d70a1-27d4-4793-a897-de5609920b7d",
        "checkpoint_ns": ""
    },
    "parent_checkpoint": {
        "checkpoint_id": "1f02f46f-7308-616c-8000-1b158a9a6955",
        "thread_id": "f15d70a1-27d4-4793-a897-de5609920b7d",
        "checkpoint_ns": ""
    },
    "checkpoint_id": "1f02f46f-733f-6b58-8001-ea90dcabb1bd",
    "parent_checkpoint_id": "1f02f46f-7308-616c-8000-1b158a9a6955"
}

可选地,若要查看线程在特定检查点的状态,只需传入检查点 id(或整个检查点对象)即可:

thread_state = await client.threads.get_state(
  thread_id=<THREAD_ID>
  checkpoint_id=<CHECKPOINT_ID>
)
const threadState = await client.threads.getState(<THREAD_ID>, <CHECKPOINT_ID>);
curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/state/<CHECKPOINT_ID> \
--header 'Content-Type: application/json'

查看完整的线程历史记录

要查看线程的历史记录,请使用 get_history 方法。这将返回线程经历过的所有状态列表。有关更多信息,请参阅 PythonJS 参考文档。

LangGraph 平台 UI

您也可以通过 LangGraph 平台 UI 在部署中查看线程。

在您的部署中,选择“Threads”标签页。这将加载您部署中的所有线程表。

选择一个线程以查看其当前状态。要查看其完整历史记录并进行进一步调试,请在 LangGraph Studio 中打开该线程。