코드 실행 도구를 사용하면 Claude가 안전한 샌드박스 환경에서 Python 코드를 실행할 수 있습니다. Claude는 API 대화 내에서 직접 데이터를 분석하고, 시각화를 생성하며, 복잡한 계산을 수행하고, 업로드된 파일을 처리할 수 있습니다.

이 기능은 베타 헤더가 필요합니다: "anthropic-beta": "code-execution-2025-05-22"

지원되는 모델

코드 실행 도구는 다음 모델에서 사용할 수 있습니다:

  • Claude Opus 4 (claude-opus-4-20250514)
  • Claude Sonnet 4 (claude-sonnet-4-20250514)
  • Claude Sonnet 3.7 (claude-3-7-sonnet-20250219)
  • Claude Haiku 3.5 (claude-3-5-haiku-latest)

빠른 시작

다음은 Claude에게 계산을 수행하도록 요청하는 간단한 예시입니다:

curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-05-22" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "max_tokens": 4096,
        "messages": [
            {
                "role": "user",
                "content": "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
            }
        ],
        "tools": [{
            "type": "code_execution_20250522",
            "name": "code_execution"
        }]
    }'

코드 실행 작동 방식

API 요청에 코드 실행 도구를 추가하면:

  1. Claude는 코드 실행이 질문에 답하는 데 도움이 될지 평가합니다
  2. Claude는 안전한 샌드박스 환경에서 Python 코드를 작성하고 실행합니다
  3. 코드 실행은 단일 요청 내에서 여러 번 발생할 수 있습니다
  4. Claude는 생성된 차트, 계산 또는 분석과 함께 결과를 제공합니다

도구 정의

코드 실행 도구는 추가 매개변수가 필요하지 않습니다:

JSON
{
  "type": "code_execution_20250522",
  "name": "code_execution"
}

응답 형식

다음은 코드 실행이 포함된 응답 예시입니다:

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll calculate the mean and standard deviation for you."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "name": "code_execution",
      "input": {
        "code": "import numpy as np\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nmean = np.mean(data)\nstd = np.std(data)\nprint(f\"Mean: {mean}\")\nprint(f\"Standard deviation: {std}\")"
      }
    },
    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "content": {
        "type": "code_execution_result",
        "stdout": "Mean: 5.5\nStandard deviation: 2.8722813232690143\n",
        "stderr": "",
        "return_code": 0
      }
    },
    {
      "type": "text",
      "text": "The mean of the dataset is 5.5 and the standard deviation is approximately 2.87."
    }
  ],
  "id": "msg_01BqK2v4FnRs4xTjgL8EuZxz",
  "model": "claude-opus-4-20250514",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 45,
    "output_tokens": 187,
    "server_tool_use": {
      "execution_time_seconds": 1.5
    }
  }
}

결과

코드 실행 결과에는 다음이 포함됩니다:

  • stdout: print 문과 성공적인 실행의 출력
  • stderr: 코드 실행이 실패할 경우 오류 메시지
  • return_code (성공은 0, 실패는 0이 아닌 값)
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01ABC123",
  "content": {
    "type": "code_execution_result",
    "stdout": "",
    "stderr": "NameError: name 'undefined_variable' is not defined",
    "return_code": 1
  }
}

오류

도구 사용 중 오류가 발생하면 code_execution_tool_result_error가 표시됩니다

{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
  "content": {
    "type": "code_execution_tool_result_error",
    "error_code": "unavailable"
  }
}

가능한 오류는 다음과 같습니다

  • unavailable: 코드 실행 도구를 사용할 수 없음
  • code_execution_exceeded: 실행 시간이 허용된 최대 시간을 초과함
  • container_expired: 컨테이너가 만료되어 사용할 수 없음

pause_turn 중지 이유

응답에는 API가 긴 턴을 일시 중지했음을 나타내는 pause_turn 중지 이유가 포함될 수 있습니다. Claude가 턴을 계속할 수 있도록 후속 요청에서 응답을 그대로 제공하거나, 대화를 중단하려면 내용을 수정할 수 있습니다.

컨테이너

코드 실행 도구는 Python 코드 실행을 위해 특별히 설계된 안전한 컨테이너화된 환경에서 실행됩니다.

