backend / main.py
riosiahaan's picture
Refactor model
3851c17
Raw History Blame Contribute Delete
4.83 kB
import os
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage
from .agent.graph import app as agent_app
from .agent.rate_limit import extract_rate_limit_headers, update_last_rate_limit, get_last_rate_limit
import time
load_dotenv()
app = FastAPI(title="BPS Sumut RAG Chatbot (Agent)")
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"], # Important: expose custom headers to frontend
)
# Mount static directories for charts and exports
os.makedirs("static/charts", exist_ok=True)
os.makedirs("static/exports", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
class ChatRequest(BaseModel):
message: str
conversation_id: str = None
class ChatResponse(BaseModel):
response: str
conversation_id: str = None
rate_limit: dict = None
processing_time: float = None
@app.get("/health")
async def health_check():
"""Health check endpoint with rate limit info."""
rate_limit = get_last_rate_limit()
return {
"status": "ok",
"rate_limit": rate_limit.to_dict() if rate_limit else None
}
@app.get("/api/rate-limit")
async def get_rate_limit_info():
"""Get current rate limit information."""
rate_limit = get_last_rate_limit()
if rate_limit:
return rate_limit.to_dict()
else:
return {
"message": "No rate limit data available yet. Make a chat request first."
}
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""
Chat endpoint with rate limit monitoring.
Returns response along with rate limit information for UI display.
"""
start_time = time.time()
try:
inputs = {"messages": [HumanMessage(content=request.message)]}
# Run the graph with recursion limit config and thread_id for conversation memory
thread_id = request.conversation_id or "default_thread"
config = {"configurable": {"thread_id": thread_id}, "recursion_limit": 50}
result = agent_app.invoke(inputs, config=config)
last_message = result["messages"][-1]
# Try to extract rate limit from LLM response metadata
# Note: LangChain might not expose raw HTTP headers directly
# This is a placeholder - actual implementation depends on LangChain version
rate_limit_info = None
# Check if we have response metadata
if hasattr(last_message, 'response_metadata'):
metadata = last_message.response_metadata
# Groq might include headers in metadata
if 'headers' in metadata:
rate_limit_data = extract_rate_limit_headers(metadata['headers'])
update_last_rate_limit(rate_limit_data)
rate_limit_info = rate_limit_data.to_dict()
# If no rate limit from response, use last known
if not rate_limit_info:
last_rate_limit = get_last_rate_limit()
if last_rate_limit:
rate_limit_info = last_rate_limit.to_dict()
processing_time = time.time() - start_time
return ChatResponse(
response=last_message.content,
conversation_id=request.conversation_id,
rate_limit=rate_limit_info,
processing_time=round(processing_time, 2)
)
except Exception as e:
error_msg = str(e)
# Check if it's a rate limit error
if "429" in error_msg or "rate limit" in error_msg.lower():
return JSONResponse(
status_code=429,
content={
"error": "Rate limit exceeded",
"message": "Terlalu banyak permintaan. Silakan tunggu beberapa saat.",
"retry_after": 60 # Default retry time
}
)
# Other errors
return JSONResponse(
status_code=500,
content={
"error": "Internal server error",
"message": f"Terjadi kesalahan: {error_msg}"
}
)
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""Middleware to add processing time to response headers."""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(round(process_time, 3))
return response