Claude는 API 대화 내에서 직접 데이터를 분석하고, 시각화를 생성하고, 복잡한 계산을 수행하고, 시스템 명령을 실행하고, 파일을 생성 및 편집하고, 업로드된 파일을 처리할 수 있습니다. 코드 실행 도구를 통해 Claude는 안전한 샌드박스 환경에서 Bash 명령을 실행하고 코드 작성을 포함한 파일 조작을 수행할 수 있습니다.
웹 검색 또는 웹 가져오기와 함께 사용할 경우 코드 실행은 무료입니다. 요청에 web_search_20260209(또는 이후 버전) 또는 web_fetch_20260209(또는 이후 버전)가 포함된 경우, 표준 입력 및 출력 토큰 비용 외에 코드 실행 도구 호출에 대한 추가 요금이 없습니다. 이러한 도구가 포함되지 않은 경우 표준 코드 실행 요금이 적용됩니다.
코드 실행은 고성능 에이전트를 구축하기 위한 핵심 기본 요소입니다. 웹 검색 및 웹 가져오기 도구에서 동적 필터링을 가능하게 하여, Claude가 결과가 컨텍스트 윈도우에 도달하기 전에 처리할 수 있도록 함으로써 정확도를 높이고 토큰 소비를 줄입니다.
이 기능에 대한 피드백을 공유하려면 피드백 양식을 통해 문의해 주세요.
이 기능은 Zero Data Retention (ZDR) 대상이 아닙니다. 데이터는 해당 기능의 표준 보존 정책에 따라 보존됩니다.
코드 실행 도구는 다음 모델에서 사용할 수 있습니다:
| 모델 | 도구 버전 |
|---|---|
| Claude Fable 5 (claude-fable-5) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Mythos 5 (claude-mythos-5) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Opus 4.8 (claude-opus-4-8) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Opus 4.7 (claude-opus-4-7) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825, code_execution_20260120, code_execution_20260521 |
| Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
| Claude Opus 4.1 (claude-opus-4-1-20250805) (지원 중단됨) | code_execution_20250825 |
code_execution_20250825는 Bash 명령 및 파일 작업을 지원하며 표의 모든 모델에서 사용할 수 있습니다. code_execution_20260120은 REPL 상태 지속성과 샌드박스 내에서의 프로그래밍 방식 도구 호출을 추가하며, Claude Fable 5, Claude Mythos 5, Opus 4.5+ 및 Sonnet 4.5+에서만 사용할 수 있습니다. code_execution_20260521은 _20260120과 동일한 런타임이지만 도구 설명에 셀당 실행 시간 제한이 명시되어 있어 Claude가 장시간 실행되는 셀의 시간을 적절히 배분할 수 있습니다. 각 셀에는 90초의 실제 시간(wall-clock time) 제한이 있으며, 이를 초과하는 코드는 detection_timeout 결과를 반환합니다. 레거시 code_execution_20250522(Python 전용)를 여전히 사용 중이라면 최신 도구 버전으로 업그레이드를 참조하여 마이그레이션하세요.
이전 도구 버전은 최신 모델과의 하위 호환성이 보장되지 않습니다. 항상 사용 중인 모델 버전에 해당하는 도구 버전을 사용하세요.
코드 실행은 다음에서 사용할 수 있습니다:
코드 실행은 현재 Amazon Bedrock 또는 Vertex AI에서 사용할 수 없습니다.
Claude Mythos Preview의 경우, 코드 실행은 Claude API 및 Microsoft Foundry에서만 지원됩니다. Amazon Bedrock, Vertex AI 또는 Claude Platform on AWS의 Mythos Preview에서는 사용할 수 없습니다.
다음은 Claude에게 계산을 수행하도록 요청하는 간단한 예제입니다:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
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_20250825", "name": "code_execution"}],
)
print(response)API 요청에 코드 실행 도구를 추가하면:
Claude는 요청이 계산이나 파일 처리의 이점을 얻을 수 있을 때 코드를 실행합니다:
Claude는 다음의 경우 코드를 실행하지 않고 직접 답변합니다:
경계선상의 요청에 대해 Claude가 코드를 실행하기를 원한다면 명시적으로 요청하세요(예: "코드를 실행하여 이를 검증해 주세요").
코드 실행을 코드를 실행하는 클라이언트 제공 도구(예: bash 도구 또는 사용자 정의 REPL)와 함께 제공하면, Claude는 다중 컴퓨터 환경에서 작동하게 됩니다. 코드 실행 도구는 Anthropic의 샌드박스 컨테이너에서 실행되는 반면, 클라이언트 제공 도구는 사용자가 제어하는 별도의 환경에서 실행됩니다. Claude는 때때로 이러한 환경을 혼동하여 잘못된 도구를 사용하려고 하거나 환경 간에 상태가 공유된다고 가정할 수 있습니다.
이를 방지하려면 시스템 프롬프트에 구분을 명확히 하는 지침을 추가하세요:
When multiple code execution environments are available, be aware that:
- Variables, files, and state do NOT persist between different execution environments
- Use the code_execution tool for general-purpose computation in Anthropic's sandboxed environment
- Use client-provided execution tools (e.g., bash) when you need access to the user's local system, files, or data
- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared state이는 코드 실행을 자동으로 활성화하는 웹 검색 또는 웹 가져오기와 결합할 때 특히 중요합니다. 애플리케이션이 이미 클라이언트 측 셸 도구를 제공하는 경우, 자동 코드 실행은 Claude가 구분해야 하는 두 번째 실행 환경을 생성합니다.
자체 데이터 파일(CSV, Excel, 이미지 등)을 분석하려면 Files API를 통해 업로드하고 요청에서 참조하세요:
Files API를 코드 실행과 함께 사용하려면 Files API 베타 헤더가 필요합니다: "anthropic-beta": "files-api-2025-04-14"
Python 환경은 Files API를 통해 업로드된 다음과 같은 다양한 파일 형식을 처리할 수 있습니다:
container_upload 콘텐츠 블록을 사용하여 메시지에서 파일을 참조하세요client = anthropic.Anthropic()
# 파일 업로드
file_object = client.beta.files.upload(
file=open("data.csv", "rb"),
)
# 코드 실행과 함께 file_id 사용
response = client.beta.messages.create(
model="claude-opus-4-8",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this CSV data"},
{"type": "container_upload", "file_id": file_object.id},
],
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response)Claude가 코드 실행 중에 파일을 생성하면 Files API를 사용하여 이러한 파일을 검색할 수 있습니다:
# 클라이언트 초기화
client = Anthropic()
# 파일을 생성하는 코드 실행 요청
response = client.beta.messages.create(
model="claude-opus-4-8",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Create a matplotlib visualization and save it as output.png",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# 응답에서 파일 ID 추출
def extract_file_ids(response):
file_ids = []
for item in response.content:
if item.type == "bash_code_execution_tool_result":
content_item = item.content
if content_item.type == "bash_code_execution_result":
# 구체적 타입 리스트: List[BashCodeExecutionOutputBlock]
for file in content_item.content:
file_ids.append(file.file_id)
return file_ids
# 생성된 파일 다운로드
for file_id in extract_file_ids(response):
file_metadata = client.beta.files.retrieve_metadata(file_id)
file_content = client.beta.files.download(file_id)
file_content.write_to_file(file_metadata.filename)
print(f"Downloaded: {file_metadata.filename}")코드 실행 도구는 추가 매개변수가 필요하지 않습니다:
{
"type": "code_execution_20250825",
"name": "code_execution"
}이 도구가 제공되면 Claude는 자동으로 두 개의 하위 도구에 접근할 수 있습니다:
bash_code_execution: 셸 명령 실행text_editor_code_execution: 코드 작성을 포함하여 파일 조회, 생성 및 편집코드 실행 도구는 작업에 따라 두 가지 유형의 결과를 반환할 수 있습니다:
{
"type": "server_tool_use",
"id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"name": "bash_code_execution",
"input": {
"command": "ls -la | head -5"
}
},
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"content": {
"type": "bash_code_execution_result",
"stdout": "total 24\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 11:00 ..\n-rw-r--r-- 1 user user 220 Jan 1 12:00 data.csv\n-rw-r--r-- 1 user user 180 Jan 1 12:00 config.json",
"stderr": "",
"return_code": 0
}
}파일 조회:
{
"type": "server_tool_use",
"id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"name": "text_editor_code_execution",
"input": {
"command": "view",
"path": "config.json"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": {
"type": "text_editor_code_execution_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"numLines": 4,
"startLine": 1,
"totalLines": 4
}
}파일 생성:
{
"type": "server_tool_use",
"id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"name": "text_editor_code_execution",
"input": {
"command": "create",
"path": "new_file.txt",
"file_text": "Hello, World!"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"content": {
"type": "text_editor_code_execution_result",
"is_file_update": false
}
}파일 편집 (str_replace):
{
"type": "server_tool_use",
"id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"name": "text_editor_code_execution",
"input": {
"command": "str_replace",
"path": "config.json",
"old_str": "\"debug\": true",
"new_str": "\"debug\": false"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"content": {
"type": "text_editor_code_execution_result",
"oldStart": 3,
"oldLines": 1,
"newStart": 3,
"newLines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}모든 실행 결과에는 다음이 포함됩니다:
stdout: 성공적인 실행의 출력stderr: 실행 실패 시 오류 메시지return_code: 성공 시 0, 실패 시 0이 아닌 값파일 작업에 대한 추가 필드:
file_type, content, numLines, startLine, totalLinesis_file_update (파일이 이미 존재했는지 여부)oldStart, oldLines, newStart, newLines, lines (diff 형식)각 도구 유형은 특정 오류를 반환할 수 있습니다:
공통 오류 (모든 도구):
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
"content": {
"type": "bash_code_execution_tool_result_error",
"error_code": "unavailable"
}
}도구 유형별 오류 코드:
| 도구 | 오류 코드 | 설명 |
|---|---|---|
| 모든 도구 | unavailable | 도구를 일시적으로 사용할 수 없음 |
| 모든 도구 | execution_time_exceeded | 실행이 최대 시간 제한을 초과함 |
| 모든 도구 | container_expired | 컨테이너가 만료되어 더 이상 사용할 수 없음 |
| 모든 도구 | invalid_tool_input | 도구에 잘못된 매개변수가 제공됨 |
| 모든 도구 | too_many_requests | 도구 사용에 대한 속도 제한 초과 |
| bash | output_file_too_large | 명령 출력이 최대 크기를 초과함 |
| text_editor | file_not_found | 파일이 존재하지 않음 (조회/편집 작업의 경우) |
| text_editor | string_not_found | 파일에서 old_str을 찾을 수 없음 (str_replace의 경우) |
pause_turn 중지 사유응답에는 pause_turn 중지 사유가 포함될 수 있으며, 이는 API가 장시간 실행되는 턴을 일시 중지했음을 나타냅니다. 후속 요청에서 응답을 그대로 다시 제공하여 Claude가 턴을 계속하도록 하거나, 대화를 중단하려는 경우 콘텐츠를 수정할 수 있습니다.
코드 실행 도구는 코드 실행을 위해 특별히 설계된 안전한 컨테이너화된 환경에서 실행되며, Python에 더 중점을 둡니다.
샌드박스 Python 환경에는 다음과 같은 일반적으로 사용되는 라이브러리가 포함되어 있습니다:
이전 응답의 컨테이너 ID를 제공하여 여러 API 요청에서 기존 컨테이너를 재사용할 수 있습니다. 이를 통해 요청 간에 생성된 파일을 유지할 수 있습니다.
# 첫 번째 요청: 난수를 포함한 파일 생성
response1 = client.messages.create(
model="claude-opus-4-8",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Write a file with a random number and save it to '/tmp/number.txt'",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# 첫 번째 응답에서 컨테이너 ID 추출
container_id = response1.container.id
# 두 번째 요청: 컨테이너를 재사용하여 파일 읽기
response2 = client.messages.create(
container=container_id, # Reuse the same container
model="claude-opus-4-8",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Read the number from '/tmp/number.txt' and calculate its square",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response2)스트리밍이 활성화되면 코드 실행 이벤트가 발생하는 즉시 수신됩니다:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}
// Code execution streamed
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())\"}"}}
// Pause while code executes
// Execution results streamed
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 요청과 동일한 가격이 적용됩니다.
코드 실행은 웹 검색 또는 웹 가져오기와 함께 사용할 때 무료입니다. API 요청에 web_search_20260209(또는 이후 버전) 또는 web_fetch_20260209(또는 이후 버전)가 포함된 경우, 표준 입력 및 출력 토큰 비용 외에 코드 실행 도구 호출에 대한 추가 요금이 부과되지 않습니다.
이러한 도구 없이 사용하는 경우, 코드 실행은 토큰 사용량과 별도로 추적되는 실행 시간을 기준으로 청구됩니다:
코드 실행 사용량은 응답에서 추적됩니다:
{
"usage": {
"input_tokens": 105,
"output_tokens": 239,
"server_tool_use": {
"code_execution_requests": 1
}
}
}code-execution-2025-08-25로 업그레이드하면 여러 언어의 코드를 포함한 파일 조작 및 Bash 기능에 접근할 수 있습니다. 가격 차이는 없습니다.
| 구성 요소 | 레거시 | 현재 |
|---|---|---|
| 베타 헤더 | code-execution-2025-05-22 | code-execution-2025-08-25 |
| 도구 유형 | code_execution_20250522 | code_execution_20250825 |
| 기능 | Python 전용 | Bash 명령, 파일 작업 |
| 응답 유형 | code_execution_result | bash_code_execution_result, text_editor_code_execution_result |
업그레이드하려면 API 요청에서 도구 유형을 업데이트하세요:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"응답 처리 검토 (프로그래밍 방식으로 응답을 파싱하는 경우):
코드 실행 컨테이너 내에서 도구를 실행하는 방법은 프로그래밍 방식 도구 호출을 참조하세요.
코드 실행은 서버 측 샌드박스 컨테이너에서 실행됩니다. 실행 아티팩트, 업로드된 파일 및 출력을 포함한 컨테이너 데이터는 최대 30일 동안 보존됩니다. 이 보존 기간은 컨테이너 환경 내에서 처리되는 모든 데이터에 적용됩니다. 코드 실행이 Files API에서 생성하는 파일(client.beta.files.download()를 통해 검색 가능)은 명시적으로 삭제될 때까지 유지됩니다.
모든 기능에 대한 ZDR 적격성은 API 및 데이터 보존을 참조하세요.
코드 실행 도구를 통해 Claude는 Agent Skills를 사용할 수 있습니다. Skills는 Claude의 기능을 확장하는 지침, 스크립트 및 리소스로 구성된 모듈식 기능입니다.
자세한 내용은 Agent Skills 및 API와 함께 Agent Skills 사용하기를 참조하세요.
Was this page helpful?