瞭解及調整安全性設定

Gemini 模型以安全為優先考量,不過,這些模型仍可能生成有害的回覆,尤其是在明確提示的情況下。為進一步提升安全性並減少濫用情形,您可以設定安全篩選器,封鎖可能有害的回覆。

我們提供兩層安全防護措施:

  • 內建核心防護機制:

    • 所有 Gemini 模型都具備內建保護措施,可防範嚴重危害 (例如兒少剝削、網路攻擊和危險武器)。
    • 這些防護措施一律啟用,會自動套用至所有提示和回覆,且無法修改或停用。
  • 可設定的安全篩選器:

    • Gemini API 提供額外的可設定安全篩選器,您可以使用應用程式中的安全設定定義這些篩選器。
    • 您可以透過這些設定,控管四大有害內容類別的封鎖門檻:騷擾、仇恨言論、情色露骨內容和危險內容。

跳至程式碼範例

重要安全概念

使用 Gemini 模型時,請務必瞭解下列重要概念:

  • 安全設定:在應用程式程式碼中定義的設定,指定要監控哪些危害類別,以及封鎖內容的門檻。

  • 安全篩選器:伺服器端分類器,會根據 Google 的安全維度評估提示和模型回覆。篩選器會根據您設定的安全設定封鎖內容。

  • 安全評分:模型在回覆物件中傳回的評估中繼資料。評分代表系統偵測到各類潛在危害的可能性和嚴重程度。

支援的模型

  • gemini-4-argon
  • gemini-3.8-flash (以及舊版 gemini-3.7-flash、gemini-3.6-flash 和 gemini-3.5-flash)
  • gemini-3.5-flash-lite (以及舊版 gemini-3.1-flash-lite)
  • gemini-nano-banana-2.1 (Nano Banana 2.1)
  • gemini-3.1-flash-image (Nano Banana 2)
  • gemini-3.1-flash-lite-image (Nano Banana 2 Lite)
  • gemini-3-pro-image (Nano Banana Pro)

gemini-3.1-pro-preview 模型以及一般用途和圖像生成 Gemini 2.5 模型 (已淘汰) 也支援這項功能。



在應用程式中調整安全設定

按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。

您可以在初始化 GenerativeModel 執行個體時設定安全設定。在該模型執行個體的生命週期內,設定會維持不變。

請參閱本頁後續內容,瞭解可用的有害內容類別,以及可為各類別設定的門檻。

Swift

建立 GenerativeModel 執行個體時,請設定 SafetySetting:


import FirebaseAILogic

let safetySettings = [
  SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh),
  SafetySetting(harmCategory: .hateSpeech, threshold: .blockMediumAndAbove)
]

// Specify the safety settings as part of creating the `GenerativeModel` instance.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: safetySettings
)

// ...

Kotlin

建立 GenerativeModel 執行個體時,請設定 SafetySetting:


// ...

val safetySettings = listOf(
    SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.ONLY_HIGH),
    SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE)
)

// Specify the safety settings as part of creating the `GenerativeModel` instance.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    safetySettings = safetySettings
)

// ...

Java

建立 GenerativeModel 執行個體時,請設定 SafetySetting:


// ...

List safetySettings = List.of(
    new SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.ONLY_HIGH),
    new SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE)
);

// Specify the safety settings as part of creating the `GenerativeModel` instance.
GenerativeModelFutures model = GenerativeModelFutures.from(
    FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel(
            /* modelName */ "GEMINI_MODEL_NAME",
            /* generationConfig is optional */ null,
            safetySettings
        )
);

// ...

Web

建立 GenerativeModel 執行個體時,請設定 SafetySetting:


