流概览
🌐 Streaming Overview
Mastra 支持来自代理和工作流程的实时增量响应,允许用户在生成输出时即可查看,而无需等待完成。这对于聊天、长篇内容、多步骤工作流程或任何需要即时反馈的场景都很有用。
🌐 Mastra supports real-time, incremental responses from agents and workflows, allowing users to see output as it’s generated instead of waiting for completion. This is useful for chat, long-form content, multi-step workflows, or any scenario where immediate feedback matters.
入门Direct link to 入门
🌐 Getting started
Mastra 的流 API 会根据你的模型版本进行调整:
🌐 Mastra's streaming API adapts based on your model version:
.stream():对于 V2 模型,支持 AI SDK v5 及更高版本(LanguageModelV2)。.streamLegacy():对于 V1 模型,支持 AI SDK v4(LanguageModelV1)。
使用代理进行流播放Direct link to 使用代理进行流播放
🌐 Streaming with agents
对于简单的提示,你可以传递一个字符串;当提供多个上下文时,可以传递一个字符串数组;或者传递一个包含 role 和 content 的消息对象数组,以精确控制角色和对话流程。
🌐 You can pass a single string for simple prompts, an array of strings when providing multiple pieces of context, or an array of message objects with role and content for precise control over roles and conversational flows.
使用 Agent.stream()Direct link to using-agentstream
🌐 Using Agent.stream()
textStream 会在生成响应时将其分成块,从而允许输出逐步流式传输,而不是一次性全部到达。使用 for await 循环迭代 textStream,以检查每个流块。
🌐 A textStream breaks the response into chunks as it's generated, allowing output to stream progressively instead of arriving all at once. Iterate over the textStream using a for await loop to inspect each stream chunk.
const testAgent = mastra.getAgent("testAgent");
const stream = await testAgent.stream([
{ role: "user", content: "Help me organize my day" },
]);
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}
访问 Agent.stream() 获取更多信息。
🌐 Visit Agent.stream() for more information.
Agent.stream() 的输出Direct link to output-from-agentstream
🌐 Output from Agent.stream()
输出流显示代理生成的响应。
🌐 The output streams the generated response from the agent.
Of course!
To help you organize your day effectively, I need a bit more information.
Here are some questions to consider:
...
代理流属性Direct link to 代理流属性
🌐 Agent stream properties
代理流提供对各种响应属性的访问:
🌐 An agent stream provides access to various response properties:
stream.textStream:一个可读流,用于输出文本块。stream.text:返回完整文本响应的 Promise。stream.finishReason:代理停止流式传输的原因。stream.usage:令牌使用信息。
AI SDK v5+ 兼容性Direct link to AI SDK v5+ 兼容性
🌐 AI SDK v5+ Compatibility
AI SDK v5(及更高版本)使用 LanguageModelV2 作为模型提供商。如果你收到使用 AI SDK v4 模型的错误,则需要将你的模型包升级到下一个主版本。
🌐 AI SDK v5 (and later) uses LanguageModelV2 for the model providers. If you are getting an error that you are using an AI SDK v4 model you will need to upgrade your model package to the next major version.
要与 AI SDK v5+ 集成,使用来自 @mastra/ai-sdk 的 toAISdkV5Stream() 工具将 Mastra 流转换为 AI SDK 兼容格式:
🌐 For integration with AI SDK v5+, use the toAISdkV5Stream() utility from @mastra/ai-sdk to convert Mastra streams to AI SDK-compatible format:
import { toAISdkV5Stream } from "@mastra/ai-sdk";
const testAgent = mastra.getAgent("testAgent");
const stream = await testAgent.stream([
{ role: "user", content: "Help me organize my day" },
]);
// Convert to AI SDK v5+ compatible stream
const aiSDKStream = toAISdkV5Stream(stream, { from: "agent" });
// Use with AI SDK v5+ methods
要将消息转换为 AI SDK v5+ 格式,请使用来自 @mastra/ai-sdk/ui 的 toAISdkV5Messages() 工具:
🌐 For converting messages to AI SDK v5+ format, use the toAISdkV5Messages() utility from @mastra/ai-sdk/ui:
import { toAISdkV5Messages } from "@mastra/ai-sdk/ui";
const messages = [{ role: "user", content: "Hello" }];
const aiSDKMessages = toAISdkV5Messages(messages);
使用 Agent.network()Direct link to using-agentnetwork
🌐 Using Agent.network()
network() 方法通过执行一个网络循环,实现多智能体协作,使多个智能体能够共同处理复杂任务。路由智能体根据对话上下文,将任务分配给合适的子智能体、工作流程和工具。
🌐 The network() method enables multi-agent collaboration by executing a network loop where multiple agents can work together to handle complex tasks. The routing agent delegates tasks to appropriate sub-agents, workflows, and tools based on the conversation context.
注意:此方法是实验性的,需要在代理上配置内存。
const testAgent = mastra.getAgent("testAgent");
const networkStream = await testAgent.network("Help me organize my day");
for await (const chunk of networkStream) {
console.log(chunk);
}
访问 Agent.network() 以获取更多信息。
🌐 Visit Agent.network() for more information.
网络流属性Direct link to 网络流属性
🌐 Network stream properties
网络流提供对执行信息的访问:
🌐 The network stream provides access to execution information:
networkStream.status:返回工作流执行状态的 PromisenetworkStream.result:返回完整执行结果的 PromisenetworkStream.usage:返回令牌使用信息的 Promise
const testAgent = mastra.getAgent("testAgent");
const networkStream = await testAgent.network(
"Research dolphins then write a report",
);
for await (const chunk of networkStream) {
console.log(chunk);
}
console.log("Final status:", await networkStream.status);
console.log("Final result:", await networkStream.result);
console.log("Token usage:", await networkStream.usage);
使用工作流进行流Direct link to 使用工作流进行流
🌐 Streaming with workflows
从工作流进行流式传输会返回描述运行生命周期的结构化事件序列,而不是增量的文本块。这种基于事件的格式使得在使用 .createRun() 创建运行后,可以实时跟踪和响应工作流的进度。
🌐 Streaming from a workflow returns a sequence of structured events describing the run lifecycle, rather than incremental text chunks. This event-based format makes it possible to track and respond to workflow progress in real time once a run is created using .createRun().
使用 Run.stream()Direct link to using-runstream
🌐 Using Run.stream()
stream() 方法直接返回一个 ReadableStream 的事件。
🌐 The stream() method returns a ReadableStream of events directly.
const run = await testWorkflow.createRun();
const stream = await run.stream({
inputData: {
value: "initial data",
},
});
for await (const chunk of stream) {
console.log(chunk);
}
访问 Run.stream() 了解更多信息。
🌐 Visit Run.stream() for more information.
Run.stream() 的输出Direct link to output-from-runstream
🌐 Output from Run.stream()
事件结构在顶层包含 runId 和 from,使得在不深入查看负载的情况下更容易识别和跟踪工作流运行。
🌐 The event structure includes runId and from at the top level, making it easier to identify and track workflow runs without digging into the payload.
{
type: 'workflow-start',
runId: '1eeaf01a-d2bf-4e3f-8d1b-027795ccd3df',
from: 'WORKFLOW',
payload: {
stepName: 'step-1',
args: { value: 'initial data' },
stepCallId: '8e15e618-be0e-4215-a5d6-08e58c152068',
startedAt: 1755121710066,
status: 'running'
}
}
工作流流属性Direct link to 工作流流属性
🌐 Workflow stream properties
工作流流提供对各种响应属性的访问:
🌐 A workflow stream provides access to various response properties:
stream.status:工作流运行的状态。stream.result:工作流运行的结果。stream.usage:工作流运行的总令牌使用量。
相关Direct link to 相关
🌐 Related