도구 호출 왕복
도구 호출은 두 차례의 춤이에요. 사용자의 메시지를 도구 스키마와 함께 보내면, 모델은 "{city: 'Paris'}로 get_weather를 불러"라는 tool_use 블록으로 답해요. 내 코드가 그 함수를 실행해 답을 tool_result로 돌려보내고, 그다음 모델이 그것으로 최종 응답을 써요. 이 레슨은 가운데 단계를 만들어요 -> 모델의 요청이 진짜 Python 호출이 되고 결과가 돌아가는 길을 위해 포장되는 부분이에요.
진짜 반복은 이래요(보여 주기만 해요 -> 네트워크는 부르지 않아요):
resp = client.messages.create(model="claude-opus-5-5", max_tokens=1024,
tools=TOOLS, messages=history)
# resp.stop_reason == "tool_use". The model may ask for SEVERAL tools at once:
# append its turn once, run every tool_use block, and send ALL the results
# back together in ONE user message.
history.append({"role": "assistant", "content": resp.content})
results = []
for block in resp.content:
if block.type == "tool_use":
result = TOOLS_BY_NAME[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": str(result)})
history.append({"role": "user", "content": results})
final = client.messages.create(model="claude-opus-5-5", max_tokens=1024,
tools=TOOLS, messages=history)양보할 수 없는 세부: 모델이 이름 댄 함수를 모델이 준 인자로 부르고, 모델이 각 답을 요청과 맞출 수 있도록 tool_result에 그 tool_use_id를 되울리고, 한 차례가 도구를 여러 개 요청하면 모든 결과를 하나의 user 메시지로 돌려줘요(여러 메시지로 나누면 모델에게 병렬로 묻기를 그만두라고 가르쳐요). 이 레슨에서는 가장 단순한 경우인 도구 호출 하나를 다루고, 레슨 4가 여러 개를 다뤄요. 오프라인으로 돌도록 응답을 평범한 dict로 본떠요:
{"content": [{"type": "tool_use", "id": "toolu_1",
"name": "get_weather", "input": {"city": "Paris"}}],
"stop_reason": "tool_use"}tools가 도구 이름을 Python 함수에 대응시키는 run_tool_call(resp, tools)를 만들어요. 이것은:
resp["content"]에서type이"tool_use"인 첫 블록을 찾아요.tools[name]을 찾아 블록의input을 키워드 인자로 불러요:tools[name](**block["input"]). 이름이tools에 없으면 오류를 일으키세요(KeyError나ValueError) -> 모델이 지어낸 도구는 절대 실행하지 마세요.- 결과를 실어 돌려보내는 후속 user 메시지를 돌려줘요:
{"role": "user",
"content": [{"type": "tool_result",
"tool_use_id": <the block's id>,
"content": str(result)}]}결과는 str(result)로 문자열로 바꾸세요 -> tool_result 콘텐츠는 글로 이동해요. 서로 다른 두 도구 호출(이름과 입력이 다름)이 서로 다른 두 tool_result 메시지를 만들고, 원래 tool_use_id가 되울려지고, 모르는 도구 이름은 오류를 일으키도록 만드세요.
run_tool_call(resp, tools)를 쓰세요. resp["content"]에서 첫 {"type": "tool_use", "id", "name", "input"} 블록을 찾아 tools[name](**input)을 부르고, 후속 메시지 {"role": "user", "content": [{"type": "tool_result", "tool_use_id": <id>, "content": str(result)}]}를 돌려주세요. tools에 없는 도구 이름에는 오류를 일으키세요.
이 연습은 곧 열려요
앞의 레슨을 마치면 이 레슨이 열려요. 강좌 전체가 무료이고 계정도 필요 없으며, 이 레슨은 지금 바로 읽을 수 있어요.
이 브라우저가 learn.floati.life의 쿠키를 막고 있어서, 여기서 마친 레슨들이 순서대로 열리지 않아요. 이 사이트의 쿠키를 허용하고 새로고침하세요.