聊天模型只能输出文本。AGI应用的核心跃迁是工具使用(tool use / function calling):模型能决定调用什么工具、传什么参数、看结果后决定下一步。这让AGI从"回答问题"变成"完成任务"。
但工具使用带来三个工程挑战:工具选择(几十个工具里选对)、参数正确(格式错一个字段就失败)、结果接地(工具返回错误时模型要知道,不能编造成功)。专业开发的核心,是把这三个环节做成可验证的闭环。
工具定义层:每个工具必须有清晰的schema、描述、使用条件。描述写得模糊,模型就选错。
执行层:参数校验、超时、错误码、幂等。工具执行是确定性代码,不信任模型传参。
接地层:执行结果回灌模型,模型据此决定继续还是终止。结果必须结构化,不能只是一段文本。
(1)工具定义:schema + 描述 + 使用场景
from pydantic import BaseModel, Field
from typing import Callable
class ToolSpec(BaseModel):
name: str
description: str # 写给模型看的:何时用、何时不用
params_schema: dict # JSON Schema
fn: Callable
TOOLS = {}
def register_tool(name: str, desc: str, schema: dict):
def deco(fn):
TOOLS[name] = ToolSpec(name=name, description=desc,
params_schema=schema, fn=fn)
return fn
return deco
@register_tool("query_order",
"查询订单状态。当用户询问订单物流、退款进度时使用。"
"不适用于新下单或修改地址。",
{"type": "object",
"properties": {"order_id": {"type": "string", "pattern": "^[A-Z0-9]{8,20}$"}},
"required": ["order_id"]})
def query_order(order_id: str) -> dict:
return {"order_id": order_id, "status": "shipped",
"tracking": "SF1234567890"}(2)工具选择:给模型看全部schema,让它选
def tools_for_llm() -> list[dict]:
"""转成 OpenAI tools 格式,description 直接透传——写得清楚模型才选得对"""
return [{"type": "function",
"function": {"name": t.name, "description": t.description,
"parameters": t.params_schema}}
for t in TOOLS.values()](3)执行层:参数校验 + 超时 + 错误回灌
import json, jsonschema, asyncio
class ToolError(Exception):
pass
async def execute_tool(name: str, raw_args: str, timeout=10) -> dict:
"""执行工具:非法参数/超时/异常全部返回结构化错误,而非抛给模型"""
tool = TOOLS.get(name)
if tool is None:
return {"error": "unknown_tool", "name": name}
try:
args = json.loads(raw_args)
jsonschema.validate(args, tool.params_schema) # 参数schema校验
except (json.JSONDecodeError, jsonschema.ValidationError) as e:
return {"error": "invalid_args", "detail": str(e)[:200]}
try:
result = await asyncio.wait_for(
asyncio.to_thread(tool.fn, **args), timeout=timeout)
return {"ok": True, "result": result}
except asyncio.TimeoutError:
return {"error": "timeout", "tool": name}
except Exception as e:
return {"error": "execution_failed", "detail": str(e)[:200]}(4)接地循环:结果回灌,模型决定继续或终止
async def agent_loop(client, user: str, max_steps=8, timeout_s=60) -> dict:
"""工具接地核心:每轮把执行结果回灌,模型看到真实结果再决定下一步"""
import time
msgs = [{"role": "user", "content": user}]
t0 = time.time()
for step in range(max_steps):
if time.time() - t0 > timeout_s:
return {"error": "timeout", "steps": step}
r = client.chat(model="reasoning", messages=msgs,
tools=tools_for_llm(), tool_choice="auto"
).choices[0].message
if not r.tool_calls:
return {"answer": r.content, "steps": step + 1, "tools_used": step}
msgs.append({"role": "assistant", "content": r.content or "",
"tool_calls": [{"id": c.id, "type": "function",
"function": {"name": c.function.name,
"arguments": c.function.arguments}}
for c in r.tool_calls]})
for call in r.tool_calls:
result = await execute_tool(call.function.name,
call.function.arguments)
# 错误也回灌——模型看到失败才能纠正,看不到就会编造成功
msgs.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return {"error": "max_steps_exceeded"}(5)工具冲突检测:多个工具可能都有副作用时,提前拦截
SIDE_EFFECT_TOOLS = {"create_order", "send_email", "cancel_order", "refund"}
def guard_side_effects(tool_calls: list) -> tuple[bool, str]:
"""同一轮里多个有副作用的工具不能并行执行,必须串行等待结果"""
effects = [c.function.name for c in tool_calls
if c.function.name in SIDE_EFFECT_TOOLS]
if len(effects) > 1:
return False, f"同轮多个副作用工具需串行:{effects}"
return True, "ok"(6)工具使用可观测:哪个工具选错、哪个参数常错
def tool_metrics(history: list[dict]) -> dict:
total = len(history)
errors = [h for h in history if h.get("error")]
by_err = {}
for e in errors:
by_err[e["error"]] = by_err.get(e["error"], 0) + 1
return {"calls": total,
"error_rate": round(len(errors) / max(total, 1), 3),
"by_error": by_err,
"healthy": len(errors) / max(total, 1) < 0.1}
# invalid_args高 = schema描述不够清楚;unknown_tool高 = 工具描述有歧义六项硬指标:工具选择准确率(选对工具的轮次>90%)、参数校验通过率(进入执行的参数合法>95%)、接地成功率(工具结果被正确回灌且模型基于结果行动>90%)、错误回灌率(执行失败时模型能看到错误=100%)、副作用串行率(多个副作用工具串行执行=100%)、工具错误率(<10%)。前两项决定"会不会用",中间两项决定"用了以后结果可不可信",后两项决定"用了以后安不安全"。
AGI大模型应用开发的第二条主线是工具接地:定义清楚(何时用)、校验严格(参数对)、回灌完整(结果真实)、副作用串行(不出乱)。模型能力决定"它想做什么",工具接地的工程决定"它做的事能不能落地、做错了能不能发现"。没有这套闭环,AGI就只是一个会说"我已经帮你处理了"但什么都没发生的聊天框。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。