mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 13:32:38 +00:00
工具调用失败能自救;agent 改成一步一个工具
起因是一条没人看得懂的报错:
工具 db_query__shop 执行失败:
_make_query_tool.<locals>._run() got an unexpected keyword argument 'query'
参数名写成了 query(它叫 sql),而 call_tool 对动态工具是裸 **args 展开的,
跳过了 args_schema —— pydantic 那句"缺少 sql 字段"漏成了只剩内部闭包名的
TypeError,既指不到是哪个工具,也说不出该填什么。同一个函数里内置工具那条
分支本来是校验的,两条路径不一致。
registry 里补上 prepare_args / describe_args,两条路径共用:
- 候选唯一时(多一个不认识的、少一个必填的)改名重试,并发一条 warn 说破
—— 配置里那个错名还在,替它跑通一次却不吭声,下次照样踩
- 有歧义就不猜,报错改成"参数不对:query 不是它的参数;缺少必填参数 sql。
它接受:sql(必填,字符串)— 要执行的 SQL…",模型照着这句就能改对。
这才是失败之后真正能自愈的重试
- 顺带堵了一类静默失败:pydantic 默认把认不出的键悄悄丢掉,全可选 schema 上
{"tabel": "orders"} 会"成功"执行一次什么都没查的调用
agent 循环默认改成串行:一轮只调一个工具,看到结果再想下一步。并行更快,但
一批调用中间没有任何新的思考——第二个是照着"还没看到第一个结果"时的判断发出
去的。节点上留了「并行执行工具」开关。两个必须守住的点:没执行的调用绝不发
tool.start(前端靠 call_id 配对,发了没结尾的 start 会永远转圈),但必须各有
一条配对的 tool_result(少一条下次调用直接 400)。
交错思考跟着补上。4.6 起 adaptive thinking 自带交错,不需要也不该挂 beta
header(Opus 4.6 上手动模式压根没有交错);4/4.5 那一代要手动开 thinking +
interleaved-thinking beta,光挂 header 是一条什么都不做的空设置。开了 thinking
就不能再传 temperature,这一代本来是收的,漏了就是 400。
还有两处是串行带出来的,一并治了:
- 步数用完时收尾取的是 messages[-1],而那往往是给模型看的 ToolMessage。
真漏到用户面前当过答案(run dd9927e6):一句"本轮只执行了第一个工具"冒充
结论。改成只取模型自己说过的话,并把"步数用完了、去调大最大步数"附在后面
- db_schema 一次能问多张表。一次调用就是一步,逐张问 6 张表就是 6 步——
实测 8 步的运行里 7 步花在这上面,最后只剩一步真查数据
This commit is contained in:
@@ -35,7 +35,12 @@ class _QueryArgs(BaseModel):
|
||||
|
||||
|
||||
class _SchemaArgs(BaseModel):
|
||||
table: str | None = Field(default=None, description="表名;留空则列出所有表")
|
||||
# 一次能问好几张。串行跑工具时一次调用就是一步,逐张问 6 张表就是 6 步——
|
||||
# 实测一次 8 步的运行里 7 步花在这上面,最后只剩一步来真查数据(run dd9927e6)
|
||||
table: str | list[str] | None = Field(
|
||||
default=None,
|
||||
description='表名。可以一次给多张:"user" 或 ["user","roles"];留空则列出所有表',
|
||||
)
|
||||
|
||||
|
||||
def tool_names(source: DataSource) -> list[str]:
|
||||
@@ -125,9 +130,13 @@ def _make_query_tool(source: DataSource, ctx: ToolContext) -> StructuredTool:
|
||||
|
||||
|
||||
def _make_schema_tool(source: DataSource) -> StructuredTool:
|
||||
async def _run(table: str | None = None) -> str:
|
||||
if table:
|
||||
return introspect.describe_table(source, table)
|
||||
async def _run(table: str | list[str] | None = None) -> str:
|
||||
wanted = [table] if isinstance(table, str) else list(table or [])
|
||||
# 逗号分隔也认:"user, roles" 和 ["user","roles"] 是同一个意思,
|
||||
# 而模型两种都会写。为此拒绝一次调用,纯属浪费一步
|
||||
wanted = [t.strip() for one in wanted for t in str(one).split(",") if t.strip()]
|
||||
if wanted:
|
||||
return "\n\n".join(introspect.describe_table(source, t) for t in wanted)
|
||||
tables = introspect.table_names(source)
|
||||
if not tables:
|
||||
return (
|
||||
@@ -142,7 +151,8 @@ def _make_schema_tool(source: DataSource) -> StructuredTool:
|
||||
name=f"{SCHEMA_PREFIX}{source.name}",
|
||||
description=(
|
||||
f"查看数据源「{source.name}」的表结构。"
|
||||
"传 table 看某张表的字段;不传则列出所有表。写 SQL 前先用它确认字段名。"
|
||||
"写 SQL 前先用它确认字段名。不传 table 则列出所有表;"
|
||||
"**要看多张表就一次全传进来**(table 可以是数组),不要一张一张问。"
|
||||
),
|
||||
args_schema=_SchemaArgs,
|
||||
coroutine=_run,
|
||||
|
||||
@@ -6,7 +6,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
from langchain_core.tools import BaseTool, StructuredTool
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
ToolFunc = Callable[..., Awaitable[Any]]
|
||||
|
||||
@@ -151,12 +151,157 @@ async def build_tools(
|
||||
return tools
|
||||
|
||||
|
||||
async def call_tool(name: str, args: dict[str, Any], ctx: ToolContext, session: Any = None) -> Any:
|
||||
"""直接调用一个工具(工具节点、以及设置页的"试一下"按钮用)。"""
|
||||
class ToolArgsError(ValueError):
|
||||
"""工具参数对不上 schema。
|
||||
|
||||
message 是直接给人和模型看的:报错里必须说清楚"收到了什么"和"它接受什么",
|
||||
因为看到这句话的下一步动作就是照着改参数名。不要再往外包一层。
|
||||
"""
|
||||
|
||||
|
||||
_TYPE_LABELS = {
|
||||
"string": "字符串", "integer": "整数", "number": "数字",
|
||||
"boolean": "布尔", "array": "数组", "object": "对象",
|
||||
}
|
||||
|
||||
|
||||
def _type_label(prop: dict[str, Any]) -> str:
|
||||
"""JSON Schema 的类型写成人话。可选字段是 anyOf[T, null],要摊开看。"""
|
||||
names: list[str] = []
|
||||
for node in [prop, *(prop.get("anyOf") or [])]:
|
||||
kind = node.get("type")
|
||||
if isinstance(kind, str) and kind != "null":
|
||||
names.append(_TYPE_LABELS.get(kind, kind))
|
||||
return "/".join(dict.fromkeys(names)) or "任意"
|
||||
|
||||
|
||||
def args_model_of(tool: BaseTool) -> type[BaseModel] | None:
|
||||
"""工具的参数模型。
|
||||
|
||||
MCP 这类动态工具的 args_schema 可能直接是一份 JSON Schema dict,拿不到
|
||||
pydantic 模型——那种只能原样放行,不能因为校验不了就拒绝调用。
|
||||
"""
|
||||
schema = getattr(tool, "args_schema", None)
|
||||
if isinstance(schema, type) and issubclass(schema, BaseModel):
|
||||
return schema
|
||||
return None
|
||||
|
||||
|
||||
def describe_args(
|
||||
schema: type[BaseModel],
|
||||
got: dict[str, Any] | None = None,
|
||||
error: ValidationError | None = None,
|
||||
) -> str:
|
||||
"""把"哪里不对、它到底要什么"写成一句能照着改的话。
|
||||
|
||||
字段说明取 Field(description=...),各工具定义里本来就写了,这里只是搬到报错里
|
||||
——模型拿到这句话就能在下一步自己改对,不用人工介入。
|
||||
|
||||
返回的永远是一句完整的话("参数不对:…。它接受:…"),调用方直接拼在
|
||||
工具名后面即可,不用猜这次会不会缺个主语。
|
||||
"""
|
||||
js = schema.model_json_schema()
|
||||
props: dict[str, Any] = js.get("properties") or {}
|
||||
required = [k for k in (js.get("required") or []) if k in props]
|
||||
|
||||
fields: list[str] = []
|
||||
for key, prop in props.items():
|
||||
tag = "必填" if key in required else "可选"
|
||||
desc = str(prop.get("description") or "").strip()
|
||||
fields.append(f"{key}({tag},{_type_label(prop)})" + (f" — {desc}" if desc else ""))
|
||||
tail = "它接受:" + ";".join(fields) if fields else "它不接受任何参数。"
|
||||
|
||||
got = dict(got or {})
|
||||
unknown = [k for k in got if k not in props]
|
||||
missing = [k for k in required if k not in got]
|
||||
problems: list[str] = []
|
||||
if unknown:
|
||||
problems.append(f"{'、'.join(unknown)} 不是它的参数")
|
||||
if missing:
|
||||
problems.append(f"缺少必填参数 {'、'.join(missing)}")
|
||||
for err in error.errors() if error else ():
|
||||
loc = ".".join(str(p) for p in (err.get("loc") or ()))
|
||||
if not loc or loc in unknown or loc in missing:
|
||||
continue # 上面两条已经说过了,不重复
|
||||
# 用 schema 里的类型说,不要把 pydantic 那句英文原样甩出去
|
||||
problems.append(
|
||||
f"{loc} 的值不合法,应为{_type_label(props[loc])}"
|
||||
if loc in props
|
||||
else f"{loc} 的值不合法({err.get('msg', '')})"
|
||||
)
|
||||
|
||||
head = "参数不对:" + ";".join(problems) + "。" if problems else "参数不对。"
|
||||
return f"{head}{tail}"
|
||||
|
||||
|
||||
def prepare_args(
|
||||
schema: type[BaseModel], args: dict[str, Any]
|
||||
) -> tuple[dict[str, Any], str | None]:
|
||||
"""校验工具参数,必要时纠正一个明显写错的参数名。
|
||||
|
||||
返回 (可直接展开给函数的 payload, 纠正说明或 None)。纠正说明不为空时调用方
|
||||
**必须**把它说出去——参数还错在配置里/还错在模型脑子里,替它跑通一次却不吭声,
|
||||
下一次照样踩。
|
||||
|
||||
多余的参数名在这里是硬错误,哪怕校验能过:pydantic 默认把认不出的键悄悄丢掉,
|
||||
于是全可选字段的 schema 上 {"tabel": "orders"} 会"成功"执行一次什么都没查的调用。
|
||||
这种静默失败比报错难查得多。
|
||||
|
||||
纠正只在候选唯一时发生。多于一个就有排列组合,猜对了也是运气,不如把 schema
|
||||
摊开让人或模型自己改。
|
||||
"""
|
||||
args = dict(args or {})
|
||||
js = schema.model_json_schema()
|
||||
props: dict[str, Any] = js.get("properties") or {}
|
||||
required = [k for k in (js.get("required") or []) if k in props]
|
||||
|
||||
unknown = [k for k in args if k not in props]
|
||||
if not unknown:
|
||||
try:
|
||||
return schema(**args).model_dump(), None
|
||||
except ValidationError as e:
|
||||
raise ToolArgsError(describe_args(schema, args, e)) from e
|
||||
|
||||
# 少了哪个必填的,就是多出来那个想写的;一个必填都不缺时,退而看还空着哪个可选字段
|
||||
missing = [k for k in required if k not in args] or [k for k in props if k not in args]
|
||||
residual: ValidationError | None = None
|
||||
if len(unknown) == 1 and len(missing) == 1:
|
||||
fixed = dict(args)
|
||||
fixed[missing[0]] = fixed.pop(unknown[0])
|
||||
try:
|
||||
payload = schema(**fixed).model_dump()
|
||||
except ValidationError as e:
|
||||
# 改完名还是不合法。把这些毛病一并说出来,省得对方改对了名字
|
||||
# 再回来撞一次类型——describe_args 会跳过已经报过的那几个字段
|
||||
residual = e
|
||||
else:
|
||||
return payload, f"参数名 {unknown[0]} 不存在,已按唯一候选 {missing[0]} 执行"
|
||||
|
||||
raise ToolArgsError(describe_args(schema, args, residual))
|
||||
|
||||
|
||||
async def call_tool(
|
||||
name: str,
|
||||
args: dict[str, Any],
|
||||
ctx: ToolContext,
|
||||
session: Any = None,
|
||||
*,
|
||||
on_fix: Callable[[str], None] | None = None,
|
||||
) -> Any:
|
||||
"""直接调用一个工具(工具节点、以及设置页的"试一下"按钮用)。
|
||||
|
||||
两条分支都先过 args_schema。动态工具那条以前是裸 `**args` 展开的,参数名写错
|
||||
时抛的是 TypeError,报错里只剩内部闭包名——`_make_query_tool.<locals>._run() got
|
||||
an unexpected keyword argument 'query'` 既指不到是哪个工具,也说不出该填什么。
|
||||
|
||||
on_fix 在参数名被纠正时回调一次。call_tool 不该知道事件系统长什么样,
|
||||
所以只把这件事交出去,由调用方决定说给谁听。
|
||||
"""
|
||||
spec = get_spec(name)
|
||||
if spec:
|
||||
validated = spec.args_schema(**args)
|
||||
payload = validated.model_dump()
|
||||
payload, note = prepare_args(spec.args_schema, args)
|
||||
if note and on_fix:
|
||||
on_fix(note)
|
||||
if spec.needs_context:
|
||||
return await spec.func(ctx, **payload)
|
||||
return await spec.func(**payload)
|
||||
@@ -165,9 +310,18 @@ async def call_tool(name: str, args: dict[str, Any], ctx: ToolContext, session:
|
||||
if not tools:
|
||||
raise KeyError(f"找不到工具 {name!r}")
|
||||
tool = tools[0]
|
||||
|
||||
model = args_model_of(tool)
|
||||
if model is None:
|
||||
payload = dict(args)
|
||||
else:
|
||||
payload, note = prepare_args(model, args)
|
||||
if note and on_fix:
|
||||
on_fix(note)
|
||||
|
||||
if tool.coroutine:
|
||||
return await tool.coroutine(**args)
|
||||
result = tool.invoke(args)
|
||||
return await tool.coroutine(**payload)
|
||||
result = tool.invoke(payload)
|
||||
if inspect.isawaitable(result):
|
||||
return await result
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user