diff --git a/app/[docs_id]/chatForm.tsx b/app/[docs_id]/chatForm.tsx index 14dc441..0b86077 100644 --- a/app/[docs_id]/chatForm.tsx +++ b/app/[docs_id]/chatForm.tsx @@ -1,112 +1,160 @@ "use client"; -import { hello } from "./chatServer"; +import { useState, FormEvent } from "react"; -export function ChatForm() {return ( +interface ChatApiResponse { + response: string; +} + +export function ChatForm() { + const [inputValue, setInputValue] = useState(""); + const [response, setResponse] = useState(""); + const [isLoading, setIsLoading] = useState(false); + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault(); + setIsLoading(true); + setResponse(""); + + try { + const res = await fetch("/api/chat", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ message: inputValue }), + }); + + const data = (await res.json()) as ChatApiResponse; + if (!res.ok) { + throw new Error(data.response || "エラーが発生しました。"); + } + setResponse(data.response); + } catch (error: unknown) { + if (error instanceof Error) { + setResponse(`エラー: ${error.message}`); + } else { + setResponse(`エラー: ${String(error)}`); + } + } finally { + setIsLoading(false); + } + }; + return ( <> - + `} -
+
- +
-
-
- -
-
- -
+
+
+ +
-
+ + {response &&
{response}
} -)} \ No newline at end of file + ); +} diff --git a/app/chat/route.js b/app/api/chat/route.js similarity index 86% rename from app/chat/route.js rename to app/api/chat/route.js index 7d2d89a..64127c9 100644 --- a/app/chat/route.js +++ b/app/api/chat/route.js @@ -1,13 +1,11 @@ -import { NextResponse } from 'next/server'; -import { GoogleGenerativeAI } from '@google/generative-ai'; - +import { NextResponse } from "next/server"; +import { GoogleGenerativeAI } from "@google/generative-ai"; const genAI = new GoogleGenerativeAI(process.env.API_KEY); export async function POST(request) { const { message } = await request.json(); - if (!message) { return NextResponse.json( { error: "メッセージがありません。" }, @@ -17,19 +15,17 @@ export async function POST(request) { try { const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); - + const result = await model.generateContent(message); const response = result.response; const text = response.text(); return NextResponse.json({ response: text }); - } catch (e) { - console.error("Error:", e); return NextResponse.json( { response: "エラーが発生しました。" }, { status: 500 } ); } -} \ No newline at end of file +}