agent.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # app/api/endpoints/agent.py
  2. from typing import List, Dict, Any
  3. from fastapi import APIRouter, Depends, status
  4. from fastapi.responses import StreamingResponse
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from redis.asyncio import Redis
  7. from app.core.database import get_db
  8. from app.core.auth import get_current_user
  9. from app.core.redis import get_redis_client
  10. from app.models.user import VasUser
  11. from app.utils.response import success
  12. from app.schemas.common import ApiResponse
  13. from app.schemas.agent import (
  14. AgentChatRequest,
  15. AgentChatResponse,
  16. )
  17. from app.services.agent.engine import AgentEngine
  18. from app.services.agent.memory import AgentMemory
  19. from app.services.agent.tools.registry import tool_registry
  20. protected_router = APIRouter(prefix="/agent", tags=["AI Agent"])
  21. @protected_router.post(
  22. "/chat",
  23. summary="AI Agent 对话与指令执行接口",
  24. description="支持自然语言指令接收,自主调用系统后端工具完成功能,提供同步 JSON 和 SSE 流式双模式",
  25. response_model=ApiResponse[AgentChatResponse],
  26. )
  27. async def agent_chat(
  28. payload: AgentChatRequest,
  29. current_user: VasUser = Depends(get_current_user),
  30. db: AsyncSession = Depends(get_db),
  31. redis_client: Redis = Depends(get_redis_client),
  32. ):
  33. """
  34. Agent 统一交互接口:
  35. - 若 payload.stream == True,返回 text/event-stream 流式响应
  36. - 若 payload.stream == False,返回完整包含工具调用轨迹的 JSON 响应
  37. """
  38. if payload.stream:
  39. return StreamingResponse(
  40. AgentEngine.run_stream(
  41. request=payload,
  42. current_user=current_user,
  43. db=db,
  44. redis_client=redis_client,
  45. ),
  46. media_type="text/event-stream",
  47. headers={
  48. "Cache-Control": "no-cache",
  49. "Connection": "keep-alive",
  50. "X-Accel-Buffering": "no",
  51. },
  52. )
  53. response = await AgentEngine.run_sync(
  54. request=payload,
  55. current_user=current_user,
  56. db=db,
  57. redis_client=redis_client,
  58. )
  59. return success(data=response)
  60. @protected_router.get(
  61. "/tools",
  62. summary="获取 Agent 当前已注册的所有后端能力工具",
  63. response_model=ApiResponse[List[Dict[str, Any]]],
  64. )
  65. async def list_agent_tools(
  66. current_user: VasUser = Depends(get_current_user),
  67. ):
  68. """获取所有可用工具元信息及 OpenAPI Function Schema"""
  69. tools = tool_registry.get_all_tools()
  70. items = [
  71. {
  72. "name": t.name,
  73. "description": t.description,
  74. "is_dangerous": t.is_dangerous,
  75. "schema": t.openai_schema,
  76. }
  77. for t in tools
  78. ]
  79. return success(data=items)
  80. @protected_router.delete(
  81. "/session/{session_id}",
  82. summary="清空指定会话的上下文记忆",
  83. response_model=ApiResponse[Dict[str, Any]],
  84. )
  85. async def clear_agent_session(
  86. session_id: str,
  87. current_user: VasUser = Depends(get_current_user),
  88. ):
  89. """清空 Redis 中保存的 Agent 会话记忆"""
  90. cleared = await AgentMemory.clear_session(session_id)
  91. return success(data={"session_id": session_id, "cleared": cleared})