import { HarmBlockThreshold, HarmCategory, getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

const safetySettings = [
  {
    category: HarmCategory.HARM_CATEGORY_HARASSMENT,
    threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
  },
  {
    category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
];

// Specify the safety settings as part of creating the `GenerativeModel` instance.
const model = getGenerativeModel(ai, {
  model: "GEMINI_MODEL_NAME",
  safetySettings,
});

// ...

Dart

建立 GenerativeModel 例項時,請設定 SafetySetting:


import 'package:firebase_ai/firebase_ai.dart';

final safetySettings = [
  SafetySetting(HarmCategory.harassment, HarmBlockThreshold.high),
  SafetySetting(HarmCategory.hateSpeech, HarmBlockThreshold.medium),
];

// Specify the safety settings as part of creating the `GenerativeModel` instance.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  safetySettings: safetySettings,
);

// ...

Unity

建立 GenerativeModel 執行個體時,請設定 SafetySetting:


// ...

var safetySettings = new SafetySetting[] {
  new SafetySetting(HarmCategory.Harassment, SafetySetting.HarmBlockThreshold.OnlyHigh),
  new SafetySetting(HarmCategory.HateSpeech, SafetySetting.HarmBlockThreshold.MediumAndAbove)
};

// Specify the safety settings as part of creating the `GenerativeModel` instance.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: safetySettings
);

// ...



可用的有害內容類別

安全篩選器會根據下列可設定的危害類別,評估提示和模型回覆:

危害類別 說明
HARM_CATEGORY_HARASSMENT 針對個人或身分發表負面、威脅、恐嚇、霸凌或辱罵言論。
HARM_CATEGORY_HATE_SPEECH 內容基於受保護特質 (例如種族、族裔、宗教、身心障礙、年齡、國籍、退除役身分、性傾向或性別認同),攻擊、貶低、鼓吹仇恨或煽動暴力對待特定個人或群體。
HARM_CATEGORY_SEXUALLY_EXPLICIT 提及性行為、色情內容或其他猥褻和煽情露骨內容。
HARM_CATEGORY_DANGEROUS_CONTENT 宣傳、促進、鼓勵或提供有害行為、非法商品和服務、武器、自傷或危險活動的指示。
HARM_CATEGORY_CIVIC_INTEGRITY 可能誤導選民或破壞公民和選舉程序的內容。(僅支援特定型號和地區)。

無法設定的安全篩選機制

除了可設定的類別外,所有要求都會通過系統層級的篩選器,這些篩選器無法調整:

  • 兒少性虐待內容/禁止宣傳的內容:如果提示或回覆含有禁止宣傳的內容,系統會立即封鎖 (PROHIBITED_CONTENT)。

  • 具敏感性的個人識別資訊 (SPII):如果回覆可能洩漏敏感個人資料 (例如金融帳號或身分證字號),系統會封鎖這類回覆 (SPII)。



設定門檻

針對您要在應用程式中控管的每個有害內容類別,您需要設定門檻。如果評估內容達到或超過該門檻,系統就會封鎖內容。

安全評估的運作方式:機率與嚴重程度

安全篩選器會從兩個不同面向評估內容:

  • 機率:模型對內容屬於特定有害類別的信心程度。

  • 嚴重程度:如果內容有害,潛在危害的程度或嚴重程度。

每個維度都會指派下列其中一個層級:NEGLIGIBLE、LOW、MEDIUM 或 HIGH。

內容可能機率高但嚴重程度低 (例如溫和的喜劇玩笑或友善的侮辱),或機率低但嚴重程度高 (例如提及暴力的醫療或歷史討論)。

可用的有害內容封鎖門檻

您可以為要控管的有害類別設定下列任一門檻:

門檻 說明 允許的層級
BLOCK_LOW_AND_ABOVE 最嚴格。
當機率 (或嚴重程度) 為 LOW、MEDIUM 或 HIGH 時,封鎖內容。
僅允許 NEGLIGIBLE
BLOCK_MEDIUM_AND_ABOVE 中度限制。
當機率 (或嚴重程度) 為MEDIUM或HIGH時,封鎖內容。
允許 NEGLIGIBLE 和 LOW
BLOCK_ONLY_HIGH 最寬鬆的有效篩選器。
只有在機率 (或嚴重程度) 為HIGH時,才會封鎖內容。
允許 NEGLIGIBLE、LOW 和 MEDIUM
BLOCK_NONE 這個類別已停用自動封鎖回覆功能。系統仍會計算安全性評等中繼資料,並隨回覆傳回,方便應用程式執行自訂審核。 允許所有內容
OFF 完全關閉這個類別的安全篩選器。系統不會自動封鎖,也不會傳回安全評分中繼資料。 允許所有內容



檢查安全評分並處理遭封鎖的內容

