Skip to main content

chatRoute()

为使用 AI SDK 格式流式传输代理对话创建聊天路由处理程序。此函数注册一个 HTTP POST 端点,该端点接收消息、执行代理,并以 AI SDK 兼容的格式将响应流式传输回客户端。你必须在自定义 API 路由中使用它。

🌐 Creates a chat route handler for streaming agent conversations using the AI SDK format. This function registers an HTTP POST endpoint that accepts messages, executes an agent, and streams the response back to the client in AI SDK-compatible format. You have to use it inside a custom API route.

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

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

使用示例
Direct link to 使用示例

🌐 Usage example

此示例演示了如何在 /chat 端点设置聊天路由,该路由使用 ID 为 weatherAgent 的代理。

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

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

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

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

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

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

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

参数
Direct link to 参数

🌐 Parameters

path:

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

agent?:

string
The ID of the agent to use for this chat 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.

sendStart?:

boolean
= true
Whether to send start events in the stream.

sendFinish?:

boolean
= true
Whether to send finish events in the stream.

sendReasoning?:

boolean
= false
Whether to include reasoning steps in the stream.

sendSources?:

boolean
= false
Whether to include source citations in the stream.

附加配置
Direct link to 附加配置

🌐 Additional configuration

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

🌐 You can use prepareSendMessagesRequest to customize the request sent to the chat 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/chat",
prepareSendMessagesRequest({ messages }) {
return {
body: {
messages,
// Pass memory config
memory: {
thread: "user-1",
resource: "user-1",
},
},
};
},
}),
});