《AI Agent 开发入门》3.3 抽成 Agent 类:状态、步骤与回调

保留既有停止保护,将历史与回调加入共享循环,提供完整 Agent 文件和两轮离线演示,并验证失败轨迹与系统指令去重。

3.3 抽成 Agent 类:状态、步骤与回调

3.2 已建立停止条件。抽成对象时不能退回只检查「有没有工具」的旧循环,否则输出截断、重复动作和连续失败又会失去保护。本节复用同一个 run(),只新增历史输入和回调。

3.3.1 扩展循环,不复制另一套控制流

下面替换 minagent/loop.py。前半的错误识别和停止逻辑保留;新增 history、on_step、on_tool_call 均是可选参数,3.1 的调用方式仍可使用。

# file: minagent/loop.py | write
from __future__ import annotations
import json
from .tools import ToolRegistry
from .types import Message, Model, RunResult, Step, ToolCall

class AgentLoopError(RuntimeError):
    def __init__(self, reason: str, result: RunResult) -> None:
        super().__init__(reason)
        self.reason = reason
        self.result = result

def _signature(tc: ToolCall) -> tuple[str, str]:
    return tc.name, json.dumps(tc.arguments, sort_keys=True)

def is_tool_error(result: str) -> bool:
    try:
        value = json.loads(result)
    except (ValueError, TypeError):
        return False
    return isinstance(value, dict) and "error" in value

def run(model: Model, registry: ToolRegistry, user_input: str,
        system: str = "", max_steps: int = 8,
        max_consecutive_failures: int = 3, *,
        history: list[Message] | None = None,
        on_step=None, on_tool_call=None) -> RunResult:
    if max_steps < 1 or max_consecutive_failures < 1:
        raise ValueError("limits must be positive")
    messages = list(history) if history is not None else []
    if system and not messages:
        messages.append(Message(role="system", content=system))
    messages.append(Message(role="user", content=user_input))

    steps: list[Step] = []
    def record(step: Step) -> None:
        steps.append(step)
        if on_step is not None:
            on_step(step)
    last_sig: tuple[str, str] | None = None
    failures = 0

    for i in range(max_steps):
        resp = model.complete(messages, registry.schemas())
        msg = resp.message
        messages.append(msg)

        if resp.stop_reason == "max_tokens":
            raise AgentLoopError("max_tokens", RunResult(messages, steps, msg.content))

        if not msg.tool_calls:
            record(Step(index=i, kind="final", detail=msg.content))
            return RunResult(messages=messages, steps=steps, final=msg.content)

        for tc in msg.tool_calls:
            sig = _signature(tc)
            if sig == last_sig:
                raise AgentLoopError("repeated_action", RunResult(messages, steps, ""))
            last_sig = sig

            result = registry.call(tc)
            messages.append(Message(role="tool", content=result, tool_call_id=tc.id))
            if on_tool_call is not None:
                on_tool_call(tc, result)
            record(Step(index=i, kind="tool_call",
                              detail=f"{tc.name}({tc.arguments}) -> {result}"))

            failures = failures + 1 if is_tool_error(result) else 0
            if failures >= max_consecutive_failures:
                raise AgentLoopError("tool_failures", RunResult(messages, steps, ""))

    raise AgentLoopError("max_steps", RunResult(messages, steps, ""))

历史用新列表承载追加,避免直接往调用者原列表写入。Message 本身仍是可变对象,浅复制不提供并发隔离;同一个 Agent 不要同时执行两轮。回调运行在当前线程中,耗时回调会拖慢循环,回调异常也会向调用方传播。

3.3.2 完整 Agent 类

保存为 minagent/agent.py:

# file: minagent/agent.py | write
from __future__ import annotations
from typing import Callable
from .loop import run, AgentLoopError
from .tools import ToolRegistry
from .types import Message, Model, RunResult, Step, ToolCall

StepHook = Callable[[Step], None]
ToolHook = Callable[[ToolCall, str], None]

class Agent:
    def __init__(self, model: Model, registry: ToolRegistry, system: str = "",
                 max_steps: int = 8, max_consecutive_failures: int = 3) -> None:
        self.model = model
        self.registry = registry
        self.system = system
        self.max_steps = max_steps
        self.max_consecutive_failures = max_consecutive_failures
        self.history: list[Message] = []
        self.on_step: StepHook | None = None
        self.on_tool_call: ToolHook | None = None

    def run(self, user_input: str) -> RunResult:
        try:
            result = run(self.model, self.registry, user_input,
                         self.system, self.max_steps, self.max_consecutive_failures,
                         history=self.history, on_step=self.on_step,
                         on_tool_call=self.on_tool_call)
        except AgentLoopError as exc:
            self.history = list(exc.result.messages)
            raise
        self.history = list(result.messages)
        return result

配置在构造时保存,回调可在运行前挂载。成功和 AgentLoopError 两种受控路径都保留当前对话;其他模型或回调异常仍需调用者处理,本节不声称覆盖所有失败。失败轨迹可能含待处理的工具请求,不能未经检查直接送给任意真实供应商继续对话。

3.3.3 两轮对话与可验证的状态

保存为 demo_agent.py,从仓库根执行 python3 demo_agent.py:

# file: demo_agent.py | write
from minagent.agent import Agent
from minagent.fake import FakeModel
from minagent.tools import Tool, ToolRegistry
from minagent.types import ToolCall

reg = ToolRegistry()
reg.add(Tool("add", "两数相加", {
    "type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
    "required": ["a", "b"], "additionalProperties": False,
}, lambda a, b: a + b))
model = FakeModel([[ToolCall("c1", "add", {"a": 2, "b": 3})], "5", "15"])
agent = Agent(model, reg, system="你是计算助手")
seen = []
agent.on_step = seen.append
assert agent.run("2+3").final == "5"
assert agent.run("再加10").final == "15"
assert len(agent.history) == 7
assert sum(m.role == "system" for m in agent.history) == 1
assert [s.kind for s in seen] == ["tool_call", "final", "final"]
print("two turns OK: 7 messages, one system prompt, 3 callbacks")

本次执行输出:

two turns OK: 7 messages, one system prompt, 3 callbacks

第二轮的 15 是假模型剧本,不证明真实模型已经推理正确;这里验证的是系统指令没有重复插入、上下文确实保留、回调与步骤对齐。新任务若不应继承旧状态,应创建新 Agent,或在确认不需要旧轨迹后清空 history。

3.3.4 练习与答案检查点

  1. 将假模型的第一条响应改成 stop_reason="max_tokens":应抛 AgentLoopError("max_tokens", ...),而不是把半截文本当作正常答案。
  2. 连续两轮调用相同工具和参数:同一轮中的相邻重复由本节策略拦截;不同用户轮次重新开始检测,不要把正常追问误判为死循环。
  3. 让工具返回包含单词 "error" 的普通文本。应视为成功;顶层 JSON error 字段才是协议中的失败反馈。

基础项目的回归用例覆盖上述状态与失败路径。它不包含真实供应商 API、并发会话或生产权限系统。

阅读导航:上一节:停止条件 · 下一节:工具注册表 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「agent」更多文章

  1. 《AI Agent 高级编程》目录
  2. 《AI Agent 高级编程》11.3 全景回顾:从零到框架的完整路径与展望
  3. 《AI Agent 高级编程》11.2 真实 API 冒烟:假模型 vs 真模型量化差距