---
title: 程式碼執行工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool
description: 在沙箱容器中執行 Python 和 bash 程式碼，以分析資料、產生檔案並反覆改進解決方案。
featureMetadata:
  status: ga
  zdr: not-eligible
  supportedModels:
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-opus-5-5
    - claude-opus-5
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-sonnet-4-6
    - claude-sonnet-4-5-20250929
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
  supportedPlatforms:
    Claude API: ga
    Claude Platform on AWS: ga
    Microsoft Foundry:
      availability: ga
      note: 在 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 上，程式碼執行需要 [Hosted on Anthropic 部署](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)。
  details:
    - 每個支援的模型都接受全部三個[工具版本](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#tool-versions)。在 Claude Haiku 4.5 上，程式化工具呼叫和 REPL 狀態持久化無法使用，因此較新的版本在該模型上的行為與 `code_execution_20250825` 相同。
    - 對於 [Claude Mythos Preview](https://anthropic.com/glasswing)，Claude API 和 Microsoft Foundry 支援程式碼執行。
---

Claude 可以直接在 API 對話中分析資料、建立視覺化圖表、執行複雜計算、執行系統命令、建立和編輯檔案，以及處理上傳的檔案。「Code execution tool」（程式碼執行工具）讓 Claude 能夠在安全的「sandboxed」（沙箱化）環境中執行 Bash 命令並操作檔案，包括撰寫程式碼。

**與網頁搜尋或網頁擷取（`web_search_20260209`、`web_fetch_20260209` 或更新版本）一起使用時，程式碼執行是免費的。** 當您的請求中包含其中一個工具時，該請求中的程式碼執行除了標準 token 費用外，不會產生額外費用。這涵蓋了動態篩選背後的程式碼執行，以及 Claude 直接執行的任何程式碼。若未包含這些工具，則適用標準程式碼執行定價。

程式碼執行也為[網頁搜尋](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool)和[網頁擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool)工具中的「dynamic filtering」（動態篩選）提供支援：Claude 會在結果進入「context window」（上下文視窗）之前，先在程式碼執行環境中篩選結果。當動態篩選執行時，API 會自動為該請求佈建所需的程式碼執行，因此您不需要為此在請求中加入程式碼執行工具。

<Note>
  請透過[意見回饋表單](https://forms.gle/LTAU6Xn2puCJMi1n6)分享您對此功能的意見。
</Note>

## 工具版本

程式碼執行工具目前有三個版本，每個[支援的模型](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#compatibility)都接受全部三個版本。每個版本都建立在前一個版本之上：

* `code_execution_20250825` 支援 Bash 命令和檔案操作。
* `code_execution_20260120` 新增了「REPL state persistence」（REPL 狀態持久化），以及從沙箱內進行的[「programmatic tool calling」（程式化工具呼叫）](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling)。Claude Haiku 4.5 接受 `code_execution_20260120` 和 `code_execution_20260521` 工具類型，但程式化工具呼叫以及依賴它的 REPL 狀態持久化在該模型上無法使用，因此較新的版本在該模型上的行為與 `code_execution_20250825` 相同。
* `code_execution_20260521` 與 `code_execution_20260120` 使用相同的執行環境。差別在於工具描述會告知 Claude 程式化工具呼叫中每個 Python 儲存格有 90 秒的實際時間限制，讓 Claude 能為長時間執行的儲存格做好規劃。超過限制的儲存格會傳回一般的程式碼執行結果，其中包含非零的 `return_code`，並在輸出中包含 `detection_timeout` 狀態訊息。這與 `execution_time_exceeded` [錯誤代碼](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#errors)不同，後者是在整個工具呼叫超過最長執行時間時由 API 傳回。

這三個工具版本都不需要 `anthropic-beta` 標頭。舊版的程式碼執行 beta 標頭仍然是有效的選擇性啟用方式。

本頁的範例使用 `code_execution_20250825`，它涵蓋了範例所示範的 Bash 和檔案操作，且在每個支援的模型上行為都相同；當您需要程式化工具呼叫或 REPL 狀態持久化時，請使用 `code_execution_20260120` 或更新版本。目前的[網頁搜尋](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool)和[網頁擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool)工具（`web_search_20260209`、`web_fetch_20260209` 及更新版本）需要 `code_execution_20260120` 或更新版本作為其程式碼執行版本。

較舊的工具版本不保證能與較新的模型保持相容。當您採用新模型時，請查看[工具版本](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#tool-versions)和[相容性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#compatibility)，並優先使用您的整合所支援的最新工具版本。

若要在傳送請求之前檢查模型是否接受程式碼執行工具，請從 Models API 讀取其 `capabilities.server_tools.code_execution.supported` 值。請勿為此使用頂層的 `capabilities.code_execution` 值。該值回報的是在此工具中執行的程式碼是否能呼叫您請求中的其他工具，如同程式化工具呼叫。[使用 Models API](https://platform.claude.com/docs/zh-TW/models/overview#using-the-models-api) 說明了這兩個欄位。

<Note>
  如果您仍在使用舊版的 `code_execution_20250522`（僅限 Python），請參閱[升級至最新工具版本](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#upgrade-to-latest-tool-version)以從該版本遷移。
</Note>

## 快速入門

以下是請 Claude 執行計算的範例：

<CodeGroup>
  ```bash cURL
  curl --fail-with-body -sS https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Use the code execution tool to 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"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{
      role: user,
      content: "Use the code execution tool to calculate the mean and standard
        deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
    }' \
    --tool '{type: code_execution_20250825, name: code_execution}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Use the code execution tool to 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.to_json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content:
          "Use the code execution tool to 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" }]
  });

  console.log(JSON.stringify(response));
  ```

  ```csharp C#
  AnthropicClient client = new();

  var message = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response = client.messages().create(params);
  IO.println(ObjectMappers.jsonMapper().valueToTree(response));
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]',
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  puts message.to_json
  ```
</CodeGroup>

回應會將 `server_tool_use` 區塊（Claude 執行的命令）與其工具結果區塊交錯排列，接著是 Claude 的文字。頂層還包含一個 `container` 物件，您可以[在多個請求之間重複使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#container-reuse)其 `id`。區塊結構請參閱[回應格式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#response-format)。

## 程式碼執行的運作方式

當您將程式碼執行工具加入 API 請求時：

1. Claude 會評估程式碼執行是否有助於回答您的問題

2. 該工具會自動為 Claude 提供以下功能：

   * **Bash 命令：** 執行 shell 命令以進行系統操作
   * **檔案操作：** 直接建立、檢視和編輯檔案，包括撰寫程式碼

3. Claude 可以在單一請求中使用這些功能的任意組合

4. 所有操作都在安全的沙箱「container」（容器）中執行。容器沒有網際網路存取權限，因此 Claude 無法在執行時下載套件：只能使用[預先安裝的函式庫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#pre-installed-libraries)

5. API 會在伺服器端執行每個命令，並在同一個請求中將結果傳回給 Claude，因此您永遠不需要自行執行程式碼或傳回 `tool_result` 區塊。唯一的例外是當 Claude 在程式碼執行的同時呼叫您的某個用戶端工具時：API 會傳回不含結果的程式碼執行呼叫。結果會在您傳回用戶端工具的 `tool_result` 區塊之後，於稍後的回應中送達

6. 除非您將先前回應的容器 ID 傳回，否則每個請求都會在新的容器中執行（請參閱[容器重複使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#container-reuse)）

7. Claude 會提供結果，以及任何產生的圖表、計算或分析

容器已預先安裝 Python。Claude 使用檔案操作子工具撰寫 Python，並透過 Bash 命令執行。使用 `code_execution_20260120` 或更新版本搭配[程式化工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling)時，Python 直譯器狀態（例如變數繫結）也會在重複使用該容器的請求之間持續保留。

### Claude 何時執行程式碼

當請求能從運算或檔案處理中受益時，Claude 會執行程式碼：

* 非簡單的數學運算（大數字、多個步驟、對精確度敏感的結果）
* 資料分析、檔案剖析或視覺化
* 演算法執行或模擬
* 明確要求「run」、「compute」或「execute」

對於以下情況，Claude 會直接回答而不執行程式碼：

* 簡單的算術和眾所周知的數學事實
* 事實性、對話性或創意性的請求
* 簡單的單位換算或翻譯

如果您希望 Claude 針對模稜兩可的請求執行程式碼，請明確提出要求（例如「執行程式碼來驗證這一點」）。

## 處理檔案

### 上傳並分析您自己的檔案

若要分析您自己的資料檔案（例如 CSV、Excel 或圖片），請透過 Files API 上傳，並在請求中參照這些檔案。

Python 環境可以處理透過 Files API 上傳的各種檔案類型，包括：

* CSV
* Excel（.xlsx、.xls）
* JSON
* XML
* 圖片（JPEG、PNG、GIF、WebP）
* 文字檔案（.txt、.md、.py 等）

#### 上傳並分析檔案

1. 使用 [Files API](https://platform.claude.com/docs/zh-TW/build-with-claude/files) **上傳您的檔案**
2. 在訊息中使用 `container_upload` 內容區塊**參照該檔案**
3. 在 API 請求中**包含程式碼執行工具**

<CodeGroup>
  ```bash cURL
  # 首先，上傳檔案並取得檔案 ID（使用 jq）
  FILE_ID=$(curl --fail-with-body -sS https://api.anthropic.com/v1/files \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -F "file=@data.csv" | jq -r '.id')

  # 接著在程式碼執行中使用 file_id
  curl --fail-with-body -sS https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [{
        "role": "user",
        "content": [
          {"type": "text", "text": "Analyze this CSV data"},
          {"type": "container_upload", "file_id": "'"$FILE_ID"'"}
        ]
      }],
      "tools": [{
        "type": "code_execution_20250825",
        "name": "code_execution"
      }]
    }'
  ```

  ```bash CLI
  # 首先，上傳檔案並取得檔案 ID
  FILE_ID=$(ant files upload --file ./data.csv --transform id --raw-output)

  # 接著搭配程式碼執行使用 file_id
  ant messages create <<YAML
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content:
        - type: text
          text: Analyze this CSV data
        - type: container_upload
          file_id: $FILE_ID
  tools:
    - type: code_execution_20250825
      name: code_execution
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  # 上傳檔案
  file_object = client.files.upload(file=Path("data.csv"))

  # 搭配程式碼執行使用 file_id
  response = client.messages.create(
      model="claude-opus-5-5",
      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.to_json())
  ```

  ```typescript TypeScript
  import { createReadStream } from "node:fs";
  // ...
  const client = new Anthropic();

  // 上傳檔案
  const fileObject = await client.files.upload({
    file: createReadStream("data.csv")
  });

  // 搭配程式碼執行使用 file_id
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Analyze this CSV data" },
          { type: "container_upload", file_id: fileObject.id }
        ]
      }
    ],
    tools: [
      {
        type: "code_execution_20250825",
        name: "code_execution"
      }
    ]
  });

  console.log(JSON.stringify(response));
  ```

  ```csharp C#
  AnthropicClient client = new();

  // 上傳檔案
  var fileObject = await client.Files.Upload(new FileUploadParams
  {
      File = File.OpenRead("data.csv")
  });

  // 搭配程式碼執行使用 file_id
  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [
          new()
          {
              Role = Role.User,
              Content = new([
                  new TextBlockParam { Text = "Analyze this CSV data" },
                  new ContainerUploadBlockParam { FileID = fileObject.ID }
              ])
          }
      ],
      Tools = [new CodeExecutionTool20250825()]
  };

  var response = await client.Messages.Create(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  ctx := context.Background()
  client := anthropic.NewClient()

  // 上傳檔案
  file, err := os.Open("data.csv")
  if err != nil {
  	log.Fatal(err)
  }
  defer file.Close()

  fileObject, err := client.Files.Upload(ctx, anthropic.FileUploadParams{
  	File: file,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // 搭配程式碼執行使用 file_id
  response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewTextBlock("Analyze this CSV data"),
  			anthropic.NewContainerUploadBlock(fileObject.ID),
  		),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // 上傳檔案
  FileMetadata fileObject = client.files().upload(
      FileUploadParams.builder()
          .file(Path.of("data.csv"))
          .build()
  );

  // 搭配程式碼執行使用 file_id
  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessageOfBlockParams(List.of(
              ContentBlockParam.ofText(TextBlockParam.builder()
                  .text("Analyze this CSV data")
                  .build()),
              ContentBlockParam.ofContainerUpload(ContainerUploadBlockParam.builder()
                  .fileId(fileObject.id())
                  .build())
          ))
          .addTool(CodeExecutionTool20250825.builder().build())
          .build()
  );

  IO.println(ObjectMappers.jsonMapper().valueToTree(response));
  ```

  ```php PHP
  $client = new Client();

  // 上傳檔案
  $fileObject = $client->files->upload(
      file: FileParam::fromResource(fopen('data.csv', 'r')),
  );

  // 搭配程式碼執行使用 file_id
  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => [
                  TextBlockParam::with(text: 'Analyze this CSV data'),
                  ContainerUploadBlockParam::with(fileID: $fileObject->id),
              ],
          ],
      ],
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($response), PHP_EOL;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  # 上傳檔案
  file_object = client.files.upload(
    file: Pathname("data.csv")
  )

  # 搭配程式碼執行使用 file_id
  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Analyze this CSV data" },
          { type: "container_upload", file_id: file_object.id }
        ]
      }
    ],
    tools: [
      Anthropic::CodeExecutionTool20250825.new
    ]
  )

  puts response.to_json
  ```
</CodeGroup>

### 擷取產生的檔案

當 Claude 在程式碼執行期間將檔案儲存到其輸出目錄時（請參閱[產生的檔案如何被擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#how-generated-files-are-captured)），每個檔案的 ID 都會出現在程式碼執行工具結果中，您可以使用 [Files API](https://platform.claude.com/docs/zh-TW/build-with-claude/files) 下載該檔案：

<CodeGroup exclude="shell">
  <CodeGroupItem language="cURL">
    下載每個產生的檔案需要對工具結果中的檔案 ID 進行迴圈處理，所需的邏輯超出單一 shell 命令所能處理的範圍。請使用 [Claude SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview) 來完成此操作。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    下載每個產生的檔案需要對工具結果中的檔案 ID 進行迴圈處理，所需的邏輯超出單一 shell 命令所能處理的範圍。請使用 [Claude SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview) 來完成此操作。
  </CodeGroupItem>

  ```python Python
  client = Anthropic()

  # 請求執行會建立檔案的程式碼
  response = client.messages.create(
      model="claude-opus-5-5",
      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: Message) -> list[str]:
      file_ids: list[str] = []
      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":
                  for output_block in content_item.content:
                      file_ids.append(output_block.file_id)
      return file_ids


  # 下載已建立的檔案
  for file_id in extract_file_ids(response):
      file_metadata = client.files.retrieve_metadata(file_id)
      file_content = client.files.download(file_id)
      file_content.write_to_file(file_metadata.filename)
      print(f"Downloaded: {file_metadata.filename}")
  ```

  ```typescript TypeScript
  import { writeFile } from "node:fs/promises";

  const client = new Anthropic();

  // 請求執行會建立檔案的程式碼
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    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，並下載每個已建立的檔案
  for (const block of response.content) {
    if (block.type === "bash_code_execution_tool_result") {
      const result = block.content;
      if (result.type === "bash_code_execution_result") {
        for (const outputBlock of result.content) {
          const [fileMetadata, fileResponse] = await Promise.all([
            client.files.retrieveMetadata(outputBlock.file_id),
            client.files.download(outputBlock.file_id)
          ]);
          await writeFile(fileMetadata.filename, await fileResponse.bytes());
          console.log(`Downloaded: ${fileMetadata.filename}`);
        }
      }
    }
  }
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Create a matplotlib visualization and save it as output.png" }],
      Tools = [new CodeExecutionTool20250825()]
  };

  var response = await client.Messages.Create(parameters);

  // 從工具結果中收集檔案 ID
  List<string> fileIds = [];
  foreach (var block in response.Content)
  {
      if (!block.TryPickBashCodeExecutionToolResult(out var toolResult))
          continue;
      if (!toolResult.Content.TryPickBashCodeExecutionResultBlock(out var result))
          continue;
      foreach (var output in result.Content)
      {
          fileIds.Add(output.FileID);
      }
  }

  // 下載每個已建立的檔案
  foreach (var fileId in fileIds)
  {
      var fileMetadata = await client.Files.RetrieveMetadata(fileId);
      using var download = await client.Files.Download(fileId);
      var downloadStream = await download.ReadAsStream();
      await using var target = File.Create(fileMetadata.Filename);
      await downloadStream.CopyToAsync(target);
      Console.WriteLine($"Downloaded: {fileMetadata.Filename}");
  }
  ```

  ```go Go
  	client := anthropic.NewClient()
  	ctx := context.Background()

  	response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 4096,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock("Create a matplotlib visualization and save it as output.png")),
  		},
  		Tools: []anthropic.ToolUnionParam{
  			{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fileIDs := extractFileIDs(response)

  	for _, fileID := range fileIDs {
  		fileMetadata, err := client.Files.GetMetadata(ctx, fileID, anthropic.FileGetMetadataParams{})
  		if err != nil {
  			log.Fatal(err)
  		}

  		fileContent, err := client.Files.Download(ctx, fileID, anthropic.FileDownloadParams{})
  		if err != nil {
  			log.Fatal(err)
  		}

  		outFile, err := os.Create(fileMetadata.Filename)
  		if err != nil {
  			log.Fatal(err)
  		}

  		_, err = io.Copy(outFile, fileContent.Body)
  		if err != nil {
  			log.Fatal(err)
  		}
  		outFile.Close()
  		fileContent.Body.Close()

  		fmt.Printf("Downloaded: %s\n", fileMetadata.Filename)
  	}
  // ...

  func extractFileIDs(response *anthropic.Message) []string {
  	var fileIDs []string
  	for _, item := range response.Content {
  		switch variant := item.AsAny().(type) {
  		case anthropic.BashCodeExecutionToolResultBlock:
  			// 從工具結果中收集檔案 ID
  			for _, file := range variant.Content.Content {
  				if file.FileID != "" {
  					fileIDs = append(fileIDs, file.FileID)
  				}
  			}
  		}
  	}
  	return fileIDs
  }
  ```

  ```java Java
  void main() throws Exception {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Create a matplotlib visualization and save it as output.png")
          .addTool(CodeExecutionTool20250825.builder().build())
          .build();

      Message response = client.messages().create(params);

      List<String> fileIds = extractFileIds(response);

      for (String fileId : fileIds) {
          FileMetadata fileMetadata = client.files().retrieveMetadata(fileId);
          try (HttpResponse fileContent = client.files().download(fileId)) {
              Files.copy(
                  fileContent.body(),
                  Path.of(fileMetadata.filename()),
                  StandardCopyOption.REPLACE_EXISTING);
          }
          IO.println("Downloaded: " + fileMetadata.filename());
      }
  }

  List<String> extractFileIds(Message response) {
      List<String> fileIds = new ArrayList<>();
      // 從工具結果中收集檔案 ID
      for (ContentBlock item : response.content()) {
          item.bashCodeExecutionToolResult().ifPresent(toolResult -> {
              if (toolResult.content().isBashCodeExecutionResultBlock()) {
                  BashCodeExecutionResultBlock result =
                      toolResult.content().asBashCodeExecutionResultBlock();
                  for (BashCodeExecutionOutputBlock output : result.content()) {
                      fileIds.add(output.fileId());
                  }
              }
          });
      }
      return fileIds;
  }
  ```

  ```php PHP
  $client = new Client();

  // 請求執行會建立檔案的程式碼
  $response = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Create a matplotlib visualization and save it as output.png',
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  /**
   * Extract file IDs from the response.
   *
   * @return list<string>
   */
  function extractFileIds(Message $response): array
  {
      $fileIds = [];
      foreach ($response->content as $block) {
          if ($block->type !== 'bash_code_execution_tool_result') {
              continue;
          }
          $resultBlock = $block->content;
          if ($resultBlock->type !== 'bash_code_execution_result') {
              continue;
          }
          foreach ($resultBlock->content as $outputBlock) {
              $fileIds[] = $outputBlock->fileID;
          }
      }
      return $fileIds;
  }

  // 下載已建立的檔案
  foreach (extractFileIds($response) as $fileId) {
      $fileMetadata = $client->files->retrieveMetadata($fileId);
      $fileContent = $client->files->download($fileId);

      file_put_contents($fileMetadata->filename, $fileContent);
      echo "Downloaded: {$fileMetadata->filename}\n";
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    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"
      }
    ]
  )

  def extract_file_ids(response)
    file_ids = []
    response.content.each do |item|
      if item.type == :bash_code_execution_tool_result
        # 針對 anthropic-sdk-ruby union 強制轉型錯誤（SDK-636）的暫時解法：item.content 是
        # 巢狀的 content union，因此 `item.content` 上的型別化存取器並不可靠。
        # 請改為透過公開的 `BaseModel#[]` API 讀取原始回應資料。
        content_item = item.content
        if content_item[:type].to_s == "bash_code_execution_result"
          Array(content_item[:content]).each do |output_block|
            file_ids << output_block[:file_id]
          end
        end
      end
    end
    file_ids
  end

  extract_file_ids(response).each do |file_id|
    file_metadata = client.files.retrieve_metadata(file_id)
    file_content = client.files.download(file_id)

    File.open(file_metadata.filename, "wb") do |f|
      f.write(file_content.read)
    end

    puts "Downloaded: #{file_metadata.filename}"
  end
  ```
</CodeGroup>

#### 產生的檔案如何被擷取

每次 `bash_code_execution` 呼叫都會取得一個新的空目錄，命令可透過 `$OUTPUT_DIR` 使用該目錄。命令完成時，該目錄頂層的檔案會被擷取，並作為結果 `content` 清單中的 `file_id` 項目傳回。寫入其他任何位置的檔案會留在容器中，不會被傳回。

工具描述會告知 Claude 透過將檔案複製到 `$OUTPUT_DIR` 來分享檔案。如果您的應用程式需要接收某個檔案，請提示 Claude 將其複製到 `$OUTPUT_DIR`，並在同一個命令中列出該目錄，讓 `ls` 輸出確認擷取成功（Claude 看不到 `content` 清單）：

```bash
python /tmp/make_report.py && cp /tmp/report.pdf "$OUTPUT_DIR/" && ls "$OUTPUT_DIR"
```

Claude 寫入其他位置的檔案仍然存在於容器中，因此您可以[重複使用容器](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#container-reuse)，並請 Claude 將其複製到 `$OUTPUT_DIR`。

### 產生檔案上的 Content Credentials

在 Claude API 上，當您透過 [Files API](https://platform.claude.com/docs/zh-TW/build-with-claude/files) 下載 Claude 在程式碼執行沙箱中產生的受支援圖片、影片和音訊檔案時，這些檔案會帶有 [C2PA](https://c2pa.org/)「Content Credentials」（內容憑證）。[支援的格式](https://opensource.contentauthenticity.org/docs/sdk-repos/c2pa-python/docs/supported-formats/)包括 PNG、JPEG、GIF、WebP、TIFF、HEIC、AVIF、SVG、MP4、MOV、MP3、WAV、FLAC 和 M4A。此憑證是嵌入在檔案中繼資料中、經過加密簽署的「manifest」（資訊清單）。它將 Anthropic 標識為簽發者，帶有時間戳記，並記錄動作描述「Claude provided this file at the request of a user and may have created or modified the file contents.」

簽署不需要對您的請求或回應處理進行任何變更，且資訊清單不會記錄任何關於您、您的組織或您的請求的資訊。檔案的可見內容保持不變。資訊清單會增加幾 KB 的大小，因此下載檔案的大小和「checksum」（總和檢查碼）會與容器內的檔案不同。文字檔案、PDF 和辦公文件不會被簽署，因為它們不是支援簽署的格式。您上傳的檔案會按原樣儲存，包括它們已帶有的任何 Content Credentials。

若要驗證憑證，請使用任何與 C2PA 相容的工具檢查檔案，例如開放原始碼的 [c2patool 命令列公用程式](https://github.com/contentauth/c2pa-rs)。重新編碼、格式轉換、螢幕截圖以及會移除中繼資料的工具都會移除憑證，因此缺少憑證並不代表檔案不是由 Claude 產生的。如需進一步了解憑證可能缺失的原因，請參閱 [Claude 如何標記 AI 產生的內容](https://support.claude.com/en/articles/16266773-how-claude-marks-ai-generated-content)。

## 工具定義

程式碼執行工具不需要額外的參數：

```json JSON
{
  "type": "code_execution_20250825",
  "name": "code_execution"
}
```

這兩個欄位都是固定的：`type` 用於選擇工具版本，而 `name` 必須是 `code_execution`。

當您提供此工具時，Claude 會自動取得兩個子工具的存取權：

* `bash_code_execution`：執行 shell 命令
* `text_editor_code_execution`：檢視、建立和編輯檔案，包括撰寫程式碼

當 Claude 執行程式碼時，回應還會包含一個頂層 `container` 物件，其中含有容器的 `id` 和 `expires_at` 時間戳記。將該 ID 傳回頂層的 `container` 請求參數，即可繼續使用同一個容器。請參閱[容器重複使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#container-reuse)。

## 回應格式

程式碼執行工具可根據操作傳回兩種類型的結果：

### Bash 命令回應

```json Output
{
  "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,
    "content": []
  }
}
```

### 檔案操作回應

**檢視檔案：**

```json Output
{
  "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_view_result",
    "file_type": "text",
    "content": "{\n  \"setting\": \"value\",\n  \"debug\": true\n}",
    "num_lines": 4,
    "start_line": 1,
    "total_lines": 4
  }
}
```

**建立檔案：**

```json Output
{
  "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_create_result",
    "is_file_update": false
  }
}
```

**編輯檔案（str\_replace）：**

```json Output
{
  "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_str_replace_result",
    "old_start": 3,
    "old_lines": 1,
    "new_start": 3,
    "new_lines": 1,
    "lines": ["-  \"debug\": true", "+  \"debug\": false"]
  }
}
```

### 結果

Bash 命令結果（`bash_code_execution_result`）包含：

* `stdout`：成功執行時的輸出
* `stderr`：執行失敗時的錯誤訊息
* `return_code`：0 表示成功，非零表示失敗
* `content`：一個清單，其中針對命令留在 `$OUTPUT_DIR` 中的每個檔案各有一個項目（請參閱[產生的檔案如何被擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#how-generated-files-are-captured)）。每個項目都帶有 `file_id`，可用於透過 Files API [擷取該檔案](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#retrieve-generated-files)

檔案操作結果有各自的欄位：

* **檢視**（`text_editor_code_execution_view_result`）：`file_type`、`content`、`num_lines`、`start_line`、`total_lines`
* **建立**（`text_editor_code_execution_create_result`）：`is_file_update`（檔案是否已存在）
* **編輯**（`text_editor_code_execution_str_replace_result`）：`old_start`、`old_lines`、`new_start`、`new_lines`、`lines`（diff 格式）

### 錯誤

每種工具類型都可能傳回特定的錯誤：

**常見錯誤（所有工具）：**

```json Output
{
  "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` | 工具呼叫超過最長執行時間      |
| 所有工具         | `invalid_tool_input`      | 提供給工具的參數無效        |
| 所有工具         | `too_many_requests`       | 工具使用超過速率限制        |
| bash         | `output_file_too_large`   | 命令輸出超過最大大小        |
| text\_editor | `file_not_found`          | 檔案不存在（適用於檢視/編輯操作） |

已過期的容器無法重複使用：參照該容器的請求會傳回錯誤，而不會還原容器。請在不帶 `container` 參數的情況下重新傳送請求，以取得新的容器。

### `pause_turn` 停止原因

回應可能包含 `pause_turn` 停止原因，表示 API 暫停了一個長時間執行的回合。您可以 在後續請求中按原樣提供該回應，讓 Claude 繼續其回合，或者如果您 想中斷對話，也可以修改內容。

## 容器

程式碼執行工具在專為程式碼執行設計的安全容器化環境中執行，並更著重於 Python。

### 執行環境

* **Python 版本：** 3.11
* **作業系統：** 以 Linux 為基礎的容器
* **架構：** x86\_64（AMD64）

### 資源限制

* **記憶體：** 5 GiB RAM
* **磁碟空間：** 5 GiB 工作區儲存空間
* **CPU：** 1 個 CPU
* **執行時間：** 執行超過最長執行時間的工具呼叫會傳回 `execution_time_exceeded` [錯誤](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#errors)。使用[程式化工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling)時，每個 REPL 儲存格還有 90 秒的實際時間限制

### 網路與安全性

* **網際網路存取：** 基於安全考量完全停用
* **外部連線：** 不允許任何對外網路請求
* **沙箱隔離：** 與主機系統及其他容器完全隔離
* **檔案存取：** 僅限於工作區目錄
* **工作區範圍：** 與 [Files API](https://platform.claude.com/docs/zh-TW/build-with-claude/files) 相同，容器的範圍限定於請求所屬的工作區
* **過期：** 容器在建立 30 天後過期

### 預先安裝的函式庫

沙箱化的 Python 環境包含以下常用函式庫：

* **資料科學：** pandas、numpy、scipy、scikit-learn、statsmodels
* **視覺化：** matplotlib、seaborn
* **檔案處理：** pyarrow、openpyxl、xlsxwriter、xlrd、pillow、python-pptx、python-docx、pypdf、pdfplumber、pypdfium2、pdf2image、pdfkit、tabula-py、reportlab\[pycairo]、Img2pdf
* **數學與運算：** sympy、mpmath
* **公用程式：** tqdm、python-dateutil、pytz、joblib

容器還包含命令列工具，例如 unzip、unrar、7zip、bc、rg（ripgrep）、fd 和 sqlite。

容器沒有網際網路存取權限，因此 Claude 無法在執行時下載或安裝額外的套件：只能使用預先安裝的函式庫。

## 容器重複使用

您可以提供先前回應中的容器 ID，在多個 API 請求之間重複使用現有的容器。 這讓您能在請求之間保留已建立的檔案。使用 `code_execution_20260120` 或更新版本搭配[程式化工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling)時，Python 直譯器狀態也會持續保留。

容器在建立 30 天後過期。容器在閒置約 5 分鐘後會建立「checkpoint」（檢查點），在 30 天期限內傳送帶有其 ID 的請求即可還原該容器。回應 `container` 物件中的 `expires_at` 時間戳記是一個較短的滾動值，並不反映 30 天的期限。已過期的容器無法重複使用。請在不帶 `container` 參數的情況下重新傳送請求，以取得新的容器。

### 範例

<CodeGroup>
  ```bash cURL
  # 第一個請求：建立含有隨機數字的檔案，並擷取容器 ID（使用 jq）
  CONTAINER_ID=$(curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "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"
      }]
    }' | jq -r '.container.id')

  # 第二個請求：重複使用該容器來讀取檔案
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "container": "'"$CONTAINER_ID"'",
      "model": "claude-opus-5-5",
      "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"
      }]
    }'
  ```

  ```bash CLI
  # 第一個請求：建立一個包含隨機數字的檔案
  CONTAINER_ID=$(ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{role: user, content: Write a file with a random number and save it to "/tmp/number.txt"}' \
    --tool '{type: code_execution_20250825, name: code_execution}' \
    --transform container.id --raw-output)

  # 第二個請求：重複使用容器來讀取該檔案
  ant messages create \
    --container "$CONTAINER_ID" \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{role: user, content: Read the number from "/tmp/number.txt" and calculate its square}' \
    --tool '{type: code_execution_20250825, name: code_execution}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  # 第一個請求：在新的容器中建立一個含有隨機數字的檔案
  response1 = client.messages.create(
      model="claude-opus-5-5",
      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，讓 Claude 重複使用同一個容器
  response2 = client.messages.create(
      container=response1.container.id,
      model="claude-opus-5-5",
      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.to_json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  // 第一個請求：Claude 在全新的 code execution（程式碼執行）容器中建立檔案
  const response1 = await client.messages.create({
    model: "claude-opus-5-5",
    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" }]
  });

  // 程式碼執行工具執行後，回應中會包含該容器
  if (!response1.container) {
    throw new Error("Expected the first response to include a container");
  }

  // 第二個請求：傳回容器 ID，以重複使用同一個容器
  const response2 = await client.messages.create({
    container: response1.container.id,
    model: "claude-opus-5-5",
    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" }]
  });

  console.log(JSON.stringify(response2));
  ```

  ```csharp C#
  AnthropicClient client = new();

  // 第一個請求：Claude 在全新的程式碼執行容器中建立檔案
  var response1 = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Write a file with a random number and save it to '/tmp/number.txt'" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  // 第二個請求：傳回容器 ID，讓 Claude 重複使用同一個容器
  var response2 = await client.Messages.Create(new()
  {
      Container = response1.Container!.ID,
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Read the number from '/tmp/number.txt' and calculate its square" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  Console.WriteLine(response2);
  ```

  ```go Go
  client := anthropic.NewClient()
  ctx := context.Background()

  codeExecution := []anthropic.ToolUnionParam{
  	{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  }

  // 第一個請求：在新的容器中建立一個含有隨機數字的檔案
  response1, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Write a file with a random number and save it to '/tmp/number.txt'")),
  	},
  	Tools: codeExecution,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // 重複使用第一個請求的容器，讓檔案仍然存在。
  response2, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Container: anthropic.MessageCreateParamsContainerUnion{
  		OfString: anthropic.String(response1.Container.ID),
  	},
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Read the number from '/tmp/number.txt' and calculate its square")),
  	},
  	Tools: codeExecution,
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response2.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // 第一個請求：在新的容器中建立一個包含隨機數字的檔案
  MessageCreateParams params1 = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Write a file with a random number and save it to '/tmp/number.txt'")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response1 = client.messages().create(params1);

  // 第二個請求：傳回容器 ID，以重複使用同一個容器
  MessageCreateParams params2 = MessageCreateParams.builder()
      .container(response1.container().orElseThrow().id())
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Read the number from '/tmp/number.txt' and calculate its square")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response2 = client.messages().create(params2);
  IO.println(ObjectMappers.jsonMapper().valueToTree(response2));
  ```

  ```php PHP
  $client = new Client();

  // 第一個請求：Claude 在全新的程式碼執行容器中寫入檔案
  $response1 = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => "Write a file with a random number and save it to '/tmp/number.txt'",
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  // 第二個請求：重複使用該容器，讓 '/tmp/number.txt' 仍然存在
  $response2 = $client->messages->create(
      container: $response1->container->id,
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => "Read the number from '/tmp/number.txt' and calculate its square",
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($response2), PHP_EOL;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  # 第一個請求：Claude 在全新的程式碼執行容器中建立檔案
  response1 = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Write a file with a random number and save it to '/tmp/number.txt'"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  # 第二個請求：傳回容器 ID，讓 Claude 重複使用同一個容器
  response2 = client.messages.create(
    container: response1.container.id,
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Read the number from '/tmp/number.txt' and calculate its square"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  puts response2.to_json
  ```
</CodeGroup>

## 將程式碼執行與其他執行工具搭配使用

當您將程式碼執行與同樣會執行程式碼的用戶端提供工具（例如 [Bash 工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/bash-tool)或自訂 REPL）一起提供時，Claude 就是在「multicomputer environment」（多電腦環境）中運作。程式碼執行工具在 Anthropic 的沙箱容器中執行，而您的用戶端提供工具則在您控制的另一個獨立環境中執行。Claude 有時可能會混淆這些環境，嘗試使用錯誤的工具，或假設它們之間共享狀態。

為避免這種情況，請在您的「system prompt」（系統提示）中加入說明以釐清兩者的區別：

```text wrap
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
```

當您將程式碼執行與[網頁搜尋](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool)或[網頁擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool)結合使用時，這一點尤其重要，因為這些工具會自動啟用程式碼執行。如果您的應用程式已經提供用戶端 shell 工具，自動啟用的程式碼執行會建立第二個執行環境，Claude 需要能夠區分兩者。

當 Claude 在程式碼執行的同時呼叫您的某個用戶端工具時，API 會傳回不含結果的程式碼執行呼叫。結果會在您傳回用戶端工具的 `tool_result` 區塊之後，於稍後的回應中送達。

## 串流

啟用[「streaming」（串流）](https://platform.claude.com/docs/zh-TW/build-with-claude/streaming)（`"stream": true`）後，您會在程式碼執行事件發生時即時收到這些事件。子工具的輸入會以 `input_json_delta` 事件串流傳送，而每個結果區塊會在單一 `content_block_start` 事件中完整送達：

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

// Tool input streamed as partial JSON
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"python analyze.py\"}"}}

// Pause while the command runs

// Execution result delivered as a complete block
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "bash_code_execution_result", "stdout": "   A  B  C\n0  1  2  3\n1  4  5  6", "stderr": "", "return_code": 0, "content": []}}}
```

## 批次請求

您可以在 [Messages Batches API](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing) 中包含程式碼執行工具。透過 Messages Batches API 進行的程式碼執行工具呼叫，其定價與一般 Messages API 請求中的呼叫相同。

## 使用量與定價

**與網頁搜尋或網頁擷取搭配使用時，程式碼執行是免費的。** 當您的 API 請求中包含 `web_search_20260209`（或更新版本）或 `web_fetch_20260209`（或更新版本）時，除了標準的輸入與輸出 token 費用之外，程式碼執行工具呼叫不會產生額外費用。

若未搭配這些工具使用，程式碼執行將依執行時間計費，並與 token 用量分開追蹤：

* 執行時間最少以 5 分鐘計算
* 每個組織每月可獲得 **1,550 小時的免費**用量
* 超過 1,550 小時的額外用量，將以**每個容器每小時 $0.05 美元**計費
* 若請求中包含檔案，即使未呼叫該工具，仍會依執行時間計費，因為檔案會預先載入至容器中

程式碼執行用量會在回應中追蹤：

```json
{
  "usage": {
    "input_tokens": 105,
    "output_tokens": 239,
    "server_tool_use": {
      "code_execution_requests": 1
    }
  }
}
```

## 升級至最新工具版本

最新的工具版本是 `code_execution_20260521`。若要在三個目前版本之間切換，請更新請求中的 `type` 字串：這三個版本都會傳回[回應格式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#response-format)中記載的回應區塊。請參閱[工具版本](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#tool-versions)了解每個版本新增的功能，並參閱[相容性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#compatibility)了解支援這些版本的模型。

本節其餘部分說明如何從舊版僅限 Python 的 `code_execution_20250522` 遷移至目前的工具版本。

### 變更內容

| 元件      | 舊版                          | 目前版本                                                               |
| ------- | --------------------------- | ------------------------------------------------------------------ |
| Beta 標頭 | `code-execution-2025-05-22` | 不需要                                                                |
| 工具類型    | `code_execution_20250522`   | `code_execution_20250825` 或更新版本                                    |
| 功能      | 僅限 Python                   | Bash 命令、檔案操作                                                       |
| 回應類型    | `code_execution_result`     | `bash_code_execution_result`、`text_editor_code_execution_*_result` |

### 向後相容性

* 所有現有的 Python 程式碼執行都會繼續完全照舊運作
* 現有的僅限 Python 工作流程不需要任何變更

### 升級步驟

若要升級，請更新 API 請求中的工具類型：

```diff
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"
```

**檢查回應處理方式**（如果您以程式方式剖析回應）：

* API 不再為 Python 執行回應傳送先前的區塊
* 取而代之的是，API 會為 Bash 和檔案操作傳送新的回應類型（請參閱[回應格式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#response-format)）

## 資料保留

程式碼執行在伺服器端的沙箱容器中執行。容器資料（包括執行產物、上傳的檔案和輸出）最多保留 30 天。此保留規定適用於在容器環境中處理的所有資料。程式碼執行在 [Files API](https://platform.claude.com/docs/zh-TW/build-with-claude/files) 中建立的檔案（可透過 `client.files.download()` (csharp, go: `client.Files.Download()`; java: `client.files().download()`; php: `$client->files->download()`) 擷取）會持續保留，直到被明確刪除為止。

如需了解所有功能的「Zero Data Retention」（零資料保留），即 ZDR 資格，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。

## 後續步驟

<CardGroup cols={2}>
  <Card title="顧問工具" icon="compass" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/advisor-tool">
    將速度較快的執行者模型與智慧程度較高的顧問模型配對，由顧問模型在生成過程中提供策略性 指引。
  </Card>

  <Card title="程式化工具呼叫" icon="code" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling">
    從在程式碼執行容器內執行的程式碼中呼叫您自己的工具。
  </Card>

  <Card title="Files API" icon="file" href="https://platform.claude.com/docs/zh-TW/build-with-claude/files">
    上傳檔案以供分析，並下載程式碼執行所建立的檔案。
  </Card>

  <Card title="透過 API 使用 Agent Skills" icon="book" href="https://platform.claude.com/docs/zh-TW/build-with-claude/skills-guide">
    了解如何使用 Agent Skills 透過 API 擴展 Claude 的功能。
  </Card>
</CardGroup>