系統可在要求期間的兩個階段封鎖內容:

  1. 提示詞已封鎖 (PromptFeedback):輸入提示詞違反安全篩選器,因此模型未生成任何輸出內容。不會傳回任何候選回覆。

  2. 候選回覆遭封鎖 (finishReason == SAFETY):模型評估或生成的候選回覆超過設定的門檻。生成的候選文字會清除或遮蓋。

SafetyRating 物件

每個評估過的提示或候選回覆都包含 SafetyRating 物件陣列。每個評分都會提供下列資訊:

  • Gemini Developer API 和 Agent Platform Gemini API (formerly Vertex AI) 均可使用的屬性:

    • category:評估的 HarmCategory。

    • probability:離散評分 (NEGLIGIBLE、LOW、MEDIUM 或 HIGH)。

    • blocked:如果這個特定分級導致內容遭到封鎖,則為 true。

  • Agent Platform Gemini API (formerly Vertex AI) 提供的其他屬性:

    • probabilityScore:浮點可信度分數,範圍從 0.0 到 1.0。

    • severity:離散嚴重性等級 (NEGLIGIBLE、LOW、MEDIUM 或 HIGH)。

    • severityScore:嚴重程度分數,以浮點值表示,範圍從 0.0 到 1.0。

SafetyRating 物件範例

以下範例說明候選內容遭安全篩選器封鎖時,原始 JSON 回覆酬載的樣貌:

{
  "candidates": [
    {
      "finishReason": "SAFETY",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "blocked": false
        },
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "blocked": false
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "blocked": false
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "HIGH",
          "blocked": true
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 24,
    "totalTokenCount": 24
  }
}

找出程式碼中的安全錯誤

內容遭到封鎖時,用戶端 SDK 會將封鎖顯示為例外狀況或錯誤代碼,讓應用程式能妥善處理。

Swift

您可以擷取 GenerateContentError.promptBlocked 或 GenerateContentError.responseStoppedEarly:

do {
  let response = try await model.generateContent("Your prompt here")
  print(response.text ?? "No text generated.")
} catch GenerateContentError.promptBlocked(let response) {
  // The input prompt was blocked
  if let feedback = response.promptFeedback {
    let reason = feedback.blockReason?.rawValue ?? "unknown"
    print("Prompt blocked for reason: \(reason)")
    for rating in feedback.safetyRatings {
      let cat = rating.category.rawValue
      let prob = rating.probability.rawValue
      print("Category: \(cat), probability: \(prob)")
    }
  }
} catch GenerateContentError.responseStoppedEarly(let reason, let response) {
  // Candidate response was blocked or stopped early
  if reason == .safety {
    print("Response blocked due to safety.")
    if let candidate = response.candidates.first {
      for rating in candidate.safetyRatings where rating.blocked {
        print("Blocked by category: \(rating.category.rawValue)")
      }
    }
  }
} catch {
  print("Unexpected error: \(error)")
}

Kotlin

您可以擷取 PromptBlockedException 或檢查 candidate.finishReason:

try {
  val response = model.generateContent("Your prompt here")
  val candidate = response.candidates.firstOrNull()

  if (candidate?.finishReason == FinishReason.SAFETY) {
    val blockedRating =
      candidate.safetyRatings.firstOrNull { it.blocked }
    println("Response blocked by category: ${blockedRating?.category}")
  } else {
    println(response.text)
  }
} catch (e: PromptBlockedException) {
  val reason = e.response?.promptFeedback?.blockReason
  println("Prompt was blocked: $reason")
} catch (e: Exception) {
  println("Error generating content: ${e.message}")
}

Java

您可以擷取 PromptBlockedException 或檢查 candidate.getFinishReason():

try {
  GenerateContentResponse response = model.generateContent("Your prompt here").get();
  Candidate candidate = response.getCandidates().isEmpty() ? null : response.getCandidates().get(0);

  if (candidate != null && candidate.getFinishReason() == FinishReason.SAFETY) {
    SafetyRating blockedRating = null;
    for (SafetyRating rating : candidate.getSafetyRatings()) {
      if (Boolean.TRUE.equals(rating.getBlocked())) {
        blockedRating = rating;
        break;
      }
    }
    System.out.println("Response blocked by category: " +
        (blockedRating != null ? blockedRating.getCategory() : "unknown"));
  } else {
    System.out.println(response.getText());
  }
} catch (ExecutionException e) {
  if (e.getCause() instanceof PromptBlockedException) {
    PromptBlockedException pbe = (PromptBlockedException) e.getCause();
    GenerateContentResponse blockedResponse = pbe.getResponse();
    String reason = (blockedResponse != null && blockedResponse.getPromptFeedback() != null)
        ? String.valueOf(blockedResponse.getPromptFeedback().getBlockReason())
        : "unknown";
    System.out.println("Prompt was blocked: " + reason);
  } else {
    System.out.println("Error generating content: " + e.getMessage());
  }
} catch (InterruptedException e) {
  System.out.println("Generation was interrupted: " + e.getMessage());
}

