Spaces:
Sleeping
Sleeping
| # main.py | |
| import os | |
| import asyncio | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from fastapi.middleware.cors import CORSMiddleware | |
| # Import agent handler | |
| from agent import run_agent_query | |
| app = FastAPI(title="CFO Bot - Agent API") | |
| # --------------------------------------------------------- | |
| # CORS (adjust for production) | |
| # --------------------------------------------------------- | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # replace with your frontend domain | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --------------------------------------------------------- | |
| # Request / Response Models | |
| # --------------------------------------------------------- | |
| class QueryRequest(BaseModel): | |
| query: str | |
| thread_id: str # REQUIRED — not optional | |
| class QueryResponse(BaseModel): | |
| output: str | |
| # --------------------------------------------------------- | |
| # Health check | |
| # --------------------------------------------------------- | |
| def root(): | |
| return {"status": "CFO Bot API running", "version": "1.0.0"} | |
| # --------------------------------------------------------- | |
| # Query Route | |
| # --------------------------------------------------------- | |
| async def query_endpoint(req: QueryRequest): | |
| # Validate query | |
| if not req.query or not req.query.strip(): | |
| raise HTTPException(status_code=400, detail="Query cannot be empty.") | |
| # Validate thread_id | |
| if not req.thread_id or not req.thread_id.strip(): | |
| raise HTTPException(status_code=400, detail="thread_id is required.") | |
| try: | |
| # Run agent — NO DEFAULT thread_id | |
| result = await run_agent_query( | |
| req.query, | |
| thread_id=req.thread_id | |
| ) | |
| print(req.query) | |
| except Exception as exc: | |
| raise HTTPException(status_code=500, detail=f"Agent failed: {str(exc)}") | |
| # Extract output properly | |
| final_output = ( | |
| getattr(result, "final_output", None) | |
| or (result.get("final_output") if isinstance(result, dict) else None) | |
| ) | |
| if not final_output: | |
| final_output = "No response generated." | |
| return QueryResponse(output=final_output) | |