Skip to main content

networkRoute()

为使用 AI SDK 格式的流式网络执行创建网络路由处理程序。此函数会注册一个 HTTP POST 端点,接收消息,执行代理网络,并以 AI SDK 兼容的格式将响应流回客户端。代理网络允许路由代理将任务委派给其他代理。你必须在 自定义 API 路由 中使用它。

🌐 Creates a network route handler for streaming network execution using the AI SDK format. This function registers an HTTP POST endpoint that accepts messages, executes an agent network, and streams the response back to the client in AI SDK-compatible format. Agent networks allow a routing agent to delegate tasks to other agents. You have to use it inside a custom API route.

如果你需要一个与框架无关的处理器,请使用 handleNetworkStream()

🌐 Use handleNetworkStream() if you need a framework-agnostic handler.

使用示例
Direct link to 使用示例

🌐 Usage example

此示例演示了如何在 /network 端点设置使用 ID 为 weatherAgent 的代理的网络路由。

🌐 This example shows how to set up a network route at the /network endpoint that uses an agent with the ID weatherAgent.

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { networkRoute } from "@mastra/ai-sdk";

export const mastra = new Mastra({
server: {
apiRoutes: [
networkRoute({
path: "/network",
agent: "weatherAgent",
}),
],
},
});

你还可以基于 agentId 使用动态代理路由。URL /network/weatherAgent 将解析为 ID 为 weatherAgent 的代理。

🌐 You can also use dynamic agent routing based on an agentId. The URL /network/weatherAgent will resolve to the agent with the ID weatherAgent.

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { networkRoute } from "@mastra/ai-sdk";

export const mastra = new Mastra({
server: {
apiRoutes: [
networkRoute({
path: "/network/:agentId",
}),
],
},
});

参数
Direct link to 参数

🌐 Parameters

path:

string
= '/network/:agentId'
The route path (e.g., `/network` or `/network/:agentId`). Include `:agentId` for dynamic agent routing.

agent?:

string
The ID of the routing agent to use for this network route. Required if the path doesn't include `:agentId`.

defaultOptions?:

AgentExecutionOptions
Default options passed to agent execution. These can include instructions, memory configuration, maxSteps, and other execution settings.

附加配置
Direct link to 附加配置

🌐 Additional configuration

你可以使用 prepareSendMessagesRequest 来自定义发送到网络路由的请求,例如传递额外的配置给代理:

🌐 You can use prepareSendMessagesRequest to customize the request sent to the network route, for example to pass additional configuration to the agent:

const { error, status, sendMessage, messages, regenerate, stop } = useChat({
transport: new DefaultChatTransport({
api: "http://localhost:4111/network",
prepareSendMessagesRequest({ messages }) {
return {
body: {
messages,
// Pass memory config
memory: {
thread: "user-1",
resource: "user-1",
},
},
};
},
}),
});