Menu
CoddyTech

도구 결과 체이닝하기

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

많은 요청은 연속으로 두 개의 도구를 필요로 하며, 두 번째 도구는 첫 번째 도구가 반환한 결과를 필요로 합니다. What is the price of the kettle with tax?라는 질문을 받았을 때, get_price 도구와 add_tax 도구를 가진 모델은 아직 add_tax를 호출할 수 없습니다. 가격이 없기 때문입니다. 모델은 get_price를 호출하고, 결과에서 30 dollars를 읽은 다음, 해당 숫자를 사용하여 add_tax를 호출합니다.

get_price {'item': 'kettle'}
add_tax {'price': 30}

루프는 사전에 알지 못해도 이를 가능하게 합니다: 각 결과를 다시 보내고 stop_reason이 "tool_use"인 동안 계속 진행합니다. 한 라운드만 처리하는 루프는 get_price 이후에 중단되므로 두 번째 호출이 이루어지지 않습니다.

체인이 작동하는 데는 두 가지가 도움이 됩니다. 모델이 결과를 다음 호출로 복사하므로, 결과는 내부 코드가 아닌 숫자를 명확하게 표시해야 합니다(30 dollars). 그리고 숫자를 받는 인수는 "type": "number" 또는 "integer"이어야 모델이 작성한 함수로 계산할 수 있는 값을 전달합니다.

challenge icon

챌린지

어려움

기차 도우미는 유로 단위의 요금을 찾을 수 있습니다. 모델이 이 두 작업을 연쇄적으로 수행할 수 있도록 이를 변환하는 도구를 추가하세요.

  1. TOOLS에 이름이 convert_euros인 도구를 추가하세요. 설명은 Convert an amount in euros to another currency.로 지정하고, 두 개의 필수 속성을 갖도록 합니다: amount(숫자, 유로 단위 금액) 및 currency(문자열, 통화 코드: USD, JPY 또는 GBP).
  2. convert_euros(amount, currency) 함수를 작성하세요. 이 함수는 <amount> euros is <converted> <currency>를 반환합니다. 여기서 변환된 값은 소수점 둘째 자리까지의 amount * RATES[currency]입니다.
  3. 이를 FUNCTIONS에 추가하세요.

예를 들어, 입력이 What does the train to Lyon cost in dollars?인 경우 프로그램은 다음을 출력합니다:

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 USD

직접 해보기

import coddy_ai as anthropic  # 프로덕션 환경: 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"],
        },
    },
    # 여기에 convert_euros 도구를 추가하세요
]


def get_fare(destination):
    return f"{destination}: {FARES[destination]} euros"


# 여기에 convert_euros(amount, currency)를 작성하세요

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)
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

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

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