审批与报告
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 19 课,共 22 课。
挑战
困难预订机票会花费旅客的资金,因此智能体必须先询问。然后报告运行的消耗成本。保留目前为止编写的所有代码。
- 添加一个名为
book_flight的工具,描述为Book a seat on a flight to a destination,并包含一个必需的字符串属性destination,描述为The destination city。将其添加到TOOLS以及发送的工具列表中。 - 当
tool_use块指定为book_flight时,在打印其Tool:行后额外读取一行输入。如果是yes,打印Approved并运行该工具。否则打印Declined,并在不运行工具的情况下发送包含"is_error": True的结果The traveller said no to this booking。 - 累加每次调用(包括第一次调用)的
input_tokens和output_tokens。 - 最后,打印
Steps:和工具轮数,然后打印总计的Tokens: <input> in, <output> out。
例如,对于输入 Book a flight to Lisbon 和 yes,程序输出:
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 out亲手试试
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]
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)
工具与 Agent中的所有课
自己练习: Python 在线编译器