| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- # app/api/endpoints/agent.py
- from typing import List, Dict, Any
- from fastapi import APIRouter, Depends, status
- from fastapi.responses import StreamingResponse
- from sqlalchemy.ext.asyncio import AsyncSession
- from redis.asyncio import Redis
- from app.core.database import get_db
- from app.core.auth import get_current_user
- from app.core.redis import get_redis_client
- from app.models.user import VasUser
- from app.utils.response import success
- from app.schemas.common import ApiResponse
- from app.schemas.agent import (
- AgentChatRequest,
- AgentChatResponse,
- )
- from app.services.agent.engine import AgentEngine
- from app.services.agent.memory import AgentMemory
- from app.services.agent.tools.registry import tool_registry
- protected_router = APIRouter(prefix="/agent", tags=["AI Agent"])
- @protected_router.post(
- "/chat",
- summary="AI Agent 对话与指令执行接口",
- description="支持自然语言指令接收,自主调用系统后端工具完成功能,提供同步 JSON 和 SSE 流式双模式",
- response_model=ApiResponse[AgentChatResponse],
- )
- async def agent_chat(
- payload: AgentChatRequest,
- current_user: VasUser = Depends(get_current_user),
- db: AsyncSession = Depends(get_db),
- redis_client: Redis = Depends(get_redis_client),
- ):
- """
- Agent 统一交互接口:
- - 若 payload.stream == True,返回 text/event-stream 流式响应
- - 若 payload.stream == False,返回完整包含工具调用轨迹的 JSON 响应
- """
- if payload.stream:
- return StreamingResponse(
- AgentEngine.run_stream(
- request=payload,
- current_user=current_user,
- db=db,
- redis_client=redis_client,
- ),
- media_type="text/event-stream",
- headers={
- "Cache-Control": "no-cache",
- "Connection": "keep-alive",
- "X-Accel-Buffering": "no",
- },
- )
- response = await AgentEngine.run_sync(
- request=payload,
- current_user=current_user,
- db=db,
- redis_client=redis_client,
- )
- return success(data=response)
- @protected_router.get(
- "/tools",
- summary="获取 Agent 当前已注册的所有后端能力工具",
- response_model=ApiResponse[List[Dict[str, Any]]],
- )
- async def list_agent_tools(
- current_user: VasUser = Depends(get_current_user),
- ):
- """获取所有可用工具元信息及 OpenAPI Function Schema"""
- tools = tool_registry.get_all_tools()
- items = [
- {
- "name": t.name,
- "description": t.description,
- "is_dangerous": t.is_dangerous,
- "schema": t.openai_schema,
- }
- for t in tools
- ]
- return success(data=items)
- @protected_router.delete(
- "/session/{session_id}",
- summary="清空指定会话的上下文记忆",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def clear_agent_session(
- session_id: str,
- current_user: VasUser = Depends(get_current_user),
- ):
- """清空 Redis 中保存的 Agent 会话记忆"""
- cleared = await AgentMemory.clear_session(session_id)
- return success(data={"session_id": session_id, "cleared": cleared})
|