Spaces:
Sleeping
Sleeping
File size: 1,103 Bytes
2f4e610 540f1c5 2f4e610 453889e 540f1c5 2f4e610 540f1c5 2f4e610 540f1c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from huggingface_hub import InferenceClient
import os
HF_TOKEN = os.getenv("HF_TOKEN")
MODEL_ID = "google/gemma-2b-it"
client = InferenceClient(token=HF_TOKEN)
app = FastAPI()
# Allow CORS for all origins (for development and Netlify)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # For production, specify frontend domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ChatRequest(BaseModel):
message: str
@app.get("/")
def root():
return {"message": "Gemma Chat API is running π. Use POST /chat to send messages."}
@app.post("/chat")
async def chat(req: ChatRequest):
try:
messages = [{"role": "user", "content": req.message}]
response = client.chat_completion(
model=MODEL_ID,
messages=messages,
temperature=0.7,
)
return {"response": response.choices[0].message.content}
except Exception as e:
return {"error": str(e)} |