Web

您可以檢查 promptFeedback 和 candidate.finishReason:

try {
  const response = await model.generateContent("Your prompt here");

  // Check if the prompt was blocked
  if (response.promptFeedback?.blockReason) {
    console.warn(`Prompt blocked: ${response.promptFeedback.blockReason}`);
    return;
  }

  const candidate = response.candidates?.[0];
  if (candidate?.finishReason === "SAFETY") {
    const blockedRating = candidate.safetyRatings?.find((r) => r.blocked);
    console.warn(`Response blocked by category: ${blockedRating?.category}`);
  } else {
    console.log(response.text);
  }
} catch (error) {
  console.error("Error generating content:", error);
}

Dart

您可以檢查 promptFeedback 和 candidate.finishReason:

try {
  final response = await model.generateContent([Content.text('Your prompt here')]);

  // Check if the prompt was blocked
  if (response.promptFeedback?.blockReason != null) {
    print('Prompt blocked: ${response.promptFeedback?.blockReason}');
    return;
  }

  final candidate = response.candidates.firstOrNull;
  if (candidate?.finishReason == FinishReason.safety) {
    final blockedRating =
        candidate?.safetyRatings?.where((r) => r.isBlocked == true).firstOrNull;
    print('Response blocked by category: ${blockedRating?.category.name}');
  } else {
    print(response.text);
  }
} catch (e) {
  print('Error generating content: $e');
}

Unity

您可以檢查 PromptFeedback 和 candidate.FinishReason:

try {
  var response = await model.GenerateContentAsync("Your prompt here");

  // Check if the prompt was blocked
  if (response.PromptFeedback?.BlockReason != null) {
    Debug.LogWarning($"Prompt blocked: {response.PromptFeedback.BlockReason}");
    return;
  }

  var candidate = response.Candidates.FirstOrDefault();
  if (candidate?.FinishReason == FinishReason.Safety) {
    var blockedRating = candidate.SafetyRatings?.FirstOrDefault(r => r.Blocked);
    Debug.LogWarning($"Response blocked by category: {blockedRating?.Category}");
  } else {
    Debug.Log(response.Text);
  }
} catch (Exception ex) {
  Debug.LogError($"Error generating content: {ex.Message}");
}



負責任應用程式設計的最佳做法

  • 縱深防禦:安全篩選器是防護措施,而非指令。結合安全性設定、明確的系統指令和特定提示設計,引導模型採用適當的語氣和範圍。

  • 提供適當的使用者意見回饋:內容遭到封鎖時,絕不當機或顯示空白畫面。偵測 finishReason == SAFETY 或 PromptBlockedException,並顯示友善訊息,告知使用者要求不符合內容規範,因此無法執行。

  • 使用 BLOCK_NONE 進行自訂審核:如果您已有自己的用戶端或伺服器端審核管道,請將門檻設為 BLOCK_NONE,以便接收模型的 safetyRatings,而不自動封鎖,讓應用程式強制執行自訂審核政策。

  • 詳閱《服務條款》:如果使用較寬鬆的設定 (BLOCK_ONLY_HIGH 或 BLOCK_NONE),請確保應用程式持續遵守 Google 的《使用限制政策》。

其他控制內容生成的方式

  • 進一步瞭解提示設計,引導模型生成符合您特定需求的輸出內容。
  • 設定模型參數,控制模型生成回覆的方式,例如輸出詞元數量上限、輸出詞元重複的機率等。
  • 設定系統指令,引導模型行為。這項功能就像前導提示,在模型接收使用者進一步指示前,先提供指引。
  • 傳送回覆結構定義和提示,指定特定輸出內容結構定義。這項功能最常用於生成 JSON 輸出內容,但也能用於分類工作 (例如希望模型使用特定標籤或標記)。