新手做 Agent 通常死在三件事上:工具 schema 写得太随意导致模型乱调、规划写成死循环、记忆无脑全塞导致上下文爆炸。这三个模块不是独立组件,而是一条链:规划决定调哪个工具,工具结果决定记忆写什么,记忆又反过来约束规划。任何一个环节没有工程约束,Agent 就会从"智能"退化成"随机"。
工具描述的质量直接决定调用准确率。三条硬规则:参数必须用 enum 收敛取值范围、description 必须写清"什么时候该调"而非"这是什么"、返回值必须是结构化 JSON 而非自然语言。
# tools.py
TOOLS = [{
"type": "function",
"function": {
"name": "query_order",
"description": "查询订单状态。仅在用户提供了订单号时调用;"
"无订单号时应先调 search_order_by_phone。",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "pattern": r"^\d{18}$",
"description": "18 位订单号"},
"fields": {"type": "array",
"items": {"enum": ["status", "amount", "logistics"]},
"description": "需要的字段,避免全量返回"},
},
"required": ["order_id"],
},
},
}]
def query_order(order_id: str, fields: list[str]) -> dict:
"""工具内部必须做参数校验,不信任模型传参"""
if not re.match(r"^\d{18}$", order_id):
return {"ok": False, "error": "invalid_order_id",
"hint": "订单号为 18 位数字,请向用户确认"}
rows = db.fetch(order_id, fields or ["status"])
return {"ok": True, "data": rows, "truncated": len(rows) > 20}关键设计:错误也要结构化返回,并带 hint 告诉模型下一步怎么做。返回自然语言错误(如"查询失败")会让模型原地重试,返回 {"error":"invalid_order_id","hint":"..."} 才能让它转向追问用户。工具级并发用 asyncio.gather 扇出,但有副作用的工具必须串行,且携带幂等键。
模式 | 适用 | 风险 |
|---|---|---|
ReAct | 步骤少、依赖工具反馈 | 长任务易绕圈 |
Plan-Execute | 步骤多、可预分解 | 计划僵硬,需重规划 |
混合 | 先出计划,每步内用 ReAct | 实现复杂度高 |
生产建议默认混合:先让模型出结构化计划,每步执行时允许局部 ReAct,并在每步后做"计划校验"——步骤是否仍成立、是否需要重规划。必须加两道闸:最大步数和循环检测(同一工具同参数重复调用即中断)。
# planner.py
PLAN_PROMPT = """把任务拆成步骤,输出 JSON:
{"steps":[{"id":1,"action":"工具名或think","args":{},"goal":"..."}]}
最多 8 步。无法拆解时只输出一个 think 步骤。只输出 JSON。"""
def detect_loop(history: list[dict], window=4) -> bool:
"""同一 (tool, args_hash) 在窗口内重复即判定绕圈"""
keys = [f"{h['tool']}:{hashlib.md5(json.dumps(h['args'], sort_keys=True).encode()).hexdigest()}"
for h in history[-window:]]
return len(keys) == window and len(set(keys)) == 1
async def execute_plan(plan: dict, tools: dict, state: dict, max_steps=12):
history = []
for step in plan["steps"][:max_steps]:
if detect_loop(history):
plan = await replan(state, reason="loop_detected") # 重规划而非硬重试
history.clear(); continue
if step["action"] == "think":
history.append({"tool": "think", "args": step}); continue
tool = tools.get(step["action"])
if not tool:
return {"ok": False, "error": f"unknown_tool:{step['action']}"}
result = await tool(**step["args"])
history.append({"tool": step["action"], "args": step["args"], "result": result})
state["observations"].append(result)
if not result.get("ok"):
plan = await replan(state, reason=result.get("error")) # 失败即重规划
return {"ok": True, "state": state, "history": history}规划的本质不是"想得远",而是"错了能改"。没有重规划能力的 Agent,计划越长越脆弱。
记忆分三层,混在一起是灾难:
最容易被忽略的是写入策略——不是所有对话都值得记。写入前先判定"是否包含可复用的事实或偏好",避免把闲聊污染进长期记忆。
# memory.py
class Memory:
def __init__(self, vec, kv, max_ctx_tokens=6000):
self.vec, self.kv, self.max_ctx = vec, kv, max_ctx_tokens
self.working: list[dict] = []
def add_turn(self, role, content, tokens):
self.working.append({"role": role, "content": content, "tokens": tokens})
self._compress()
def _compress(self):
"""超预算时把最早若干轮压成摘要,保留最近 6 轮原文"""
total = sum(m["tokens"] for m in self.working)
if total <= self.max_ctx: return
head, tail = self.working[:-6], self.working[-6:]
summary = llm_summarize(head) # 一次便宜模型调用
self.working = [{"role": "system", "content": f"[摘要]{summary}"}] + tail
def write_longterm(self, turn: dict):
"""写入前判定:只记事实与偏好,不记闲聊"""
judge = llm_json("判断该轮是否含可复用的用户偏好或业务事实,"
'输出 {"worth":true/false,"kind":"pref|fact|none"}',
turn["content"])
if not judge["worth"]: return
rec = {"kind": judge["kind"], "text": turn["content"],
"ts": time.time(), "user": turn.get("user")}
self.vec.add(rec) # 向量库,供召回
if judge["kind"] == "pref":
self.kv.set(f"pref:{rec['user']}", rec["text"]) # 偏好走 KV 精确读取
def recall(self, query: str, top_k=3) -> list[dict]:
return self.vec.search(query, top_k)召回时机比召回技术更重要:不要在每轮都注入记忆,只在任务开始时、以及检测到"用户提到过去"时召回。无差别注入会让模型被历史噪声干扰。
坑 | 后果 | 对策 |
|---|---|---|
工具返回自然语言 | 模型反复重试 | 统一结构化 JSON + hint |
无最大步数 | 死循环烧 token | max_steps + 循环检测 |
失败直接重试 | 雪崩 | 失败即重规划 |
记忆全量注入 | 上下文爆炸、精度下降 | 分层 + 按需召回 |
副作用工具无幂等 | 重复下单 | 幂等键 + 去重表 |
工具参数不校验 | 脏数据入库 | 工具内部二次校验 |
一个可交付的 Agent 必须能回答三个问题:工具调错时它怎么自愈、计划失效时它怎么重规划、记忆里存的到底是事实还是垃圾。三个模块的工程质量,最终体现为线上指标:工具调用成功率、平均步数、重规划触发率、记忆召回准确率。没有这四个数字的 Agent,只是一个能演示的玩具。百渡可搜索【极致it】相关平台获取完整版内容
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。