chat.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import uuid
  2. from fastapi import APIRouter
  3. from app.models.chat import ChatRequest, ChatResponse, SourceInfo
  4. from app.graphs.chat_graph import create_chat_graph
  5. router = APIRouter(prefix="/api/v1", tags=["chat"])
  6. _graph = None
  7. def get_graph():
  8. global _graph
  9. if _graph is None:
  10. _graph = create_chat_graph()
  11. return _graph
  12. @router.post("/chat", response_model=ChatResponse)
  13. async def chat(req: ChatRequest):
  14. """家庭聊天: 意图分类→上下文→LLM→记忆"""
  15. trace_id = str(uuid.uuid4())
  16. graph = get_graph()
  17. initial_state = {
  18. "query": req.query,
  19. "user_id": req.user_id,
  20. "conversation_id": req.conversation_id,
  21. "child_id": req.context.child_id if req.context else None,
  22. "intent": None,
  23. "context": None,
  24. "self_check_result": req.context.self_check_result if req.context and req.context.self_check_result else None,
  25. "messages": None,
  26. "answer": None,
  27. "tasks": [],
  28. "sources": [],
  29. }
  30. config = {
  31. "configurable": {"thread_id": req.conversation_id or str(req.user_id)},
  32. }
  33. result = await graph.ainvoke(initial_state, config)
  34. sources = []
  35. for s in result.get("sources", []):
  36. sources.append(SourceInfo(
  37. type=s.get("type", "tool"),
  38. title=s.get("name", ""),
  39. ))
  40. conv_id = req.conversation_id or f"conv_{req.user_id}_{__import__('time').time()}"
  41. return ChatResponse(
  42. answer=result.get("answer", ""),
  43. conversation_id=conv_id,
  44. sources=sources,
  45. tasks=result.get("tasks", []),
  46. trace_id=trace_id,
  47. )