-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
257 lines (204 loc) · 8.05 KB
/
Copy pathmain.py
File metadata and controls
257 lines (204 loc) · 8.05 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import os
import time
import json
import logging
import asyncio
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from config import config
from schemas import ResearchRequest, ResearchResponse, HealthResponse, Source
from agent.agent import run_research
from cache import get_cached, set_cache, cache_stats, clear_cache
from database import (
connect_db, close_db,
save_research, get_history,
get_by_id, search_history,
delete_by_id
)
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting up...")
if not config.HF_TOKEN:
raise RuntimeError("HF_TOKEN not set")
await connect_db()
logger.info("Ready.")
yield
await close_db()
logger.info("Shut down.")
app = FastAPI(
title="Research Agent API",
description="Agentic AI that researches any topic and stores results in MongoDB.",
version=config.API_VERSION,
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.middleware("http")
async def log_requests(request: Request, call_next):
start = time.time()
response = await call_next(request)
duration = round(time.time() - start, 2)
logger.info(f"{request.method} {request.url.path} — {response.status_code} — {duration}s")
return response
# ── Frontend ──────────────────────────────────────────────
@app.get("/", include_in_schema=False)
async def serve_frontend():
return FileResponse("static/index.html")
# ── System ────────────────────────────────────────────────
@app.get("/health", response_model=HealthResponse, tags=["System"])
async def health():
return HealthResponse(
status="ok",
model=config.MODEL_ID,
version=config.API_VERSION,
database="mongodb"
)
@app.get("/cache/stats", tags=["System"])
async def get_cache_stats():
"""View cache usage stats."""
return cache_stats()
@app.delete("/cache", tags=["System"])
async def flush_cache():
"""Clear all cached results."""
count = clear_cache()
return {"cleared": count}
# ── Agent ─────────────────────────────────────────────────
@app.post("/research", response_model=ResearchResponse, tags=["Agent"])
async def research(request: ResearchRequest):
"""Run the research agent. Returns cached result if available."""
logger.info(f"Research: '{request.topic}' depth={request.depth}")
# Check cache first
cached = get_cached(request.topic, request.depth.value)
if cached:
logger.info(f"Cache hit for: '{request.topic}'")
try:
sources = [Source(**s) for s in cached.get("sources", [])]
except Exception:
sources = []
return ResearchResponse(
id=cached.get("id"),
topic=request.topic,
depth=request.depth.value,
summary=cached.get("summary", ""),
key_points=cached.get("key_points", []),
sources=sources,
follow_up_questions=cached.get("follow_up_questions", []),
warning=cached.get("warning"),
cached=True,
)
# Run agent
try:
result = run_research(topic=request.topic, depth=request.depth.value)
except Exception as e:
logger.error(f"Agent error: {e}")
raise HTTPException(status_code=500, detail=str(e))
if "error" in result:
raise HTTPException(status_code=500, detail=result["error"])
try:
sources = [Source(**s) for s in result.get("sources", [])]
except Exception:
sources = []
# Save to MongoDB
doc_id = await save_research(
topic=request.topic,
depth=request.depth.value,
result=result
)
logger.info(f"Saved to MongoDB: {doc_id}")
result["id"] = doc_id
set_cache(request.topic, request.depth.value, result)
return ResearchResponse(
id=doc_id,
topic=request.topic,
depth=request.depth.value,
summary=result.get("summary", ""),
key_points=result.get("key_points", []),
sources=sources,
follow_up_questions=result.get("follow_up_questions", []),
warning=result.get("warning"),
cached=False,
)
@app.post("/research/stream", tags=["Agent"])
async def research_stream(request: ResearchRequest):
"""Stream research progress as server-sent events."""
async def generate():
# Check cache
cached = get_cached(request.topic, request.depth.value)
if cached:
yield f"data: {json.dumps({'type': 'cache_hit', 'message': 'Returning cached result...'})}\n\n"
await asyncio.sleep(0.3)
yield f"data: {json.dumps({'type': 'done', 'result': cached})}\n\n"
return
# Stream progress steps
steps = [
"Initializing agent...",
"Searching the web for sources...",
"Reading and analyzing pages...",
"Synthesizing findings...",
"Formatting report...",
]
for i, step in enumerate(steps):
yield f"data: {json.dumps({'type': 'progress', 'step': i+1, 'total': len(steps), 'message': step})}\n\n"
await asyncio.sleep(0.5)
# Run agent in thread so it doesn't block
loop = asyncio.get_event_loop()
try:
result = await loop.run_in_executor(
None,
lambda: run_research(topic=request.topic, depth=request.depth.value)
)
except Exception as e:
yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
return
if "error" in result:
yield f"data: {json.dumps({'type': 'error', 'message': result['error']})}\n\n"
return
# Save to MongoDB
doc_id = await save_research(
topic=request.topic,
depth=request.depth.value,
result=result
)
result["id"] = doc_id
set_cache(request.topic, request.depth.value, result)
yield f"data: {json.dumps({'type': 'done', 'result': result})}\n\n"
return StreamingResponse(generate(), media_type="text/event-stream")
# ── History ───────────────────────────────────────────────
@app.get("/history", tags=["History"])
async def history(limit: int = 20):
return await get_history(limit=limit)
@app.get("/history/search/{query}", tags=["History"])
async def search(query: str):
return await search_history(query)
@app.get("/history/{research_id}", tags=["History"])
async def get_one(research_id: str):
doc = await get_by_id(research_id)
if not doc:
raise HTTPException(status_code=404, detail="Not found")
return doc
@app.delete("/history/{research_id}", tags=["History"])
async def delete_one(research_id: str):
deleted = await delete_by_id(research_id)
if not deleted:
raise HTTPException(status_code=404, detail="Not found")
return {"deleted": True, "id": research_id}
# ── Error handler ─────────────────────────────────────────
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"Unhandled error: {exc}")
return JSONResponse(
status_code=500,
content={"detail": "Internal server error", "error": str(exc)}
)