Menu
CoddyTech

回顾:导购助手

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

challenge icon

挑战

困难

构建商店助手的 Agent 循环。初始代码定义了两个工具,其背后的函数存储在 FUNCTIONS 中,以及 MAX_STEPS 和第一条消息。对于未知商品,两个函数都会抛出 ValueError,当仓库系统不可用时,check_stock 会抛出 TimeoutError。

  1. 编写 run_tool(block):运行 FUNCTIONS[block.name](**block.input) 并返回其 tool_result。捕获 ValueError 和 TimeoutError,并返回带有错误消息和 "is_error": True 的错误结果。对于正常结果,打印 Tool: <name> <input> -> <output>;对于错误,打印 Tool: <name> <input> -> error: <message>。
  2. 调用模型(model="claude-opus-5-5"、max_tokens=500、tools=TOOLS),并在模型要求使用工具时进行循环:追加 assistant 轮次,在一个 user 消息中发送所有结果,然后再次调用。
  3. 当调用模型的次数达到 MAX_STEPS 次时停止循环,然后打印 Stopped: no answer after 4 steps。
  4. 当有最终文本时,打印 Answer: 和该文本,然后打印 Steps: 和调用次数。

例如,对于输入 Check stock for the desk lamp and the price of the desk lamp,程序会打印:

Tool: check_stock {'product': 'desk lamp'} -> desk lamp: 12 in stock
Tool: get_price {'item': 'desk lamp'} -> desk lamp: 40 dollars
Answer: Here is what I found:
- desk lamp: 12 in stock
- desk lamp: 40 dollars
Steps: 2

亲手试试

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

client = anthropic.Anthropic()

MAX_STEPS = 4
STOCK = {"desk lamp": 12, "bookshelf": 5, "office chair": 0}
PRICES = {"desk lamp": 40, "bookshelf": 85, "office chair": 65, "garden bench": 150}


def check_stock(product):
    if product == "garden bench":
        raise TimeoutError("The warehouse system is temporarily unavailable, try again")
    if product not in STOCK:
        raise ValueError(f"Unknown product: {product}")
    return f"{product}: {STOCK[product]} in stock"


def get_price(item):
    if item not in PRICES:
        raise ValueError(f"No price for {item}")
    return f"{item}: {PRICES[item]} dollars"


TOOLS = [
    {
        "name": "check_stock",
        "description": "Check how many units of a product are in stock",
        "input_schema": {
            "type": "object",
            "properties": {"product": {"type": "string", "description": "The product name"}},
            "required": ["product"],
        },
    },
    {
        "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"],
        },
    },
]
FUNCTIONS = {"check_stock": check_stock, "get_price": get_price}

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

# 在下方编写你的代码

工具与 Agent中的所有课

自己练习: Python 在线编译器