-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
404 lines (320 loc) · 11.2 KB
/
api_server.py
File metadata and controls
404 lines (320 loc) · 11.2 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""
FastAPI Web 服务 - 学术文献调研 Agent
支持 WebSocket 流式响应
"""
import os
import json
import asyncio
from typing import AsyncGenerator, Dict, Any
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
# 导入 Agent 组件
from research_agent import create_workflow, ResearchState
from llm_config import get_model_config, create_llm_client
# ============== 数据模型 ==============
class ResearchRequest(BaseModel):
topic: str
class ResearchResponse(BaseModel):
status: str
message: str
data: Dict[str, Any] = {}
# ============== 全局状态 ==============
class ConnectionManager:
"""WebSocket 连接管理器"""
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
# 安全检查:避免重复移除或移除不存在的连接
if websocket in self.active_connections:
self.active_connections.remove(websocket)
async def send_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
manager = ConnectionManager()
# ============== FastAPI 应用 ==============
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
print("=" * 60)
print("Research Agent API Server Starting...")
print("=" * 60)
try:
config = get_model_config()
print(f"[LLM] Model: {config.name} ({config.format})")
if config.base_url:
print(f"[LLM] API URL: {config.base_url}")
except Exception as e:
print(f"[WARNING] LLM Config Error: {e}")
print("=" * 60)
yield
print("\nServer shutting down...")
app = FastAPI(
title="Research Agent API",
description="学术文献调研 Agent Web 服务",
version="1.0.0",
lifespan=lifespan
)
# CORS 配置
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============== API 路由 ==============
@app.get("/")
async def root():
"""返回前端页面"""
return FileResponse("web/index.html")
@app.get("/api/health")
async def health_check():
"""健康检查"""
try:
config = get_model_config()
return {
"status": "healthy",
"model": config.name,
"format": config.format,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
return JSONResponse(
status_code=503,
content={"status": "unhealthy", "error": str(e)}
)
@app.post("/api/research")
async def create_research(request: ResearchRequest):
"""同步研究接口 (非流式)"""
try:
workflow = create_workflow()
result = workflow.invoke({
"topic": request.topic,
"queries": [],
"documents": [],
"final_report": ""
})
return {
"status": "success",
"data": {
"topic": request.topic,
"queries": result.get("queries", []),
"documents": result.get("documents", []),
"report": result.get("final_report", "")
}
}
except Exception as e:
return JSONResponse(
status_code=500,
content={"status": "error", "message": str(e)}
)
# ============== WebSocket 流式接口 ==============
async def run_research_stream(topic: str) -> AsyncGenerator[Dict[str, Any], None]:
"""
流式运行研究任务,产生进度事件
"""
from langgraph.graph import StateGraph, END
from langchain_core.prompts import ChatPromptTemplate
# 初始化
yield {"type": "init", "message": "初始化研究任务...", "topic": topic}
await asyncio.sleep(0.1)
# 手动执行每个节点以便流式输出
llm = create_llm_client()
# Step 1: Planner
yield {"type": "progress", "step": "planner", "status": "running", "message": "正在生成检索词..."}
prompt = ChatPromptTemplate.from_template("""You are an academic search assistant.
Given a research topic:
{topic}
Generate 3–5 high-quality English search queries suitable for:
- Arxiv
- PubMed
- Google Scholar
Requirements:
- Use precise academic terminology
- Cover different aspects if possible
Return ONLY a list of queries, one per line, without numbering or bullet points.
""")
try:
chain = prompt | llm
result = chain.invoke({"topic": topic})
queries = [q.strip() for q in result.content.strip().split('\n') if q.strip()]
queries = queries[:5]
yield {
"type": "progress",
"step": "planner",
"status": "completed",
"message": f"生成 {len(queries)} 个检索词",
"queries": queries
}
except Exception as e:
yield {"type": "error", "step": "planner", "message": str(e)}
return
await asyncio.sleep(0.2)
# Step 2: Searcher
yield {"type": "progress", "step": "searcher", "status": "running", "message": "正在检索文献..."}
try:
from research_agent import search_arxiv, search_pubmed
all_documents = []
for query in queries:
yield {"type": "progress", "step": "searcher", "status": "running", "message": f"搜索: {query}"}
arxiv_papers = search_arxiv(query, max_results=2)
all_documents.extend(arxiv_papers)
pubmed_papers = search_pubmed(query, max_results=2)
all_documents.extend(pubmed_papers)
await asyncio.sleep(0.1)
# 去重
seen_titles = set()
unique_docs = []
for doc in all_documents:
title_lower = doc["title"].lower()
if title_lower not in seen_titles:
seen_titles.add(title_lower)
unique_docs.append(doc)
yield {
"type": "progress",
"step": "searcher",
"status": "completed",
"message": f"检索到 {len(unique_docs)} 篇文献",
"documents": unique_docs
}
except Exception as e:
yield {"type": "error", "step": "searcher", "message": str(e)}
return
await asyncio.sleep(0.2)
# Step 3: Writer
yield {"type": "progress", "step": "writer", "status": "running", "message": "正在生成综述报告..."}
try:
if not unique_docs:
report = "未检索到相关文献,请尝试其他关键词。"
else:
docs_text = "\n\n".join([
f"[{i+1}] {doc['title']}\nSource: {doc['source']} ({doc.get('published', 'N/A')})\n{doc['summary']}\nURL: {doc['url']}"
for i, doc in enumerate(unique_docs)
])
writer_prompt = ChatPromptTemplate.from_template("""You are writing an academic research summary.
Based ONLY on the provided papers:
{documents}
Rules:
1. Do NOT fabricate any papers
2. Only use the given documents
3. Cite using [number] format
4. If information is insufficient, say "limited evidence"
Output structure in Chinese:
## 研究背景
简要介绍该领域的背景和重要性。
## 最新进展
总结文献中报告的最新研究进展。
## 关键方法
归纳文献中使用的主要研究方法和技术。
## 存在挑战
分析该领域面临的主要挑战和局限。
## 文献列表
- [1] 标题 - 来源 - URL
(列出所有参考文献)
""")
# 在异步上下文中执行可能耗时的 LLM 调用,避免事件循环阻塞导致 WebSocket 被上游超时断开
async def invoke_writer():
return await asyncio.get_running_loop().run_in_executor(
None,
lambda: (writer_prompt | llm).invoke({"documents": docs_text})
)
writer_task = asyncio.create_task(invoke_writer())
# 心跳保活:每隔10秒发送一次状态,避免中间无消息导致连接被代理/浏览器关闭
while not writer_task.done():
await asyncio.sleep(10)
yield {"type": "heartbeat", "message": "正在生成报告,请稍候(连接保活中)..."}
result = await writer_task
report = result.content
yield {
"type": "progress",
"step": "writer",
"status": "completed",
"message": "报告生成完成",
"report": report
}
# 最终完成
yield {
"type": "complete",
"message": "研究任务完成",
"data": {
"topic": topic,
"queries": queries,
"documents": unique_docs,
"report": report
}
}
except Exception as e:
yield {"type": "error", "step": "writer", "message": str(e)}
@app.websocket("/ws/research")
async def websocket_research(websocket: WebSocket):
"""WebSocket 流式研究接口"""
await manager.connect(websocket)
# 配置心跳超时检测(30秒)
websocket.ping_interval = 20
websocket.ping_timeout = 30
try:
while True:
# 接收消息
try:
data = await asyncio.wait_for(
websocket.receive_text(),
timeout=60.0 # 接收消息超时60秒
)
except asyncio.TimeoutError:
# 发送 ping 保活
try:
await websocket.send_json({"type": "ping"})
continue
except:
break
request = json.loads(data)
# 处理 ping 响应
if request.get("type") == "pong":
continue
topic = request.get("topic", "").strip()
if not topic:
await websocket.send_json({
"type": "error",
"message": "请提供研究主题"
})
continue
# 流式执行研究
async for event in run_research_stream(topic):
await websocket.send_json(event)
except WebSocketDisconnect:
pass
except Exception as e:
try:
await websocket.send_json({
"type": "error",
"message": f"服务器错误: {str(e)}"
})
except:
pass
finally:
manager.disconnect(websocket)
# ============== 静态文件服务 ==============
if os.path.exists("web"):
app.mount("/static", StaticFiles(directory="web/static"), name="static")
# ============== 启动入口 ==============
if __name__ == "__main__":
import uvicorn
# 确保 web 目录存在
os.makedirs("web/static", exist_ok=True)
uvicorn.run(
"api_server:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)