Skip to main content

handleNetworkStream()

用于 AI SDK 兼容格式中流式网络执行的框架无关处理器。当你需要在 Hono 或 Mastra 自有的 apiRoutes 功能之外处理网络流时,可以直接使用此函数。

🌐 Framework-agnostic handler for streaming network execution in AI SDK-compatible format. Use this function directly when you need to handle network streaming outside Hono or Mastra's own apiRoutes feature.

handleNetworkStream() 返回一个 ReadableStream,你可以用 createUIMessageStreamResponse() 封装它。

如果你想在 Mastra 服务器内创建网络路由,请使用 networkRoute()

🌐 Use networkRoute() if you want to create a network route inside a Mastra server.

使用示例
Direct link to 使用示例

🌐 Usage example

Next.js 应用路由示例:

🌐 Next.js App Router example:

app/api/network/route.ts
import { handleNetworkStream } from '@mastra/ai-sdk';
import { createUIMessageStreamResponse } from 'ai';
import { mastra } from '@/src/mastra';

export async function POST(req: Request) {
const params = await req.json();
const stream = await handleNetworkStream({
mastra,
agentId: 'routingAgent',
params,
});
return createUIMessageStreamResponse({ stream });
}

参数
Direct link to 参数

🌐 Parameters

mastra:

Mastra
The Mastra instance to use for agent lookup and execution.

agentId:

string
The ID of the routing agent to execute as a network.

params:

NetworkStreamHandlerParams
The request parameters containing messages and execution options. Includes `messages` (required) and any AgentExecutionOptions like `memory`, `maxSteps`, `runId`, etc.

defaultOptions?:

AgentExecutionOptions
Default options passed to agent execution. These are merged with params, with params taking precedence.