This commit is contained in:
@@ -5,14 +5,17 @@ FastAPI 后端 - 支持动态模型切换,使用 PostgreSQL 持久化记忆
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Depends, Request
|
||||
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Depends, Request, Query
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
||||
from app.agent import AIAgentService
|
||||
from app.history import ThreadHistoryService
|
||||
from app.logger import debug, info, warning, error
|
||||
|
||||
# 加载 .env 文件
|
||||
@@ -37,13 +40,17 @@ async def lifespan(app: FastAPI):
|
||||
agent_service = AIAgentService(checkpointer)
|
||||
await agent_service.initialize()
|
||||
|
||||
# 3. 将服务实例存入 app.state
|
||||
# 3. 创建历史查询服务
|
||||
history_service = ThreadHistoryService(checkpointer)
|
||||
|
||||
# 4. 将服务实例存入 app.state
|
||||
app.state.agent_service = agent_service
|
||||
app.state.history_service = history_service
|
||||
|
||||
# 应用运行中...
|
||||
yield
|
||||
|
||||
# 4. 关闭时自动清理数据库连接(async with 负责)
|
||||
# 5. 关闭时自动清理数据库连接(async with 负责)
|
||||
info("🛑 应用关闭,数据库连接池已释放")
|
||||
|
||||
|
||||
@@ -90,6 +97,11 @@ def get_agent_service(request: Request) -> AIAgentService:
|
||||
return request.app.state.agent_service
|
||||
|
||||
|
||||
def get_history_service(request: Request) -> ThreadHistoryService:
|
||||
"""从 app.state 中获取全局 ThreadHistoryService 实例"""
|
||||
return request.app.state.history_service
|
||||
|
||||
|
||||
# ========== HTTP 端点 ==========
|
||||
@app.post("/chat", response_model=ChatResponse)
|
||||
async def chat_endpoint(
|
||||
@@ -124,6 +136,75 @@ async def chat_endpoint(
|
||||
)
|
||||
|
||||
|
||||
# ========== 历史查询接口 ==========
|
||||
@app.get("/threads")
|
||||
async def list_threads(
|
||||
user_id: str = Query("default_user", description="用户 ID"),
|
||||
limit: int = Query(50, ge=1, le=200, description="返回数量限制"),
|
||||
history_service: ThreadHistoryService = Depends(get_history_service)
|
||||
):
|
||||
"""获取当前用户的对话历史列表"""
|
||||
threads = await history_service.get_user_threads(user_id, limit)
|
||||
return {"threads": threads}
|
||||
|
||||
|
||||
@app.get("/thread/{thread_id}/messages")
|
||||
async def get_thread_messages(
|
||||
thread_id: str,
|
||||
user_id: str = Query("default_user", description="用户 ID"),
|
||||
history_service: ThreadHistoryService = Depends(get_history_service)
|
||||
):
|
||||
"""获取指定线程的完整消息历史"""
|
||||
messages = await history_service.get_thread_messages(thread_id)
|
||||
return {"messages": messages}
|
||||
|
||||
|
||||
@app.get("/thread/{thread_id}/summary")
|
||||
async def get_thread_summary(
|
||||
thread_id: str,
|
||||
user_id: str = Query("default_user", description="用户 ID"),
|
||||
history_service: ThreadHistoryService = Depends(get_history_service)
|
||||
):
|
||||
"""获取指定线程的摘要信息"""
|
||||
summary = await history_service.get_thread_summary(thread_id)
|
||||
return summary
|
||||
|
||||
|
||||
# ========== 流式对话接口 ==========
|
||||
@app.post("/chat/stream")
|
||||
async def chat_stream_endpoint(
|
||||
request: ChatRequest,
|
||||
agent_service: AIAgentService = Depends(get_agent_service)
|
||||
):
|
||||
"""流式对话接口(SSE)"""
|
||||
if not request.message:
|
||||
raise HTTPException(status_code=400, detail="message required")
|
||||
|
||||
thread_id = request.thread_id or str(uuid.uuid4())
|
||||
|
||||
async def event_generator():
|
||||
try:
|
||||
async for chunk in agent_service.process_message_stream(
|
||||
request.message, thread_id, request.model, request.user_id
|
||||
):
|
||||
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
except Exception as e:
|
||||
error(f"流式响应异常: {e}")
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': str(e)}, ensure_ascii=False)}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_generator(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no", # 禁用 Nginx 缓冲
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ========== WebSocket 端点(可选) ==========
|
||||
@app.websocket("/ws")
|
||||
async def websocket_endpoint(
|
||||
|
||||
Reference in New Issue
Block a user