"""工具参数守卫:拒绝参数过大的工具调用,防止模型生成超大输入。""" import json from app.application.agent.extensions import ( AgentRunContext, BeforeToolCallDecision, ExtensionRegistry, ToolCallContext, ) from app.application.agent.python_skills import PythonSkillDefinition # 单次工具调用参数序列化后的字符上限;超出则拒绝并要求模型精简。 _MAX_ARG_CHARS = 8000 async def _reject_oversized_args( call: ToolCallContext, _run: AgentRunContext ) -> BeforeToolCallDecision | None: size = len(json.dumps(call.input, ensure_ascii=False)) if size <= _MAX_ARG_CHARS: return None return BeforeToolCallDecision( allowed=False, reason=f"工具 {call.name} 的参数过大({size} 字符超过 {_MAX_ARG_CHARS}),请精简后重试。", ) def _setup(registry: ExtensionRegistry) -> None: registry.add_before_tool_hook(_reject_oversized_args) SKILL = PythonSkillDefinition( name="arg_guard", description="拒绝参数过大的工具调用,避免超大输入挤占上下文或触发限制。", triggers=("大参数", "arg guard"), instructions="发起工具调用时保持参数精简;超大参数会被拒绝。", setup=_setup, )