Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import requests | |
| import os | |
| app = FastAPI() | |
| # --- Gemini API key --- | |
| GEMINI_API_KEY = "AIzaSyApC_u1SScesLRbTfdz5lEcQExDaX-5IwQ" # Replace this with your real key | |
| GEMINI_URL = ( | |
| "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" | |
| ) | |
| # --- Static prompt --- | |
| STATIC_INSTRUCTION = ( | |
| "Reply with a short, well-written summary in 2 to 3 sentences. " | |
| "Be clear and concise. Avoid unnecessary explanations." | |
| ) | |
| # --- Input schema --- | |
| class ChatRequest(BaseModel): | |
| query: str | |
| # --- Output schema (optional) --- | |
| class ChatResponse(BaseModel): | |
| reply: str | |
| # --- Endpoint --- | |
| def chat(req: ChatRequest): | |
| try: | |
| # Combine prompt and query as a single user message | |
| full_prompt = f"{STATIC_INSTRUCTION}\n\nUser question: {req.query}" | |
| contents = [ | |
| {"role": "user", "parts": [{"text": full_prompt}]} | |
| ] | |
| response = requests.post( | |
| GEMINI_URL, | |
| headers={ | |
| "Content-Type": "application/json", | |
| "x-goog-api-key": GEMINI_API_KEY | |
| }, | |
| json={"contents": contents} | |
| ) | |
| response.raise_for_status() # raise exception if status != 200 | |
| data = response.json() | |
| reply = ( | |
| data.get("candidates", [{}])[0] | |
| .get("content", {}).get("parts", [{}])[0] | |
| .get("text", "No reply") | |
| ) | |
| return {"reply": reply.strip()} | |
| except Exception as e: | |
| return {"reply": f"Error: {e}"} | |