---
title: 任務預算
url: https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets
description: 為 Claude 提供涵蓋完整代理迴圈的建議性 token 預算，協助模型在長時間的代理任務中自我調節。
featureMetadata:
  status: beta
  betaHeader: task-budgets-2026-03-13
  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-sonnet-5-5
    - claude-haiku-5-5
---

「Task budgets」（任務預算）讓您告訴 Claude 在一個完整的「agentic loop」（代理迴圈）中有多少 token 可用，包括思考、工具呼叫、工具結果與輸出。模型會看到一個持續更新的倒數計數，並據此安排工作的優先順序，在預算逐漸耗盡時優雅地收尾。

## 何時使用任務預算

任務預算最適合用於 Claude 在完成輸出並等待下一次人類回應之前，會進行多次工具呼叫與決策的代理工作流程。在以下情況使用：

* 您希望 Claude 在長時程任務中自我調節 token 花費。
* 您需要強制執行可預測的每項任務成本或「latency」（延遲）上限。
* 您希望模型在接近預算時優雅地收尾（總結發現、回報進度），而非在動作進行到一半時中斷。

任務預算與 [effort 參數](https://platform.claude.com/docs/zh-TW/build-with-claude/effort)相輔相成：effort 控制 Claude 對每個步驟推理的深入程度，而任務預算則限制 Claude 在整個代理迴圈中可執行的總工作量。

## 設定任務預算

將 `task_budget` 加入 `output_config`，並附上 beta 標頭：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -N \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: task-budgets-2026-03-13" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 128000,
      "stream": true,
      "messages": [{
        "role": "user",
        "content": "Review the codebase and propose a refactor plan."
      }],
      "output_config": {
        "effort": "high",
        "task_budget": {"type": "tokens", "total": 64000}
      }
    }'
  ```

  ```bash CLI
  ant beta:messages create --beta task-budgets-2026-03-13 \
    --stream --format jsonl <<'YAML' | jq 'select(.type == "message_delta").usage'
  model: claude-opus-5-5
  max_tokens: 128000
  messages:
    - role: user
      content: Review the codebase and propose a refactor plan.
  output_config:
    effort: high
    task_budget:
      type: tokens
      total: 64000
  YAML
  ```

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

  with client.beta.messages.stream(
      model="claude-opus-5-5",
      max_tokens=128000,
      output_config={
          "effort": "high",
          "task_budget": {"type": "tokens", "total": 64000},
      },
      messages=[
          {"role": "user", "content": "Review the codebase and propose a refactor plan."}
      ],
      betas=["task-budgets-2026-03-13"],
  ) as stream:
      response = stream.get_final_message()

  print(response.usage)
  ```

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

  const stream = client.beta.messages.stream({
    model: "claude-opus-5-5",
    max_tokens: 128000,
    output_config: {
      effort: "high",
      task_budget: { type: "tokens", total: 64000 }
    },
    messages: [{ role: "user", content: "Review the codebase and propose a refactor plan." }],
    betas: ["task-budgets-2026-03-13"]
  });

  const response = await stream.finalMessage();
  console.log(response.usage);
  ```

  ```csharp C#

  var client = new AnthropicClient();

  var responseUpdates = client.Beta.Messages.CreateStreaming(new MessageCreateParams
  {
      Model = Messages::Model.ClaudeOpus5_5,
      MaxTokens = 128000,
      Messages = [new() { Role = Role.User, Content = "Review the codebase and propose a refactor plan." }],
      OutputConfig = new BetaOutputConfig
      {
          Effort = Effort.High,
          TaskBudget = new BetaTokenTaskBudget { Total = 64000 },
      },
      Betas = ["task-budgets-2026-03-13"],
  });

  var response = await responseUpdates.Aggregate();
  Console.WriteLine(response.Usage);
  ```

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

  stream := client.Beta.Messages.NewStreaming(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 128000,
  	Betas:     []anthropic.AnthropicBeta{"task-budgets-2026-03-13"},
  	Messages: []anthropic.BetaMessageParam{{
  		Role: anthropic.BetaMessageParamRoleUser,
  		Content: []anthropic.BetaContentBlockParamUnion{{
  			OfText: &anthropic.BetaTextBlockParam{Text: "Review the codebase and propose a refactor plan."},
  		}},
  	}},
  	OutputConfig: anthropic.BetaOutputConfigParam{
  		Effort: anthropic.BetaOutputConfigEffortHigh,
  		TaskBudget: anthropic.BetaTokenTaskBudgetParam{
  			Total: 64000,
  		},
  	},
  })

  message := anthropic.BetaMessage{}
  for stream.Next() {
  	event := stream.Current()
  	if err := message.Accumulate(event); err != nil {
  		panic(err)
  	}
  }
  if stream.Err() != nil {
  	panic(stream.Err())
  }

  fmt.Printf("Usage: input_tokens=%d, output_tokens=%d\n", message.Usage.InputTokens, message.Usage.OutputTokens)
  ```

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

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(128000L)
      .addUserMessage("Review the codebase and propose a refactor plan.")
      .outputConfig(BetaOutputConfig.builder()
          .effort(BetaOutputConfig.Effort.HIGH)
          .taskBudget(BetaTokenTaskBudget.builder().total(64000L).build())
          .build())
      .addBeta("task-budgets-2026-03-13")
      .build();

  BetaMessageAccumulator accumulator = BetaMessageAccumulator.create();
  try (StreamResponse<BetaRawMessageStreamEvent> stream =
          client.beta().messages().createStreaming(params)) {
      stream.stream().forEach(accumulator::accumulate);
  }

  BetaMessage response = accumulator.message();
  IO.println(response.usage());
  ```

  ```php PHP
  use Anthropic\Beta\Messages\BetaRawMessageDeltaEvent;

  $client = new Client();

  $stream = $client->beta->messages->createStream(
      model: 'claude-opus-5-5',
      maxTokens: 128000,
      messages: [
          ['role' => 'user', 'content' => 'Review the codebase and propose a refactor plan.'],
      ],
      outputConfig: [
          'effort' => 'high',
          'taskBudget' => ['type' => 'tokens', 'total' => 64000],
      ],
      betas: ['task-budgets-2026-03-13'],
  );

  // 最後的 message_delta 事件會帶有此請求的累計 token 用量。
  $usage = null;
  foreach ($stream as $event) {
      if ($event instanceof BetaRawMessageDeltaEvent) {
          $usage = $event->usage;
      }
  }

  echo $usage;
  ```

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

  stream = client.beta.messages.stream(
    model: "claude-opus-5-5",
    max_tokens: 128_000,
    messages: [
      { role: "user", content: "Review the codebase and propose a refactor plan." }
    ],
    output_config: {
      effort: :high,
      task_budget: { type: :tokens, total: 64_000 }
    },
    betas: ["task-budgets-2026-03-13"]
  )

  response = stream.accumulated_message

  puts response.usage
  ```
