库存智能体
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 21 课,共 22 课。
挑战
困难构建一个用于检查并补充商店库存的智能体。起始代码包含 STOCK 并读取请求。
- 定义两个工具。
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。 - 编写这两个函数。如果商品不在
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>。 - 运行智能体循环(
model="claude-opus-5-5"、max_tokens=500,最多 5 轮)。为每次调用打印一行Tool:(名称、一个空格、输入)。ValueError作为其消息返回,并带有"is_error": True。 - 最后,打印
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 在线编译器