项目概述
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 16 课,共 22 课。
挑战
中等在接下来的 4 节课中,你将构建一个旅行代理程序:一个能让模型搜索航班和酒店并预订座位的程序。初始代码包含行程数据和三个 Python 函数,今天你将把其中一个提供给模型。
- 定义一个名为
search_flights的工具,描述为Search flights to a destination and give the ticket price,以及一个必需的字符串属性destination,描述为The destination city。 - 将输入请求作为唯一的 user 消息发送,并指定
tools=[...]、model="claude-opus-5-5"和max_tokens=500。 - 对于每个
tool_use块,打印Tool:、工具名称、一个空格及其输入参数,然后传入目的地运行search_flights。 - 追加 assistant 的 content,以及包含
tool_result块的 user 消息,使用相同的工具再次调用模型,并打印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()
# 在下方编写你的代码
工具与 Agent中的所有课
自己练习: Python 在线编译器