代码讲解.md 2.6 KB

S01 Agent Loop 代码讲解

这一节只讲一个核心:

Agent 不是一次问答,而是一个循环。模型决定要不要调用工具,程序执行工具,再把结果交还给模型。


1. 本节新增内容

  • TOOLS:告诉模型现在有哪些工具可以用。
  • run_bash():真正执行 bash 命令的 Python 函数。
  • agent_loop(messages):最小 Agent Loop。

2. Messages 数据结构

messages 是一个列表:

messages: list[dict]

里面每一项是一条对话消息:

{"role": "user", "content": "列出当前目录"}

模型返回工具调用后,程序会追加:

{"role": "assistant", "content": response.content}

工具执行完成后,程序再追加:

{
    "role": "user",
    "content": [
        {
            "type": "tool_result",
            "tool_use_id": "toolu_xxx",
            "content": "命令输出"
        }
    ]
}

3. TOOLS

TOOLS 是给模型看的工具说明,不是 Python 真正执行工具的地方。

TOOLS = [{
    "name": "bash",
    "description": "运行一条 shell 命令。",
    "input_schema": {
        "type": "object",
        "properties": {"command": {"type": "string"}},
        "required": ["command"],
    },
}]

可以理解成:

工具名:bash
参数:command
参数类型:string

模型看到这个 schema 后,才知道自己可以生成这样的工具请求:

{
    "type": "tool_use",
    "name": "bash",
    "input": {"command": "ls"}
}

4. run_bash(command)

run_bash() 是真正执行命令的地方。

模型不会真的执行 bash,它只会提出:

我要调用 bash,参数是 {"command": "ls"}

程序收到之后,才会调用:

run_bash("ls")

返回值会被包装成 tool_result,再塞回 messages


5. agent_loop(messages)

这是本节课最核心的函数。

流程可以理解成:

while True:
    调用模型
    保存模型回复

    如果模型没有要求调用工具:
        结束

    如果模型要求调用工具:
        执行工具
        把工具结果放回 messages
        继续下一轮

关键点:

模型负责判断,工具负责执行,循环负责持续推进。


6. 本节课堂重点

不要把 Function Call 理解成“模型执行函数”。

真正发生的是:

模型生成 tool_use
Python 执行 run_bash
Python 生成 tool_result
模型继续读取 tool_result

这就是 Coding Agent 的最小内核。