Die Agenten-Schleife läuft
Teil des Abschnitts Tools und Agenten der AI Engineering-Journey von Coddy. Lektion 17 von 22.
Aufgabe
MittelLass den Agenten auch nach Hotels suchen und fahre fort, bis das Modell aufhört, nach Tools zu fragen. Behalte alles bei, was du bisher geschrieben hast.
- Füge ein Tool namens
find_hotelmit der BeschreibungFind a hotel room in a city with its nightly rateund einer erforderlichen String-Eigenschaftcityhinzu, die alsThe city to stay inbeschrieben ist. - Füge
TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel}hinzu und sende beide Tools bei jedem Aufruf. - Ersetze den einzelnen Folgeaufruf durch eine Schleife: Während
response.stop_reasonden Wert"tool_use"hat, gib dieTool:-Zeile für jedentool_use-Block aus, führe die vonTOOLSbenannte Funktion mit der Eingabe des Blocks aus, sende alle Ergebnisse in einer User-Nachricht zurück und rufe das Modell erneut auf. - Gib nach der Schleife
Agent:und den Text des Textblocks aus.
Für die Eingabe Find a flight to Rome and a hotel in Lisbon gibt das Programm beispielsweise Folgendes aus:
Tool: search_flights {'destination': 'Rome'}
Tool: find_hotel {'city': 'Lisbon'}
Agent: Here is what I found:
- Flight to Rome: 95 dollars
- Hotel in Lisbon: 80 dollars a nightDas Modell hat beide Tools in einer Antwort angefordert, sodass beide Ergebnisse in einer User-Nachricht zurückgehen.
Probier es selbst
import coddy_ai as anthropic # In Produktion: 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()
# Schreibe deinen Code unten
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"],
},
}
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
result = search_flights(block.input["destination"])
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=[flight_tool], messages=messages)
for block in response.content:
if block.type == "text":
print("Agent: " + block.text)
Alle Lektionen in Tools und Agenten
Übe selbstständig: Online-Python-Compiler