Menu
CoddyTech

Loop Agen Berjalan

Termasuk bagian Tools dan Agent dalam perjalanan AI Engineering di Coddy. Pelajaran 17 dari 22.

challenge icon

Tantangan

Sedang

Biarkan agent mencari hotel juga, dan terus berjalan sampai model berhenti meminta tool. Pertahankan semua yang sudah kamu tulis sejauh ini.

  1. Tambahkan tool bernama find_hotel dengan deskripsi Find a hotel room in a city with its nightly rate dan satu property string yang wajib, city, yang dideskripsikan sebagai The city to stay in.
  2. Tambahkan TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel} dan kirim kedua tool pada setiap pemanggilan.
  3. Ganti pemanggilan lanjutan tunggal dengan perulangan: selama response.stop_reason bernilai "tool_use", cetak baris Tool: untuk setiap block tool_use, jalankan fungsi yang dinamai oleh TOOLS dengan input dari block tersebut, kirim semua hasil kembali dalam satu pesan user, dan panggil model lagi.
  4. Setelah perulangan, cetak Agent: dan teks dari block teks.

Sebagai contoh, untuk input Find a flight to Rome and a hotel in Lisbon program akan mencetak:

Tool: search_flights {'destination': 'Rome'}
Tool: find_hotel {'city': 'Lisbon'}
Agent: Here is what I found:
- Flight to Rome: 95 dollars
- Hotel in Lisbon: 80 dollars a night

Model meminta kedua tool dalam satu respons, jadi kedua hasil dikembalikan dalam satu pesan user.

Coba sendiri

import coddy_ai as anthropic  # dalam produksi: 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()

# Tulis kodemu di bawah ini
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"],
    },
}

messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)

results = []
for block in response.content:
    if block.type == "tool_use":
        print(f"Tool: {block.name} {block.input}")
        result = search_flights(block.input["destination"])
        results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
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=[flight_tool], messages=messages)
for block in response.content:
    if block.type == "text":
        print("Agent: " + block.text)

Semua pelajaran di Tools dan Agent

Latihan sendiri: Compiler Python online