チャットAPIの実装
🌐 チャット API の実装
このレッスンでは、フロントエンドからAI Agentを呼び出すためのAPIエンドポイントを実装します。
このAPIはユーザーのメッセージを受け取り、Section 4で作成したAI Agentに渡しレスポンスを返します。
📝 実装するファイル
src/app/api/chat/route.tsファイルを作成し、以下のコードを記述します。
まず、ファイルを作成します:
cd jpyc-ai-agent
mkdir -p src/app/api/chat
touch src/app/api/chat/route.ts
以下のコードを記述します:
import { jpycAgent } from "@/lib/mastra/agent";
import type { NextRequest } from "next/server";
/**
* AI AgentのAPIを呼び出すエンドポイント
* @param req
* @returns
*/
export async function POST(req: NextRequest) {
try {
// リクエストパラメータからメッセージ、会話ID、プロフィール、友達リストを取得
const { message, conversationId, profile, friends } = await req.json();
if (!message) {
return new Response(
JSON.stringify({ success: false, error: "Message is required" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// プロフィールと友達リストをコンテキストとして追加
let contextMessage = message;
if (profile || (friends && friends.length > 0)) {
let context = "\n\n[ユーザー情報]\n";
if (profile) {
context += `- 自分の名前: ${profile.name}\n`;
context += `- 自分のアドレス: ${profile.address}\n`;
}
if (friends && friends.length > 0) {
context += "\n[友達リスト]\n";
for (const friend of friends) {
context += `- ${friend.name}: ${friend.address}\n`;
}
}
contextMessage = message + context;
}
// Mastraで定義したJPYC AI Agentの機能を呼び出す
const response = await jpycAgent.generate(contextMessage, {
...(conversationId && { conversationId }),
});
console.log("Full generate response:", JSON.stringify(response, null, 2));
console.log("Generate response summary:", {
text: response.text,
textLength: response.text?.length,
object: response.object,
steps: response.steps?.length,
toolResults: response.toolResults?.length,
});
// レスポンステキストを返す
return new Response(
response.text || "エージェントからの応答がありませんでした",
{
headers: {
"Content-Type": "text/plain; charset=utf-8",
},
},
);
} catch (error) {
console.error("Chat API Error:", error);
return new Response(
JSON.stringify({
success: false,
error:
error instanceof Error
? error.message
: "An error occurred while processing your request",
}),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
}
💡 コードの解説
このファイルは、Next.js 15のApp Router API Routeとして実装されています。
主要なポイントを見ていきましょう。
1. POSTメソッドの定義
export async function POST(req: NextRequest) {
// 処理
}
Next.js 15のApp Routerでは、APIルートをroute.tsファイルで定義し、HTTPメソッドごとに関数をエクスポートします。