Entender e usar as configurações de segurança

Você pode usar as configurações de segurança para ajustar a probabilidade de receber respostas que possam ser consideradas nocivas. Por padrão, as configurações de segurança bloqueiam conteúdo com probabilidade média e/ou alta de não ser seguro em todas as dimensões.

Acessar as configurações de segurança do Gemini Acessar as configurações de segurança do Imagen

Configurações de segurança para modelos Gemini

Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página.

Saiba mais sobre as configurações de segurança para modelos Gemini na documentação do Gemini Developer API.

Swift

Você configura o SafetySettings ao criar uma instância GenerativeModel.

Exemplo com uma configuração de segurança:


import FirebaseAI

// Initialize the Gemini Developer API backend service
// Create an `GenerativeModel` instance and add safety settings to its config
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: [
    SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh)
  ]
)

// ...

Exemplo com várias configurações de segurança:


import FirebaseAI

let harassmentSafety = SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh)
let hateSpeechSafety = SafetySetting(harmCategory: .hateSpeech, threshold: .blockMediumAndAbove)

// Initialize the Gemini Developer API backend service
// Create an `GenerativeModel` instance and add safety settings to its config
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: [harassmentSafety, hateSpeechSafety]
)

// ...

Kotlin

Você configura o SafetySettings ao criar uma instância GenerativeModel.

Exemplo com uma configuração de segurança:


import com.google.firebase.vertexai.type.HarmBlockThreshold
import com.google.firebase.vertexai.type.HarmCategory
import com.google.firebase.vertexai.type.SafetySetting

// Create a `GenerativeModel` instance and add safety settings to its config
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    safetySettings = listOf(
        SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.ONLY_HIGH)
    )
)

// ...

Exemplo com várias configurações de segurança:


import com.google.firebase.vertexai.type.HarmBlockThreshold
import com.google.firebase.vertexai.type.HarmCategory
import com.google.firebase.vertexai.type.SafetySetting

val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.ONLY_HIGH)
val hateSpeechSafety = SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE)

// Create a `GenerativeModel` instance and add safety settings to its config
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    safetySettings = listOf(harassmentSafety, hateSpeechSafety)
)

// ...

Java

Você configura o SafetySettings ao criar uma instância GenerativeModel.


SafetySetting harassmentSafety = new SafetySetting(HarmCategory.HARASSMENT,
HarmBlockThreshold.ONLY_HIGH);

// Create an `GenerativeModel` instance and add safety settings to its config
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "IMAGEN_MODEL_NAME",
                  /* generationConfig is optional */ null,
                  Collections.singletonList(harassmentSafety)
                );
);

// ...

Exemplo com várias configurações de segurança:


SafetySetting harassmentSafety = new SafetySetting(HarmCategory.HARASSMENT,
HarmBlockThreshold.ONLY_HIGH);

SafetySetting hateSpeechSafety = new SafetySetting(HarmCategory.HATE_SPEECH,
HarmBlockThreshold.MEDIUM_AND_ABOVE);

// Create an `GenerativeModel` instance and add safety settings to its config
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "IMAGEN_MODEL_NAME",
                  /* generationConfig is optional */ null,
                  List.of(harassmentSafety, hateSpeechSafety)
                );
);

// ...

Web

Você configura o SafetySettings ao criar uma instância GenerativeModel.

Exemplo com uma configuração de segurança:


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

// ...

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

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

// Create a `GenerativeModel` instance and add safety settings to its config
const model = getGenerativeModel(ai, { model: "GEMINI_MODEL_NAME", safetySettings });

// ...

Exemplo com várias configurações de segurança:


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

// ...

// Initialize the Gemini Developer API backend service
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,
  },
];

// Create a `GenerativeModel` instance and add safety settings to its config
const model = getGenerativeModel(ai, { model: "GEMINI_MODEL_NAME", safetySettings });

// ...

Dart

Você configura SafetySettings ao criar uma instância GenerativeModel.

Exemplo com uma configuração de segurança:


// ...

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance and add safety settings to its config
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  safetySettings: safetySettings,
);

// ...

Exemplo com várias configurações de segurança:


// ...

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance and add safety settings to its config
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  safetySettings: safetySettings,
);

// ...

Unity

