まとめ:ショップアシスタント
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 10/22。
チャレンジ
難しいショップアシスタントのエージェントループを構築します。スターターコードでは、2つのツール、その背後にある FUNCTIONS 内の関数、MAX_STEPS、および最初のメッセージが定義されています。両方の関数は不明な商品に対して ValueError を発生させ、check_stock は倉庫システムが停止しているときに TimeoutError を発生させます。
run_tool(block)を作成します:FUNCTIONS[block.name](**block.input)を実行し、そのtool_resultを返します。ValueErrorとTimeoutErrorをキャッチし、メッセージと"is_error": Trueを含むエラー結果を返します。結果の場合はTool: <name> <input> -> <output>、エラーの場合はTool: <name> <input> -> error: <message>と出力します。- モデルを呼び出し(
model="claude-opus-5-5"、max_tokens=500、tools=TOOLS)、モデルがツールを要求している間ループします: アシスタントのターンを追加し、すべての結果を1つのユーザーメッセージで送信し、再度呼び出します。 - モデルを
MAX_STEPS回呼び出したらループを停止し、Stopped: no answer after 4 stepsを出力します。 - 最終テキストがある場合は
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}]
# 以下にコードを記述してください
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