fix(agent): show API parameters in verbose mode

This commit is contained in:
jxxghp
2026-09-01 11:57:36 +08:00
parent 41c54d138d
commit 449ef4b8df
4 changed files with 94 additions and 3 deletions

View File

@@ -11,10 +11,14 @@ from pydantic import BaseModel, Field, PrivateAttr
from app.agent.api.executor import ApiExecutionContext, ApiExecutionError, MoviePilotApiExecutor
from app.agent.policy.api import resolve_api_operation
from app.agent.policy.contracts import PrincipalRole
from app.agent.policy.sanitizer import summarize_input
from app.agent.tools.base import MoviePilotTool
from app.agent.tools.tags import ToolTag
from app.schemas.types import NotificationChannel
_TOOL_MESSAGE_OPERATION_MAX_CHARS = 96
_TOOL_MESSAGE_PARAMETER_MAX_CHARS = 320
@lru_cache(maxsize=1)
def _load_api_mcp_input_schema() -> dict[str, Any]:
@@ -100,9 +104,25 @@ class MoviePilotApiTool(MoviePilotTool):
self._executor = executor
def get_tool_message(self, **kwargs: Any) -> Optional[str]:
"""生成结构化 API 调用提示。"""
operation_id = kwargs.get("operation_id") or "未知操作"
return f"调用 MoviePilot API:{operation_id}"
"""生成包含脱敏、有界主要参数的结构化 API 调用提示。"""
operation_id = summarize_input(
kwargs.get("operation_id") or "未知操作",
max_chars=_TOOL_MESSAGE_OPERATION_MAX_CHARS,
)
message = f"调用 MoviePilot API:{operation_id}"
parameters = {
field_name: field_value
for field_name in ("path_params", "query", "body")
if (field_value := kwargs.get(field_name)) is not None
and not (isinstance(field_value, dict) and not field_value)
}
if not parameters:
return message
parameter_summary = summarize_input(
parameters,
max_chars=_TOOL_MESSAGE_PARAMETER_MAX_CHARS,
)
return f"{message},主要参数:{parameter_summary}"
def get_mcp_input_schema(self) -> dict[str, Any]:
"""返回包含全部白名单 operation 精确参数的 MCP JSON Schema。"""

View File

@@ -366,4 +366,11 @@ action,并使用 MoviePilot 已配置的具体服务实例访问其自身 API
- 完整锁定测试已通过:4 个分片分别为 `1620 passed, 3 skipped`、`1860 passed, 4 skipped`、`1917 passed`、`2250 passed, 2 skipped`,合计 `7647 passed, 9 skipped`;变更文件 Pylint 为 `10.00/10`,Ruff、生成物幂等与 `git diff --check` 均通过
- 当前未托管后端使用的 API 身份与工作区 CLI 配置不一致,真实 CLI 调用被既有 API key 校验拒绝;本轮未擅自重启正在运行的服务,运行进程需在代码部署并重载后再做在线会话复验
### 2026-09-01:啰嗦模式 API 主要参数展示修复
- 旧领域工具各自通过 `get_tool_message()` 展示目标和主要参数;收敛为 `moviepilot_api` 后,该方法只展示 `operation_id`,导致 Web Agent 与通知渠道在啰嗦模式下失去 `path_params`、`query` 和 `body` 的调用上下文
- `moviepilot_api` 现按路径、查询、请求体顺序生成最多 320 字符的主要参数摘要;空参数桶不展示,工具执行与 API 输入结构保持不变
- 参数摘要统一复用宿主递归脱敏器,设置凭据、密码、Cookie、Token 与 API key 等仅显示 `***`,避免为了恢复可观察性而泄露敏感输入
- 新增 Web Agent 实际流式回调回归和设置凭据脱敏回归;扩展 Agent/API/流式专项 `487 passed`,完整锁定测试 4 个分片分别为 `1620 passed, 3 skipped`、`1860 passed, 4 skipped`、`1917 passed`、`2253 passed, 2 skipped`,合计 `7650 passed, 9 skipped`;Ruff、Pylint `10.00/10` 和全量 mypy ratchet 均通过
本文件作为本次重构的持续记录,保留阶段状态、实际变更、验证结果、提交状态与已知基线边界。

View File

@@ -73,6 +73,32 @@ def test_api_operation_registry_matches_migration_batches() -> None:
}.issubset(API_OPERATION_ROUTES)
def test_api_tool_message_displays_secret_safe_major_parameters() -> None:
"""啰嗦模式提示应展示 API 主要参数,同时对设置凭据值脱敏。"""
tool = MoviePilotApiTool(session_id="session", user_id="api_user")
list_message = tool.get_tool_message(
operation_id="subscription.list",
query={"page": 1, "count": 20},
)
secret_message = tool.get_tool_message(
operation_id="config.system.update",
body={
"setting_key": "OPENAI_API_KEY",
"value": "sk-secret-value",
"operation": "replace",
},
)
assert list_message == (
'调用 MoviePilot API:subscription.list,主要参数:'
'{"query": {"page": 1, "count": 20}}'
)
assert "OPENAI_API_KEY" in secret_message
assert '"value": "***"' in secret_message
assert "sk-secret-value" not in secret_message
def test_music_operations_expose_bidirectional_artist_album_navigation() -> None:
"""音乐 Skill 必须完整暴露作品到作者、作者到作品及关联浏览合同。"""
schema = MoviePilotApiTool(session_id="session", user_id="api_user").get_mcp_input_schema()

View File

@@ -11,7 +11,9 @@ from app.agent.callback import StreamingHandler
from app.agent.middleware.subagents import is_subagent_stream_metadata
from app.agent.orchestrator import _ThinkTagStripper
from app.agent.tools.base import MoviePilotTool
from app.agent.tools.impl.api import MoviePilotApiTool
from app.agent.tools.impl.send_voice_message import SendVoiceMessageTool
from app.agent.web import _get_web_agent_streaming_handler_type
from app.api.endpoints.openai import _get_openai_streaming_handler_type
from app.runtime.config import settings
from app.schemas.message import Message, MessageResponse
@@ -457,6 +459,42 @@ class TestAgentToolStreaming:
assert text == "前置内容\n\n⚙️ => run test tool\n\n"
assert rich_message == "前置内容\n\n> ⚙️ => run test tool\n\n"
def test_verbose_web_api_tool_message_includes_major_parameters(self):
"""Web Agent 啰嗦模式应实时输出 API operation 及其主要参数。"""
async def _run():
emitted = []
handler = _get_web_agent_streaming_handler_type()(emitted.append)
await handler.start_streaming(
channel=NotificationChannel.WebAgent.value,
source="web-agent",
user_id="1",
username="admin",
)
tool = MoviePilotApiTool(session_id="session-1", user_id="1")
tool.set_stream_handler(handler)
with (
patch.object(settings, "AI_AGENT_VERBOSE", True),
patch.object(MoviePilotApiTool, "run", new_callable=AsyncMock) as run_mock,
):
run_mock.return_value = '{"success": true}'
result = await tool._arun(
operation_id="subscription.list",
query={"page": 1, "count": 20},
)
return result, "".join(emitted), handler._buffer
result, emitted, buffered = asyncio.run(_run())
expected = (
'\n\n⚙️ => 调用 MoviePilot API:subscription.list,主要参数:'
'{"query": {"page": 1, "count": 20}}\n\n'
)
assert result == '{"success": true}'
assert emitted == expected
assert buffered == expected
def test_rich_message_keeps_body_text_unquoted_for_telegram(self):
"""校验 Telegram 富文本只转换工具摘要行,正文保持原样。"""
handler = StreamingHandler()