Skip to main content

代理网络

🌐 Agent Networks

Mastra 中的代理网络协调多个代理、工作流程和工具,以处理那些起初并不明确规定但可以从用户的消息或上下文推断出来的任务。一个顶层 路由代理(一个配置有其他代理、工作流程和工具的 Mastra 代理)使用大型语言模型(LLM)来解释请求,并决定调用哪些原语(子代理、工作流程或工具)、调用顺序以及使用哪些数据。

🌐 Agent networks in Mastra coordinate multiple agents, workflows, and tools to handle tasks that aren't clearly defined upfront but can be inferred from the user's message or context. A top-level routing agent (a Mastra agent with other agents, workflows, and tools configured) uses an LLM to interpret the request and decide which primitives (sub-agents, workflows, or tools) to call, in what order, and with what data.

何时使用网络
Direct link to 何时使用网络

🌐 When to use networks

将网络用于需要跨多个原语进行协调的复杂任务。与遵循预定义顺序的工作流不同,网络依赖大语言模型的推断来解释请求并决定要执行的操作。

🌐 Use networks for complex tasks that require coordination across multiple primitives. Unlike workflows, which follow a predefined sequence, networks rely on LLM reasoning to interpret the request and decide what to run.

核心原则
Direct link to 核心原则

🌐 Core principles

Mastra代理网络的运作基于以下原则:

🌐 Mastra agent networks operate using these principles:

  • 使用 .network() 时需要内存,内存用于存储任务历史并确定任务何时完成。
  • 原语是根据其描述进行选择的。清晰、具体的描述可以改善路由。对于工作流和工具,输入模式有助于在运行时确定正确的输入。
  • 如果多个原语功能重叠,代理会优先选择更具体的那个,并使用模式和描述的组合来决定执行哪一个。

建立代理网络
Direct link to 建立代理网络

🌐 Creating an agent network

代理网络是围绕一个顶层路由代理构建的,该代理将任务分配给其配置中定义的代理、工作流和工具。内存通过在路由代理上使用 memory 选项来配置,而 instructions 定义了代理的路由行为。

🌐 An agent network is built around a top-level routing agent that delegates tasks to agents, workflows, and tools defined in its configuration. Memory is configured on the routing agent using the memory option, and instructions define the agent's routing behavior.

src/mastra/agents/routing-agent.ts
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/libsql";

import { researchAgent } from "./research-agent";
import { writingAgent } from "./writing-agent";

import { cityWorkflow } from "../workflows/city-workflow";
import { weatherTool } from "../tools/weather-tool";

export const routingAgent = new Agent({
id: "routing-agent",
name: "Routing Agent",
instructions: `
You are a network of writers and researchers.
The user will ask you to research a topic.
Always respond with a complete report—no bullet points.
Write in full paragraphs, like a blog post.
Do not answer with incomplete or uncertain information.`,
model: "openai/gpt-5.1",
agents: {
researchAgent,
writingAgent,
},
workflows: {
cityWorkflow,
},
tools: {
weatherTool,
},
memory: new Memory({
storage: new LibSQLStore({
id: 'mastra-storage',
url: "file:../mastra.db",
}),
}),
});

为网络原语编写描述
Direct link to 为网络原语编写描述

🌐 Writing descriptions for network primitives

在配置 Mastra 代理网络时,每个原语(代理、工作流或工具)都需要有清晰的描述,以帮助路由代理决定使用哪一个。路由代理使用每个原语的描述和架构来确定其功能及使用方法。清晰的描述和明确定义的输入输出架构可以提高路由的准确性。

🌐 When configuring a Mastra agent network, each primitive (agent, workflow, or tool) needs a clear description to help the routing agent decide which to use. The routing agent uses each primitive's description and schema to determine what it does and how to use it. Clear descriptions and well-defined input and output schemas improve routing accuracy.

代理描述
Direct link to 代理描述

🌐 Agent descriptions

网络中的每个代理都应该包含一个清晰的 description,说明该代理的功能。

🌐 Each agent in a network should include a clear description that explains what the agent does.

src/mastra/agents/research-agent.ts
export const researchAgent = new Agent({
id: "research-agent",
name: "Research Agent",
description: `This agent gathers concise research insights in bullet-point form.
It's designed to extract key facts without generating full
responses or narrative content.`,
});
src/mastra/agents/writing-agent.ts
export const writingAgent = new Agent({
id: "writing-agent",
name: "Writing Agent",
description: `This agent turns researched material into well-structured
written content. It produces full-paragraph reports with no bullet points,
suitable for use in articles, summaries, or blog posts.`,
});

工作流程描述
Direct link to 工作流程描述

🌐 Workflow descriptions

网络中的工作流程应包括一个 description 来说明其目的,以及 inputSchemaoutputSchema 来描述预期的数据。

🌐 Workflows in a network should include a description to explain their purpose, along with inputSchema and outputSchema to describe the expected data.

src/mastra/workflows/city-workflow.ts
export const cityWorkflow = createWorkflow({
id: "city-workflow",
description: `This workflow handles city-specific research tasks.
It first gathers factual information about the city, then synthesizes
that research into a full written report. Use it when the user input
includes a city to be researched.`,
inputSchema: z.object({
city: z.string(),
}),
outputSchema: z.object({
text: z.string(),
}),
});

工具描述
Direct link to 工具描述

🌐 Tool descriptions

网络中的工具应包括一个 description 来说明它们的用途,以及 inputSchemaoutputSchema 来描述预期的数据。

