Menu
CoddyTech

库存智能体

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

challenge icon

挑战

困难

构建一个用于检查并补充商店库存的智能体。起始代码包含 STOCK 并读取请求。

  1. 定义两个工具。check_stock:描述为 Check how many units of a product are in stock,包含一个必需的字符串属性 product,描述为 Which product。order_more:描述为 Order more of a product from the supplier,包含相同的 product 属性以及一个必需的整数属性 quantity,描述为 How many units to order。
  2. 编写这两个函数。如果商品不在 STOCK 中,两者都会引发 ValueError("Unknown product: <product>")。check_stock 返回 <product>: <count> in stock。order_more 除非数量是 1 到 50 之间的整数,否则会引发 ValueError("Quantity must be between 1 and 50");否则它会将其添加到 STOCK 中并返回 Ordered <quantity> of <product>, stock is now <count>。
  3. 运行智能体循环(model="claude-opus-5-5"、max_tokens=500,最多 5 轮)。为每次调用打印一行 Tool:(名称、一个空格、输入)。ValueError 作为其消息返回,并带有 "is_error": True。
  4. 最后,打印 Agent: 和回复文本,然后打印 Stock: 以及每种商品及其数量,用逗号和空格分隔。

例如,对于输入 Order 80 more of the office chair,程序打印:

Tool: order_more {'product': 'office chair', 'quantity': 80}
Agent: Sorry, I could not finish: Quantity must be between 1 and 50
Stock: desk lamp 7, office chair 3, standing desk 0

亲手试试

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

client = anthropic.Anthropic()

STOCK = {"desk lamp": 7, "office chair": 3, "standing desk": 0}

request = input()

# 在下方编写你的代码

工具与 Agent中的所有课

自己练习: Python 在线编译器