Skip to content

Commit 8724386

Browse files
authored
Merge pull request #6 from ssdeanx/develop
feat: implement chat API with agent streaming capabilities
2 parents cefa8f1 + 534946f commit 8724386

2 files changed

Lines changed: 65 additions & 1 deletion

File tree

app/api/chat/r.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { mastra } from "@/src/mastra";
2+
import { createAgentStreamResponse } from "@/lib/client-stream-to-ai-sdk";
3+
import type { UIMessage } from "ai";
4+
5+
export const maxDuration = 60;
6+
7+
interface ChatRequestBody {
8+
messages: UIMessage[];
9+
agentId?: string;
10+
threadId?: string;
11+
resourceId?: string;
12+
memory?: {
13+
thread?: string | { id: string; resourceId?: string };
14+
resource?: string;
15+
options?: {
16+
lastMessages?: number;
17+
semanticRecall?: boolean;
18+
workingMemory?: { enabled?: boolean };
19+
};
20+
};
21+
maxSteps?: number;
22+
}
23+
24+
export async function POST(req: Request) {
25+
const body: ChatRequestBody = await req.json();
26+
27+
// Get available agents dynamically from mastra
28+
const agentsMap = await mastra.getAgents();
29+
const availableAgents = Object.keys(agentsMap);
30+
31+
// Use first available agent if none specified
32+
const agentId = body.agentId || availableAgents[0];
33+
34+
if (!agentId || !availableAgents.includes(agentId)) {
35+
return Response.json(
36+
{ error: `Invalid or missing agentId. Available: ${availableAgents.join(", ")}` },
37+
{ status: 400 }
38+
);
39+
}
40+
41+
if (!body.messages?.length) {
42+
return Response.json({ error: "messages required" }, { status: 400 });
43+
}
44+
45+
try {
46+
return await createAgentStreamResponse(mastra as Parameters<typeof createAgentStreamResponse>[0], agentId, body.messages, {
47+
threadId: body.threadId,
48+
resourceId: body.resourceId,
49+
memory: body.memory,
50+
maxSteps: body.maxSteps ?? 50,
51+
});
52+
} catch (error) {
53+
return Response.json(
54+
{ error: error instanceof Error ? error.message : "Stream failed" },
55+
{ status: 500 }
56+
);
57+
}
58+
}
59+
60+
export async function GET() {
61+
const agentsMap = await mastra.getAgents();
62+
const availableAgents = Object.keys(agentsMap);
63+
return Response.json({ agents: availableAgents, count: availableAgents.length });
64+
}

lib/client-stream-to-ai-sdk.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ async function* asyncIterableFromReadableStream<T>(
5050
/**
5151
* Creates a streaming Response for Next.js API routes using server-side Mastra agent.
5252
*
53-
* IMPORTANT: This should be used in API routes with the SERVER-SIDE mastra instance,
53+
* IMPORTANT: This should be used in API 5stra instance,
5454
* not the client SDK. The client SDK (MastraClient) is for frontend use only.
5555
*
5656
* @example

0 commit comments

Comments
 (0)