46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
import os
|
|
from dotenv import load_dotenv
|
|
from fastapi import FastAPI, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
import openai
|
|
import redis
|
|
|
|
AI_TOKEN = os.environ["AI_HANDLER_TOKEN"]
|
|
openai.api_key = os.environ["OPENAI_API_KEY"]
|
|
r = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379"))
|
|
|
|
class MessagePayload(BaseModel):
|
|
roomId: str
|
|
userId: str
|
|
eventId: str
|
|
serverTimestamp: int
|
|
content: str
|
|
|
|
app = FastAPI()
|
|
|
|
@app.post("/api/v1/message")
|
|
async def message(
|
|
payload: MessagePayload,
|
|
authorization: str = Header(None)
|
|
):
|
|
if authorization != f"Bearer {AI_TOKEN}":
|
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
|
|
# Idempotency: ignore duplicates
|
|
if r.get(payload.eventId):
|
|
return {"reply": r.get(payload.eventId).decode()}
|
|
|
|
# Build prompt (very simple example)
|
|
prompt = f"User {payload.userId} said: {payload.content}\nBot:"
|
|
resp = openai.Completion.create(
|
|
model="text-davinci-003",
|
|
prompt=prompt,
|
|
max_tokens=150
|
|
)
|
|
reply = resp.choices[0].text.strip()
|
|
|
|
# Cache reply for idempotency
|
|
r.set(payload.eventId, reply, ex=3600)
|
|
|
|
return {"reply": reply}
|