Menu
CoddyTech

오류와 제한 사항

Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 18번째.

challenge icon

챌린지

어려움

실제 여행 중에는 없는 도시나 작동하지 않는 서비스와 마주칠 수 있습니다. 에이전트가 두 상황 모두에서 작동할 수 있도록 만드세요. 지금까지 작성한 모든 코드를 유지하세요.

  1. try 안에서 각 도구를 실행하세요. 예외가 발생하면 예외 메시지(str(error))를 내용으로 하고 "is_error": True를 포함한 tool_result를 보내 모델이 무엇이 잘못되었는지 읽을 수 있도록 하세요.
  2. MAX_STEPS = 5를 추가하고 steps에서 도구 호출 라운드 수를 세세요. 라운드를 실행하기 전에 steps가 이미 MAX_STEPS와 같으면 루프를 중지하세요.
  3. 루프가 끝난 후, 모델이 여전히 도구를 원한다면 Stopped after 5 steps를 출력하고(MAX_STEPS 사용), 그렇지 않다면 이전과 같이 Agent: 줄을 출력하세요.

오슬로(Oslo)행 항공권 서비스는 다시 시도하라는 에러를 반환하므로 모델은 계속 재시도합니다. 예를 들어 입력이 Find a flight to Oslo인 경우 프로그램은 다음을 출력합니다:

Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Tool: search_flights {'destination': 'Oslo'}
Stopped after 5 steps

항공편이 없는 도시인 Find a flight to Paris 입력의 경우 다음을 출력합니다:

Tool: search_flights {'destination': 'Paris'}
Agent: Sorry, I could not finish: No flights to Paris

직접 해보기

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]

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

while response.stop_reason == "tool_use":
    results = []
    for block in response.content:
        if block.type == "tool_use":
            print(f"Tool: {block.name} {block.input}")
            result = TOOLS[block.name](**block.input)
            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=tools, messages=messages)

for block in response.content:
    if block.type == "text":
        print("Agent: " + block.text)

도구와 에이전트의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러