🌐 Tools in a network should include a description to explain their purpose, along with inputSchema and outputSchema to describe the expected data.

src/mastra/tools/weather-tool.ts
export const weatherTool = createTool({
id: "weather-tool",
description: ` Retrieves current weather information using the wttr.in API.
Accepts a city or location name as input and returns a short weather summary.
Use this tool whenever up-to-date weather data is requested.
`,
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
weather: z.string(),
}),
});

调用代理网络
Direct link to 调用代理网络

🌐 Calling agent networks

使用 .network() 调用 Mastra 代理网络并发送用户消息。该方法会返回一个事件流,你可以迭代该流以跟踪执行进度并获取最终结果。

🌐 Call a Mastra agent network using .network() with a user message. The method returns a stream of events that you can iterate over to track execution progress and retrieve the final result.

代理示例
Direct link to 代理示例

🌐 Agent example

在此示例中,网络会解读消息,并将请求同时路由到 researchAgentwritingAgent 以生成完整的响应。

🌐 In this example, the network interprets the message and would route the request to both the researchAgent and writingAgent to generate a complete response.

const result = await routingAgent.network(
"Tell me three cool ways to use Mastra",
);

for await (const chunk of result) {
console.log(chunk.type);
if (chunk.type === "network-execution-event-step-finish") {
console.log(chunk.payload.result);
}
}

代理输出
Direct link to 代理输出

🌐 Agent output

在此请求期间会触发以下 chunk.type 事件:

🌐 The following chunk.type events are emitted during this request:

routing-agent-start
routing-agent-end
agent-execution-start
agent-execution-event-start
agent-execution-event-step-start
agent-execution-event-text-start
agent-execution-event-text-delta
agent-execution-event-text-end
agent-execution-event-step-finish
agent-execution-event-finish
agent-execution-end
network-execution-event-step-finish

工作流程示例
Direct link to 工作流程示例

🌐 Workflow example

在这个例子中,路由代理会识别消息中的城市名称并运行 cityWorkflow。工作流定义了调用 researchAgent 收集信息的步骤,然后调用 writingAgent 生成最终文本。

🌐 In this example, the routing agent recognizes the city name in the message and runs the cityWorkflow. The workflow defines steps that call the researchAgent to gather facts, then the writingAgent to generate the final text.

const result = await routingAgent.network(
"Tell me some historical facts about London",
);

for await (const chunk of result) {
console.log(chunk.type);
if (chunk.type === "network-execution-event-step-finish") {
console.log(chunk.payload.result);
}
}

工作流输出
Direct link to 工作流输出

🌐 Workflow output

在此请求期间会触发以下 chunk.type 事件:

🌐 The following chunk.type events are emitted during this request:

routing-agent-end
workflow-execution-start
workflow-execution-event-workflow-start
workflow-execution-event-workflow-step-start
workflow-execution-event-workflow-step-result
workflow-execution-event-workflow-finish
workflow-execution-end
routing-agent-start
network-execution-event-step-finish

工具示例
Direct link to 工具示例

🌐 Tool example

在此示例中,路由代理会跳过 researchAgentwritingAgentcityWorkflow,直接调用 weatherTool 来完成任务。

🌐 In this example, the routing agent skips the researchAgent, writingAgent, and cityWorkflow, and calls the weatherTool directly to complete the task.

const result = await routingAgent.network("What's the weather in London?");

for await (const chunk of result) {
console.log(chunk.type);
if (chunk.type === "network-execution-event-step-finish") {
console.log(chunk.payload.result);
}
}

工具输出
Direct link to 工具输出

🌐 Tool output

在此请求期间会触发以下 chunk.type 事件:

🌐 The following chunk.type events are emitted during this request:

routing-agent-start
routing-agent-end
tool-execution-start
tool-execution-end
network-execution-event-step-finish

结构化输出
Direct link to 结构化输出

🌐 Structured output

当你需要从网络获取经过打字和验证的结果时,请使用 structuredOutput 选项。网络完成任务后,它会生成与你的架构匹配的结构化响应。

🌐 When you need typed, validated results from a network, use the structuredOutput option. After the network completes its task, it generates a structured response matching your schema.

import { z } from "zod";

const resultSchema = z.object({
summary: z.string().describe("A brief summary of the findings"),
recommendations: z.array(z.string()).describe("List of recommendations"),
confidence: z.number().min(0).max(1).describe("Confidence score"),
});

const stream = await routingAgent.network("Research AI trends", {
structuredOutput: {
schema: resultSchema,
},
});

// Consume the stream
for await (const chunk of stream) {
if (chunk.type === "network-object") {
// Partial object during generation
console.log("Partial:", chunk.payload.object);
}
if (chunk.type === "network-object-result") {
// Final structured object
console.log("Final:", chunk.payload.object);
}
}

// Get the typed result
const result = await stream.object;
console.log(result?.summary);
console.log(result?.recommendations);
console.log(result?.confidence);

流式传输部分对象
Direct link to 流式传输部分对象

🌐 Streaming partial objects

在结构化输出生成过程中获取实时更新,请使用 objectStream

🌐 For real-time updates during structured output generation, use objectStream:

const stream = await routingAgent.network("Analyze market data", {
structuredOutput: { schema: resultSchema },
});

// Stream partial objects as they're generated
for await (const partial of stream.objectStream) {
console.log("Building result:", partial);
}

// Get the final typed result
const final = await stream.object;

🌐 Related