---
title: 處理串流拒絕
url: https://platform.claude.com/docs/zh-TW/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
description: 偵測並處理串流回應中的拒絕停止原因，並在備援模型上重試被拒絕的請求。
featureMetadata:
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Claude Platform on AWS: stable
    Amazon Bedrock: stable
    Amazon Bedrock (InvokeModel): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

**API 支援**：用法因產品而異。

* **Messages API**：串流以 `stop_reason` `"refusal"` 結束，且 `stop_details`（`category` 與 `explanation`）會在 `message_delta` 事件中送達。
* **Managed Agents**：遭拒絕的回合會結束，工作階段隨即進入閒置狀態。若 `stop_details.type` 或 `stop_reason.type` 為 `"refusal"`，請將該回合視為遭拒絕。

從 Claude 4 模型開始，當串流分類器介入處理潛在的政策違規時，Claude API 的「streaming」（串流）回應會回傳 **`stop_reason`: `"refusal"`**。此安全功能有助於在即時串流期間維持內容合規。

<Tip>
  本頁說明拒絕在串流回應中的呈現方式。如需了解每個 `stop_reason` 值及其處理方式，請參閱[停止原因與備援](https://platform.claude.com/docs/zh-TW/build-with-claude/handling-stop-reasons)。若要在另一個 Claude 模型上重試被拒絕的請求，請參閱[拒絕與備援](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback)。
</Tip>

## API 回應格式

當串流分類器偵測到違反 Anthropic 政策的內容時，API 會回傳以下回應：

```json
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello.."
    }
  ],
  "stop_reason": "refusal",
  "stop_details": {
    "type": "refusal",
    "category": "cyber",
    "explanation": "This request was declined because it could enable cyber harm."
  }
}
```

在事件串流中，`stop_details` 會與 `stop_reason` 一同出現在 `message_delta` 事件中。

<Note>
  來自串流分類器的 `refusal` 回應包含一個 `stop_details` 物件，其中含有 `category` 以及一段人類可讀的 `explanation`，您可以將其呈現給使用者。如需完整的回應結構及可用類別，請參閱[拒絕的樣貌](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback#refusal-response)。

  發生拒絕時，`stop_details` 物件一定存在，但其 `category` 與 `explanation` 欄位可能為 `null`，例如當該拒絕未對應到任何具名類別時。請依據 `stop_reason` 或 `stop_details.type` 進行分支判斷，而非假設 `category` 與 `explanation` 已填入值，並在它們為 `null` 時提供您自己的使用者端訊息。
</Note>

## 拒絕後重設上下文

當您收到 **`stop_reason`: `refusal`** 時，必須在繼續之前重設對話上下文。您可以移除或改寫觸發拒絕的那一輪對話，或完全清除對話歷史。若未重設便嘗試繼續，將會導致持續的拒絕。

<Note>
  即使回應被拒絕，回應中仍會提供用量指標。被拒絕的請求是否計費，取決於拒絕發生的時間點及其類別；請參閱[拒絕的計費方式](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback#how-refusals-are-billed)。
</Note>

<Tip>
  重設上下文並非唯一的復原方式。您也可以在不同的 Claude 模型上重試被拒絕的請求，[拒絕與備援](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback)頁面說明了如何透過伺服器端備援、SDK 中介軟體或手動重試來進行設定。
</Tip>

## 實作指南

以下說明如何在您的應用程式中偵測並處理串流拒絕：

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    在串流中偵測拒絕並重設對話需要的邏輯超出單一 shell 指令所能處理的範圍。請使用 [Claude SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview) 來執行。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    在串流中偵測拒絕並重設對話需要的邏輯超出單一 shell 指令所能處理的範圍。請使用 [Claude SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview) 來執行。
  </CodeGroupItem>

  ```python Python
  client = anthropic.Anthropic()
  messages = []


  def reset_conversation():
      """Reset conversation context after refusal"""
      global messages
      messages = []
      print("Conversation reset due to refusal")


  try:
      with client.messages.stream(
          max_tokens=1024,
          messages=messages + [{"role": "user", "content": "Hello"}],
          model="claude-opus-5-5",
      ) as stream:
          for event in stream:
              # 檢查訊息增量中是否有拒絕回應
              if event.type == "message_delta":
                  if event.delta.stop_reason == "refusal":
                      reset_conversation()
                      break
  except Exception as e:
      print(f"Error: {e}")
  ```

  ```typescript TypeScript
  const client = new Anthropic();
  let messages: Anthropic.MessageParam[] = [];

  function resetConversation() {
    // 拒絕後重設對話上下文
    messages = [];
    console.log("Conversation reset due to refusal");
  }

  try {
    const stream = await client.messages.stream({
      messages: [...messages, { role: "user", content: "Hello" }],
      model: "claude-opus-5-5",
      max_tokens: 1024
    });

    for await (const event of stream) {
      // 檢查訊息增量中是否有拒絕
      if (event.type === "message_delta" && event.delta.stop_reason === "refusal") {
        resetConversation();
        break;
      }
    }
  } catch (error) {
    console.error("Error:", error);
  }
  ```

  ```csharp C#
  List<Message> messages = new();
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "Hello" }]
  };

  try
  {
      await foreach (var streamEvent in client.Messages.CreateStreaming(parameters))
      {
          if (
              streamEvent.TryPickDelta(out var deltaEvent)
              && deltaEvent.Delta.StopReason == StopReason.Refusal
          )
          {
              ResetConversation();
              break;
          }
      }
  }
  catch (Exception e)
  {
      Console.WriteLine($"Error: {e.Message}");
  }

  void ResetConversation()
  {
      messages.Clear();
      Console.WriteLine("Conversation reset due to refusal");
  }
  ```

  ```go Go
  var messages []anthropic.MessageParam

  func resetConversation() {
  	messages = []anthropic.MessageParam{}
  	fmt.Println("Conversation reset due to refusal")
  }
  // ...
  	client := anthropic.NewClient()

  	stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 1024,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock("Hello")),
  		},
  	})

  streamLoop:
  	for stream.Next() {
  		event := stream.Current()
  		switch eventVariant := event.AsAny().(type) {
  		case anthropic.MessageDeltaEvent:
  			if eventVariant.Delta.StopReason == anthropic.StopReasonRefusal {
  				resetConversation()
  				break streamLoop
  			}
  		}
  	}

  	if err := stream.Err(); err != nil {
  		log.Fatal(err)
  	}
  ```

  ```java Java
  import com.anthropic.core.http.StreamResponse;
  import com.anthropic.models.messages.RawMessageStreamEvent;
  import com.anthropic.models.messages.StopReason;
  // ...

  List<MessageParam> messages = new ArrayList<>();

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addUserMessage("Hello")
          .build();

      try (StreamResponse<RawMessageStreamEvent> stream = client.messages().createStreaming(params)) {
          stream.stream().forEach(event -> {
              event.messageDelta().ifPresent(deltaEvent -> {
                  deltaEvent.delta().stopReason().ifPresent(stopReason -> {
                      if (stopReason.equals(StopReason.REFUSAL)) {
                          resetConversation();
                      }
                  });
              });
          });
      } catch (Exception e) {
          System.err.println("Error: " + e.getMessage());
      }
  }

  void resetConversation() {
      messages.clear();
      IO.println("Conversation reset due to refusal");
  }
  ```

  ```php PHP
  $client = new Client();
  $messages = [];

  function resetConversation(&$messages)
  {
      $messages = [];
      echo "Conversation reset due to refusal\n";
  }

  try {
      $stream = $client->messages->createStream(
          maxTokens: 1024,
          messages: [
              ['role' => 'user', 'content' => 'Hello']
          ],
          model: 'claude-opus-5-5',
      );

      foreach ($stream as $event) {
          if ($event->type === 'message_delta' && $event->delta->stopReason === 'refusal') {
              resetConversation($messages);
              break;
          }
      }
  } catch (\Exception $e) {
      echo 'Error: ' . $e->getMessage() . "\n";
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new
  messages = []

  def reset_conversation(messages)
    messages.clear
    puts "Conversation reset due to refusal"
  end

  begin
    stream = client.messages.stream(
      model: :"claude-opus-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello" }]
    )

    stream.each do |event|
      if event.type == :message_delta && event.delta.stop_reason == :refusal
        reset_conversation(messages)
        break
      end
    end
  rescue => e
    puts "Error: #{e.message}"
  end
  ```
</CodeGroup>

## 目前的拒絕類型

API 目前以三種不同方式處理拒絕：

| 拒絕類型         | 回應格式                         | 發生時機        |
| ------------ | ---------------------------- | ----------- |
| 串流分類器拒絕      | **`stop_reason`: `refusal`** | 串流期間內容違反政策時 |
| API 輸入與著作權驗證 | 400 錯誤代碼                     | 輸入未通過驗證檢查時  |
| 模型產生的拒絕      | 標準文字回應                       | 模型本身拒絕時     |

## 最佳實務

* **監控拒絕：** 在您的錯誤處理中加入 **`stop_reason`: `refusal`** 檢查。
* **自動重設：** 在偵測到拒絕時實作自動上下文重設。
* **改用其他模型：** 設定[伺服器端備援或 SDK 中介軟體](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback)，讓遭拒絕的請求改以另一個 Claude 模型重試，而不是將拒絕呈現給使用者。Claude Haiku 5.5 沒有伺服器端備援，因此請在您的用戶端設定其重試。
* **在手動重試時兌換備援額度：** 如果您自行建構重試，請傳入該拒絕的[備援額度](https://platform.claude.com/docs/zh-TW/build-with-claude/fallback-credit)權杖，讓重試不必重複支付提示快取成本。Claude Haiku 5.5 的拒絕不附帶備援額度。
* **提供自訂訊息：** 在發生拒絕時建立對使用者友善的訊息，以提供更好的使用者體驗。
* **追蹤拒絕模式：** 監控拒絕頻率，以找出您的提示可能存在的問題。

## 遷移注意事項

若您在此功能首次推出時便已建構拒絕處理機制，或正要將其加入既有的整合中，請檢查以下事項：

* **拒絕是回應，而非錯誤。** 拒絕會以成功的 HTTP 200 回應形式送達，並帶有 `stop_reason`: `"refusal"`，因此僅依據錯誤率建立的監控無法發現它。請將拒絕作為獨立的訊號進行追蹤。
* **拒絕包含結構化的詳細資訊。** 在每個模型上，拒絕也會包含一個 `stop_details` 物件，用以識別造成拒絕的政策類別。請參閱[拒絕的樣貌](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback#refusal-response)以了解完整的回應結構。
* **在不同模型上重試。** 將被拒絕的請求重新傳送到同一個模型，通常會再次遭到拒絕。與其只重設上下文，不如透過[伺服器端備援、SDK 中介軟體或手動重試](https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback)在備援模型上重試，並在您自行建置重試時兌換[備援額度](https://platform.claude.com/docs/zh-TW/build-with-claude/fallback-credit)。Claude Haiku 5.5 沒有伺服器端備援，其拒絕也不附帶備援額度，因此請在您的用戶端設定其重試。
* **檢查批次結果中的拒絕。** [Message Batch](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing) 中被拒絕的請求會以成功結果的形式回傳，並帶有 `stop_reason`: `"refusal"`，而非以錯誤結果回傳。
* **以 `stop_reason` 集中處理。** API 持續將拒絕處理整合至 `stop_reason`: `"refusal"`，因此請依據停止原因進行分支判斷，而非依據特定模型的行為。

## 後續步驟

<CardGroup cols={2}>
  <Card title="拒絕與備援" icon="arrows-clockwise" href="https://platform.claude.com/docs/zh-TW/build-with-claude/refusals-and-fallback">
    在另一個 Claude 模型上重試被拒絕的請求，可於伺服器端或您的用戶端進行。
  </Card>

  <Card title="停止原因與備援" icon="code" href="https://platform.claude.com/docs/zh-TW/build-with-claude/handling-stop-reasons">
    每個 `stop_reason` 值及其處理方式。
  </Card>

  <Card title="串流訊息" icon="lightning" href="https://platform.claude.com/docs/zh-TW/build-with-claude/streaming">
    串流回應，並在 `message_delta` 事件送達時從中讀取 `stop_reason`。
  </Card>

  <Card title="多語言支援" icon="text-aa" href="https://platform.claude.com/docs/zh-TW/build-with-claude/multilingual-support">
    運用 Claude 的跨語言能力服務各種語言的使用者。
  </Card>
</CardGroup>

## 可用性

串流拒絕可供使用或處於 Beta 階段，視API而定。

### API 支援

#### [Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)

* 可用性：永遠開啟
* 用法：串流以 `stop_reason` `"refusal"` 結束，且 `stop_details`（`category` 與 `explanation`）會在 `message_delta` 事件中送達。

| 狀態 | 雲端平台                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 可用 | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws), [Amazon Bedrock](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-amazon-bedrock), [Amazon Bedrock (InvokeModel)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-on-amazon-bedrock-legacy), [Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/google-managed), [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) |

#### [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview)

* 可用性：永遠開啟
* 用法：遭拒絕的回合會結束，工作階段隨即進入閒置狀態。若 `session.status_idle` 事件上的 `stop_details.type` 或 `stop_reason.type` 為 `"refusal"`，請將該回合視為遭拒絕。在遭拒絕的回合中，`stop_reason.type` 可能為 `"end_turn"`。在其他任何回合中，`stop_details` 皆為 `null`，且在遭拒絕的回合中也可能為 `null`。

| 狀態   | 雲端平台                                                                                                                  |
| ---- | --------------------------------------------------------------------------------------------------------------------- |
| Beta | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws) |
