Переглянути джерело

feat(agent): implement AI agent interface with DeepSeek support, ReAct loop, and ops tools

jerry 2 місяців тому
батько
коміт
fcdcee3974

+ 3 - 0
.env

@@ -2,6 +2,9 @@ ENV=DEV
 DATABASE_URL=mysql+asyncmy://root:GqLLL7Bofj0WaaOpp.0@text.skin:3306/book_user_info?charset=utf8mb4
 REDIS_URL=redis://:STEs2x6ML0U1HlpE9SojM6YU7QPhqzY8@text.skin:6379/0
 OPENAI_API_KEY=sk-893e895724c6403d81374e515ffaf427
+LLM_API_KEY=sk-3eea553bb7844623a7da401c8323ce8c
+LLM_BASE_URL=https://api.deepseek.com
+LLM_MODEL=deepseek-v4-flash
 STRIPE_API_KEY=sk_live_xxxx
 STRIPE_WEBHOOK_SECRET=whsec_xxxx
 TELEGRAM_API_TOKEN=xxxxx

+ 100 - 0
app/api/endpoints/agent.py

@@ -0,0 +1,100 @@
+# 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})

+ 2 - 0
app/api/router.py

@@ -2,6 +2,7 @@ from fastapi import APIRouter
 
 from app.api.endpoints import (
     account,
+    agent,
     auth,
     common,
     config,
@@ -33,6 +34,7 @@ admin_required_router = APIRouter()
 # 模块列表
 _modules = [
     account,
+    agent,
     auth,
     common,
     config,

+ 3 - 3
app/core/config.py

@@ -39,10 +39,10 @@ class Settings(BaseSettings):
     # LLM Configuration (OpenAI-compatible)
     # -----------------------
     llm_api_key: str = Field("", description="LLM API Key (defaults to openai_api_key)")
-    llm_base_url: str = Field("https://dashscope.aliyuncs.com/compatible-mode/v1", description="OpenAI-compatible Base URL")
-    llm_model: str = Field("qwen-plus", description="Default model name, e.g., qwen-plus, gpt-4o, deepseek-chat")
+    llm_base_url: str = Field("https://api.deepseek.com", description="OpenAI-compatible Base URL")
+    llm_model: str = Field("deepseek-v4-flash", description="Default model name, e.g., deepseek-v4-flash, deepseek-v4-pro")
     llm_temperature: float = Field(0.0, description="LLM sampling temperature")
-    llm_timeout_seconds: int = Field(30, description="LLM request timeout in seconds")
+    llm_timeout_seconds: int = Field(60, description="LLM request timeout in seconds")
 
     model_config = SettingsConfigDict(
         env_file=".env",

+ 34 - 0
app/schemas/agent.py

@@ -0,0 +1,34 @@
+# app/schemas/agent.py
+from typing import Optional, List, Dict, Any
+from pydantic import BaseModel, Field
+
+
+class AgentChatRequest(BaseModel):
+    """Agent 对话请求入参"""
+    message: str = Field(..., description="用户输入的指令或问题", min_length=1)
+    session_id: Optional[str] = Field(None, description="会话ID,若不传则自动生成并开启新会话")
+    stream: bool = Field(False, description="是否启用 SSE 流式输出")
+    max_steps: int = Field(8, description="单次交互最大工具调用步数限制,防死循环", ge=1, le=20)
+    model: Optional[str] = Field(None, description="指定使用的 LLM 模型名称,不传则使用默认配置")
+
+
+class AgentToolCallStep(BaseModel):
+    """单个工具调用的执行记录"""
+    tool: str = Field(..., description="调用的工具名称")
+    arguments: Dict[str, Any] = Field(default_factory=dict, description="传给工具的入参")
+    result: Any = Field(None, description="工具执行结果")
+    is_error: bool = Field(False, description="工具执行是否报错")
+
+
+class AgentChatResponse(BaseModel):
+    """Agent 同步对话响应体"""
+    session_id: str = Field(..., description="会话ID")
+    answer: str = Field(..., description="Agent 最终返回给用户的回答")
+    steps: List[AgentToolCallStep] = Field(default_factory=list, description="执行的工具调用轨迹")
+    steps_count: int = Field(0, description="执行的工具步骤数")
+
+
+class AgentStreamEvent(BaseModel):
+    """SSE 流式事件载荷"""
+    event: str = Field(..., description="事件类型:think | tool_start | tool_end | message | finish | error")
+    data: Dict[str, Any] = Field(default_factory=dict, description="事件详情数据")

+ 6 - 0
app/services/agent/__init__.py

@@ -0,0 +1,6 @@
+# app/services/agent/__init__.py
+from app.services.agent.engine import AgentEngine
+from app.services.agent.memory import AgentMemory
+from app.services.agent.tools.registry import tool_registry, agent_tool
+
+__all__ = ["AgentEngine", "AgentMemory", "tool_registry", "agent_tool"]

+ 295 - 0
app/services/agent/engine.py

@@ -0,0 +1,295 @@
+# app/services/agent/engine.py
+import json
+import uuid
+import asyncio
+from typing import AsyncGenerator, Dict, Any, List, Optional
+from sqlalchemy.ext.asyncio import AsyncSession
+from redis.asyncio import Redis
+
+from app.core.logger import logger
+from app.models.user import VasUser
+from app.schemas.agent import (
+    AgentChatRequest,
+    AgentChatResponse,
+    AgentToolCallStep,
+)
+from app.services.llm_service import LlmService
+from app.services.agent.memory import AgentMemory
+from app.services.agent.tools.registry import tool_registry
+# 自动加载内置业务工具
+import app.services.agent.tools.builtin  # noqa: F401
+
+
+SYSTEM_PROMPT = """你是一个专业的智能业务助理,具备自主调用系统后端工具(Tools)的能力。
+你可以根据用户的自然语言需求,自主规划并按顺序调用相关工具来完成查询、数据检索或操作任务。
+
+【行为规范与准则】:
+1. 遇到需要查询、修改、统计具体业务数据时,必须调用对应的工具获取真实结果,禁止凭空捏造数据或订单状态。
+2. 若用户需要执行操作(如取消订单),请先确认订单状态及所需参数,必要时先查询详情再执行操作。
+3. 如果工具返回错误或未查到结果,请友好告知用户原因或提出可能的解决建议。
+4. 工具调用完成后,请用清晰、结构化、自然的语言向用户总结执行结果。
+5. 回答始终保持礼貌、高效与专业。"""
+
+
+class AgentEngine:
+    """Agent 核心编排引擎,支持 ReAct 循环与 SSE 流式输出"""
+
+    @classmethod
+    def _format_sse(cls, event: str, data: Dict[str, Any]) -> str:
+        return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
+
+    @classmethod
+    async def run_sync(
+        cls,
+        request: AgentChatRequest,
+        current_user: VasUser,
+        db: AsyncSession,
+        redis_client: Optional[Redis] = None,
+    ) -> AgentChatResponse:
+        """同步执行 Agent 对话并返回完整结果"""
+        session_id = request.session_id or f"sess_{uuid.uuid4().hex[:12]}"
+        history = await AgentMemory.get_history(session_id, max_messages=10)
+
+        tools_schema = tool_registry.get_openai_tools_schema()
+        context = {
+            "db": db,
+            "current_user": current_user,
+            "redis_client": redis_client,
+        }
+
+        # 组装本轮执行的消息列表
+        messages: List[Dict[str, Any]] = [
+            {"role": "system", "content": SYSTEM_PROMPT},
+        ]
+        # 追加历史对话
+        messages.extend(history)
+        # 追加当前用户输入
+        user_msg = {"role": "user", "content": request.message}
+        messages.append(user_msg)
+
+        # 用于持久化到 Redis 的增量消息
+        new_history_messages: List[Dict[str, Any]] = [user_msg]
+        steps_record: List[AgentToolCallStep] = []
+
+        step = 0
+        final_answer = ""
+
+        while step < request.max_steps:
+            step += 1
+            logger.info(f"[AgentEngine] Step {step}/{request.max_steps} calling LLM (session={session_id})...")
+
+            llm_reply = await LlmService.chat_completion_with_tools_async(
+                messages=messages,
+                tools=tools_schema if tools_schema else None,
+                model=request.model,
+            )
+
+            tool_calls = llm_reply.get("tool_calls")
+            content = llm_reply.get("content") or ""
+
+            if not tool_calls:
+                # LLM 没有触发工具调用,直接作为最终答案返回
+                final_answer = content
+                assistant_msg = {"role": "assistant", "content": final_answer}
+                new_history_messages.append(assistant_msg)
+                break
+
+            # 处理工具调用
+            assistant_call_msg = {
+                "role": "assistant",
+                "content": content,
+                "tool_calls": tool_calls,
+            }
+            messages.append(assistant_call_msg)
+            new_history_messages.append(assistant_call_msg)
+
+            for call in tool_calls:
+                fn_info = call.get("function", {})
+                tool_name = fn_info.get("name", "")
+                raw_args = fn_info.get("arguments", "{}")
+                call_id = call.get("id", f"call_{uuid.uuid4().hex[:8]}")
+
+                try:
+                    args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
+                except Exception:
+                    args = {}
+
+                logger.info(f"[AgentEngine] Invoking tool: {tool_name} with args: {args}")
+                tool_result = await tool_registry.execute(tool_name, args, context=context)
+
+                is_error = isinstance(tool_result, dict) and "error" in tool_result
+                steps_record.append(
+                    AgentToolCallStep(
+                        tool=tool_name,
+                        arguments=args,
+                        result=tool_result,
+                        is_error=is_error,
+                    )
+                )
+
+                tool_reply_msg = {
+                    "role": "tool",
+                    "tool_call_id": call_id,
+                    "name": tool_name,
+                    "content": json.dumps(tool_result, ensure_ascii=False),
+                }
+                messages.append(tool_reply_msg)
+                new_history_messages.append(tool_reply_msg)
+
+        if not final_answer and step >= request.max_steps:
+            # 达到最大步数未停止,强制做一次总结
+            summary_reply = await LlmService.chat_completion_with_tools_async(
+                messages=messages + [{"role": "user", "content": "请根据以上所有工具执行结果,做最终汇总回答。"}],
+                tools=None,
+                model=request.model,
+            )
+            final_answer = summary_reply.get("content", "已完成操作处理。")
+            new_history_messages.append({"role": "assistant", "content": final_answer})
+
+        # 持久化更新历史记录到 Redis
+        await AgentMemory.append_messages(session_id, new_history_messages)
+
+        return AgentChatResponse(
+            session_id=session_id,
+            answer=final_answer,
+            steps=steps_record,
+            steps_count=len(steps_record),
+        )
+
+    @classmethod
+    async def run_stream(
+        cls,
+        request: AgentChatRequest,
+        current_user: VasUser,
+        db: AsyncSession,
+        redis_client: Optional[Redis] = None,
+    ) -> AsyncGenerator[str, None]:
+        """以 SSE 格式流式生成 Agent 运行状态、工具调用过程与最终回答"""
+        session_id = request.session_id or f"sess_{uuid.uuid4().hex[:12]}"
+
+        try:
+            yield cls._format_sse("think", {"status": "started", "session_id": session_id})
+
+            history = await AgentMemory.get_history(session_id, max_messages=10)
+            tools_schema = tool_registry.get_openai_tools_schema()
+            context = {
+                "db": db,
+                "current_user": current_user,
+                "redis_client": redis_client,
+            }
+
+            messages: List[Dict[str, Any]] = [
+                {"role": "system", "content": SYSTEM_PROMPT},
+            ]
+            messages.extend(history)
+            user_msg = {"role": "user", "content": request.message}
+            messages.append(user_msg)
+
+            new_history_messages: List[Dict[str, Any]] = [user_msg]
+            steps_record: List[AgentToolCallStep] = []
+
+            step = 0
+            final_answer = ""
+
+            while step < request.max_steps:
+                step += 1
+                yield cls._format_sse("think", {"status": "planning", "step": step})
+
+                llm_reply = await LlmService.chat_completion_with_tools_async(
+                    messages=messages,
+                    tools=tools_schema if tools_schema else None,
+                    model=request.model,
+                )
+
+                tool_calls = llm_reply.get("tool_calls")
+                content = llm_reply.get("content") or ""
+                reasoning = llm_reply.get("reasoning_content") or ""
+
+                if reasoning:
+                    yield cls._format_sse("think", {"status": "reasoning", "reasoning": reasoning, "step": step})
+
+                if not tool_calls:
+                    final_answer = content
+                    # 推送最终回复文本
+                    yield cls._format_sse("message", {"delta": final_answer, "full": final_answer})
+                    new_history_messages.append({"role": "assistant", "content": final_answer})
+                    break
+
+                # 记录 assistant 的 tool_calls
+                assistant_call_msg = {
+                    "role": "assistant",
+                    "content": content,
+                    "tool_calls": tool_calls,
+                }
+                messages.append(assistant_call_msg)
+                new_history_messages.append(assistant_call_msg)
+
+                for call in tool_calls:
+                    fn_info = call.get("function", {})
+                    tool_name = fn_info.get("name", "")
+                    raw_args = fn_info.get("arguments", "{}")
+                    call_id = call.get("id", f"call_{uuid.uuid4().hex[:8]}")
+
+                    try:
+                        args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
+                    except Exception:
+                        args = {}
+
+                    # 推送 tool_start 事件
+                    yield cls._format_sse("tool_start", {
+                        "tool": tool_name,
+                        "arguments": args,
+                        "call_id": call_id,
+                    })
+
+                    tool_result = await tool_registry.execute(tool_name, args, context=context)
+                    is_error = isinstance(tool_result, dict) and "error" in tool_result
+
+                    step_obj = AgentToolCallStep(
+                        tool=tool_name,
+                        arguments=args,
+                        result=tool_result,
+                        is_error=is_error,
+                    )
+                    steps_record.append(step_obj)
+
+                    # 推送 tool_end 事件
+                    yield cls._format_sse("tool_end", {
+                        "tool": tool_name,
+                        "result": tool_result,
+                        "is_error": is_error,
+                        "call_id": call_id,
+                    })
+
+                    tool_reply_msg = {
+                        "role": "tool",
+                        "tool_call_id": call_id,
+                        "name": tool_name,
+                        "content": json.dumps(tool_result, ensure_ascii=False),
+                    }
+                    messages.append(tool_reply_msg)
+                    new_history_messages.append(tool_reply_msg)
+
+            if not final_answer and step >= request.max_steps:
+                summary_reply = await LlmService.chat_completion_with_tools_async(
+                    messages=messages + [{"role": "user", "content": "请根据以上所有工具执行结果,做最终汇总回答。"}],
+                    tools=None,
+                    model=request.model,
+                )
+                final_answer = summary_reply.get("content", "已完成操作处理。")
+                yield cls._format_sse("message", {"delta": final_answer, "full": final_answer})
+                new_history_messages.append({"role": "assistant", "content": final_answer})
+
+            # 更新记忆
+            await AgentMemory.append_messages(session_id, new_history_messages)
+
+            # 发送 finish 完成事件
+            yield cls._format_sse("finish", {
+                "session_id": session_id,
+                "answer": final_answer,
+                "steps_count": len(steps_record),
+            })
+
+        except Exception as e:
+            logger.error(f"[AgentEngine.stream] error: {e}", exc_info=True)
+            yield cls._format_sse("error", {"error": str(e)})

+ 73 - 0
app/services/agent/memory.py

@@ -0,0 +1,73 @@
+# app/services/agent/memory.py
+import json
+from typing import List, Dict, Any, Optional
+from app.core.redis import get_redis_client
+from app.core.logger import logger
+
+SESSION_KEY_PREFIX = "agent:session:"
+DEFAULT_SESSION_TTL = 86400  # 24小时过期
+
+
+class AgentMemory:
+    """基于 Redis 的 Agent 会话上下文记忆管理器"""
+
+    @classmethod
+    def _make_key(cls, session_id: str) -> str:
+        return f"{SESSION_KEY_PREFIX}{session_id.strip()}"
+
+    @classmethod
+    async def get_history(cls, session_id: Optional[str], max_messages: int = 20) -> List[Dict[str, Any]]:
+        """获取指定 session 的历史消息"""
+        if not session_id:
+            return []
+
+        try:
+            redis = await get_redis_client()
+            key = cls._make_key(session_id)
+            raw = await redis.get(key)
+            if not raw:
+                return []
+            history = json.loads(raw)
+            if isinstance(history, list):
+                return history[-max_messages:]
+            return []
+        except Exception as e:
+            logger.warning(f"[AgentMemory] Failed to read history for session {session_id}: {e}")
+            return []
+
+    @classmethod
+    async def append_messages(
+        cls,
+        session_id: Optional[str],
+        new_messages: List[Dict[str, Any]],
+        ttl: int = DEFAULT_SESSION_TTL,
+        max_stored_messages: int = 40,
+    ) -> None:
+        """向 session 追加新消息并刷新 TTL"""
+        if not session_id or not new_messages:
+            return
+
+        try:
+            redis = await get_redis_client()
+            key = cls._make_key(session_id)
+            existing = await cls.get_history(session_id, max_messages=max_stored_messages)
+            combined = existing + new_messages
+            # 控制保存的历史最大长度,防止 token 溢出
+            trimmed = combined[-max_stored_messages:]
+            await redis.setex(key, ttl, json.dumps(trimmed, ensure_ascii=False))
+        except Exception as e:
+            logger.warning(f"[AgentMemory] Failed to append messages for session {session_id}: {e}")
+
+    @classmethod
+    async def clear_session(cls, session_id: str) -> bool:
+        """清除指定 session 历史"""
+        if not session_id:
+            return False
+        try:
+            redis = await get_redis_client()
+            key = cls._make_key(session_id)
+            await redis.delete(key)
+            return True
+        except Exception as e:
+            logger.warning(f"[AgentMemory] Failed to delete session {session_id}: {e}")
+            return False

+ 4 - 0
app/services/agent/tools/__init__.py

@@ -0,0 +1,4 @@
+# app/services/agent/tools/__init__.py
+from app.services.agent.tools.registry import tool_registry, agent_tool, ToolRegistry, AgentTool
+
+__all__ = ["tool_registry", "agent_tool", "ToolRegistry", "AgentTool"]

+ 17 - 0
app/services/agent/tools/builtin/__init__.py

@@ -0,0 +1,17 @@
+# app/services/agent/tools/builtin/__init__.py
+# 导入内置工具以触发 @agent_tool 自动注册
+from app.services.agent.tools.builtin import (
+    order_tools,
+    product_tools,
+    node_config_tools,
+    plugin_tools,
+    proxy_pool_tools,
+)
+
+__all__ = [
+    "order_tools",
+    "product_tools",
+    "node_config_tools",
+    "plugin_tools",
+    "proxy_pool_tools",
+]

+ 261 - 0
app/services/agent/tools/builtin/node_config_tools.py

@@ -0,0 +1,261 @@
+# app/services/agent/tools/builtin/node_config_tools.py
+from typing import Optional, Dict, Any, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.models.user import VasUser
+from app.services.node_configuration_service import NodeConfigurationService
+from app.services.agent.tools.registry import agent_tool
+
+
+ADMIN_CHECK_MSG = "权限不足:该运维操作仅系统管理员(admin)可执行"
+
+
+@agent_tool(
+    name="list_node_configurations",
+    description="查询爬虫节点配置列表(booker/sentinel/standalone),支持按 identifier 标识与启用状态筛选(管理员专有)",
+)
+async def list_node_configurations(
+    entry_type: str = "booker",
+    identifier: Optional[str] = None,
+    enable: Optional[bool] = None,
+    page: int = 1,
+    page_size: int = 10,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """查询爬虫节点配置列表"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    clean_type = entry_type.strip().lower()
+    enable_int = 1 if enable is True else (0 if enable is False else None)
+
+    try:
+        entries, total = await NodeConfigurationService.list_entries(
+            db=db,
+            entry_type=clean_type,
+            page=page,
+            page_size=min(page_size, 30),
+            identifier=identifier.strip() if identifier else None,
+            enable=enable_int,
+        )
+
+        items = []
+        for e in entries:
+            items.append({
+                "id": e.id,
+                "node_id": e.node_id,
+                "identifier": e.identifier,
+                "enable": bool(e.enable),
+                "debug": bool(e.debug),
+                "proxy_cd": getattr(e, "proxy_cd", None),
+                "session_max_life": getattr(e, "session_max_life", None),
+                "version": e.version,
+                "updated_by": e.updated_by,
+                "updated_at": e.updated_at.strftime("%Y-%m-%d %H:%M:%S") if e.updated_at else None,
+            })
+
+        return {
+            "entry_type": clean_type,
+            "total": total,
+            "page": page,
+            "items": items,
+        }
+    except Exception as e:
+        return {"error": f"查询节点配置失败: {str(e)}"}
+
+
+@agent_tool(
+    name="get_node_configuration_detail",
+    description="获取指定爬虫节点配置的完整详情(含代理池、时间窗、Plugin配置等,管理员专有)",
+)
+async def get_node_configuration_detail(
+    entry_type: str,
+    entry_id: int,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """获取单个节点配置完整详情"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        entry = await NodeConfigurationService.get_entry(db, entry_type.strip().lower(), entry_id)
+        snapshot = NodeConfigurationService._to_snapshot(entry)
+        return {
+            "entry_type": entry_type,
+            "entry_id": entry_id,
+            "configuration": snapshot,
+        }
+    except Exception as e:
+        return {"error": f"获取节点配置详情失败: {str(e)}"}
+
+
+@agent_tool(
+    name="toggle_node_configuration",
+    description="一键启用或禁用指定的爬虫节点配置(管理员专有)",
+    is_dangerous=True,
+)
+async def toggle_node_configuration(
+    entry_type: str,
+    entry_id: int,
+    enable: bool,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """启停节点配置"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    operator = current_user.email or current_user.nickname or current_user.id
+    try:
+        updated = await NodeConfigurationService.toggle_enable(
+            db=db,
+            entry_type=entry_type.strip().lower(),
+            entry_id=entry_id,
+            enable=enable,
+            operator=operator,
+        )
+        return {
+            "success": True,
+            "entry_type": entry_type,
+            "entry_id": entry_id,
+            "identifier": updated.identifier,
+            "enable": bool(updated.enable),
+            "version": updated.version,
+            "message": f"节点 {updated.identifier} 已成功{'启用' if enable else '禁用'}",
+        }
+    except Exception as e:
+        return {"error": f"启停节点配置失败: {str(e)}"}
+
+
+@agent_tool(
+    name="update_node_configuration_settings",
+    description="调整指定爬虫节点的关键运维参数,如 proxy_cd(秒), session_max_life(秒), debug模式(管理员专有)",
+    is_dangerous=True,
+)
+async def update_node_configuration_settings(
+    entry_type: str,
+    entry_id: int,
+    proxy_cd: Optional[int] = None,
+    session_max_life: Optional[int] = None,
+    debug: Optional[int] = None,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """修改节点配置关键参数"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    set_data = {}
+    if proxy_cd is not None:
+        set_data["proxy_cd"] = proxy_cd
+    if session_max_life is not None:
+        set_data["session_max_life"] = session_max_life
+    if debug is not None:
+        set_data["debug"] = 1 if debug else 0
+
+    if not set_data:
+        return {"message": "未传入需要更新的参数"}
+
+    operator = current_user.email or current_user.nickname or current_user.id
+    try:
+        updated = await NodeConfigurationService.sparse_update_entry(
+            db=db,
+            entry_type=entry_type.strip().lower(),
+            entry_id=entry_id,
+            set_data=set_data,
+            operator=operator,
+        )
+        return {
+            "success": True,
+            "entry_type": entry_type,
+            "entry_id": entry_id,
+            "identifier": updated.identifier,
+            "updated_fields": set_data,
+            "version": updated.version,
+            "message": f"节点 {updated.identifier} 配置更新成功",
+        }
+    except Exception as e:
+        return {"error": f"更新节点配置参数失败: {str(e)}"}
+
+
+@agent_tool(
+    name="list_node_configuration_revisions",
+    description="查询指定节点配置的历史版本审计记录,用于排错与回滚(管理员专有)",
+)
+async def list_node_configuration_revisions(
+    entry_type: str,
+    entry_id: int,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """查询节点配置历史版本"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        revisions = await NodeConfigurationService.get_revisions(
+            db=db,
+            entry_type=entry_type.strip().lower(),
+            entry_id=entry_id,
+        )
+        items = []
+        for r in revisions[:15]:
+            items.append({
+                "revision_id": r.id,
+                "version": r.version,
+                "action": r.action,
+                "updated_by": r.updated_by,
+                "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S") if r.created_at else None,
+            })
+        return {
+            "entry_type": entry_type,
+            "entry_id": entry_id,
+            "count": len(items),
+            "revisions": items,
+        }
+    except Exception as e:
+        return {"error": f"查询版本记录失败: {str(e)}"}
+
+
+@agent_tool(
+    name="rollback_node_configuration",
+    description="将节点配置紧急回滚到指定的历史版本 revision_id(管理员专有)",
+    is_dangerous=True,
+)
+async def rollback_node_configuration(
+    entry_type: str,
+    entry_id: int,
+    revision_id: int,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """回滚节点配置"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    operator = current_user.email or current_user.nickname or current_user.id
+    try:
+        rolled = await NodeConfigurationService.rollback_revision(
+            db=db,
+            entry_type=entry_type.strip().lower(),
+            entry_id=entry_id,
+            revision_id=revision_id,
+            operator=operator,
+        )
+        return {
+            "success": True,
+            "entry_type": entry_type,
+            "entry_id": entry_id,
+            "identifier": rolled.identifier,
+            "current_version": rolled.version,
+            "message": f"节点 {rolled.identifier} 已成功回滚至历史版本 #{revision_id}",
+        }
+    except Exception as e:
+        return {"error": f"回滚节点配置失败: {str(e)}"}

+ 129 - 0
app/services/agent/tools/builtin/order_tools.py

@@ -0,0 +1,129 @@
+# app/services/agent/tools/builtin/order_tools.py
+from typing import Optional, Dict, Any, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, desc
+from app.models.order import VasOrder
+from app.models.user import VasUser
+from app.services.order_service import OrderService
+from app.services.agent.tools.registry import agent_tool
+from app.core.logger import logger
+
+
+@agent_tool(
+    name="query_user_orders",
+    description="查询当前登录用户的订单列表,可按订单状态筛选(pending-待支付, paid-已支付, completed-已完成, closed-已关闭)",
+)
+async def query_user_orders(
+    status: Optional[str] = None,
+    limit: int = 10,
+    offset: int = 0,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """查询用户的订单列表"""
+    limit = max(1, min(limit, 50))
+    offset = max(0, offset)
+
+    stmt = select(VasOrder).where(VasOrder.user_id == current_user.id)
+    if status and status.strip():
+        stmt = stmt.where(VasOrder.status == status.strip().lower())
+    stmt = stmt.order_by(desc(VasOrder.created_at)).offset(offset).limit(limit)
+
+    res = await db.execute(stmt)
+    orders = res.scalars().all()
+
+    items = []
+    for o in orders:
+        items.append({
+            "order_id": o.id,
+            "product_name": o.product_name,
+            "final_amount": o.final_amount,
+            "currency": o.base_currency,
+            "status": o.status,
+            "created_at": o.created_at.strftime("%Y-%m-%d %H:%M:%S") if o.created_at else None,
+        })
+
+    return {
+        "count": len(items),
+        "orders": items,
+    }
+
+
+@agent_tool(
+    name="get_order_detail",
+    description="获取指定订单ID的详细信息,包含产品信息、金额、状态及填写的数据",
+)
+async def get_order_detail(
+    order_id: str,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """获取指定订单详情"""
+    stmt = select(VasOrder).where(VasOrder.id == order_id.strip())
+    res = await db.execute(stmt)
+    order = res.scalar_one_or_none()
+
+    if not order:
+        return {"error": f"订单 {order_id} 不存在"}
+
+    # 数据权限校验:非管理员只能查看自己的订单
+    if order.user_id != current_user.id and current_user.role != "admin":
+        return {"error": f"无权查看该订单 {order_id}"}
+
+    return {
+        "order_id": order.id,
+        "product_id": order.product_id,
+        "product_name": order.product_name,
+        "base_amount": order.base_amount,
+        "final_amount": order.final_amount,
+        "currency": order.base_currency,
+        "status": order.status,
+        "user_inputs": order.user_inputs,
+        "created_at": order.created_at.strftime("%Y-%m-%d %H:%M:%S") if order.created_at else None,
+        "updated_at": order.updated_at.strftime("%Y-%m-%d %H:%M:%S") if order.updated_at else None,
+    }
+
+
+@agent_tool(
+    name="cancel_user_order",
+    description="取消指定的订单(仅未完成/未关闭的订单可取消)",
+    is_dangerous=True,
+)
+async def cancel_user_order(
+    order_id: str,
+    reason: Optional[str] = None,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """取消用户自己的订单"""
+    order_id_clean = order_id.strip()
+    stmt = select(VasOrder).where(VasOrder.id == order_id_clean)
+    res = await db.execute(stmt)
+    order = res.scalar_one_or_none()
+
+    if not order:
+        return {"error": f"订单 {order_id_clean} 不存在"}
+
+    if order.user_id != current_user.id and current_user.role != "admin":
+        return {"error": f"无权取消订单 {order_id_clean}"}
+
+    if order.status == "closed":
+        return {"message": f"订单 {order_id_clean} 已经处于已关闭状态,无需重复取消"}
+
+    if order.status == "completed":
+        return {"error": f"订单 {order_id_clean} 已履约完成,无法取消"}
+
+    try:
+        cancelled = await OrderService.cancel(db, order_id_clean)
+        logger.info(f"Agent cancelled order {order_id_clean} on behalf of user {current_user.id}, reason={reason}")
+        return {
+            "success": True,
+            "order_id": cancelled.id,
+            "status": cancelled.status,
+            "message": f"订单 {order_id_clean} 已成功取消",
+        }
+    except Exception as e:
+        return {"error": f"取消订单失败: {str(e)}"}

+ 187 - 0
app/services/agent/tools/builtin/plugin_tools.py

@@ -0,0 +1,187 @@
+# app/services/agent/tools/builtin/plugin_tools.py
+from typing import Optional, Dict, Any, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+
+from app.models.user import VasUser
+from app.models.plugin import Plugin
+from app.schemas.plugin import PluginUpdate
+from app.services.plugin_service import PluginService
+from app.services.agent.tools.registry import agent_tool
+
+ADMIN_CHECK_MSG = "权限不足:该运维操作仅系统管理员(admin)可执行"
+
+
+@agent_tool(
+    name="list_plugins",
+    description="查询当前系统注册的爬虫插件列表,包含插件名、最新版本号与启用状态(管理员专有)",
+)
+async def list_plugins(
+    status: Optional[int] = None,
+    page: int = 1,
+    page_size: int = 20,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """查询插件列表"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        res = await PluginService.get_plugin_list(
+            db=db,
+            page=page,
+            page_size=min(page_size, 50),
+            status=status,
+        )
+
+        items = []
+        for p in res.get("list", []):
+            items.append({
+                "id": p.id,
+                "name": p.name,
+                "display_name": p.display_name,
+                "filename": p.filename,
+                "latest_version": p.latest_version,
+                "description": p.description,
+                "status": p.status,
+                "status_cn": "已启用" if p.status == 1 else "已停用",
+            })
+
+        return {
+            "total": res.get("total", len(items)),
+            "plugins": items,
+        }
+    except Exception as e:
+        return {"error": f"查询插件列表失败: {str(e)}"}
+
+
+@agent_tool(
+    name="get_plugin_detail",
+    description="获取指定插件的完整信息及所有发布历史版本与更新日志(管理员专有)",
+)
+async def get_plugin_detail(
+    plugin_id: Optional[int] = None,
+    plugin_name: Optional[str] = None,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """获取单个插件详情"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        target_id = plugin_id
+        if target_id is None and plugin_name:
+            stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
+            target_id = (await db.execute(stmt)).scalar_one_or_none()
+
+        if not target_id:
+            return {"error": f"未找到插件: id={plugin_id}, name={plugin_name}"}
+
+        detail = await PluginService.get_plugin_detail(db, target_id)
+        versions_info = []
+        for v in detail.get("versions", []):
+            versions_info.append({
+                "version": v.version,
+                "download_url": v.download_url,
+                "sha256": v.sha256[:16] + "..." if v.sha256 else "",
+                "changelog": v.changelog,
+                "created_at": v.created_at.strftime("%Y-%m-%d %H:%M:%S") if v.created_at else None,
+            })
+
+        return {
+            "id": detail["id"],
+            "name": detail["name"],
+            "display_name": detail["display_name"],
+            "latest_version": detail["latest_version"],
+            "status": detail["status"],
+            "description": detail["description"],
+            "versions_count": len(versions_info),
+            "versions": versions_info,
+        }
+    except Exception as e:
+        return {"error": f"获取插件详情失败: {str(e)}"}
+
+
+@agent_tool(
+    name="toggle_plugin_status",
+    description="一键启用(status=1)或停用(status=0)指定插件(管理员专有)",
+    is_dangerous=True,
+)
+async def toggle_plugin_status(
+    plugin_id: Optional[int] = None,
+    plugin_name: Optional[str] = None,
+    status: int = 1,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """启停插件"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        target_id = plugin_id
+        if target_id is None and plugin_name:
+            stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
+            target_id = (await db.execute(stmt)).scalar_one_or_none()
+
+        if not target_id:
+            return {"error": f"未找到插件: id={plugin_id}, name={plugin_name}"}
+
+        clean_status = 1 if status == 1 else 0
+        updated = await PluginService.update_plugin(
+            db=db,
+            plugin_id=target_id,
+            plugin_in=PluginUpdate(status=clean_status),
+        )
+        return {
+            "success": True,
+            "plugin_id": updated.id,
+            "name": updated.name,
+            "status": updated.status,
+            "message": f"插件 {updated.name} 已成功{'启用' if clean_status == 1 else '停用'}",
+        }
+    except Exception as e:
+        return {"error": f"操作插件状态失败: {str(e)}"}
+
+
+@agent_tool(
+    name="switch_plugin_version",
+    description="一键切换/回滚插件的当前生效版本号(管理员专有)",
+    is_dangerous=True,
+)
+async def switch_plugin_version(
+    version: str,
+    plugin_id: Optional[int] = None,
+    plugin_name: Optional[str] = None,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """切换插件生效版本"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        target_id = plugin_id
+        if target_id is None and plugin_name:
+            stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
+            target_id = (await db.execute(stmt)).scalar_one_or_none()
+
+        if not target_id:
+            return {"error": f"未找到插件: id={plugin_id}, name={plugin_name}"}
+
+        plugin = await PluginService.switch_version(db, target_id, version.strip())
+        return {
+            "success": True,
+            "plugin_id": plugin.id,
+            "name": plugin.name,
+            "current_version": plugin.latest_version,
+            "message": f"插件 {plugin.name} 生效版本已成功切换为 {version}",
+        }
+    except Exception as e:
+        return {"error": f"切换插件版本失败: {str(e)}"}

+ 88 - 0
app/services/agent/tools/builtin/product_tools.py

@@ -0,0 +1,88 @@
+# app/services/agent/tools/builtin/product_tools.py
+from typing import Optional, Dict, Any, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, or_, desc
+from app.models.product import VasProduct
+from app.services.agent.tools.registry import agent_tool
+
+
+@agent_tool(
+    name="search_products",
+    description="检索可用的增值服务/签证/产品列表,支持按国家、签证类型或关键词搜索",
+)
+async def search_products(
+    keyword: Optional[str] = None,
+    country: Optional[str] = None,
+    visa_type: Optional[str] = None,
+    limit: int = 10,
+    *,
+    db: AsyncSession,
+) -> Dict[str, Any]:
+    """搜索并列出可用的产品"""
+    limit = max(1, min(limit, 30))
+
+    stmt = select(VasProduct).where(VasProduct.enabled == 1)
+
+    if country and country.strip():
+        stmt = stmt.where(VasProduct.country.ilike(f"%{country.strip()}%"))
+    if visa_type and visa_type.strip():
+        stmt = stmt.where(VasProduct.visa_type.ilike(f"%{visa_type.strip()}%"))
+    if keyword and keyword.strip():
+        kw = f"%{keyword.strip()}%"
+        stmt = stmt.where(or_(VasProduct.title.ilike(kw), VasProduct.description.ilike(kw)))
+
+    stmt = stmt.order_by(desc(VasProduct.recommend_score), desc(VasProduct.id)).limit(limit)
+
+    res = await db.execute(stmt)
+    products = res.scalars().all()
+
+    items = []
+    for p in products:
+        items.append({
+            "product_id": p.id,
+            "title": p.title,
+            "country": p.country,
+            "city": p.city,
+            "visa_type": p.visa_type,
+            "price_amount": p.price_amount,
+            "currency": p.price_currency,
+            "description": p.description[:200] if p.description else "",
+        })
+
+    return {
+        "count": len(items),
+        "products": items,
+    }
+
+
+@agent_tool(
+    name="get_product_detail",
+    description="获取指定商品ID的详细信息与配置说明",
+)
+async def get_product_detail(
+    product_id: int,
+    *,
+    db: AsyncSession,
+) -> Dict[str, Any]:
+    """获取单个产品的详细信息"""
+    stmt = select(VasProduct).where(VasProduct.id == product_id)
+    res = await db.execute(stmt)
+    p = res.scalar_one_or_none()
+
+    if not p:
+        return {"error": f"商品 ID {product_id} 不存在"}
+
+    return {
+        "product_id": p.id,
+        "title": p.title,
+        "country": p.country,
+        "city": p.city,
+        "visa_type": p.visa_type,
+        "provider": p.provider,
+        "price_amount": p.price_amount,
+        "currency": p.price_currency,
+        "enabled": bool(p.enabled),
+        "description": p.description,
+        "extra_fields": p.extra_fields,
+        "schema_id": p.schema_id,
+    }

+ 157 - 0
app/services/agent/tools/builtin/proxy_pool_tools.py

@@ -0,0 +1,157 @@
+# app/services/agent/tools/builtin/proxy_pool_tools.py
+from typing import Optional, Dict, Any, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, func, desc
+
+from app.models.user import VasUser
+from app.models.proxy_pool import ProxyPool
+from app.services.agent.tools.registry import agent_tool
+
+ADMIN_CHECK_MSG = "权限不足:该运维操作仅系统管理员(admin)可执行"
+
+
+@agent_tool(
+    name="get_proxy_pool_stats",
+    description="按所属代理池统计代理总数、可用状态(active/disable)及可用就绪比例(管理员专有)",
+)
+async def get_proxy_pool_stats(
+    pool_name: Optional[str] = None,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """统计代理池健康指标"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        stmt = select(
+            ProxyPool.pool_name,
+            ProxyPool.status,
+            func.count(ProxyPool.id).label("count"),
+        ).group_by(ProxyPool.pool_name, ProxyPool.status)
+
+        if pool_name and pool_name.strip():
+            stmt = stmt.where(ProxyPool.pool_name == pool_name.strip())
+
+        res = await db.execute(stmt)
+        rows = res.all()
+
+        pools_summary: Dict[str, Dict[str, int]] = {}
+        total_proxies = 0
+
+        for r_pool, r_status, r_count in rows:
+            if r_pool not in pools_summary:
+                pools_summary[r_pool] = {"total": 0, "active": 0, "disable": 0}
+            pools_summary[r_pool]["total"] += r_count
+            if r_status == "active":
+                pools_summary[r_pool]["active"] += r_count
+            elif r_status == "disable":
+                pools_summary[r_pool]["disable"] += r_count
+            total_proxies += r_count
+
+        return {
+            "total_proxies": total_proxies,
+            "pools_count": len(pools_summary),
+            "pools": pools_summary,
+        }
+    except Exception as e:
+        return {"error": f"统计代理池失败: {str(e)}"}
+
+
+@agent_tool(
+    name="list_proxies",
+    description="查询代理池中的代理列表,支持按代理池名与状态筛选(管理员专有)",
+)
+async def list_proxies(
+    pool_name: Optional[str] = None,
+    status: Optional[str] = None,
+    page: int = 1,
+    page_size: int = 20,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """查询代理列表"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    try:
+        stmt = select(ProxyPool)
+        if pool_name and pool_name.strip():
+            stmt = stmt.where(ProxyPool.pool_name == pool_name.strip())
+        if status and status.strip():
+            stmt = stmt.where(ProxyPool.status == status.strip().lower())
+
+        page = max(1, page)
+        page_size = min(page_size, 50)
+        stmt = stmt.order_by(desc(ProxyPool.id)).offset((page - 1) * page_size).limit(page_size)
+
+        res = await db.execute(stmt)
+        proxies = res.scalars().all()
+
+        items = []
+        for p in proxies:
+            # 遮蔽 IP 末段保护安全
+            ip_parts = p.ip.split(".")
+            masked_ip = ".".join(ip_parts[:2] + ["*", "*"]) if len(ip_parts) == 4 else p.ip[:8] + "***"
+
+            items.append({
+                "id": p.id,
+                "pool_name": p.pool_name,
+                "proto": p.proto,
+                "masked_ip": masked_ip,
+                "port": p.port,
+                "status": p.status,
+                "next_use_time": p.next_use_time.strftime("%Y-%m-%d %H:%M:%S") if p.next_use_time else None,
+                "time_zone": p.time_zone,
+            })
+
+        return {
+            "count": len(items),
+            "page": page,
+            "proxies": items,
+        }
+    except Exception as e:
+        return {"error": f"获取代理列表失败: {str(e)}"}
+
+
+@agent_tool(
+    name="toggle_proxy_status",
+    description="将指定代理设置为 active(启用)或 disable(禁用)(管理员专有)",
+    is_dangerous=True,
+)
+async def toggle_proxy_status(
+    proxy_id: int,
+    status: str,
+    *,
+    db: AsyncSession,
+    current_user: VasUser,
+) -> Dict[str, Any]:
+    """启停单个代理"""
+    if current_user.role != "admin":
+        return {"error": ADMIN_CHECK_MSG}
+
+    clean_status = status.strip().lower()
+    if clean_status not in ("active", "disable"):
+        return {"error": f"无效状态: '{status}',仅支持 'active' 或 'disable'"}
+
+    try:
+        stmt = select(ProxyPool).where(ProxyPool.id == proxy_id)
+        proxy = (await db.execute(stmt)).scalar_one_or_none()
+        if not proxy:
+            return {"error": f"代理 ID #{proxy_id} 不存在"}
+
+        proxy.status = clean_status
+        await db.commit()
+        await db.refresh(proxy)
+
+        return {
+            "success": True,
+            "proxy_id": proxy.id,
+            "pool_name": proxy.pool_name,
+            "new_status": proxy.status,
+            "message": f"代理 #{proxy_id} 状态已更新为 {clean_status}",
+        }
+    except Exception as e:
+        return {"error": f"更新代理状态失败: {str(e)}"}

+ 177 - 0
app/services/agent/tools/registry.py

@@ -0,0 +1,177 @@
+# app/services/agent/tools/registry.py
+import inspect
+import functools
+from typing import Callable, Dict, Any, List, Optional, get_type_hints, get_origin, get_args
+from app.core.logger import logger
+
+
+# 上下文保留关键字,这些参数不向 LLM 暴露,而在执行时由框架自动注入
+CONTEXT_PARAM_NAMES = {"db", "current_user", "redis_client", "context"}
+
+
+def python_type_to_json_type(py_type: Any) -> str:
+    """将 Python 类型转换为 JSON Schema 类型"""
+    origin = get_origin(py_type)
+    if origin is not None:
+        if origin in (list, List):
+            return "array"
+        if origin in (dict, Dict):
+            return "object"
+        # 处理 Optional[T] / Union[T, None]
+        args = get_args(py_type)
+        non_none_args = [a for a in args if a is not type(None)]
+        if non_none_args:
+            return python_type_to_json_type(non_none_args[0])
+
+    if py_type in (int,):
+        return "integer"
+    if py_type in (float,):
+        return "number"
+    if py_type in (bool,):
+        return "boolean"
+    if py_type in (dict, Dict):
+        return "object"
+    if py_type in (list, List):
+        return "array"
+    return "string"
+
+
+class AgentTool:
+    """Agent 工具包装类"""
+
+    def __init__(
+        self,
+        name: str,
+        description: str,
+        func: Callable,
+        is_dangerous: bool = False,
+    ):
+        self.name = name
+        self.description = description.strip()
+        self.func = func
+        self.is_dangerous = is_dangerous
+        self.is_async = inspect.iscoroutinefunction(func)
+        self.signature = inspect.signature(func)
+        self.type_hints = get_type_hints(func) if hasattr(func, "__annotations__") else {}
+        self.openai_schema = self._build_openai_schema()
+
+    def _build_openai_schema(self) -> Dict[str, Any]:
+        """根据函数签名自动推导 OpenAI Tool Function Schema"""
+        properties = {}
+        required = []
+
+        for param_name, param in self.signature.parameters.items():
+            if param_name in CONTEXT_PARAM_NAMES:
+                continue
+
+            param_type = self.type_hints.get(param_name, str)
+            json_type = python_type_to_json_type(param_type)
+
+            param_desc = f"Parameter {param_name}"
+            # 尝试从 docstring 中提取简单描述(如果存在)
+            properties[param_name] = {
+                "type": json_type,
+                "description": param_desc,
+            }
+
+            # 判断是否必选
+            if param.default is inspect.Parameter.empty:
+                # 没有默认值,且不是 Optional
+                origin = get_origin(param_type)
+                args = get_args(param_type)
+                is_optional = origin is not None and type(None) in args
+                if not is_optional:
+                    required.append(param_name)
+
+        return {
+            "type": "function",
+            "function": {
+                "name": self.name,
+                "description": self.description,
+                "parameters": {
+                    "type": "object",
+                    "properties": properties,
+                    "required": required,
+                },
+            },
+        }
+
+    async def execute(self, arguments: Dict[str, Any], context: Optional[Dict[str, Any]] = None) -> Any:
+        """执行该工具,并根据需要注入上下文(如 db, current_user)"""
+        context = context or {}
+        call_kwargs = {}
+
+        for param_name, param in self.signature.parameters.items():
+            if param_name in CONTEXT_PARAM_NAMES:
+                if param_name in context:
+                    call_kwargs[param_name] = context[param_name]
+                elif "context" in context and param_name in context["context"]:
+                    call_kwargs[param_name] = context["context"][param_name]
+            elif param_name in arguments:
+                call_kwargs[param_name] = arguments[param_name]
+            elif param.default is not inspect.Parameter.empty:
+                call_kwargs[param_name] = param.default
+
+        try:
+            if self.is_async:
+                result = await self.func(**call_kwargs)
+            else:
+                result = self.func(**call_kwargs)
+            return result
+        except Exception as e:
+            logger.error(f"[AgentTool:{self.name}] execution error: {e}", exc_info=True)
+            return {"error": str(e)}
+
+
+class ToolRegistry:
+    """全局工具注册中心"""
+
+    def __init__(self):
+        self._tools: Dict[str, AgentTool] = {}
+
+    def register(
+        self,
+        name: Optional[str] = None,
+        description: Optional[str] = None,
+        is_dangerous: bool = False,
+    ):
+        """装饰器:注册函数为 Agent 工具"""
+        def decorator(func: Callable):
+            tool_name = name or func.__name__
+            tool_desc = description or (func.__doc__ or f"Tool {tool_name}").strip()
+            tool = AgentTool(
+                name=tool_name,
+                description=tool_desc,
+                func=func,
+                is_dangerous=is_dangerous,
+            )
+            self._tools[tool_name] = tool
+            return func
+
+        return decorator
+
+    def get_tool(self, name: str) -> Optional[AgentTool]:
+        return self._tools.get(name)
+
+    def get_all_tools(self) -> List[AgentTool]:
+        return list(self._tools.values())
+
+    def get_openai_tools_schema(self) -> List[Dict[str, Any]]:
+        """获取所有已注册工具的 OpenAI Function Calling 定义列表"""
+        return [tool.openai_schema for tool in self._tools.values()]
+
+    async def execute(
+        self,
+        name: str,
+        arguments: Dict[str, Any],
+        context: Optional[Dict[str, Any]] = None,
+    ) -> Any:
+        tool = self.get_tool(name)
+        if not tool:
+            return {"error": f"Tool '{name}' not found in registry"}
+        return await tool.execute(arguments, context=context)
+
+
+# 全局默认单例注册中心
+tool_registry = ToolRegistry()
+agent_tool = tool_registry.register

+ 128 - 1
app/services/llm_service.py

@@ -172,4 +172,131 @@ Extract data from the text strictly based on the provided JSON Schema.
                     raise BizLogicError(f"LLM invocation error: {str(e)}")
                 await asyncio.sleep(0.5)
 
-        raise BizLogicError("LLM request failed")
+        raise BizLogicError("LLM request failed")
+
+    @classmethod
+    async def chat_completion_with_tools_async(
+        cls,
+        messages: list[dict],
+        tools: Optional[list[dict]] = None,
+        model: Optional[str] = None,
+        temperature: Optional[float] = None,
+        max_retries: int = 1,
+    ) -> dict:
+        """
+        调用 OpenAI 兼容接口,支持 Function Calling (tools)
+        返回 choices[0]["message"] (包含 role, content, tool_calls 等)
+        """
+        api_key = cls.get_api_key()
+        if not api_key:
+            logger.warning("[LlmService] No LLM API Key configured.")
+            raise BizLogicError("LLM API Key not configured")
+
+        url = cls.get_completions_url()
+        selected_model = (model or "").strip() or cls.get_default_model()
+        temp = settings.llm_temperature if temperature is None else temperature
+        timeout_seconds = settings.llm_timeout_seconds or 45
+
+        headers = {
+            "Authorization": f"Bearer {api_key}",
+            "Content-Type": "application/json",
+        }
+
+        payload: dict[str, Any] = {
+            "model": selected_model,
+            "messages": messages,
+            "temperature": temp,
+        }
+        if tools:
+            payload["tools"] = tools
+            payload["tool_choice"] = "auto"
+
+        timeout = aiohttp.ClientTimeout(total=float(timeout_seconds))
+
+        for attempt in range(max_retries + 1):
+            try:
+                async with aiohttp.ClientSession(timeout=timeout) as session:
+                    async with session.post(url, headers=headers, json=payload) as response:
+                        if response.status != 200:
+                            error_text = await response.text()
+                            logger.error(f"[LlmService] HTTP {response.status} from {url}: {error_text}")
+                            if attempt == max_retries:
+                                raise BizLogicError(f"LLM request failed: HTTP {response.status} - {error_text[:200]}")
+                            await asyncio.sleep(0.5)
+                            continue
+
+                        result = await response.json()
+                        choices = result.get("choices", [])
+                        if not choices:
+                            raise BizLogicError("LLM response did not contain completion choices")
+
+                        return choices[0].get("message", {})
+            except BizLogicError:
+                raise
+            except Exception as e:
+                logger.error(f"[LlmService] Exception on attempt {attempt + 1}: {e}")
+                if attempt == max_retries:
+                    raise BizLogicError(f"LLM invocation error: {str(e)}")
+                await asyncio.sleep(0.5)
+
+        raise BizLogicError("LLM request failed")
+
+    @classmethod
+    async def chat_completion_stream_async(
+        cls,
+        messages: list[dict],
+        tools: Optional[list[dict]] = None,
+        model: Optional[str] = None,
+        temperature: Optional[float] = None,
+    ):
+        """
+        流式调用 OpenAI 兼容接口,逐块 yield delta 字典
+        """
+        api_key = cls.get_api_key()
+        if not api_key:
+            logger.warning("[LlmService] No LLM API Key configured.")
+            raise BizLogicError("LLM API Key not configured")
+
+        url = cls.get_completions_url()
+        selected_model = (model or "").strip() or cls.get_default_model()
+        temp = settings.llm_temperature if temperature is None else temperature
+        timeout_seconds = settings.llm_timeout_seconds or 60
+
+        headers = {
+            "Authorization": f"Bearer {api_key}",
+            "Content-Type": "application/json",
+        }
+
+        payload: dict[str, Any] = {
+            "model": selected_model,
+            "messages": messages,
+            "temperature": temp,
+            "stream": True,
+        }
+        if tools:
+            payload["tools"] = tools
+            payload["tool_choice"] = "auto"
+
+        timeout = aiohttp.ClientTimeout(total=float(timeout_seconds))
+        async with aiohttp.ClientSession(timeout=timeout) as session:
+            async with session.post(url, headers=headers, json=payload) as response:
+                if response.status != 200:
+                    error_text = await response.text()
+                    logger.error(f"[LlmService stream] HTTP {response.status} from {url}: {error_text}")
+                    raise BizLogicError(f"LLM stream request failed: HTTP {response.status}")
+
+                async for line in response.content:
+                    line_str = line.decode("utf-8").strip()
+                    if not line_str or not line_str.startswith("data:"):
+                        continue
+                    data_str = line_str[5:].strip()
+                    if data_str == "[DONE]":
+                        break
+                    try:
+                        chunk = json.loads(data_str)
+                        choices = chunk.get("choices", [])
+                        if choices:
+                            delta = choices[0].get("delta", {})
+                            yield delta
+                    except Exception:
+                        continue

+ 305 - 0
tests/test_agent.py

@@ -0,0 +1,305 @@
+# -*- coding: utf-8 -*-
+import unittest
+import json
+from unittest.mock import patch, AsyncMock, MagicMock
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.schemas.agent import AgentChatRequest
+from app.models.user import VasUser
+from app.services.agent.tools.registry import ToolRegistry, agent_tool, tool_registry
+from app.services.agent.memory import AgentMemory
+from app.services.agent.engine import AgentEngine
+from app.services.agent.tools.builtin.order_tools import query_user_orders, cancel_user_order
+from app.services.agent.tools.builtin.product_tools import search_products
+
+
+class TestAgentToolsAndRegistry(unittest.IsolatedAsyncioTestCase):
+    """测试工具注册、OpenAPI Schema 自动生成与上下文自动注入"""
+
+    def test_tool_schema_generation(self):
+        registry = ToolRegistry()
+
+        @registry.register(name="mock_search", description="Search items")
+        def mock_search(keyword: str, limit: int = 10, *, db: AsyncSession, current_user: VasUser):
+            return {"keyword": keyword, "limit": limit}
+
+        tool = registry.get_tool("mock_search")
+        self.assertIsNotNone(tool)
+        schema = tool.openai_schema
+
+        self.assertEqual(schema["type"], "function")
+        fn = schema["function"]
+        self.assertEqual(fn["name"], "mock_search")
+        self.assertEqual(fn["description"], "Search items")
+
+        # 验证保留参数 db, current_user 没有暴露给 LLM
+        props = fn["parameters"]["properties"]
+        self.assertIn("keyword", props)
+        self.assertIn("limit", props)
+        self.assertNotIn("db", props)
+        self.assertNotIn("current_user", props)
+        self.assertEqual(props["keyword"]["type"], "string")
+        self.assertEqual(props["limit"]["type"], "integer")
+
+        # keyword 无默认值应为必填,limit 有默认值不应在 required 中
+        self.assertIn("keyword", fn["parameters"]["required"])
+        self.assertNotIn("limit", fn["parameters"]["required"])
+
+    async def test_tool_execution_with_context_injection(self):
+        registry = ToolRegistry()
+
+        @registry.register(name="echo_tool", description="Echo tool")
+        async def echo_tool(msg: str, *, db: AsyncSession, current_user: VasUser):
+            return {
+                "echo": msg,
+                "user_id": current_user.id,
+                "db_injected": db is not None,
+            }
+
+        mock_user = VasUser(id="usr_123", role="user")
+        mock_db = MagicMock(spec=AsyncSession)
+
+        result = await registry.execute(
+            "echo_tool",
+            arguments={"msg": "hello agent"},
+            context={"db": mock_db, "current_user": mock_user},
+        )
+
+        self.assertEqual(result["echo"], "hello agent")
+        self.assertEqual(result["user_id"], "usr_123")
+        self.assertTrue(result["db_injected"])
+
+
+class TestAgentMemory(unittest.IsolatedAsyncioTestCase):
+    """测试 Redis 会话记忆"""
+
+    @patch("app.services.agent.memory.get_redis_client")
+    async def test_memory_append_and_get(self, mock_get_redis):
+        mock_redis = AsyncMock()
+        storage = {}
+
+        async def fake_get(key):
+            return storage.get(key)
+
+        async def fake_setex(key, ttl, value):
+            storage[key] = value
+
+        async def fake_delete(key):
+            storage.pop(key, None)
+
+        mock_redis.get = fake_get
+        mock_redis.setex = fake_setex
+        mock_redis.delete = fake_delete
+        mock_get_redis.return_value = mock_redis
+
+        session_id = "test_sess_001"
+        # 初始为空
+        history = await AgentMemory.get_history(session_id)
+        self.assertEqual(history, [])
+
+        # 追加新消息
+        await AgentMemory.append_messages(
+            session_id,
+            [
+                {"role": "user", "content": "我的订单状态是什么?"},
+                {"role": "assistant", "content": "您有1笔待支付订单。"},
+            ],
+        )
+
+        history2 = await AgentMemory.get_history(session_id)
+        self.assertEqual(len(history2), 2)
+        self.assertEqual(history2[0]["content"], "我的订单状态是什么?")
+
+        # 清除 session
+        await AgentMemory.clear_session(session_id)
+        history3 = await AgentMemory.get_history(session_id)
+        self.assertEqual(history3, [])
+
+
+class TestAgentEngine(unittest.IsolatedAsyncioTestCase):
+    """测试 Agent 编排引擎:多步工具调用与流式事件生成"""
+
+    @patch("app.services.agent.memory.AgentMemory.append_messages", new_callable=AsyncMock)
+    @patch("app.services.agent.memory.AgentMemory.get_history", new_callable=AsyncMock)
+    @patch("app.services.llm_service.LlmService.chat_completion_with_tools_async")
+    async def test_agent_sync_tool_call_loop(self, mock_chat, mock_get_history, mock_append):
+        mock_get_history.return_value = []
+        mock_user = VasUser(id="user_test_99", role="user")
+        mock_db = MagicMock(spec=AsyncSession)
+
+        # 模拟 LLM 第一步发起工具调用,第二步汇总回答
+        mock_chat.side_effect = [
+            {
+                "role": "assistant",
+                "content": "",
+                "tool_calls": [
+                    {
+                        "id": "call_abc123",
+                        "type": "function",
+                        "function": {
+                            "name": "query_user_orders",
+                            "arguments": json.dumps({"limit": 5}),
+                        },
+                    }
+                ],
+            },
+            {
+                "role": "assistant",
+                "content": "您当前有0笔订单。",
+                "tool_calls": None,
+            },
+        ]
+
+        # 模拟 db.execute 返回空订单列表
+        mock_result = MagicMock()
+        mock_result.scalars().all.return_value = []
+        mock_db.execute = AsyncMock(return_value=mock_result)
+
+        request = AgentChatRequest(message="查一下我的最新订单", session_id="test_sess_run")
+        response = await AgentEngine.run_sync(
+            request=request,
+            current_user=mock_user,
+            db=mock_db,
+        )
+
+        self.assertEqual(response.answer, "您当前有0笔订单。")
+        self.assertEqual(len(response.steps), 1)
+        self.assertEqual(response.steps[0].tool, "query_user_orders")
+        self.assertEqual(response.steps[0].arguments, {"limit": 5})
+        self.assertFalse(response.steps[0].is_error)
+
+    @patch("app.services.agent.memory.AgentMemory.append_messages", new_callable=AsyncMock)
+    @patch("app.services.agent.memory.AgentMemory.get_history", new_callable=AsyncMock)
+    @patch("app.services.llm_service.LlmService.chat_completion_with_tools_async")
+    async def test_agent_stream_events(self, mock_chat, mock_get_history, mock_append):
+        mock_get_history.return_value = []
+        mock_user = VasUser(id="user_test_99", role="user")
+        mock_db = MagicMock(spec=AsyncSession)
+
+        # 模拟无工具调用直接回答
+        mock_chat.return_value = {
+            "role": "assistant",
+            "content": "你好,我是你的系统业务助手!",
+            "tool_calls": None,
+        }
+
+        request = AgentChatRequest(message="你好", stream=True)
+        events = []
+        async for chunk in AgentEngine.run_stream(
+            request=request,
+            current_user=mock_user,
+            db=mock_db,
+        ):
+            events.append(chunk)
+
+        combined = "".join(events)
+        self.assertIn("event: think", combined)
+        self.assertIn("event: message", combined)
+        self.assertIn("event: finish", combined)
+        self.assertIn("你好,我是你的系统业务助手!", combined)
+
+
+class TestAgentAPIEndpoints(unittest.TestCase):
+    """测试 FastAPI 接口层挂载与鉴权"""
+
+    def setUp(self):
+        from fastapi.testclient import TestClient
+        from app.main import app
+        from app.core.auth import get_current_user
+
+        self.mock_user = VasUser(id="api_test_user", role="user", email="test@example.com")
+
+        async def override_current_user():
+            return self.mock_user
+
+        app.dependency_overrides[get_current_user] = override_current_user
+        self.client = TestClient(app)
+
+    def tearDown(self):
+        from app.main import app
+        app.dependency_overrides.clear()
+
+    def test_list_tools_endpoint(self):
+        response = self.client.get("/api/agent/tools")
+        self.assertEqual(response.status_code, 200)
+        data = response.json()
+        self.assertEqual(data["code"], 0)
+        tool_names = [t["name"] for t in data["data"]]
+        self.assertIn("query_user_orders", tool_names)
+        self.assertIn("search_products", tool_names)
+        self.assertIn("list_node_configurations", tool_names)
+        self.assertIn("toggle_node_configuration", tool_names)
+        self.assertIn("rollback_node_configuration", tool_names)
+        self.assertIn("list_plugins", tool_names)
+        self.assertIn("get_proxy_pool_stats", tool_names)
+
+    @patch("app.services.agent.engine.AgentEngine.run_sync")
+    def test_agent_chat_sync_endpoint(self, mock_run_sync):
+        from app.schemas.agent import AgentChatResponse
+
+        mock_run_sync.return_value = AgentChatResponse(
+            session_id="sess_123",
+            answer="为您查到以下商品",
+            steps=[],
+            steps_count=0,
+        )
+
+        response = self.client.post(
+            "/api/agent/chat",
+            json={"message": "帮我看看有什么商品", "stream": False},
+        )
+        self.assertEqual(response.status_code, 200)
+        data = response.json()
+        self.assertEqual(data["code"], 0)
+        self.assertEqual(data["data"]["answer"], "为您查到以下商品")
+
+
+class TestOpsToolsPermissions(unittest.IsolatedAsyncioTestCase):
+    """测试运维管理工具的管理员角色鉴权拦截"""
+
+    async def test_non_admin_blocked_from_node_configs(self):
+        from app.services.agent.tools.builtin.node_config_tools import list_node_configurations, toggle_node_configuration
+
+        normal_user = VasUser(id="u1", role="user")
+        mock_db = MagicMock(spec=AsyncSession)
+
+        res1 = await list_node_configurations(db=mock_db, current_user=normal_user)
+        self.assertIn("error", res1)
+        self.assertIn("权限不足", res1["error"])
+
+        res2 = await toggle_node_configuration(entry_type="booker", entry_id=1, enable=True, db=mock_db, current_user=normal_user)
+        self.assertIn("error", res2)
+        self.assertIn("权限不足", res2["error"])
+
+    async def test_non_admin_blocked_from_plugins_and_proxies(self):
+        from app.services.agent.tools.builtin.plugin_tools import list_plugins
+        from app.services.agent.tools.builtin.proxy_pool_tools import get_proxy_pool_stats
+
+        normal_user = VasUser(id="u1", role="user")
+        mock_db = MagicMock(spec=AsyncSession)
+
+        p_res = await list_plugins(db=mock_db, current_user=normal_user)
+        self.assertIn("error", p_res)
+        self.assertIn("权限不足", p_res["error"])
+
+        prx_res = await get_proxy_pool_stats(db=mock_db, current_user=normal_user)
+        self.assertIn("error", prx_res)
+        self.assertIn("权限不足", prx_res["error"])
+
+    @patch("app.services.node_configuration_service.NodeConfigurationService.list_entries")
+    async def test_admin_allowed_for_node_configs(self, mock_list_entries):
+        from app.services.agent.tools.builtin.node_config_tools import list_node_configurations
+
+        admin_user = VasUser(id="admin_1", role="admin")
+        mock_db = MagicMock(spec=AsyncSession)
+        mock_list_entries.return_value = ([], 0)
+
+        res = await list_node_configurations(db=mock_db, current_user=admin_user)
+        self.assertNotIn("error", res)
+        self.assertEqual(res["total"], 0)
+
+
+
+if __name__ == "__main__":
+    unittest.main()
+