Skip to content

Commit 43d5020

Browse files
committed
簡単なチャットAPIを実装
1 parent a982136 commit 43d5020

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

chat.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# .env ファイルを作成して環境変数を設定してください
2+
# `uvicorn chat:app --reload --port 8000` でサーバーを起動できます
3+
# pip install fastapi uvicorn python-dotenv google-generativeai
4+
import os
5+
from fastapi import FastAPI
6+
from fastapi.middleware.cors import CORSMiddleware
7+
from pydantic import BaseModel
8+
import google.generativeai as genai
9+
from dotenv import load_dotenv
10+
11+
load_dotenv()
12+
13+
app = FastAPI()
14+
15+
# CORS設定
16+
origins = [
17+
"http://localhost:3000",
18+
]
19+
app.add_middleware(
20+
CORSMiddleware,
21+
allow_origins=origins,
22+
allow_credentials=True,
23+
allow_methods=["*"],
24+
allow_headers=["*"],
25+
)
26+
27+
try:
28+
genai.configure(api_key=os.getenv("API_KEY"))
29+
except Exception as e:
30+
print(f"APIキーの設定に失敗しました: {e}")
31+
32+
33+
# フロントエンドから受け取るデータ構造を定義
34+
class ChatMessage(BaseModel):
35+
message: str
36+
37+
# APIエンドポイント
38+
@app.post("/api/chat")
39+
async def create_chat(chat_message: ChatMessage):
40+
"""
41+
ユーザーからのメッセージを受け取り、Gemini 1.5 Flashからの応答を返す
42+
"""
43+
try:
44+
model = genai.GenerativeModel('gemini-1.5-flash')
45+
response = model.generate_content(chat_message.message)
46+
return {"response": response.text}
47+
48+
except Exception as e:
49+
print(f"Error: {e}")
50+
return {"response": "エラーが発生しました。"}

0 commit comments

Comments
 (0)