6.2 连接部署服务
本章依据上游 Notebook 与 Python 实现重新整理;教学说明为本站新增中文内容,英文版与之对应。
版本与运行环境
代码对应上游 2025-10-12 快照,并非对最新版 SDK 的兼容承诺。以下原始代码按 Notebook 单元顺序保留,包含 Jupyter %pip / %%capture 等语法,应在 Notebook 环境分单元执行。凭据通过本地环境配置,不要写入网页或提交 Git。本网站只渲染教程,未运行这些付费模型或 Docker 实验。
Run、Thread 与 Store
通过 langgraph_sdk.get_client 连接服务 URL。Run 是一次执行,Thread 组织会话检查点,Store 保存跨会话记忆。若在 LangGraph 中组合远程图,也可使用 RemoteGraph。
后台与流式运行
runs.create 启动后台执行,runs.get 查询状态,runs.join 等待结束。等待某个 run 并不会全局禁止其他客户端发起任务。快照使用 messages-tuple 流式事件,事件名称和数据结构需要与实际服务及 SDK 版本匹配。
检查、分叉与共享记忆
修改检查点前先读取 thread 状态与历史。复用 message ID 会通过 reducer 替换原消息,而非追加。部署版的 ToDo namespace 是 (todo, todo_category, user_id),不同于 Module 5 的简化版本;默认 category 为 general。
原始代码单元
保留上游代码中的英文注释和标识符。各单元共享前面的变量;Notebook 输出与历史截图不作为本次运行结果。
单元 1
%%capture --no-stderr
%pip install -U langgraph_sdk单元 2
from langgraph_sdk import get_client
# Connect via SDK
url_for_cli_deployment = "http://localhost:8123"
client = get_client(url=url_for_cli_deployment)单元 3
%%capture --no-stderr
%pip install -U langchain_openai langgraph langchain_core单元 4
from langgraph.pregel.remote import RemoteGraph
from langchain_core.messages import convert_to_messages
from langchain_core.messages import HumanMessage, SystemMessage
# Connect via remote graph
url = "http://localhost:8123"
graph_name = "task_maistro"
remote_graph = RemoteGraph(graph_name, url=url)单元 5
# Create a thread
thread = await client.threads.create()
thread单元 6
# Check any existing runs on a thread
thread = await client.threads.create()
runs = await client.runs.list(thread["thread_id"])
print(runs)单元 7
# Ensure we've created some ToDos and saved them to my user_id
user_input = "Add a ToDo to finish booking travel to Hong Kong by end of next week. Also, add a ToDo to call parents back about Thanksgiving plans."
config = {"configurable": {"user_id": "Test"}}
graph_name = "task_maistro"
run = await client.runs.create(thread["thread_id"], graph_name, input={"messages": [HumanMessage(content=user_input)]}, config=config)单元 8
# Kick off a new thread and a new run
thread = await client.threads.create()
user_input = "Give me a summary of all ToDos."
config = {"configurable": {"user_id": "Test"}}
graph_name = "task_maistro"
run = await client.runs.create(thread["thread_id"], graph_name, input={"messages": [HumanMessage(content=user_input)]}, config=config)单元 9
# Check the run status
print(await client.runs.get(thread["thread_id"], run["run_id"]))单元 10
# Wait until the run completes
await client.runs.join(thread["thread_id"], run["run_id"])
print(await client.runs.get(thread["thread_id"], run["run_id"]))单元 11
user_input = "What ToDo should I focus on first."
async for chunk in client.runs.stream(thread["thread_id"],
graph_name,
input={"messages": [HumanMessage(content=user_input)]},
config=config,
stream_mode="messages-tuple"):
if chunk.event == "messages":
print("".join(data_item['content'] for data_item in chunk.data if 'content' in data_item), end="", flush=True)单元 12
thread_state = await client.threads.get_state(thread['thread_id'])
for m in convert_to_messages(thread_state['values']['messages']):
m.pretty_print()单元 13
# Copy the thread
copied_thread = await client.threads.copy(thread['thread_id'])单元 14
# Check the state of the copied thread
copied_thread_state = await client.threads.get_state(copied_thread['thread_id'])
for m in convert_to_messages(copied_thread_state['values']['messages']):
m.pretty_print()单元 15
# Get the history of the thread
states = await client.threads.get_history(thread['thread_id'])
# Pick a state update to fork
to_fork = states[-2]
to_fork['values']单元 16
to_fork['values']['messages'][0]['id']单元 17
to_fork['next']单元 18
to_fork['checkpoint_id']单元 19
forked_input = {"messages": HumanMessage(content="Give me a summary of all ToDos that need to be done in the next week.",
id=to_fork['values']['messages'][0]['id'])}
# Update the state, creating a new checkpoint in the thread
forked_config = await client.threads.update_state(
thread["thread_id"],
forked_input,
checkpoint_id=to_fork['checkpoint_id']
)单元 20
# Run the graph from the new checkpoint in the thread
async for chunk in client.runs.stream(thread["thread_id"],
graph_name,
input=None,
config=config,
checkpoint_id=forked_config['checkpoint_id'],
stream_mode="messages-tuple"):
if chunk.event == "messages":
print("".join(data_item['content'] for data_item in chunk.data if 'content' in data_item), end="", flush=True)单元 21
items = await client.store.search_items(
("todo", "general", "Test"),
limit=5,
offset=0
)
items['items']单元 22
from uuid import uuid4
await client.store.put_item(
("testing", "Test"),
key=str(uuid4()),
value={"todo": "Test SDK put_item"},
)单元 23
items = await client.store.search_items(
("testing", "Test"),
limit=5,
offset=0
)
items['items']单元 24
[item['key'] for item in items['items']]单元 25
await client.store.delete_item(
("testing", "Test"),
key='3de441ba-8c79-4beb-8f52-00e4dcba68d4',
)单元 26
items = await client.store.search_items(
("testing", "Test"),
limit=5,
offset=0
)
items['items']练习与检查
创建 run、等待完成、检查 thread 状态并复制 thread。在另一个 thread 中按同一用户和 general 分类查询 ToDo。Notebook 的删除例子只应使用测试 key。
完整讲解、历史输出和图示请对照 Notebook。