File size: 1,404 Bytes
1047ad5
 
 
 
 
 
f36b84a
1047ad5
 
 
 
f36b84a
1047ad5
 
f36b84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1047ad5
 
f36b84a
1047ad5
 
 
 
f36b84a
1047ad5
 
 
 
f36b84a
1047ad5
 
 
 
 
f36b84a
 
 
 
 
1047ad5
2ada8c0
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"

from dotenv import load_dotenv
load_dotenv()

from fastapi import FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from chatbot import generate_response

# ================= APP =================
app = FastAPI(title="Aaple Sarkar Chatbot API")

# ================= AUTH =================
def verify_api_key(x_api_key: str = Header(None)):
    expected_key = os.getenv("CHATBOT_API_KEY")

    if not expected_key:
        raise HTTPException(
            status_code=500,
            detail="Server misconfiguration"
        )

    if x_api_key != expected_key:
        raise HTTPException(
            status_code=401,
            detail="Unauthorized"
        )

# ================= CORS =================
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # restrict later if needed
    allow_methods=["*"],
    allow_headers=["*"],
)

# ================= SCHEMAS =================
class ChatRequest(BaseModel):
    query: str
    language: str = "en"

# ================= ROUTES =================
@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/chat")
def chat(
    req: ChatRequest,
    x_api_key: str = Header(None)
):
    verify_api_key(x_api_key)
    answer = generate_response(req.query, req.language)
    return {"answer": answer}