流式传输 API¶
LangGraph SDK 允许你从 LangGraph API 服务器流式传输输出。
Note
LangGraph SDK 和 LangGraph Server 是 LangGraph Platform 的一部分。
基本用法¶
基本用法示例:
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>, api_key=<API_KEY>)
# Using the graph deployed with the name "agent"
assistant_id = "agent"
# create a thread
thread = await client.threads.create()
thread_id = thread["thread_id"]
# create a streaming run
# highlight-next-line
async for chunk in client.runs.stream(
thread_id,
assistant_id,
input=inputs,
stream_mode="updates"
):
print(chunk.data)
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL>, apiKey: <API_KEY> });
// Using the graph deployed with the name "agent"
const assistantID = "agent";
// create a thread
const thread = await client.threads.create();
const threadID = thread["thread_id"];
// create a streaming run
// highlight-next-line
const streamResponse = client.runs.stream(
threadID,
assistantID,
{
input,
streamMode: "updates"
}
);
for await (const chunk of streamResponse) {
console.log(chunk.data);
}
扩展示例:流式传输更新
这是可以在 LangGraph API 服务器中运行的示例图。 有关更多详细信息,请参阅 LangGraph Platform 快速入门。
# graph.py
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
topic: str
joke: str
def refine_topic(state: State):
return {"topic": state["topic"] + " and cats"}
def generate_joke(state: State):
return {"joke": f"This is a joke about {state['topic']}"}
graph = (
StateGraph(State)
.add_node(refine_topic)
.add_node(generate_joke)
.add_edge(START, "refine_topic")
.add_edge("refine_topic", "generate_joke")
.add_edge("generate_joke", END)
.compile()
)
一旦你有了正在运行的 LangGraph API 服务器,你可以使用 LangGraph SDK 与其交互
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>)
# Using the graph deployed with the name "agent"
assistant_id = "agent"
# create a thread
thread = await client.threads.create()
thread_id = thread["thread_id"]
# create a streaming run
# highlight-next-line
async for chunk in client.runs.stream( # (1)!
thread_id,
assistant_id,
input={"topic": "ice cream"},
# highlight-next-line
stream_mode="updates" # (2)!
):
print(chunk.data)
client.runs.stream()方法返回一个产生流式输出的迭代器。- 设置
stream_mode="updates"以仅在每个节点后流式传输图状态的更新。其他流式传输模式也可用。有关详细信息,请参阅支持的流式传输模式。
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// Using the graph deployed with the name "agent"
const assistantID = "agent";
// create a thread
const thread = await client.threads.create();
const threadID = thread["thread_id"];
// create a streaming run
// highlight-next-line
const streamResponse = client.runs.stream( // (1)!
threadID,
assistantID,
{
input: { topic: "ice cream" },
// highlight-next-line
streamMode: "updates" // (2)!
}
);
for await (const chunk of streamResponse) {
console.log(chunk.data);
}
client.runs.stream()方法返回一个产生流式输出的迭代器。- 设置
streamMode: "updates"以仅在每个节点后流式传输图状态的更新。其他流式传输模式也可用。有关详细信息,请参阅支持的流式传输模式。
支持的流式传输模式¶
| 模式 | 描述 | LangGraph 库方法 |
|---|---|---|
values |
在每个超步骤后流式传输完整的图状态。 | .stream() / .astream() 与 stream_mode="values" |
updates |
在图的每个步骤后流式传输状态的更新。如果在同一步骤中进行多次更新(例如,运行多个节点),则这些更新将单独流式传输。 | .stream() / .astream() 与 stream_mode="updates" |
messages-tuple |
从调用 LLM 的图节点流式传输 LLM 标记和元数据(对聊天应用程序有用)。 | .stream() / .astream() 与 stream_mode="messages" |
debug |
在图执行期间流式传输尽可能多的信息。 | .stream() / .astream() 与 stream_mode="debug" |
custom |
从图内部流式传输自定义数据 | .stream() / .astream() 与 stream_mode="custom" |
events |
流式传输所有事件(包括图的状态);主要在迁移大型 LCEL 应用程序时有用。 | .astream_events() |
流式传输多种模式¶
你可以将列表作为 stream_mode 参数传递,以同时流式传输多种模式。
流式输出将是 (mode, chunk) 的元组,其中 mode 是流式传输模式的名称,chunk 是该模式流式传输的数据。
流式传输图状态¶
使用流式传输模式 updates 和 values 来流式传输图执行时的状态。
updates流式传输图的每个步骤后状态的**更新**。values流式传输图的每个步骤后状态的**完整值**。
示例图
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
topic: str
joke: str
def refine_topic(state: State):
return {"topic": state["topic"] + " and cats"}
def generate_joke(state: State):
return {"joke": f"This is a joke about {state['topic']}"}
graph = (
StateGraph(State)
.add_node(refine_topic)
.add_node(generate_joke)
.add_edge(START, "refine_topic")
.add_edge("refine_topic", "generate_joke")
.add_edge("generate_joke", END)
.compile()
)
有状态运行
以下示例假设你希望**持久化流式运行的输出**到检查点器数据库中,并且已创建了一个线程。要创建线程:
如果你不需要持久化运行的输出,可以在流式传输时传递 None 而不是 thread_id。
使用此选项仅流式传输节点在每个步骤后返回的**状态更新**。流式输出包括节点的名称以及更新。
使用此选项在每个步骤后流式传输图的**完整状态**。
子图¶
要在流式输出中包含来自子图的输出,可以在父图的 .stream() 方法中设置 subgraphs=True。这将流式传输来自父图和任何子图的输出。
for chunk in client.runs.stream(
thread_id,
assistant_id,
input={"foo": "foo"},
# highlight-next-line
stream_subgraphs=True, # (1)!
stream_mode="updates",
):
print(chunk)
- 设置
stream_subgraphs=True以从子图流式传输输出。
扩展示例:从子图流式传输
这是可以在 LangGraph API 服务器中运行的示例图。 有关更多详细信息,请参阅 LangGraph Platform 快速入门。
# graph.py
from langgraph.graph import START, StateGraph
from typing import TypedDict
# Define subgraph
class SubgraphState(TypedDict):
foo: str # note that this key is shared with the parent graph state
bar: str
def subgraph_node_1(state: SubgraphState):
return {"bar": "bar"}
def subgraph_node_2(state: SubgraphState):
return {"foo": state["foo"] + state["bar"]}
subgraph_builder = StateGraph(SubgraphState)
subgraph_builder.add_node(subgraph_node_1)
subgraph_builder.add_node(subgraph_node_2)
subgraph_builder.add_edge(START, "subgraph_node_1")
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
subgraph = subgraph_builder.compile()
# Define parent graph
class ParentState(TypedDict):
foo: str
def node_1(state: ParentState):
return {"foo": "hi! " + state["foo"]}
builder = StateGraph(ParentState)
builder.add_node("node_1", node_1)
builder.add_node("node_2", subgraph)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
graph = builder.compile()
一旦你有了正在运行的 LangGraph API 服务器,你可以使用 LangGraph SDK 与其交互
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>)
# Using the graph deployed with the name "agent"
assistant_id = "agent"
# create a thread
thread = await client.threads.create()
thread_id = thread["thread_id"]
async for chunk in client.runs.stream(
thread_id,
assistant_id,
input={"foo": "foo"},
# highlight-next-line
stream_subgraphs=True, # (1)!
stream_mode="updates",
):
print(chunk)
- 设置
stream_subgraphs=True以从子图流式传输输出。
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// Using the graph deployed with the name "agent"
const assistantID = "agent";
// create a thread
const thread = await client.threads.create();
const threadID = thread["thread_id"];
// create a streaming run
const streamResponse = client.runs.stream(
threadID,
assistantID,
{
input: { foo: "foo" },
// highlight-next-line
streamSubgraphs: true, // (1)!
streamMode: "updates"
}
);
for await (const chunk of streamResponse) {
console.log(chunk);
}
- 设置
streamSubgraphs: true以从子图流式传输输出。
注意,我们不仅接收节点更新,还接收告诉我们从哪个图(或子图)流式传输的命名空间。
调试¶
使用 debug 流式传输模式在图执行期间流式传输尽可能多的信息。流式输出包括节点的名称以及完整状态。
LLM 标记¶
使用 messages-tuple 流式传输模式从图的任何部分(包括节点、工具、子图或任务)逐个标记地流式传输大型语言模型(LLM)输出。
messages-tuple 模式的流式输出是一个元组 (message_chunk, metadata),其中:
message_chunk:来自 LLM 的标记或消息段。metadata:包含有关图节点和 LLM 调用详细信息的字典。
示例图
from dataclasses import dataclass
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, START
@dataclass
class MyState:
topic: str
joke: str = ""
llm = init_chat_model(model="openai:gpt-4o-mini")
def call_model(state: MyState):
"""Call the LLM to generate a joke about a topic"""
# highlight-next-line
llm_response = llm.invoke( # (1)!
[
{"role": "user", "content": f"Generate a joke about {state.topic}"}
]
)
return {"joke": llm_response.content}
graph = (
StateGraph(MyState)
.add_node(call_model)
.add_edge(START, "call_model")
.compile()
)
- 请注意,即使使用
.invoke而不是.stream运行 LLM,也会发出消息事件。
async for chunk in client.runs.stream(
thread_id,
assistant_id,
input={"topic": "ice cream"},
# highlight-next-line
stream_mode="messages-tuple",
):
if chunk.event != "messages":
continue
message_chunk, metadata = chunk.data # (1)!
if message_chunk["content"]:
print(message_chunk["content"], end="|", flush=True)
- "messages-tuple" 流式传输模式返回元组
(message_chunk, metadata)的迭代器,其中message_chunk是 LLM 流式传输的标记,metadata是包含调用 LLM 的图节点和其他信息的字典。
const streamResponse = client.runs.stream(
threadID,
assistantID,
{
input: { topic: "ice cream" },
// highlight-next-line
streamMode: "messages-tuple"
}
);
for await (const chunk of streamResponse) {
if (chunk.event !== "messages") {
continue;
}
console.log(chunk.data[0]["content"]); // (1)!
}
- "messages-tuple" 流式传输模式返回元组
(message_chunk, metadata)的迭代器,其中message_chunk是 LLM 流式传输的标记,metadata是包含调用 LLM 的图节点和其他信息的字典。
过滤 LLM 标记¶
- 要按 LLM 调用过滤流式标记,你可以将
tags与 LLM 调用关联。 - 要仅从特定节点流式传输标记,请使用
stream_mode="messages"并通过流式元数据中的langgraph_node字段过滤输出。
流式传输自定义数据¶
要发送**自定义用户定义的数据**:
流式传输事件¶
要流式传输所有事件,包括图的状态:
无状态运行¶
如果你不想**持久化流式运行的输出**到检查点器数据库中,可以在不创建线程的情况下创建无状态运行:
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>, api_key=<API_KEY>)
async for chunk in client.runs.stream(
# highlight-next-line
None, # (1)!
assistant_id,
input=inputs,
stream_mode="updates"
):
print(chunk.data)
- 我们传递
None而不是thread_idUUID。
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL>, apiKey: <API_KEY> });
// create a streaming run
// highlight-next-line
const streamResponse = client.runs.stream(
// highlight-next-line
null, // (1)!
assistantID,
{
input,
streamMode: "updates"
}
);
for await (const chunk of streamResponse) {
console.log(chunk.data);
}
- 我们传递
None而不是thread_idUUID。
加入并流式传输¶
LangGraph Platform 允许你加入活动的后台运行并从中流式传输输出。为此,你可以使用 LangGraph SDK 的 client.runs.join_stream 方法:
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>, api_key=<API_KEY>)
# highlight-next-line
async for chunk in client.runs.join_stream(
thread_id,
# highlight-next-line
run_id, # (1)!
):
print(chunk)
- 这是你想要加入的现有运行的
run_id。
import { Client } from "@langchain/langgraph-sdk";
const client = new Client({ apiUrl: <DEPLOYMENT_URL>, apiKey: <API_KEY> });
// highlight-next-line
const streamResponse = client.runs.joinStream(
threadID,
// highlight-next-line
runId // (1)!
);
for await (const chunk of streamResponse) {
console.log(chunk);
}
- 这是你想要加入的现有运行的
run_id。
输出未缓冲
当你使用 .join_stream 时,输出不会被缓冲,因此在加入之前产生的任何输出都不会被接收。
API 参考¶
有关 API 使用和实现,请参阅 API 参考。