Menu
CoddyTech

步骤限制

本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 9 课,共 22 课。

当模型停止请求使用工具时,智能体循环就会结束,但没有任何机制能保证它一定会停止。一个不断返回 try again 失败的工具可能会导致模型无限重试,而每一次循环都会消耗一次调用和相应的 token。请为循环设置一个限制:

steps = 1
while response.stop_reason == "tool_use":
    if steps == MAX_STEPS:
        break
    # 运行工具,追加轮次,再次调用模型
    steps += 1
if response.stop_reason == "tool_use":
    print("Gave up: the task took too many steps")

检查位于循环的顶部,因此程序永远不会进行第 MAX_STEPS + 1 次调用。循环结束后,停止原因会告诉你它是以哪种方式结束的:仍为 tool_use 意味着是因为限制而停止,且没有可展示的答案。与其什么都不打印,不如告知用户这一点。重试往往是正确的做法:一次超时的服务可能会在下一次尝试时做出响应。限制可以让循环重试,同时确保它最终能够结束。生产环境中的 Agent 也会以同样的方式限制 token 数量和运行时间。

challenge icon

挑战

中等

当预订系统持续失败时,初始代码中的餐厅 Agent 会无限运行,因为模型每次都会重试。请添加一个步骤限制。

  1. 在循环顶部,当 steps 等于 MAX_STEPS 时 break。
  2. 在循环之后,如果停止原因仍然是 "tool_use",打印 Stopped: no answer after 5 steps(使用 MAX_STEPS)。
  3. 保持打印答案(如果有的话)以及步骤数。

例如,对于输入 Is there a table at Golden Dragon tonight?,程序输出:

Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Stopped: no answer after 5 steps
Steps: 5

亲手试试

import coddy_ai as anthropic  # 在生产环境中:import anthropic

client = anthropic.Anthropic()

MAX_STEPS = 5
TABLES = {"Bella Vista": "a table for two at 8 pm", "Sunset Grill": "a table by the window at 9 pm"}
attempts = {}


def check_table(restaurant):
    attempts[restaurant] = attempts.get(restaurant, 0) + 1
    if restaurant == "Golden Dragon":
        raise TimeoutError("The booking system is temporarily unavailable, try again")
    if restaurant == "Sunset Grill" and attempts[restaurant] < 3:
        raise TimeoutError("The booking system timed out, try again")
    if restaurant in TABLES:
        return f"{restaurant} has {TABLES[restaurant]}"
    return f"{restaurant} has no free table tonight"


TOOLS = [
    {
        "name": "check_table",
        "description": "Check if a restaurant has a free table tonight",
        "input_schema": {
            "type": "object",
            "properties": {"restaurant": {"type": "string", "description": "The restaurant name"}},
            "required": ["restaurant"],
        },
    }
]


def run_tool(block):
    try:
        output = check_table(**block.input)
    except TimeoutError as error:
        print(f"Tool: {block.name} {block.input} -> error: {error}")
        return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
    print(f"Tool: {block.name} {block.input} -> {output}")
    return {"type": "tool_result", "tool_use_id": block.id, "content": output}


request = input()
messages = [{"role": "user", "content": request}]

# 当调用模型的次数达到 MAX_STEPS 次时停止循环
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps = 1
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    results = [run_tool(block) for block in response.content if block.type == "tool_use"]
    messages.append({"role": "user", "content": results})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
    steps += 1

for block in response.content:
    if block.type == "text":
        print("Answer: " + block.text)
print(f"Steps: {steps}")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

工具与 Agent中的所有课

自己练习: Python 在线编译器