Approvazione e report
Fa parte della sezione Strumenti e Agenti del percorso AI Engineering di Coddy. Lezione 19 di 22.
Sfida
DifficileEffettuare una prenotazione comporta una spesa per il viaggiatore, quindi l'agente deve prima chiedere la conferma. Poi riferisci quanto è costata l'esecuzione. Mantieni tutto ciò che hai scritto finora.
- Aggiungi uno strumento chiamato
book_flightcon la descrizioneBook a seat on a flight to a destinatione una proprietà stringa obbligatoria,destination, descritta comeThe destination city. Aggiungilo aTOOLSe agli strumenti che invii. - Quando un blocco
tool_useindicabook_flight, leggi un'ulteriore riga di input dopo aver stampato la relativa rigaTool:. Se èyes, stampaApproveded esegui lo strumento. Altrimenti stampaDeclinede invia il risultatoThe traveller said no to this bookingcon"is_error": True, senza eseguire lo strumento. - Somma
input_tokenseoutput_tokensper ogni chiamata, inclusa la prima. - Alla fine, stampa
Steps:e il numero di cicli dello strumento, quindiTokens: <input> in, <output> outcon i totali.
Ad esempio, per l'input Book a flight to Lisbon e yes il programma stampa:
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 outProvalo tu
import coddy_ai as anthropic # in produzione: 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()
# Scrivi il tuo codice qui sotto
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)
Tutte le lezioni di Strumenti e Agenti
1Basi sull'uso dei tool
Definire un toolLeggere una chiamata a un toolRestituire i risultati di un toolScegliere tra i toolRiepilogo: Weather Desk4Progetto: Agente di viaggio
Panoramica del progettoEsecuzione del loop dell'agenteEsercitati da solo: Compilatore Python online