Nối tiếp kết quả công cụ
Thuộc phần Công cụ và agent trong hành trình AI Engineering của Coddy. Bài học 14 trên 22.
Nhiều yêu cầu cần hai công cụ liên tiếp, trong đó công cụ thứ hai cần kết quả mà công cụ đầu tiên trả về. Khi được hỏi What is the price of the kettle with tax?, mô hình có công cụ get_price và công cụ add_tax chưa thể gọi add_tax ngay: nó chưa có giá. Nó sẽ gọi get_price, đọc 30 dollars trong kết quả, sau đó gọi add_tax với con số đó.
get_price {'item': 'kettle'}
add_tax {'price': 30}Vòng lặp của bạn giúp điều này trở nên khả thi mà không cần biết trước: nó gửi lại từng kết quả và tiếp tục chạy trong khi stop_reason là "tool_use". Một vòng lặp chỉ xử lý một lượt sẽ dừng lại sau get_price và không bao giờ thực hiện lần gọi thứ hai.
Có hai điều giúp một chuỗi (chain) hoạt động tốt. Kết quả nên nêu rõ các con số (30 dollars, không phải mã nội bộ), vì mô hình (model) sẽ sao chép chúng vào lần gọi tiếp theo. Ngoài ra, đối số (argument) nhận giá trị số phải là "type": "number" hoặc "integer", để mô hình truyền một giá trị mà hàm (function) của bạn có thể tính toán được.
Thử thách
KhóTrợ lý tàu hỏa có thể tìm giá vé bằng euro. Thêm một công cụ để chuyển đổi giá vé, giúp mô hình có thể chuỗi hai công cụ lại với nhau.
- Thêm một công cụ vào
TOOLScó tên làconvert_euros, với mô tả làConvert an amount in euros to another currency., cùng hai thuộc tính bắt buộc:amount(một số, số tiền bằng euro) vàcurrency(một chuỗi, mã tiền tệ: USD, JPY hoặc GBP). - Viết hàm
convert_euros(amount, currency). Hàm trả về<amount> euros is <converted> <currency>, trong đó giá trị đã chuyển đổi làamount * RATES[currency]lấy 2 chữ số thập phân. - Thêm hàm này vào
FUNCTIONS.
Ví dụ, với đầu vào What does the train to Lyon cost in dollars? chương trình sẽ in ra:
Step 1: get_fare {'destination': 'Lyon'}
Step 2: convert_euros {'amount': 48, 'currency': 'USD'}
Answer: Here is what I found:
- Lyon: 48 euros
- 48 euros is 52.32 USDTự làm thử
import coddy_ai as anthropic # trong môi trường thực tế: import anthropic
client = anthropic.Anthropic()
FARES = {"Lyon": 48, "Nice": 95, "Lille": 35, "Bordeaux": 70}
RATES = {"USD": 1.09, "JPY": 162.0, "GBP": 0.86}
TOOLS = [
{
"name": "get_fare",
"description": "Get the price of a train ticket from Paris to a destination, in euros.",
"input_schema": {
"type": "object",
"properties": {"destination": {"type": "string", "description": "The destination city"}},
"required": ["destination"],
},
},
# Thêm công cụ convert_euros vào đây
]
def get_fare(destination):
return f"{destination}: {FARES[destination]} euros"
# Viết convert_euros(amount, currency) ở đây
FUNCTIONS = {"get_fare": get_fare}
request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
step = 0
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
step += 1
print(f"Step {step}: {block.name} {block.input}")
output = FUNCTIONS[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.
Tất cả bài học trong Công cụ và agent
3Thiết kế agent
Viết mô tả công cụXác thực đầu vào của công cụPhê duyệt từ con ngườiNối tiếp kết quả công cụTổng kết: Agent quản lý chi phíTự luyện tập: Trình biên dịch Python online