병렬 도구 호출
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 7번째.
요청에 여러 독립적인 질문이 포함되어 있을 때, 모델은 하나의 응답으로 모든 도구 호출을 요청합니다. 각 호출은 자체 id를 가진 개별 tool_use 블록입니다.
messages = [{"role": "user", "content": "Look up the opening hours for Luna Cafe and Mango House"}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
calls = [block for block in response.content if block.type == "tool_use"]
for block in calls:
print(block.name, block.input)이것은 두 줄을 출력합니다: get_hours {'place': 'Luna Cafe'} 그리고 get_hours {'place': 'Mango House'}.
모든 호출을 실행한 후 모든 결과를 함께 보냅니다. 즉, 내용이 각 호출당 하나의 tool_result를 포함하는 리스트인 하나의 사용자 메시지로 보냅니다. API는 이를 검사합니다. 도구 호출 이후의 메시지에 해당 id 중 하나라도 결과가 누락되어 있으면 요청이 400 에러로 실패하므로, 결과당 하나의 메시지를 보내는 루프는 두 개의 호출이 들어오는 즉시 작동하지 않게 됩니다. 결과를 함께 보내면 모델이 한 번에 여러 호출을 계속 요청할 수 있음을 알려주므로 매번 왕복 시간을 절약할 수 있습니다.
챌린지
중급시작 코드의 날씨 에이전트는 두 도시에 대해 요청할 때 각 결과를 별도의 메시지로 전송하여 오류가 발생합니다. 루프 내부 영역을 수정하세요.
- 응답의
tool_use블록들을 수집하고Calls:와 그 개수를 출력하세요. - 각 블록에 대해
get_weather를 실행하고 모든tool_result를 하나의 리스트에 넣으세요. - 해당 리스트를 단일 user 메시지로 추가하세요.
프로그램의 나머지 부분은 그대로 유지하세요. 예를 들어, 입력값 What is the weather in Oslo and Lima?에 대해 프로그램은 다음을 출력합니다:
Calls: 2
Answer: Here is what I found:
- Oslo: 4 C and rainy
- Lima: 19 C and misty직접 해보기
import coddy_ai as anthropic # 프로덕션 환경: import anthropic
client = anthropic.Anthropic()
WEATHER = {
"Paris": "18 C and sunny",
"Tokyo": "22 C and cloudy",
"Rome": "25 C and sunny",
"Oslo": "4 C and rainy",
"Cairo": "31 C and clear",
"Lima": "19 C and misty",
}
def get_weather(city):
return f"{city}: {WEATHER.get(city, 'no data')}"
TOOLS = [
{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string", "description": "The city name"}},
"required": ["city"],
},
}
]
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})
# 이 부분을 수정하세요: "Calls: "와 이 응답의 도구 호출 수를 출력하고,
# 그런 다음 모든 결과를 하나의 user 메시지로 보내세요
for block in response.content:
if block.type == "tool_use":
result = {"type": "tool_result", "tool_use_id": block.id, "content": get_weather(**block.input)}
messages.append({"role": "user", "content": [result]})
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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러