C.W.K.
Stream
Lesson 02 of 06 · published

한 라운드의 병렬 tool 호출

~14 min · parallel, tool-use, concurrency

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

모델이 턴마다 도구 여러 개 호출 가능

User가 복합 질문('Seoul이랑 Tokyo 날씨')하면 Claude가 한 assistant 턴에 tool_use 블록 여러 개 반환. 너가 실행, 결과 모음, 모든 tool_result 블록을 한 user 턴에 다시 보냄. Round-trip이 N+1에서 2로 떨어짐.

Concurrency는 너 일

프로토콜이 병렬 tool_use 블록 전달; 동시 실행은 너 코드 일. 블록에 대한 asyncio.gatherPromise.all이 명백한 수. 응답의 도구 순서가 tool_use_id와 매치되는지 확인 — 모델이 id로 결과 연결.

Parallel 비활성 시점

도구가 ordering 의존성 있으면(A 호출 후 B), 첫 라운드에 tool_choice: {"type": "tool", "name": "A"}, 두 번째에 다른 choice. 또는 tool_choicedisable_parallel_tool_use: True로 sequential 강제. 절제해서 — 대부분 도구 독립.

원칙: 병렬 tool use는 도구 독립일 때 free 지연 win. 디폴트 병렬; 의존성 진짜일 때만 sequential 강제.

Code

모든 tool_use 블록 동시 실행·python
import asyncio, json
from anthropic import AsyncAnthropic

client = AsyncAnthropic()

async def execute(block):
    handler = HANDLERS[block.name]
    result = await handler(**block.input)
    return {
        "type": "tool_result",
        "tool_use_id": block.id,
        "content": json.dumps(result),
    }

async def round_with_parallel(messages):
    resp = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        tools=TOOLS,
        messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":
        return resp, messages
    tool_blocks = [b for b in resp.content if b.type == "tool_use"]
    results = await asyncio.gather(*(execute(b) for b in tool_blocks))
    messages.append({"role": "user", "content": results})
    return resp, messages
특정 도구 강제 또는 병렬 비활성·python
# 모델이 이 도구를 먼저 호출하도록 강제.
resp = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=TOOLS,
    tool_choice={"type": "tool", "name": "validate_input"},
    messages=messages,
)

# 또는 downstream operations이 독립 아닐 때 병렬 호출 비활성.
resp = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=TOOLS,
    tool_choice={"type": "auto", "disable_parallel_tool_use": True},
    messages=messages,
)

External links

Exercise

Tool 루프 수정해서 어느 라운드든 모든 tool_use 블록 동시 실행. 독립 느린 도구 3개로 벤치마크 — 라운드 지연이 3*T에서 ~T로 떨어지는지 확인.
Hint
Speedup 안 보이면 gather가 어디선가 sequential await — 보통 빠진 await이나 serialized handler.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.