エラーと制限
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 18/22。
チャレンジ
難しい実際の旅行では、存在しない都市やダウンしているサービスに遭遇することがあります。エージェントがその両方を乗り切れるようにしましょう。これまでに作成したコードはすべて保持してください。
- 各ツールを
tryの中で実行します。例外が発生した場合は、モデルが何が問題だったかを読み取れるように、エラーメッセージ(str(error))を content に持ち、"is_error": Trueを設定したtool_resultを送信します。 MAX_STEPS = 5を追加し、ツール呼び出しのラウンド数をstepsでカウントします。ラウンドを実行する前に、stepsがすでにMAX_STEPSと等しい場合はループを停止します。- ループ終了後、モデルがまだツールを要求している場合は
Stopped after 5 stepsを出力し(MAX_STEPSを使用)、そうでない場合は以前と同様にAgent:の行を出力します。
オスロへのフライトサービスは再試行を促すエラーを返すため、モデルは再試行を繰り返します。たとえば、入力が Find a flight to Oslo の場合、プログラムは次のように出力します。
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Stopped after 5 stepsフライトのない都市である Find a flight to Paris の場合、次のように出力します。
Tool: search_flights {'destination': 'Paris'}
Agent: Sorry, I could not finish: No flights to Paris自分で試してみよう
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]
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=tools, messages=messages)
while response.stop_reason == "tool_use":
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
result = TOOLS[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
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)
for block in response.content:
if block.type == "text":
print("Agent: " + block.text)
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