UNPKG

@mastra/ai-sdk

Version:

Adds custom API routes to be compatible with the AI SDK UI parts

139 lines (136 loc) 3.86 kB
'use strict'; var server = require('@mastra/core/server'); // src/index.ts function chatRoute({ path = "/chat/:agentId", agent, defaultOptions }) { if (!agent && !path.includes("/:agentId")) { throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly"); } return server.registerApiRoute(path, { method: "POST", openapi: { summary: "Chat with an agent", description: "Send messages to an agent and stream the response in the AI SDK format", tags: ["ai-sdk"], parameters: [ { name: "agentId", in: "path", required: true, description: "The ID of the agent to chat with", schema: { type: "string" } } ], requestBody: { required: true, content: { "application/json": { schema: { type: "object", properties: { messages: { type: "array", description: "Array of messages in the conversation", items: { type: "object", properties: { role: { type: "string", enum: ["user", "assistant", "system"], description: "The role of the message sender" }, content: { type: "string", description: "The content of the message" } }, required: ["role", "content"] } } }, required: ["messages"] } } } }, responses: { "200": { description: "Streaming response from the agent", content: { "text/plain": { schema: { type: "string", description: "Server-sent events stream containing the agent response" } } } }, "400": { description: "Bad request - invalid input", content: { "application/json": { schema: { type: "object", properties: { error: { type: "string" } } } } } }, "404": { description: "Agent not found", content: { "application/json": { schema: { type: "object", properties: { error: { type: "string" } } } } } } } }, handler: async (c) => { const { messages, ...rest } = await c.req.json(); const mastra = c.get("mastra"); let agentToUse = agent; if (!agent) { const agentId = c.req.param("agentId"); agentToUse = agentId; } if (c.req.param("agentId") && agent) { mastra.getLogger()?.warn( `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.` ); } if (!agentToUse) { throw new Error("Agent ID is required"); } const agentObj = mastra.getAgent(agentToUse); if (!agentObj) { throw new Error(`Agent ${agentToUse} not found`); } const result = await agentObj.streamVNext(messages, { ...defaultOptions, ...rest, format: "aisdk" }); return result.toUIMessageStreamResponse(); } }); } exports.chatRoute = chatRoute; //# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map