Anthropic 프로그래매틱 도구 호출

Anthropic 프로그래매틱 도구 호출 (Programmatic Tool Calling)

프로그래매틱 도구 호출을 사용하면 Claude가 코드 실행 컨테이너 안에서 도구를 호출하는 코드를 직접 작성하게 할 수 있어요. 각 도구 호출마다 모델을 왕복(round trip)하지 않아도 되므로, 다중 도구 워크플로우의 지연 시간을 줄이고, 데이터가 모델의 컨텍스트 창에 들어오기 전에 필터링·처리할 수 있어 토큰 소비를 줄여 줍니다.

참고: 프로그래매틱 도구 호출은 현재 공개 베타 상태예요. LiteLLM은 allowed_callers 필드가 있는 도구를 자동으로 감지하고, 프로바이더에 따라 적절한 베타 헤더를 추가해요:

  • Anthropic API & Microsoft Foundry: advanced-tool-use-2025-11-20
  • Amazon Bedrock: advanced-tool-use-2025-11-20
  • Google Cloud Vertex AI: 지원하지 않음

이 기능은 코드 실행 도구가 활성화되어 있어야 해요.

출처: 문서

본문

모델 호환성 (Model Compatibility)

프로그래매틱 도구 호출은 다음 모델에서 사용할 수 있어요.

모델 도구 버전
Claude Opus 4.5 (claude-opus-4-5-20251101) code_execution_20250825
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) code_execution_20250825

빠른 시작 (Quick Start)

Claude가 데이터베이스를 여러 번 프로그래매틱하게 조회하고 결과를 집계하는 간단한 예시예요.

import litellm

response = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
        }
    ],
    tools=[
        {
            "type": "code_execution_20250825",
            "name": "code_execution"
        },
        {
            "type": "function",
            "function": {
                "name": "query_database",
                "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "sql": {
                            "type": "string",
                            "description": "SQL query to execute"
                        }
                    },
                    "required": ["sql"]
                }
            },
            "allowed_callers": ["code_execution_20250825"]
        }
    ]
)

print(response)

동작 원리 (How It Works)

도구를 코드 실행에서 호출 가능하게 구성하고 Claude가 그 도구를 사용하기로 결정하면:

  1. Claude는 그 도구를 함수로 호출하는 Python 코드를 작성하는데, 여러 도구 호출과 전/후처리 로직을 포함할 수 있어요.
  2. Claude는 코드 실행을 통해 이 코드를 샌드박스 컨테이너에서 실행해요.
  3. 도구 함수가 호출되면 코드 실행이 일시 중지되고, API가 caller 필드가 있는 tool_use 블록을 반환해요.
  4. 사용자가 도구 결과를 제공하면, 코드 실행이 계속돼요 (중간 결과는 Claude의 컨텍스트 창에 로드되지 않아요).
  5. 모든 코드 실행이 완료되면 Claude가 최종 출력을 받고 작업을 계속해요.

이 접근 방식은 특히 다음 경우에 유용해요:

  • 대규모 데이터 처리: 결과가 Claude의 컨텍스트에 도달하기 전에 필터링하거나 집계
  • 다단계 워크플로우: 도구 호출 사이에 Claude를 샘플링하지 않고 도구를 직렬(serial) 또는 루프로 호출해 토큰과 지연 시간 절약
  • 조건부 로직: 중간 도구 결과를 기반으로 결정

allowed_callers 필드

allowed_callers 필드는 어떤 컨텍스트가 도구를 호출할 수 있는지 지정해요.

{
    "type": "function",
    "function": {
        "name": "query_database",
        "description": "Execute a SQL query against the database",
        "parameters": {...}
    },
    "allowed_callers": ["code_execution_20250825"]
}

가능한 값:

  • ["direct"] — 오직 Claude만 이 도구를 직접 호출 (생략 시 기본값)
  • ["code_execution_20250825"] — 코드 실행 내에서만 호출 가능
  • ["direct", "code_execution_20250825"] — 직접 및 코드 실행에서 모두 호출 가능

팁: 각 도구에 두 가지를 모두 활성화하는 대신 ["direct"] 또는 ["code_execution_20250825"] 중 하나를 선택하는 것을 권장해요. 이렇게 하면 도구의 최적 사용 방법에 대한 명확한 지침이 되기 때문이에요.

응답의 caller 필드

모든 도구 사용 블록에는 호출 방식을 나타내는 caller 필드가 포함돼요.

직접 호출 (기존 도구 사용):

{
    "type": "tool_use",
    "id": "toolu_abc123",
    "name": "query_database",
    "input": {"sql": "<sql>"},
    "caller": {"type": "direct"}
}

프로그래매틱 호출:

{
    "type": "tool_use",
    "id": "toolu_xyz789",
    "name": "query_database",
    "input": {"sql": "<sql>"},
    "caller": {
        "type": "code_execution_20250825",
        "tool_id": "srvtoolu_abc123"
    }
}

tool_id는 프로그래매틱 호출을 만든 코드 실행 도구를 가리켜요.

컨테이너 수명 주기 (Container Lifecycle)

