Menu
CoddyTech

도구 오류

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

도구는 실패할 수 있습니다. 알 수 없는 제품이거나, 서비스가 중단되었거나, 인자가 범위를 벗어난 경우 등입니다. 예외가 빠져나가면 프로그램이 비정상 종료되고 대화 내용이 손실됩니다. 대신 예외를 포착하여 "is_error": True와 함께 실패를 결과로 보내세요:

try:
    output = get_forecast(**block.input)
except ValueError as error:
    return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
return {"type": "tool_result", "tool_use_id": block.id, "content": output}

플래그는 모델에 호출이 작동하지 않았음을 알리고, 내용은 그 이유를 알립니다. Error 17과 같은 방식 대신 Unknown city: Atlantis와 같이 사람이 보고 조치를 취할 수 있는 메시지를 작성하세요. 실제 모델은 이 메시지를 읽고 더 나은 입력으로 다시 시도하거나 사용자에게 문제를 설명할 수 있습니다. 대역(stand-in)은 이를 보고하며, 그 답변은 Sorry, I could not finish: 와 작성한 메시지가 됩니다. 플래그가 없으면 모델은 이 메시지를 정상적인 결과로 간주하여 오류를 답변으로 제시할 수 있습니다.

challenge icon

챌린지

중급

스타터의 재고 에이전트는 알 수 없는 제품이 입력되면 check_stock이 ValueError를 발생시키기 때문에 크래시됩니다. 절대로 크래시되지 않도록 run_tool을 수정하세요.

  1. check_stock 호출을 try로 감싸고 ValueError를 캐치하세요.
  2. 에러가 발생하면 Tool: , 이름, 공백, 입력값, -> error: 및 에러 메시지를 출력한 다음, content가 에러 메시지이고 is_error가 True인 tool_result를 반환하세요.
  3. 호출이 정상적으로 작동하면 스타터 코드와 동일하게 결과를 출력하고 반환하세요.

예를 들어, Check stock for the monitor stand and for the desk fan 입력에 대해 프로그램은 다음과 같이 출력합니다:

Tool: check_stock {'product': 'monitor stand'} -> monitor stand: 3 in stock
Tool: check_stock {'product': 'desk fan'} -> error: Unknown product: desk fan
Answer: Sorry, I could not finish: Unknown product: desk fan

직접 해보기

import coddy_ai as anthropic  # 프로덕션 환경: import anthropic

client = anthropic.Anthropic()

STOCK = {"desk lamp": 12, "office chair": 0, "bookshelf": 5, "monitor stand": 3}


def check_stock(product):
    if product not in STOCK:
        raise ValueError(f"Unknown product: {product}")
    return f"{product}: {STOCK[product]} in stock"


TOOLS = [
    {
        "name": "check_stock",
        "description": "Check how many units of a product are in stock",
        "input_schema": {
            "type": "object",
            "properties": {"product": {"type": "string", "description": "The product name"}},
            "required": ["product"],
        },
    }
]


def run_tool(block):
    # ValueError를 캐치하세요: "-> error: <message>"를 출력하고 에러 결과를 반환하세요
    output = check_stock(**block.input)
    print(f"Tool: {block.name} {block.input} -> {output}")
    return {"type": "tool_result", "tool_use_id": block.id, "content": output}


request = input()
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":
    messages.append({"role": "assistant", "content": response.content})
    results = [run_tool(block) for block in response.content if block.type == "tool_use"]
    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("Answer: " + block.text)
quiz icon실력 점검

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

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

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