承認とレポート
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 19/22。
チャレンジ
難しい予約は旅行者のお金を消費するため、エージェントはまず確認する必要があります。次に、実行にかかったコストを報告します。これまで作成したものはすべて保持してください。
- 説明が
Book a seat on a flight to a destinationで、The destination cityと説明されている1つの必須文字列プロパティdestinationを持つ、book_flightという名前のツールを追加します。それをTOOLSと送信するツール群に追加します。 tool_useブロックがbook_flightを指定している場合、そのTool:行を出力した後にもう1行の入力行を読み込みます。それがyesの場合はApprovedと出力してツールを実行します。それ以外の場合はDeclinedと出力し、ツールを実行せずに"is_error": TrueとともにThe traveller said no to this bookingという結果を送信します。- 最初の呼び出しも含め、すべての呼び出しにわたって
input_tokensとoutput_tokensを加算します。 - 最後に、
Steps:とツールのラウンド数を出力し、次に合計値を伴うTokens: <input> in, <output> outを出力します。
例えば、入力 Book a flight to Lisbon および yes に対して、プログラムは以下を出力します:
Tool: book_flight {'destination': 'Lisbon'}
Approved
Agent: Here is what I found: Booked a seat to Lisbon for 120 dollars
Steps: 1
Tokens: 658 in, 35 out自分で試してみよう
import coddy_ai as anthropic # 本番環境: import anthropic
client = anthropic.Anthropic()
FLIGHTS = {"Lisbon": 120, "Rome": 95, "Tokyo": 640, "Oslo": None}
HOTELS = {"Lisbon": 80, "Rome": 110, "Tokyo": 150, "Oslo": 130}
def search_flights(destination):
if destination not in FLIGHTS:
raise ValueError(f"No flights to {destination}")
if FLIGHTS[destination] is None:
raise ConnectionError("The flight service is temporarily unavailable, try again")
return f"Flight to {destination}: {FLIGHTS[destination]} dollars"
def find_hotel(city):
if city not in HOTELS:
raise ValueError(f"No hotels in {city}")
return f"Hotel in {city}: {HOTELS[city]} dollars a night"
def book_flight(destination):
return f"Booked a seat to {destination} for {FLIGHTS[destination]} dollars"
request = input()
# 以下にコードを書いてください
flight_tool = {
"name": "search_flights",
"description": "Search flights to a destination and give the ticket price",
"input_schema": {
"type": "object",
"properties": {"destination": {"type": "string", "description": "The destination city"}},
"required": ["destination"],
},
}
hotel_tool = {
"name": "find_hotel",
"description": "Find a hotel room in a city with its nightly rate",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string", "description": "The city to stay in"}},
"required": ["city"],
},
}
TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel}
tools = [flight_tool, hotel_tool]
MAX_STEPS = 5
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=tools, messages=messages)
steps = 0
while response.stop_reason == "tool_use":
if steps == MAX_STEPS:
break
steps += 1
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
try:
result = TOOLS[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
except Exception as error:
results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=tools, messages=messages)
if response.stop_reason == "tool_use":
print(f"Stopped after {MAX_STEPS} steps")
else:
for block in response.content:
if block.type == "text":
print("Agent: " + block.text)
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