主题
流式传输
了解 CrewAI 针对流程、直接 LLM 调用、工具和对话轮次的流式传输模型。
概述
流式传输让你的应用可以在工作仍在运行时接收执行更新。你不必等待最终结果,而是可以在 LLM token、工具活动、流程生命周期事件和对话消息产生时即时渲染它们。
CrewAI 有两个流式传输界面:
| 界面 | 使用者 | 输出 |
|---|---|---|
| 帧流式传输 | 流程、直接 LLM 调用、对话轮次 | 有序的 StreamFrame 对象 |
| 团队分块流式传输 | 设置了 stream=True 的团队 | CrewStreamingOutput 分块 |
对于新的运行时集成、UI、终端应用、服务桥接和对话界面,请使用帧流式传输。它提供了一个跨运行时的稳定事件封装。
StreamFrame
StreamFrame 是可流式传输运行时发出的通用对象:
python
frame.id # unique frame id
frame.seq # execution-local order, when available
frame.type # source event type, such as "llm_stream_chunk"
frame.channel # "llm", "flow", "tools", "messages", "lifecycle", or "custom"
frame.namespace # source/runtime namespace
frame.timestamp # event timestamp
frame.parent_id # parent event id, when available
frame.previous_id # previous event id, when available
frame.data # structured event payload
frame.event # alias for frame.data
frame.content # printable text for token-like frames, otherwise ""对大多数使用方而言,重要的字段是:
| 字段 | 用途 |
|---|---|
channel | 将帧路由到正确的 UI 区域 |
type | 处理某个通道内的特定事件 |
content | 打印类似 token 的文本 |
event | 读取结构化元数据,例如工具名称或消息角色 |
seq | 保持执行顺序 |
频道
帧被分组到高层级的通道中:
| 通道 | 包含 |
|---|---|
llm | LLM 调用的生命周期、文本分块和思考分块 |
flow | 流程生命周期、方法执行、路由、暂停和恢复事件 |
tools | 工具使用的开始、结束和错误事件 |
messages | 对话记录事件 |
lifecycle | 不属于其他通道的运行时生命周期事件 |
custom | 无法映射到内置通道的事件 |
流本身仍然是一条有序时间线。通道投影让使用方可以只关注该时间线的一部分。
flowchart LR
A["flow<br/>flow_started"] --> B["llm<br/>llm_call_started"]
B --> C["llm<br/>llm_stream_chunk"]
C --> D["tools<br/>tool_usage_started"]
D --> E["tools<br/>tool_usage_finished"]
E --> F["llm<br/>llm_stream_chunk"]
F --> G["flow<br/>flow_finished"]
流会话
帧流式传输会返回一个流会话:
python
stream = flow.stream_events(inputs={"topic": "AI agents"})该会话既是一个迭代器,也是最终结果的持有者:
python
with stream:
for frame in stream:
print(frame.content, end="", flush=True)
result = stream.result请在读取 stream.result 之前消费完流。过早读取结果会引发错误,因为运行时可能仍在产生帧。
通道投影
当你只需要某一类帧时,请使用通道投影:
python
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
for frame in stream.llm:
print(frame.content, end="", flush=True)
result = stream.result可用的投影:
| 投影 | 帧 |
|---|---|
stream.events | 所有帧 |
stream.llm | LLM 帧 |
stream.flow | 流程帧 |
stream.tools | 工具帧 |
stream.messages | 对话消息帧 |
stream.interleave([...]) | 按相对顺序选定的通道 |
入口点
请使用与你正在流式传输的运行时相匹配的入口点:
| 运行时 | 流式传输入口点 |
|---|---|
| 流程 | flow.stream_events(...) |
设置了 stream=True 的流程 | flow.kickoff(...) 返回一个流会话 |
| 异步流程 | flow.astream(...),或在 stream=True 时使用 await flow.kickoff_async(...) |
| 直接 LLM 调用 | llm.stream_events(...) |
| 对话流程轮次 | flow.stream_turn(...) |
| 团队 | Crew(..., stream=True).kickoff(...) 返回 CrewStreamingOutput |
直接调用 llm.call(...) 仍然会返回最终组装好的 LLM 结果。当你想在 LLM 分块到达时逐块迭代时,请使用 llm.stream_events(...)。