런타임 환경

  • Python 버전: 3.11.12
  • 운영 체제: Linux 기반 컨테이너
  • 아키텍처: x86_64 (AMD64)

리소스 제한

  • 메모리: 1GiB RAM
  • 디스크 공간: 5GiB 작업 공간 저장소
  • CPU: 1 CPU
  • 실행 시간 제한: 실행은 메시지 요청당 제한되며 max_execution_duration 매개변수로 제어할 수 있습니다
  • 컨테이너 만료: 1시간 동안 비활성 상태가 지속되면 컨테이너에 더 이상 액세스할 수 없습니다

네트워킹 및 보안

  • 인터넷 액세스: 보안을 위해 완전히 비활성화됨
  • 외부 연결: 아웃바운드 네트워크 요청 허용되지 않음
  • 샌드박스 격리: 호스트 시스템 및 다른 컨테이너와 완전히 격리됨
  • 파일 액세스: 작업 공간 디렉토리로만 제한됨

사전 설치된 라이브러리

샌드박스 Python 환경에는 다음과 같은 일반적으로 사용되는 라이브러리가 포함되어 있습니다:

  • 데이터 과학: pandas, numpy, scipy, scikit-learn, statsmodels
  • 시각화: matplotlib, seaborn
  • 파일 처리: pyarrow, openpyxl, xlrd, pillow
  • 수학 및 컴퓨팅: sympy, mpmath
  • 유틸리티: tqdm, python-dateutil, pytz, joblib

코드 실행에서 파일 작업하기

코드 실행은 Files API를 통해 업로드된 CSV 파일, Excel 파일 및 기타 데이터 형식과 같은 파일을 분석할 수 있습니다. 이를 통해 Claude는 데이터를 읽고, 처리하고, 인사이트를 생성할 수 있습니다.

코드 실행과 함께 Files API를 사용하려면 두 개의 베타 헤더가 필요합니다: "anthropic-beta": "code-execution-2025-05-22,files-api-2025-04-14"

지원되는 파일 유형

Python 환경은 다음을 포함하여 다양한 파일 유형을 처리할 수 있습니다

  • CSV
  • Excel (.xlsx, .xls)
  • JSON
  • XML
  • 이미지 (JPEG, PNG, GIF, WebP)
  • 텍스트 파일 (.txt, .md, .py 등)

예시

  1. 파일 업로드 Files API를 사용하여 파일을 업로드합니다
  2. 메시지에서 파일 참조 container_upload 콘텐츠 블록을 사용하여 파일을 참조합니다
  3. API 요청에 코드 실행 도구 포함 코드 실행 도구를 포함시킵니다
# 먼저 파일 업로드
curl https://api.anthropic.com/v1/files \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: files-api-2025-04-14" \
    --form 'file=@"data.csv"' \

# 그런 다음 코드 실행과 함께 file_id 사용
curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-05-22,files-api-2025-04-14" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this CSV data"},
                {"type": "container_upload", "file_id": "file_abc123"}
            ]
        }],
        "tools": [{
            "type": "code_execution_20250522",
            "name": "code_execution"
        }]
    }'

스트리밍

스트리밍을 활성화하면 코드 실행 이벤트가 발생할 때 수신할 수 있습니다:

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}

// 코드 실행 스트리밍
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"code\":\"import pandas as pd\\ndf = pd.read_csv('data.csv')\\nprint(df.head())\"}"}}

// 코드 실행 중 일시 중지

// 실행 결과 스트리밍
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"stdout": "   A  B  C\n0  1  2  3\n1  4  5  6", "stderr": ""}}}

배치 요청

Messages Batches API에 코드 실행 도구를 포함할 수 있습니다. Messages Batches API를 통한 코드 실행 도구 호출은 일반 Messages API 요청과 동일한 가격으로 책정됩니다.

사용량 및 가격 책정

코드 실행 도구 사용량은 토큰 사용량과 별도로 추적됩니다. 실행 시간은 최소 5분입니다. 요청에 파일이 포함된 경우, 파일이 컨테이너에 미리 로드되기 때문에 도구가 사용되지 않더라도 실행 시간이 청구됩니다.

가격: 세션-시간당 $0.05.