-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
105 lines (85 loc) · 2.93 KB
/
api.py
File metadata and controls
105 lines (85 loc) · 2.93 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
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import PlainTextResponse
import os
from datetime import datetime
import logging
from main import graph_builder
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(
title="Research Agent API",
description="AI-powered research agent that generates comprehensive reports",
version="1.0.0"
)
research_agent = None
@app.on_event("startup")
async def startup_event():
global research_agent
try:
logger.info("initializing research agent...")
research_agent = graph_builder()
logger.info("research agent ready")
except Exception as e:
logger.error(f"failed to init agent: {e}")
raise
@app.get("/")
async def root():
return {
"message": "research agent api running",
"status": "healthy",
"timestamp": datetime.now().isoformat()
}
@app.get("/research", response_class=PlainTextResponse)
async def research_endpoint(q: str = Query(..., description="research query")):
if not research_agent:
raise HTTPException(status_code=503, detail="agent not ready")
if not q.strip():
raise HTTPException(status_code=400, detail="query cannot be empty")
try:
logger.info(f"processing: {q}")
# Initialize state with defaults
initial_state = {
"user_input": q,
"enhanced_query": "",
"followup_questions": [],
"selected_urls": [],
"articles": [],
"reddit_posts": [],
"youtube_urls": [],
"twitter_urls": [],
"linkedin_urls": [],
"platform_questions": [],
"platform_content": "",
"platform_summary": "",
"platform_urls": {},
"report_markdown": "",
"errors": [],
"messages": [],
"step_info": "",
}
result = research_agent.invoke(initial_state)
final_response = result.get("report_markdown", "<no report generated>")
# If the report already has a header, use it as-is; otherwise add header
if final_response.startswith("# "):
markdown_report = final_response
else:
timestamp_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
markdown_report = f"""# Research Report
**Generated:** {timestamp_str}
**Query:** {q}
---
{final_response}
---
*Generated by Research Agent*
"""
logger.info(f"completed: {q}")
return markdown_report
except Exception as e:
logger.error(f"error: {e}")
raise HTTPException(status_code=500, detail=f"server error: {str(e)}")
if __name__ == "__main__":
import uvicorn
print(" starting api...")
print(" docs: http://localhost:8000/docs")
print(" test: http://localhost:8000/research?q=your-query")
uvicorn.run(app, host="0.0.0.0", port=8000)