Agent 循环
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 6 课,共 22 课。
有些请求需要不止一次工具调用。要以欧元计算台灯的价格,模型首先需要获取价格,然后才能请求转换。它无法同时规划这两次调用,因为第二次调用依赖于第一次调用的结果。
Agent 循环负责处理这一过程:调用模型,只要其返回 stop_reason == "tool_use",就运行它所请求的工具,将结果发送回去并再次调用它。当停止原因为其他任何情况时,文本块中即包含最终答案。
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
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)每一轮都会追加两个回合:模型的工具调用,接着是你的结果。列表会不断增长,模型会在每次调用时读取其中的所有内容。生产环境的代码通常会将这个循环交给 SDK 的工具运行器(client.beta.messages.tool_runner)或 Managed Agents;手动编写一次可以让你清楚地了解它们为你做了什么。
挑战
中等为商店的价格助手编写 Agent 循环。初始代码定义了两个工具、FUNCTIONS 中对应的函数以及第一条消息。
- 使用
model="claude-opus-5-5"、max_tokens=500、tools=TOOLS和 messages 调用模型。 - 当 stop reason 为
"tool_use"时:追加 assistant 轮次,使用FUNCTIONS[block.name](**block.input)运行每个tool_use块,打印Tool:、名称、空格和每个块的输入字典,将所有结果作为一条用户消息追加,并再次调用模型。 - 打印
Answer:和最终响应的文本。 - 打印
Steps:和你调用模型的次数。
例如,对于输入 What is the price of the mug in yen?,程序会打印:
Tool: get_price {'item': 'mug'}
Tool: convert_currency {'amount': 8, 'currency': 'JPY'}
Answer: Here is what I found:
- The mug costs 8 dollars
- 8 dollars is 1200.00 JPY
Steps: 3亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
PRICES = {"lamp": 40, "desk": 120, "chair": 65, "mug": 8}
RATES = {"EUR": 0.92, "GBP": 0.79, "JPY": 150.0}
def get_price(item):
if item in PRICES:
return f"The {item} costs {PRICES[item]} dollars"
return f"No price for {item}"
def convert_currency(amount, currency):
return f"{amount} dollars is {amount * RATES[currency]:.2f} {currency}"
TOOLS = [
{
"name": "get_price",
"description": "Look up the price of an item in dollars",
"input_schema": {
"type": "object",
"properties": {"item": {"type": "string", "description": "The item to price"}},
"required": ["item"],
},
},
{
"name": "convert_currency",
"description": "Convert a dollar amount to another currency",
"input_schema": {
"type": "object",
"properties": {
"amount": {"type": "number", "description": "The amount in dollars"},
"currency": {"type": "string", "description": "The currency code, such as EUR"},
},
"required": ["amount", "currency"],
},
},
]
FUNCTIONS = {"get_price": get_price, "convert_currency": convert_currency}
request = input()
messages = [{"role": "user", "content": request}]
# 运行 agent 循环:每次调用打印 "Tool: <name> <input>",
# 然后打印 "Answer: " 和最终文本,接着打印 "Steps: " 和 API 调用次数
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
工具与 Agent中的所有课
自己练习: Python 在线编译器