Shakeel401 commited on
Commit
67b9f40
·
verified ·
1 Parent(s): 9b0b8fe

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -0
main.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+ import os
3
+ import asyncio
4
+ from fastapi import FastAPI, HTTPException
5
+ from pydantic import BaseModel
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+
8
+ from agent import run_agent_query
9
+
10
+ app = FastAPI(title="CFO Bot - Agent API")
11
+
12
+ # Allow local dev; lock down in production
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"], # change to your frontend origin
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ class QueryRequest(BaseModel):
22
+ query: str
23
+ thread_id: str | None = None
24
+ max_steps: int | None = 4
25
+
26
+ class QueryResponse(BaseModel):
27
+ output: str
28
+ tool_calls: dict | None = None
29
+ session_id: str | None = None
30
+
31
+ @app.post("/query", response_model=QueryResponse)
32
+ async def query_endpoint(req: QueryRequest):
33
+ if not req.query or req.query.strip() == "":
34
+ raise HTTPException(status_code=400, detail="Query cannot be empty.")
35
+ # run agent
36
+ try:
37
+ result = await run_agent_query(req.query, thread_id=req.thread_id or "default", max_steps=req.max_steps or 4)
38
+ except Exception as e:
39
+ raise HTTPException(status_code=500, detail=f"Agent run failed: {e}")
40
+
41
+ # Extract useful fields from result, be resilient if SDK result shape differs
42
+ final_output = getattr(result, "final_output", None) or result.get("final_output") if isinstance(result, dict) else None
43
+ tool_calls = getattr(result, "tool_calls", None) or result.get("tool_calls") if isinstance(result, dict) else None
44
+
45
+ # Fallback: result may be an object with str() representation
46
+ if final_output is None:
47
+ try:
48
+ final_output = str(result)
49
+ except Exception:
50
+ final_output = "No output."
51
+
52
+ return QueryResponse(output=final_output, tool_calls=tool_calls, session_id=req.thread_id or "default")
53
+
54
+ # Run with: uvicorn main:app --host 0.0.0.0 --port 8080
55
+ if __name__ == "__main__":
56
+ import uvicorn
57
+ uvicorn.run("main:app", host="0.0.0.0", port=int(os.environ.get("PORT", 8080)), log_level="info")