プロジェクトの概要
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 16/22。
チャレンジ
中級4つのレッスンを通じて、トラベルエージェント(モデルがフライトやホテルを検索し、座席を予約できるようにするプログラム)を構築します。スターターコードには旅行データと3つのPython関数が含まれており、今日はそのうちの1つをモデルに与えます。
- 名前が
search_flightsで、説明がSearch flights to a destination and give the ticket priceであり、The destination cityと説明された必須の文字列プロパティdestinationを1つ持つツールを定義します。 tools=[...]、model="claude-opus-5-5"、およびmax_tokens=500を使用して、リクエストを唯一のユーザーメッセージとして送信します。- 各
tool_useブロックに対して、Tool:、ツールの名前、スペース、およびその入力を出力し、目的地(destination)を指定してsearch_flightsを実行します。 - アシスタントのコンテンツと
tool_resultブロックを含むユーザーメッセージを追加し、同じツールでモデルを再度呼び出し、Agent:とテキストブロックのテキストを出力します。
例えば、入力 Find a flight to Lisbon の場合、プログラムは次のように出力します:
Tool: search_flights {'destination': 'Lisbon'}
Agent: Here is what I found: Flight to Lisbon: 120 dollars自分で試してみよう
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()
# 以下にコードを記述してください
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