chatRoute()
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.
Use handleChatStream() if you need a framework-agnostic handler.
Usage exampleDirect link to Usage example
This example shows how to set up a chat route at the /chat endpoint that uses an agent with the ID weatherAgent.
import { Mastra } from "@mastra/core";
import { chatRoute } from "@mastra/ai-sdk";
export const mastra = new Mastra({
server: {
apiRoutes: [
chatRoute({
path: "/chat",
agent: "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.
import { Mastra } from "@mastra/core";
import { chatRoute } from "@mastra/ai-sdk";
export const mastra = new Mastra({
server: {
apiRoutes: [
chatRoute({
path: "/chat/:agentId",
}),
],
},
});
ParametersDirect link to Parameters
path:
agent?:
defaultOptions?:
sendStart?:
sendFinish?:
sendReasoning?:
sendSources?:
Additional configurationDirect link to Additional configuration
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",
},
},
};
},
}),
});