自定义流式输出
custom & get_stream_writer
可以在节点内部流式传入任何数据,通过 get_stream_writer()
输入,stream_mode="custom"
获取输出
from typing import TypedDict
from langgraph.config import get_stream_writer
class State(TypedDict):
placeholder: str
def node(state: State):
# 创建写入流
writer = get_stream_writer()
# 定制流式输出
items = ["books", "penciles", "pictures"]
for chunk in items:
writer({ "custom_data": chunk })
return { "placeholder": ",".join(items) }
graph = (
StateGraph(State)
.add_node(node)
.add_edge(START, "node")
.compile()
)
# 使用custom输出
for chunk in graph.stream({}, stream_mode="custom"):
print(chunk)