</CodeGroup>

`task_budget` 物件有三個欄位：

* `type`：一律為 `"tokens"`。
* `total`：Claude 在整個代理迴圈中可花費的 token 數量，包括思考、工具呼叫、工具結果與輸出。
* `remaining`（選用）：從先前請求延續下來的剩餘預算。省略時預設為 `total`。

## 預算倒數的運作方式

Claude 會看到在整個對話中由伺服器端注入的預算倒數標記。此標記顯示目前代理迴圈中剩餘的 token 數量，並會隨著模型產生思考、工具呼叫和輸出，以及處理工具結果而更新。Claude 利用此訊號來調整步調，並在預算逐漸消耗時從容地完成任務。

<Note>
  **倒數計數僅對模型可見。** API 回應不包含剩餘預算欄位：回應的 `usage` 物件中沒有 `task_budget` 資訊，SDK 也沒有提供存取它的方法。若要在用戶端追蹤花費，請依照[測量您目前的用量](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#measure-your-current-usage)中所示，加總迴圈中各請求的 token 使用量，或在[跨壓縮延續預算](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#carrying-a-budget-across-compaction-with-remaining)時使用 `remaining` 傳遞您自己的數值。
</Note>

<Warning>
  **倒數計數反映的是 Claude 在目前代理迴圈中已處理的 token，而不是您在請求之間重新傳送的 token。** 如果您的用戶端在每次後續請求中都傳送完整的對話歷史，您在用戶端計算的 token 數量可能會與 Claude 追蹤的預算不同。如果您在重新傳送完整歷史的同時也遞減 `remaining`，模型會看到被低報的預算，倒數計數會下降得比應有的更快，導致 Claude 比預算實際允許的更早收尾。請設定充裕的預算，讓模型依據倒數計數自我調節，而不是嘗試在用戶端複製這個倒數。
</Warning>

### 什麼算是一個回合

預算涵蓋一個代理回合，也稱為代理迴圈：即 Claude 針對一則不含工具結果的使用者訊息所做的一切。一個回合可以跨越多個請求。

不含工具結果的使用者訊息會開始一個新回合，並擁有全新的預算。目前，只要先前回合的歷史仍保留在上下文中，倒數計時仍會將其計入。常見的情況是在 Claude 結束其回合之後（例如因為預算用盡）所發出的後續訊息：

```json
{ "role": "user", "content": "Continue." }
```

包含 `tool_result` 區塊的使用者訊息會延續目前的回合，因為您的用戶端正在解析屬於該回合的工具呼叫：

```json
{
  "role": "user",
  "content": [
    { "type": "tool_result", "tool_use_id": "toolu_01", "content": "<npm audit output>" }
  ]
}
```

即使該訊息在工具結果之外還加入了新內容，也是如此：

```json
{
  "role": "user",
  "content": [
    { "type": "tool_result", "tool_use_id": "toolu_01", "content": "<npm audit output>" },
    { "type": "text", "text": "Also check the Dockerfile." }
  ]
}
```

回合期間的伺服器端[「compaction」（壓縮）](https://platform.claude.com/docs/zh-TW/build-with-claude/compaction-threshold)不會重設預算：回合在壓縮前消耗的 token 仍會計入預算。回合開始之前的 token 不會計入，即使回合開始時的壓縮對其進行了摘要也是如此。目前，此排除僅適用於跨伺服器端壓縮延續的預算；先前回合的歷史只要仍保留在上下文中，仍會被計入。

### 實際範例：跨請求的預算計算

任務預算計算的是 Claude **看到**的內容（思考、工具呼叫與結果，以及文字），而不是您請求酬載中的內容。在代理迴圈中，您的用戶端會在每次請求時重新傳送完整對話，因此酬載會持續增長，但預算只會依新增的部分遞減：也就是 Claude 產生的 token，以及它先前未看過的內容。以下範例是由三個請求組成的一個[代理回合](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#what-counts-as-a-turn)：第一個請求攜帶使用者訊息，接下來兩個請求各自重新傳送歷史並附加一個工具結果。

考慮一個設定 `task_budget: {type: "tokens", total: 100000}` 且只有單一 `bash` 工具的迴圈。

**請求 1。** 您傳送初始請求：

```json
{
  "messages": [
    { "role": "user", "content": "Audit this repo for security issues and report findings." }
  ]
}
```

Claude 進行思考，然後發出工具呼叫，並以 `stop_reason: "tool_use"` 停止：

```json
{
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "I'll start by listing dependencies to look for known-vulnerable packages..."
    },
    {
      "type": "tool_use",
      "id": "toolu_01",
      "name": "bash",
      "input": { "command": "cat package.json && npm audit --json" }
    }
  ]
}
```

假設這則助理訊息（思考加上工具呼叫）總共產生了 5,000 個 token。Claude 在生成期間看到的倒數計時最後約為 `remaining` ≈ 95,000。

**請求 2。** 您的用戶端執行工具，然後重新傳送完整歷史並附加工具結果：

```json
{
  "messages": [
    { "role": "user", "content": "Audit this repo for security issues and report findings." },
    {
      "role": "assistant",
      "content": [
        { "type": "thinking", "thinking": "I'll start by listing dependencies..." },
        {
          "type": "tool_use",
          "id": "toolu_01",
          "name": "bash",
          "input": { "command": "cat package.json && npm audit --json" }
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01",
          "content": "<2,800 tokens of npm audit output>"
        }
      ]
    }
  ]
}
```

從請求 1 重新傳送的訊息不會再次計入，但 2,800 個 token 的工具結果是新內容，會計入預算。Claude 又花費 4,000 個 token 進行思考並發出第二個工具呼叫（`grep -rn "eval(" src/`）。倒數計時最後約為 `remaining` ≈ 88,200。

**請求 3。** 再次重新傳送完整歷史，並附加第二個工具結果（1,200 個 token 的 grep 輸出）。Claude 撰寫了一份 6,000 個 token 的最終發現報告，並以 `stop_reason: "end_turn"` 停止。`remaining` ≈ 81,000。

將三個請求並列比較，可以清楚看出酬載大小與預算花費之間的差異：

| 請求     | 請求酬載（您傳送的輸入 token 約數）    | 此請求計入預算的 token                           | 之後的預算 `remaining` |
| ------ | ------------------------ | ---------------------------------------- | ----------------- |
| 1      | \~20                     | 5,000（思考 + `tool_use`）                   | \~95,000          |
| 2      | \~7,800（請求 1 的訊息 + 工具結果） | 6,800（2,800 工具結果 + 4,000 思考與 `tool_use`） | \~88,200          |
| 3      | \~13,000（完整歷史 + 第二個工具結果） | 7,200（1,200 工具結果 + 6,000 `text`）         | \~81,000          |
| **總計** | **跨請求共傳送約 20,820**       | **計入預算 19,000**                          | 不適用               |

您的用戶端傳送了原始使用者訊息三次、第一則助理訊息兩次，但每則訊息都只計算一次。預算花費了 100,000 個 token 中的 19,000 個，儘管您的用戶端傳輸的累計酬載更大，而請求 2 和 3 中經提示快取的輸入又更大。

### 使用 `remaining` 跨壓縮延續預算

如果您自己的程式碼在請求之間壓縮或改寫訊息歷史（例如摘要先前的訊息），伺服器不會記得壓縮之前已花費了多少預算。請在下一個請求中傳遞 `remaining`，讓倒數計時從您中斷的地方繼續，而不是重設為 `total`：

<CodeGroup exclude="shell">
  ```python Python
  # 壓縮前已消耗的 token 數，於用戶端追蹤
  tokens_spent_so_far = 45000

  output_config = {
      "effort": "high",
      "task_budget": {
          "type": "tokens",
          "total": 128000,
          "remaining": 128000 - tokens_spent_so_far,
      },
  }
  ```

  ```typescript TypeScript
  // 壓縮前已消耗的 token 數，於用戶端追蹤
  const tokensSpentSoFar = 45000;

  const outputConfig = {
    effort: "high",
    task_budget: {
      type: "tokens",
      total: 128000,
      remaining: 128000 - tokensSpentSoFar
    }
  };
  ```

  ```csharp C#
  // 壓縮前已消耗的 token 數，於用戶端追蹤
  var tokensSpentSoFar = 45000;

  var outputConfig = new BetaOutputConfig
  {
      Effort = Effort.High,
      TaskBudget = new BetaTokenTaskBudget
      {
          Total = 128000,
          Remaining = 128000 - tokensSpentSoFar,
      },
  };
  ```

  ```go Go
  // 壓縮前已消耗的 token 數，於用戶端追蹤
  tokensSpentSoFar := int64(45000)

  outputConfig := anthropic.BetaOutputConfigParam{
  	Effort: anthropic.BetaOutputConfigEffortHigh,
  	TaskBudget: anthropic.BetaTokenTaskBudgetParam{
  		Total:     128000,
  		Remaining: anthropic.Int(128000 - tokensSpentSoFar),
  	},
  }
  ```

  ```java Java
  // 壓縮前已消耗的 token 數，於用戶端追蹤
  long tokensSpentSoFar = 45000;

  BetaOutputConfig outputConfig = BetaOutputConfig.builder()
      .effort(BetaOutputConfig.Effort.HIGH)
      .taskBudget(BetaTokenTaskBudget.builder()
          .total(128000L)
          .remaining(128000L - tokensSpentSoFar)
          .build())
      .build();
  ```

  ```php PHP
  // 壓縮前已消耗的 token 數，於用戶端追蹤
  $tokensSpentSoFar = 45000;

  $outputConfig = [
      'effort' => 'high',
      'taskBudget' => [
          'type' => 'tokens',
          'total' => 128000,
          'remaining' => 128000 - $tokensSpentSoFar,
      ],
  ];
  ```

  ```ruby Ruby
  # 壓縮前已消耗的 token 數，於用戶端追蹤
  tokens_spent_so_far = 45_000

  output_config = {
    effort: :high,
    task_budget: {
      type: :tokens,
      total: 128_000,
      remaining: 128_000 - tokens_spent_so_far
    }
  }
  ```
</CodeGroup>

在此範例中，壓縮之前花費的 token 是您到目前為止從歷史中移除的所有訊息的使用量，測量方式如[測量您目前的使用量](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#measure-your-current-usage)所述。請排除仍存在於您所傳送訊息中的任何內容，包括您加入的任何摘要，因為伺服器會自行計算這些 token。只有在您以這種方式取代歷史時才更新此數值；不要在每次請求時遞減它。請在每個請求中都傳遞計算出的 `remaining`，而不只是在進行壓縮的那個請求中傳遞。

對於每次請求都重新傳送完整未壓縮歷史的迴圈，請省略 `remaining`，讓伺服器追蹤倒數計時。

## 在對話中途變更預算

`task_budget` 是請求層級的設定。若要在任務進行到一半時變更預算，例如在使用者擴大請求範圍時延長預算，請在下一次請求的 `output_config` 中設定新的 `task_budget`。請留意對快取的影響：預算值會參與呈現後的提示，因此變更後的值不會與在舊值下建立的快取項目相符（請參閱下方的[功能支援](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#feature-support)）。

## 任務預算是建議性的，而非強制執行

任務預算是**軟性提示，而非硬性上限**。如果 Claude 正在執行某個動作，而中斷該動作比完成它更具破壞性，Claude 偶爾可能會超出預算。對總輸出 token 的強制限制仍然是 `max_tokens`，達到該值時會以 `stop_reason: "max_tokens"` 截斷回應。

若要對成本或延遲設定硬性上限，請將任務預算與合理的 `max_tokens` 值結合使用：

* 使用 `task_budget` 為 Claude 提供一個可據以調整節奏的目標。
* 使用 `max_tokens` 作為防止失控生成的絕對上限。

由於 `task_budget` 涵蓋整個代理迴圈（可能包含多次請求），而 `max_tokens` 限制的是每個單獨請求，這兩個值彼此獨立；其中一個不需要等於或低於另一個。

<Warning>
  **對任務而言過小的預算可能導致類似拒絕的行為。** 當 Claude 看到的預算明顯不足以完成所要求的工作時（例如，為一個需時數小時的代理程式設計任務設定 20,000 個 token 的預算），它可能會完全拒絕嘗試該任務、大幅縮減範圍，或提早停止並給出部分結果，而非開始一項它無法完成的工作。如果您在設定預算後觀察到非預期的拒絕或過早停止，請先提高預算，再去除錯其他參數。請依據您實際的任務長度分布來設定預算大小，而非使用固定的預設值；請參閱[選擇預算](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#choosing-a-budget)。
</Warning>

## 選擇預算

合適的預算取決於您的代理迴圈目前執行多少工作。與其猜測，不如先測量您現有的 token 用量，再從那裡進行調整。

### 測量您目前的用量

在**未**設定 `task_budget` 的情況下執行一組具代表性的任務樣本，並記錄 Claude 每項任務花費的總 token 數。對於代理迴圈，請將迴圈中每個請求的 `usage.output_tokens` 加總，再加上您在請求之間附加的工具結果的 token 數：

<CodeGroup exclude="shell:cURL">
  ```bash CLI
  ant messages create --transform 'usage.output_tokens' <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: Review the codebase and propose a refactor plan.
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {"role": "user", "content": "Review the codebase and propose a refactor plan."}
      ],
  )

  # 加總迴圈中每個請求的 output_tokens（文字 + 思考 + 工具呼叫）。
  print(response.usage.output_tokens)
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [{ role: "user", content: "Review the codebase and propose a refactor plan." }]
  });

  // 加總迴圈中每個請求的 output_tokens（文字 + 思考 + 工具呼叫）。
  console.log(response.usage.output_tokens);
  ```

  ```csharp C#

  var client = new AnthropicClient();

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Review the codebase and propose a refactor plan." }],
  });

  // 加總迴圈中每個請求的 OutputTokens（文字 + 思考 + 工具呼叫）。
  Console.WriteLine(response.Usage.OutputTokens);
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Review the codebase and propose a refactor plan.")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  // 加總迴圈中每個請求的 OutputTokens（文字 + 思考 + 工具呼叫）。
  fmt.Println(response.Usage.OutputTokens)
  ```

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

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Review the codebase and propose a refactor plan.")
      .build();

  Message response = client.messages().create(params);
  // 加總迴圈中每個請求的 outputTokens（文字 + 思考 + 工具呼叫）。
  IO.println(response.usage().outputTokens());
  ```

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

  $response = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Review the codebase and propose a refactor plan.'],
      ],
  );

  // 加總迴圈中每個請求的 outputTokens（文字 + 思考 + 工具呼叫）。
  echo $response->usage->outputTokens . "\n";
  ```

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

  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Review the codebase and propose a refactor plan." }
    ]
  )

  # 加總迴圈中每個請求的 output_tokens（文字 + 思考 + 工具呼叫）。
  puts response.usage.output_tokens
  ```
</CodeGroup>

在一組具代表性的任務上執行此程式並記錄分布情況。先從您每項任務 token 花費的 p99 開始，以了解為模型提供任務預算可能如何改變模型的行為，然後視需要向上或向下測試。

在所有支援任務預算的模型上（請參閱[功能支援](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#feature-support)），可接受的 `task_budget.total` 最小值為 **20,000 個 token**。較小的值會傳回 400 錯誤。

## 與其他參數的互動

* **`max_tokens`：** 與任務預算互不相關。`max_tokens` 是每個請求對生成 token 的硬性上限，而 `task_budget` 是涵蓋整個代理迴圈（可能跨越許多請求）的建議性上限。在 `xhigh` 或 `max` effort 下，請將 `max_tokens` 設定為至少 64k，讓 Claude 在每個請求中都有足夠的空間進行思考和行動。
* **[Effort](https://platform.claude.com/docs/zh-TW/build-with-claude/effort)：** Effort 控制 Claude 在每個步驟中推理的深度。任務預算控制 Claude 在整個代理迴圈中完成的總工作量。兩者相輔相成：effort 調整深度，任務預算調整廣度。
* **[自適應思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)：** 任務預算會將思考 token 計入，因此自適應思考會隨著預算消耗而縮減。
* **[提示快取](https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching)：** 預算倒數標記是在每個請求中由伺服器端注入的，因此在不同請求之間不會相符。如果您的用戶端在每次後續請求中遞減 `task_budget.remaining`，變更後的值會使包含它的任何快取前綴失效。若要保留快取，請在初始請求中設定一次預算，並讓模型依據伺服器端的倒數計時自我調節，而不是在用戶端修改預算。

## 功能支援

| 模型                | 支援                                    |
| ----------------- | ------------------------------------- |
| Claude Fable 5.1  | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Mythos 5.1 | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Opus 5.5   | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Opus 5     | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Fable 5    | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Mythos 5   | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Sonnet 5.5 | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Sonnet 5   | 不支援                                   |
| Claude Haiku 5.5  | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Opus 4.8   | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Opus 4.7   | Beta（設定 `task-budgets-2026-03-13` 標頭） |
| Claude Opus 4.6   | 不支援                                   |
| Claude Sonnet 4.6 | 不支援                                   |
| Claude Haiku 4.5  | 不支援                                   |

[Claude Code](https://code.claude.com/docs/zh-TW/overview) 或 Cowork 介面不支援任務預算。請在[支援的模型](https://platform.claude.com/docs/zh-TW/build-with-claude/task-budgets#feature-support)上直接透過 Messages API 使用任務預算。

## 後續步驟

<CardGroup>
  <Card title="Effort" icon="gauge" href="https://platform.claude.com/docs/zh-TW/build-with-claude/effort">
    控制 Claude 對代理迴圈中每個步驟推理的徹底程度。
  </Card>

  <Card title="自適應思考" icon="brain" href="https://platform.claude.com/docs/zh-TW/build-with-claude/thinking">
    讓 Claude 決定何時使用擴展思考以及使用多少。
  </Card>

  <Card title="壓縮" icon="arrows-clockwise" href="https://platform.claude.com/docs/zh-TW/build-with-claude/compaction">
    透過伺服器端壓縮管理長時間對話中的上下文。
  </Card>

  <Card title="提示快取" icon="database" href="https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching">
    透過快取提示前綴，降低重複提示的成本和延遲。
  </Card>
</CardGroup>
