Menu
CoddyTech

串联工具结果

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

许多请求需要连续使用两个工具,其中第二个工具需要用到第一个工具返回的结果。当被问及 What is the price of the kettle with tax? 时,拥有 get_price 工具和 add_tax 工具的模型还无法直接调用 add_tax:因为它还没有获取到价格。它会先调用 get_price,从结果中读取 30 dollars,然后再传入该数值来调用 add_tax。

get_price {'item': 'kettle'}
add_tax {'price': 30}

你的循环在无需预先了解的情况下让这一切成为可能:它会将每个结果发回,并在 stop_reason 为 "tool_use" 时继续运行。只处理一轮的循环会在 get_price 之后停止,永远不会发起第二次调用。

有两点有助于让链式调用正常工作。结果应该清晰地指明具体数字(例如 30 dollars,而不是内部代码),因为模型会将它们复制到下一次调用中。另外,接收数字的参数必须设置为 "type": "number" 或 "integer",以便模型传递你的函数可以用来计算的值。

challenge icon

挑战

困难

火车票助手可以查找以欧元计价的票价。添加一个用于转换货币的工具,以便模型可以将两者结合使用。

  1. 在 TOOLS 中添加一个名为 convert_euros 的工具,描述为 Convert an amount in euros to another currency.,包含两个必需属性:amount(数字,以欧元为单位的金额)和 currency(字符串,货币代码:USD、JPY 或 GBP)。
  2. 编写 convert_euros(amount, currency)。它返回 <amount> euros is <converted> <currency>,其中转换后的值为 amount * RATES[currency] 并保留 2 位小数。
  3. 将其添加到 FUNCTIONS 中。

例如,对于输入 What does the train to Lyon cost in dollars?,程序会打印:

Step 1: get_fare {'destination': 'Lyon'}
Step 2: convert_euros {'amount': 48, 'currency': 'USD'}
Answer: Here is what I found:
- Lyon: 48 euros
- 48 euros is 52.32 USD

亲手试试

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

client = anthropic.Anthropic()

FARES = {"Lyon": 48, "Nice": 95, "Lille": 35, "Bordeaux": 70}
RATES = {"USD": 1.09, "JPY": 162.0, "GBP": 0.86}

TOOLS = [
    {
        "name": "get_fare",
        "description": "Get the price of a train ticket from Paris to a destination, in euros.",
        "input_schema": {
            "type": "object",
            "properties": {"destination": {"type": "string", "description": "The destination city"}},
            "required": ["destination"],
        },
    },
    # 在此处添加 convert_euros 工具
]


def get_fare(destination):
    return f"{destination}: {FARES[destination]} euros"


# 在此处编写 convert_euros(amount, currency)

FUNCTIONS = {"get_fare": get_fare}

request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
step = 0
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    results = []
    for block in response.content:
        if block.type == "tool_use":
            step += 1
            print(f"Step {step}: {block.name} {block.input}")
            output = FUNCTIONS[block.name](**block.input)
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
    messages.append({"role": "user", "content": results})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)

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

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

工具与 Agent中的所有课

自己练习: Python 在线编译器