Você configura o SafetySettings ao criar uma instância GenerativeModel.

Exemplo com uma configuração de segurança:


// ...

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance and add safety settings to its config
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: new SafetySetting[] {
    new SafetySetting(HarmCategory.Harassment, SafetySetting.HarmBlockThreshold.OnlyHigh)
  }
);

// ...

Exemplo com várias configurações de segurança:


// ...

var harassmentSafety = new SafetySetting(HarmCategory.Harassment, SafetySetting.HarmBlockThreshold.OnlyHigh);
var hateSpeechSafety = new SafetySetting(HarmCategory.HateSpeech, SafetySetting.HarmBlockThreshold.MediumAndAbove);

// Initialize the Vertex AI Gemini API backend service
// Create a `GenerativeModel` instance and add safety settings to its config
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  safetySettings: new SafetySetting[] { harassmentSafety, hateSpeechSafety }
);

// ...

Configurações de segurança para modelos Imagen

Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página.

Saiba mais sobre todas as configurações de segurança compatíveis e os valores disponíveis para modelos Imagen na documentação do Google Cloud.

Swift

Você configura o ImagenSafetySettings ao criar uma instância ImagenModel.


import FirebaseAI

// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance and add safety settings to its config
let model = FirebaseAI.firebaseAI(backend: .googleAI()).imagenModel(
  modelName: "IMAGEN_MODEL_NAME",
  safetySettings: ImagenSafetySettings(
    safetyFilterLevel: .blockLowAndAbove,
    personFilterLevel: .allowAdult
  )
)

// ...

Kotlin

Você configura o ImagenSafetySettings ao criar uma instância ImagenModel.


// Initialize the Vertex AI Gemini API backend service
// Create an `ImagenModel` instance and add safety settings to its config
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).imagenModel(
  modelName = "IMAGEN_MODEL_NAME",
  safetySettings = ImagenSafetySettings(
    safetyFilterLevel = ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE,
    personFilterLevel = ImagenPersonFilterLevel.BLOCK_ALL
  )
)

// ...

Java

Você configura o ImagenSafetySettings ao criar uma instância ImagenModel.


// Create an `ImagenModel` instance and add safety settings to its config
ImagenModelFutures model = ImagenModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .imagenModel(
                  /* modelName */ "IMAGEN_MODEL_NAME",
                  /* imageGenerationConfig */ null);
);

// ...

Web

Você configura o ImagenSafetySettings ao criar uma instância ImagenModel.


// ...

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create an `ImagenModel` instance and add safety settings to its config
const model = getImagenModel(
  ai,
  {
    model: "IMAGEN_MODEL_NAME",
    safetySettings: {
      safetyFilterLevel: ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE,
      personFilterLevel: ImagenPersonFilterLevel.ALLOW_ADULT,
    }
  }
);

// ...

Dart

Você configura o ImagenSafetySettings ao criar uma instância ImagenModel.


// ...

// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance and add safety settings to its config
final model = FirebaseAI.googleAI().imagenModel(
  model: 'IMAGEN_MODEL_NAME',
  safetySettings: ImagenSafetySettings(
    ImagenSafetyFilterLevel.blockLowAndAbove,
    ImagenPersonFilterLevel.allowAdult,
  ),
);

// ...

Unity

O uso de Imagen ainda não é compatível com o Unity, mas volte em breve.

Outras opções para controlar a geração de conteúdo

  • Saiba mais sobre o design de comando para influenciar o modelo a gerar resultados específicos para suas necessidades.
  • Configure os parâmetros do modelo para controlar como o modelo gera uma resposta. Para modelos Gemini, esses parâmetros incluem tokens de saída máximos, temperatura, topK e topP. Para modelos Imagen, isso inclui proporção, geração de pessoas, marca d'água etc.
  • Defina instruções do sistema para orientar o comportamento do modelo. Esse recurso é como um preâmbulo que você adiciona antes que o modelo seja exposto a outras instruções do usuário final.
  • Transmita um esquema de resposta com o comando para especificar um esquema de saída específico. Esse recurso é usado com mais frequência ao gerar saída JSON, mas também pode ser usado para tarefas de classificação, como quando você quer que o modelo use rótulos ou tags específicos.