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

É possível 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

// Specify the safety settings as part of creating the `GenerativeModel` instance
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)

// Specify the safety settings as part of creating the `GenerativeModel` instance
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

// Specify the safety settings as part of creating the `GenerativeModel` instance
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)

// Specify the safety settings as part of creating the `GenerativeModel` instance
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);

// Specify the safety settings as part of creating the `GenerativeModel` instance
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);

// Specify the safety settings as part of creating the `GenerativeModel` instance
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";

// ...

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

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

// Specify the safety settings as part of creating the `GenerativeModel` instance
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";

// ...

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

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

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


// ...

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

// Specify the safety settings as part of creating the `GenerativeModel` instance
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),
];

// Specify the safety settings as part of creating the `GenerativeModel` instance
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:


// ...

// 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: 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);

// 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: 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

// Specify the safety settings as part of creating the `ImagenModel` instance
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.


// Specify the safety settings as part of creating the `ImagenModel` instance
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.


// Specify the safety settings as part of creating the `ImagenModel` instance
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.


// ...

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

// Specify the safety settings as part of creating the `ImagenModel` instance
const model = getImagenModel(
  ai,
  {
    model: "IMAGEN_MODEL_NAME",
    safetySettings: {
      safetyFilterLevel: ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE,
      personFilterLevel: ImagenPersonFilterLevel.ALLOW_ADULT,
    }
  }
);

// ...

Dart

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


// ...

// Specify the safety settings as part of creating the `ImagenModel` instance
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 uma saída específica 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.