本指南展示如何创建、查看和检查 _线程_。线程与 助手 配合使用,以实现 有状态 对已部署 图的.
理解线程
线程是一个持久化对话容器,在多次运行之间保持状态。每次在线程上执行运行时,图都会使用线程的当前状态处理输入,并用新信息更新该状态。
线程通过保留运行之间的对话历史和上下文来实现有状态交互。没有线程,每次运行都是无状态的,无法记住之前的交互。线程特别适用于:
- - 助手需要记住已讨论内容的多轮对话。
- - 需要在多个步骤之间保持上下文的长时运行任务。
- - 每个用户都有自己对话历史记录的用户特定状态管理。
该图说明线程如何在两次运行之间保持状态。第二次运行可以访问第一次运行的消息,使助手能够理解"明天怎么样?"的上下文是指第一次运行中的天气查询:
sequenceDiagram
participant User
participant Thread
participant Assistant
participant Graph
Note over Thread: Thread ID: abc-123<br/>Persistent conversation
User->>Thread: Run 1: "What's the weather?"
Thread->>Assistant: Use Assistant Config
Assistant->>Graph: Execute with context
Graph-->>Thread: Update State<br/>{messages: [user_msg, ai_response]}
Thread-->>User: Response
Note over Thread: State persisted ✓
User->>Thread: Run 2: "What about tomorrow?"
Note over Thread: Previous messages<br/>still in state
Thread->>Assistant: Use Assistant Config
Assistant->>Graph: Execute with full history
Graph-->>Thread: Update State<br/>{messages: [...prev, new_msgs]}
Thread-->>User: Response with context
- - 线程通过唯一的线程 ID 维护一个持久化对话。
- - 每次运行都将助手的配置应用到图执行中。
- - 每次运行后状态都会更新,并持续保留到后续运行。
- - 后续运行可以访问完整的对话历史记录。
创建线程
要使用状态持久化运行您的图,您必须先创建一个线程:
SDK
空线程
要创建新线程,请使用以下方法之一:
from langgraph_sdk import get_client
# Initialize the client with your deployment URL
client = get_client(url=)
# Create an empty thread
# This creates a new thread with no initial state
thread = await client.threads.create()
print(thread)
// Initialize the client with your deployment URL
const client = new Client({ apiUrl: });
// Create an empty thread
// This creates a new thread with no initial state
const thread = await client.threads.create();
console.log(thread);
curl --request POST \
--url /threads \
--header 'Content-Type: application/json' \
--data '{}'
有关更多信息,请参阅 Python 和 JS SDK 文档,或 REST API reference.
Output:
{
"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 方法。这将创建一个独立线程,其历史记录与操作时的原始线程相同:
# Copy an existing thread
# The new thread will have the same state as the original at the time of copying
copied_thread = await client.threads.copy(thread["thread_id"])
// Copy an existing thread
// The new thread will have the same state as the original at the time of copying
const copiedThread = await client.threads.copy(thread["thread_id"]);
curl --request POST --url /threads/thread["thread_id"]/copy \
--header 'Content-Type: application/json'
更多信息,请参阅 Python 和 JS SDK 文档,或 REST API reference.
预填充状态
您可以通过提供 supersteps 到 create 方法来创建具有任意预定义状态的线程。 supersteps 描述了一系列状态更新,用于建立线程的初始状态。当您想要执行以下操作时,这非常有用:
- - 创建带有现有对话历史记录的线程。
- - 从另一个系统迁移对话。
- - 设置具有特定初始状态的测试场景。
- - 从上一个会话恢复对话。
有关检查点和状态管理的更多信息,请参阅 LangGraph 持久化文档.
from langgraph_sdk import get_client
# Initialize the client
client = get_client(url=)
# Create a thread with pre-populated conversation history
# The supersteps define a sequence of state updates that build up the initial state
thread = await client.threads.create(
graph_id="agent", # Specify which graph this thread is for
supersteps=[
{
updates: [
{
values: {},
as_node: '__input__', # Initial input node
},
],
},
{
updates: [
{
values: {
messages: [
{
type: 'human',
content: 'hello',
},
],
},
as_node: '__start__', # User's first message
},
],
},
{
updates: [
{
values: {
messages: [
{
content: 'Hello! How can I assist you today?',
type: 'ai',
},
],
},
as_node: 'call_model', # Assistant's response
},
],
},
])
print(thread)
// Initialize the client
const client = new Client({ apiUrl: });
// Create a thread with pre-populated conversation history
// The supersteps define a sequence of state updates that build up the initial state
const thread = await client.threads.create({
graphId: 'agent', // Specify which graph this thread is for
supersteps: [
{
updates: [
{
values: {},
asNode: '__input__', // Initial input node
},
],
},
{
updates: [
{
values: {
messages: [
{
type: 'human',
content: 'hello',
},
],
},
asNode: '__start__', // User's first message
},
],
},
{
updates: [
{
values: {
messages: [
{
content: 'Hello! How can I assist you today?',
type: 'ai',
},
],
},
asNode: 'call_model', // Assistant's response
},
],
},
],
});
console.log(thread);
curl --request POST \
--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"}]}]}'
Output:
{
"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
}
]
}
}
UI
您还可以直接从 LangSmith UI:
- 导航到您的 部署.
- 选择 **线程** tab.
- 点击 **+ 新建线程**.
- (可选)为线程提供元数据或初始状态。
- 点击 **创建线程**.
新创建的线程将出现在线程表中,可以立即用于运行。
列出线程
SDK
要列出线程,请使用 search 方法。这将列出应用中匹配所提供过滤条件的线程:
按线程状态过滤
使用 status 字段根据线程状态进行过滤。支持的值为 idle, busy, interrupted和 error。例如,要查看 idle threads:
# Search for idle threads
# The status filter accepts: idle, busy, interrupted, error
print(await client.threads.search(status="idle", limit=1))
// Search for idle threads
// The status filter accepts: idle, busy, interrupted, error
console.log(await client.threads.search({ status: "idle", limit: 1 }));
curl --request POST \
--url /threads/search \
--header 'Content-Type: application/json' \
--data '{"status": "idle", "limit": 1}'
更多信息,请参阅 Python 和 JS SDK 文档,或 REST API reference.
Output:
[
{
"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 方法允许您按元数据进行过滤。这对于查找与特定图、用户或您附加到线程的自定义元数据关联的线程非常有用。
您可以过滤的常见元数据字段包括:
| 元数据键 | 描述 |
|---|---|
graph_id | 线程所属的图(部署)。 |
assistant_id | assistant 用于在线程上创建运行。 |
langgraph_auth_user_id | 拥有线程的已认证用户(使用 自定义认证). |
cron_id | 定时任务 创建者。 |
您还可以按创建或更新线程时附加的任何自定义元数据进行过滤。
按图过滤
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 /threads/search \
--header 'Content-Type: application/json' \
--data '{"metadata": {"graph_id": "agent"}, "limit": 1}'
Output:
[
{
"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": {}
}
}
]
按助手筛选
print(await client.threads.search(
metadata={"assistant_id": "fe096781-5601-53d2-b2f6-0d3403f7e9ca"},
limit=1,
))
console.log(await client.threads.search({
metadata: { "assistant_id": "fe096781-5601-53d2-b2f6-0d3403f7e9ca" },
limit: 1,
}));
curl --request POST \
--url /threads/search \
--header 'Content-Type: application/json' \
--data '{"metadata": {"assistant_id": "fe096781-5601-53d2-b2f6-0d3403f7e9ca"}, "limit": 1}'
按定时任务筛选
print(await client.threads.search(
metadata={"cron_id": "8b98a268-e49a-4228-a0d3-1a354e3a54d0"},
limit=10,
))
console.log(await client.threads.search({
metadata: { "cron_id": "8b98a268-e49a-4228-a0d3-1a354e3a54d0" },
limit: 10,
}));
curl --request POST \
--url /threads/search \
--header 'Content-Type: application/json' \
--data '{"metadata": {"cron_id": "8b98a268-e49a-4228-a0d3-1a354e3a54d0"}, "limit": 10}'
排序
SDK 还支持按以下方式对线程排序 thread_id, status, created_at和 updated_at 使用 sort_by 和 sort_order parameters.
UI
您还可以通过以下方式查看和管理部署中的线程 LangSmith UI:
- 导航到您的 部署.
- 选择 **线程** tab.
这将加载您部署中所有线程的表格。
按线程状态筛选: 在顶部栏选择状态以按此筛选线程 idle, busy, interrupted, or error.
对线程排序: 点击任意列标题的箭头图标以按该属性排序(thread_id, status, created_at, or updated_at).
检查线程
SDK
获取线程
要查看给定 thread_id的特定线程,请使用 get 方法:
# Retrieve a specific thread by its ID
# Returns the thread metadata including status, creation time, and metadata
print((await client.threads.get(thread["thread_id"])))
// Retrieve a specific thread by its ID
// Returns the thread metadata including status, creation time, and metadata
console.log((await client.threads.get(thread["thread_id"])));
curl --request GET \
--url /threads/thread["thread_id"] \
--header 'Content-Type: application/json'
Output:
{
"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": {}
}
}
有关更多信息,请参阅 Python 和 JS SDK 文档,或 REST API reference.
检查线程状态
要查看给定线程的当前状态,请使用 get_state 方法。这会返回当前值、待执行的下一个节点以及检查点信息:
# Get the current state of a thread
# Returns values, next nodes, tasks, checkpoint info, and metadata
print((await client.threads.get_state(thread["thread_id"])))
// Get the current state of a thread
// Returns values, next nodes, tasks, checkpoint info, and metadata
console.log((await client.threads.getState(thread["thread_id"])));
curl --request GET \
--url /threads/thread["thread_id"]/state \
--header 'Content-Type: application/json'
Output:
{
"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"
}
有关更多信息,请参阅 Python 和 JS SDK 文档,或 REST API reference.
(可选)要查看线程在特定检查点的状态,请传入检查点 ID。这对于检查线程在其执行历史中特定点的状态非常有用。
首先,从线程的历史记录中获取检查点 ID:
# Get the thread history to find checkpoint IDs
history = await client.threads.get_history(thread_id=thread["thread_id"])
checkpoint_id = history[0]["checkpoint_id"] # Get the most recent checkpoint
// Get the thread history to find checkpoint IDs
const history = await client.threads.getHistory(thread["thread_id"]);
const checkpointId = history[0].checkpoint_id; // Get the most recent checkpoint
# Get the thread history to find checkpoint IDs
curl --request POST \
--url /threads/thread["thread_id"]/history \
--header 'Content-Type: application/json' \
--data '{"limit": 1}'
然后使用检查点 ID 获取该特定点的状态:
# Get thread state at a specific checkpoint
# Useful for inspecting historical state or debugging
thread_state = await client.threads.get_state(
thread_id=thread["thread_id"],
checkpoint_id=checkpoint_id
)
// Get thread state at a specific checkpoint
// Useful for inspecting historical state or debugging
const threadState = await client.threads.getState(thread["thread_id"], checkpointId);
curl --request GET \
--url /threads/thread["thread_id"]/state/ \
--header 'Content-Type: application/json'
检查完整的线程历史
要查看线程的历史记录,请使用 get_history 方法。这会返回线程经历的每个状态的列表,允许您追踪完整的执行路径:
# Get the full history of a thread
# Returns a list of all state snapshots from the thread's execution
history = await client.threads.get_history(
thread_id=thread["thread_id"],
limit=10 # Optional: limit the number of states returned
)
for state in history:
print(f"Checkpoint: {state['checkpoint_id']}")
print(f"Step: {state['metadata']['step']}")
// Get the full history of a thread
// Returns a list of all state snapshots from the thread's execution
const history = await client.threads.getHistory(
thread["thread_id"],
{
limit: 10 // Optional: limit the number of states returned
}
);
for (const state of history) {
console.log(`Checkpoint: ${state.checkpoint_id}`);
console.log(`Step: ${state.metadata.step}`);
}
curl --request POST \
--url /threads/thread["thread_id"]/history \
--header 'Content-Type: application/json' \
--data '{"limit": 10}'
此方法对于以下场景特别有用: - 通过查看状态如何演变来调试执行流程。 - 理解图中执行的决策点。 - 审计对话历史和状态变更。 - 重放或分析过去的交互。
UI
您还可以在 LangSmith UI:
- 导航至您的 部署.
- 选择 **线程** 标签页以查看所有线程。
- 点击某个线程以检查其当前状态。
要查看完整的线程历史记录并执行详细调试,请点击 **在 Studio 中打开** 以在 Studio中打开该线程。Studio 提供了一个可视化界面,用于探索线程的执行历史、状态变化和检查点详细信息。