Aprovação e Relatório
Parte da seção Ferramentas e Agentes do Journey de AI Engineering da Coddy. Lição 19 de 22.
Desafio
DifícilFazer uma reserva gasta o dinheiro do viajante, então o agente deve perguntar primeiro. Depois, informe quanto a execução custou. Mantenha tudo o que você escreveu até agora.
- Adicione uma ferramenta chamada
book_flightcom a descriçãoBook a seat on a flight to a destinatione uma propriedade string obrigatória,destination, descrita comoThe destination city. Adicione-a aoTOOLSe às ferramentas que você envia. - Quando um bloco
tool_usenomearbook_flight, leia mais uma linha de entrada após imprimir sua linhaTool:. Se foryes, imprimaApprovede execute a ferramenta. Caso contrário, imprimaDeclinede envie o resultadoThe traveller said no to this bookingcom"is_error": True, sem executar a ferramenta. - Some
input_tokenseoutput_tokensem todas as chamadas, incluindo a primeira. - No final, imprima
Steps:e o número de rodadas de ferramentas, depoisTokens: <input> in, <output> outcom os totais.
Por exemplo, para a entrada Book a flight to Lisbon e yes o programa imprime:
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 outExperimente você mesmo
import coddy_ai as anthropic # em produção: 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()
# Escreva seu código abaixo
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)
Todas as lições de Ferramentas e Agentes
1Fundamentos do Uso de Ferramentas
Definindo uma FerramentaLendo uma Chamada de FerramentaRetornando Resultados de FerramentasEscolhendo Entre FerramentasRecapitulação: Weather Desk4Projeto: Agente de Viagens
Visão Geral do ProjetoO Loop do Agente em ExecuçãoPratique por conta própria: Compilador de Python online