Menu
CoddyTech

도구 결과 반환하기

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

도구를 실행한 후에도 모델이 답변하려면 결과를 확인해야 합니다. 대화에 턴 두 개를 추가하고 다시 호출하세요. 모델의 전체 content(도구 호출 포함)가 담긴 assistant 턴을 추가한 다음, tool_result 블록을 포함하는 user 턴을 추가합니다. 블록의 tool_use_id는 호출의 id이고, content는 함수가 반환한 값입니다.

messages.append({"role": "assistant", "content": response.content})
messages.append({
    "role": "user",
    "content": [{"type": "tool_result", "tool_use_id": call.id, "content": "Lima: 14:05"}],
})
final = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=tools, messages=messages)

동일한 tools를 다시 전달하세요: 모델이 또 다른 호출을 원할 수 있습니다. API는 짝이 맞는지 확인합니다. 다음 메시지에 tool_result가 없는 tool_use나 어떤 호출과도 id가 일치하지 않는 결과는 BadRequestError와 함께 거부됩니다. 대역은 이 결과로부터 Here is what I found: ... 형태로 답변하며, 실제 모델은 결과 주변에 자신만의 문장을 작성합니다.

challenge icon

챌린지

중급

왕복 요청을 완료하세요: 도구를 실행하고, 그 결과를 다시 전송한 다음 모델의 답변을 출력하세요. 시작 코드는 질문을 전송하고 도구 호출을 call에 보관합니다.

  1. 호출의 입력에서 얻은 day를 사용하여 get_opening_hours를 호출하고 Result: 와 반환된 결과를 출력하세요.
  2. response.content를 담은 assistant 턴을 추가한 다음, 내용이 해당 결과이고 call.id에 대한 하나의 tool_result 블록을 가진 user 턴을 추가하세요.
  3. 동일한 model, max_tokens, tools 및 messages를 사용하여 모델을 다시 호출하세요.
  4. Answer: 와 텍스트 블록의 텍스트를 출력하세요.

예를 들어, 입력 When are you open on Saturday?에 대해 프로그램은 다음을 출력합니다:

Result: Saturday: 10 am to 4 pm
Answer: Here is what I found: Saturday: 10 am to 4 pm

직접 해보기

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

client = anthropic.Anthropic()

HOURS = {"monday": "9 am to 6 pm", "friday": "9 am to 8 pm", "saturday": "10 am to 4 pm", "sunday": "closed"}


def get_opening_hours(day):
    return f"{day}: {HOURS.get(day.lower(), '9 am to 6 pm')}"


hours_tool = {
    "name": "get_opening_hours",
    "description": "Get the shop's opening hours for a day of the week",
    "input_schema": {
        "type": "object",
        "properties": {"day": {"type": "string", "description": "A day of the week"}},
        "required": ["day"],
    },
}

question = input()
messages = [{"role": "user", "content": question}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=[hours_tool], messages=messages)
call = next(block for block in response.content if block.type == "tool_use")

# 1. 도구를 실행하고 "Result: "와 반환된 값을 출력합니다.
# 2. 어시스턴트 턴을 추가한 다음, tool_result를 포함한 사용자 턴을 추가합니다.
# 3. 동일한 도구들로 다시 질문하고 "Answer: "와 답변 텍스트를 출력합니다.
quiz icon실력 점검

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

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

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