프로그래매틱 도구 호출은 코드 실행 컨테이너를 사용해요.

  • 컨테이너 생성: 기존 컨테이너를 재사용하지 않는 한 각 세션마다 새 컨테이너가 생성돼요.
  • 만료: 컨테이너는 약 4.5분간 비활성 상태면 만료돼요 (변경될 수 있음).
  • 컨테이너 ID: 기존 컨테이너를 재사용하려면 container 파라미터를 전달해요.
  • 재사용: 요청 간에 상태를 유지하려면 컨테이너 ID를 전달해요.
# First request - creates a new container
response1 = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Query the database"}],
    tools=[...]
)

# Get container ID from response (if available in response metadata)
container_id = response1.get("container", {}).get("id")

# Second request - reuse the same container
response2 = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[...],
    tools=[...],
    container=container_id  # Reuse container
)

경고: 도구가 프로그래매틱하게 호출되어 컨테이너가 도구 결과를 기다리는 동안, 컨테이너가 만료되기 전에 응답해야 해요. expires_at 필드를 모니터링하세요. 컨테이너가 만료되면 Claude는 도구 호출이 시간 초과된 것으로 간주하고 재시도할 수 있어요.

예시 워크플로우 (Example Workflow)

1단계: 초기 요청

import litellm

response = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[{
        "role": "user",
        "content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
    }],
    tools=[
        {
            "type": "code_execution_20250825",
            "name": "code_execution"
        },
        {
            "type": "function",
            "function": {
                "name": "query_database",
                "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "sql": {"type": "string", "description": "SQL query to execute"}
                    },
                    "required": ["sql"]
                }
            },
            "allowed_callers": ["code_execution_20250825"]
        }
    ]
)

2단계: 도구 호출이 포함된 API 응답

Claude가 도구를 호출하는 코드를 작성해요. 응답에는 다음이 포함됩니다:

{
    "role": "assistant",
    "content": [
        {
            "type": "text",
            "text": "I'll query the purchase history and analyze the results."
        },
        {
            "type": "server_tool_use",
            "id": "srvtoolu_abc123",
            "name": "code_execution",
            "input": {
                "code": "results = await query_database('<sql>')\ntop_customers = sorted(results, key=lambda x: x['revenue'], reverse=True)[:5]"
            }
        },
        {
            "type": "tool_use",
            "id": "toolu_def456",
            "name": "query_database",
            "input": {"sql": "<sql>"},
            "caller": {
                "type": "code_execution_20250825",
                "tool_id": "srvtoolu_abc123"
            }
        }
    ],
    "stop_reason": "tool_use"
}

3단계: 도구 결과 제공

# Add assistant's response and tool result to conversation
messages = [
    {"role": "user", "content": "Query customer purchase history..."},
    {
        "role": "assistant",
        "content": response.choices[0].message.content,
        "tool_calls": response.choices[0].message.tool_calls
    },
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": "toolu_def456",
                "content": '[{"customer_id": "C1", "revenue": 45000}, ...]'
            }
        ]
    }
]

# Continue the conversation
response2 = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=messages,
    tools=[...]
)

4단계: 최종 응답

코드 실행이 완료되면 Claude가 최종 응답을 제공해요.

{
    "content": [
        {
            "type": "code_execution_tool_result",
            "tool_use_id": "srvtoolu_abc123",
            "content": {
                "type": "code_execution_result",
                "stdout": "Top 5 customers by revenue:\n1. Customer C1: $45,000\n...",
                "stderr": "",
                "return_code": 0
            }
        },
        {
            "type": "text",
            ...

고급 패턴 (Advanced Patterns)

  • 루프를 통한 배치 처리 (Batch Processing with Loops): 도구를 루프로 호출해 큰 데이터셋을 배치 처리.
  • 조기 종료 (Early Termination): 중간 결과에 따라 코드 실행을 조기에 종료.
  • 데이터 필터링 (Data Filtering): Claude의 컨텍스트에 들어가기 전에 도구 결과를 필터링.

모범 사례 (Best Practices)

  • 도구 설계 (Tool Design): allowed_callers를 명확히 지정해 도구를 설계.
  • 언제 프로그래매틱 호출을 쓸까 (When to Use Programmatic Calling): 대량 데이터 처리, 다단계·다중 호출 워크플로우에 적합.

토큰 효율성 (Token Efficiency)

프로그래매틱 호출은 중간 도구 결과가 Claude의 컨텍스트 창에 로드되지 않으므로, 특히 다중 도구 워크플로우에서 토큰을 크게 절약해요.

프로바이더 지원 (Provider Support)

  • Anthropic API & Microsoft Foundry: 베타 헤더 advanced-tool-use-2025-11-20 (자동 추가)
  • Amazon Bedrock: 베타 헤더 advanced-tool-use-2025-11-20 (자동 추가)
  • Google Cloud Vertex AI: 지원하지 않음

제약 사항 (Limitations)

기능 비호환 (Feature Incompatibilities)

일부 기능과 함께 사용할 수 없을 수 있어요. 자세한 내용은 원본 문서를 참고해 주세요.

도구 제한 (Tool Restrictions)

프로그래매틱 호출은 allowed_callers가 설정된 도구만 사용할 수 있어요.

문제 해결 (Troubleshooting)

흔한 문제 (Common Issues)

  • 컨테이너 만료로 도구 호출 시간 초과
  • allowed_callers 미설정으로 프로그래매틱 호출 불가

더 알아보기 (Learn more)