Используйте конфигурацию модели для управления ответами

При каждом обращении к модели вы можете передать конфигурацию модели, чтобы управлять тем, как модель генерирует ответ. Каждая модель предлагает различные параметры конфигурации.

You can also experiment with prompts and model configurations using Google AI Studio .

Jump to Gemini config options Jump to Imagen config options (Deprecated)



Настройка моделей Gemini

This section shows you how to set up a configuration for use with Gemini models and provides a description of each parameter .

Настройка конфигурации модели ( Gemini )

Config for general Gemini use cases

Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него.

The configuration is maintained for the lifetime of the instance. If you want to use a different config, create a new GenerativeModel instance with that config.

Быстрый

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


import FirebaseAILogic

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
let config = GenerationConfig(
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: ["red"]
)

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `GenerativeModel` instance
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: config
)

// ...

Kotlin

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


// ...

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
val config = generationConfig {
    candidateCount = 1
    maxOutputTokens = 200
    stopSequences = listOf("red")
}

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `GenerativeModel` instance
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    generationConfig = config
)

// ...

Java

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


// ...

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.candidateCount = 1;
configBuilder.maxOutputTokens = 200;
configBuilder.stopSequences = List.of("red");

GenerationConfig config = configBuilder.build();

// Specify the config as part of creating the `GenerativeModel` instance
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                    "GEMINI_MODEL_NAME",
                    config
                );
);

// ...

Web

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


// ...

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

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
const generationConfig = {
  candidate_count: 1,
  maxOutputTokens: 200,
  stopSequences: ["red"],
};

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

// ...

Dart

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


// ...

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
final generationConfig = GenerationConfig(
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: ["red"],
);

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `GenerativeModel` instance
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  config: generationConfig,
);

// ...

Единство

Set the values of the parameters in a GenerationConfig as part of creating a GenerativeModel instance.


// ...

// Set parameter values in a `GenerationConfig`.
// IMPORTANT: Example values shown here. Make sure to update for your use case.
var generationConfig = new GenerationConfig(
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: new string[] { "red" }
);

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

You can find a description of each parameter in the next section of this page.

Настройка Gemini Live API

Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него.

Данная конфигурация сохраняется на протяжении всего срока службы экземпляра. Если вы хотите использовать другую конфигурацию, создайте новый экземпляр LiveModel с этой конфигурацией.

Быстрый

Set the values of parameters in the liveGenerationConfig during initialization of the LiveModel instance:


// ...

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
let config = LiveGenerationConfig(
  maxOutputTokens: 200,
  responseModalities: [.audio],
  speech: SpeechConfig(voiceName: "Fenrir"),
)

// Specify the config as part of creating the `liveModel` instance
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_MODEL_NAME",
  generationConfig: config
)

// ...

Kotlin

Set the values of parameters in a LiveGenerationConfig as part of creating a LiveModel instance.


// ...

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
val config = liveGenerationConfig {
    maxOutputTokens = 200
    responseModality = ResponseModality.AUDIO
    speechConfig = SpeechConfig(voice = Voices.FENRIR)
}

// Specify the config as part of creating the `LiveModel` instance
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_MODEL_NAME",
    generationConfig = config
)

// ...

Java

Задайте значения параметров в LiveGenerationConfig при создании экземпляра LiveModel .


// ...

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
LiveGenerationConfig.Builder configBuilder = new LiveGenerationConfig.Builder();
configBuilder.setMaxOutputTokens(200);
configBuilder.setResponseModality(ResponseModality.AUDIO);

configBuilder.setSpeechConfig(new SpeechConfig(Voices.FENRIR));

LiveGenerationConfig config = configBuilder.build();

// Specify the config as part of creating the `LiveModel` instance
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
          "GEMINI_LIVE_MODEL_NAME",
          config
);

// ...

Web

Задайте значения параметров в файле LiveGenerationConfig во время инициализации экземпляра LiveGenerativeModel :


// ...

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

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
const liveGenerationConfig = {
  maxOutputTokens: 200,
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    voiceConfig: {
      prebuiltVoiceConfig: { voiceName: "Fenrir" },
    },
  },
};

// Specify the config as part of creating the `LiveGenerativeModel` instance
const liveModel = getLiveGenerativeModel(ai, {
  model: "GEMINI_LIVE_MODEL_NAME",
  liveGenerationConfig,
});

// ...

Dart

Задайте значения параметров в LiveGenerationConfig при создании экземпляра LiveGenerativeModel .


// ...

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
final config = LiveGenerationConfig(
  maxOutputTokens: 200,
  responseModalities: [ResponseModalities.audio],
  speechConfig: SpeechConfig(voiceName: 'Fenrir'),
);

// Specify the config as part of creating the `liveGenerativeModel` instance
final liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'GEMINI_LIVE_MODEL_NAME',
  liveGenerationConfig: config,
);

// ...

Единство

Set the values of parameters in a LiveGenerationConfig as part of creating a LiveModel instance.


// ...

// Set parameter values in a `LiveGenerationConfig` (example values shown here)
var config = new LiveGenerationConfig(
  maxOutputTokens: 200,
  responseModalities: new[] { ResponseModality.Audio },
  speechConfig: SpeechConfig.UsePrebuiltVoice("Fenrir")
);

// Specify the config as part of creating the `LiveModel` instance
var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
  modelName: "GEMINI_LIVE_MODEL_NAME",
  liveGenerationConfig: config
);

// ...

You can find a description of each parameter in the next section of this page.

Описание параметров ( Gemini )

Here is a high-level overview of the available parameters, as applicable. You can find a comprehensive list of parameters and their values in the documentation for your chosen Gemini API provider: Gemini Developer API orVertex AI Gemini API .

Параметр Описание Значение по умолчанию
Audio timestamp
audioTimestamp

A boolean that enables timestamp understanding for audio-only input files.

Only applicable when using generateContent or generateContentStream calls and the input type is an audio-only file.

false
Количество кандидатов
candidateCount

Указывает количество вариантов ответа, которые необходимо вернуть. За каждый запрос взимается плата за выходные токены всех кандидатов, но плата за входные токены взимается только один раз.

Supported values: 1 - 8 (inclusive)

Применимо только при использовании generateContent и последних моделей Gemini . Модели Live API и generateContentStream не поддерживаются.

1
Frequency penalty
frequencyPenalty
Controls the probability of including tokens that repeatedly appear in the generated response.
Положительные значения наказывают токены, которые неоднократно появляются в сгенерированном контенте, снижая вероятность повторения контента.
---
Максимальное количество выходных токенов
maxOutputTokens
Указывает максимальное количество токенов, которые могут быть сгенерированы в ответе. ---
Presence penalty
presencePenalty
Управляет вероятностью включения токенов, которые уже присутствуют в сгенерированном ответе.
Positive values penalize tokens that already appear in the generated content, increasing the probability of generating more diverse content.
---
Стоп-последовательности
stopSequences

Specifies a list of strings that tells the model to stop generating content if one of the strings is encountered in the response.

Only applicable when using a GenerativeModel configuration.

---
Способы реагирования
responseModalities

Specifies the type of output (like text, audio, or images).

Only applicable when using the Live API models, or when using a Gemini model capable of multimodal output (like the "Nano Banana" models).

---
Речь (голос)
speechConfig

Specifies the voice used for the streamed audio output when using the Live API .

Only applicable when using the Live API models.

Puck
Характеристики изображения
imageConfig

Specifies aspect ratio and resolution of generated images.

Supported values: See Configure image generation

Only applicable when using a Gemini model capable of image output (like the "Nano Banana" models).

Соотношение сторон 1:1 (квадрат)
разрешение 1024x1024

The following parameters are supported; however, setting them for Gemini 3.x and later models is not recommended . For more deterministic responses, define system instructions with explicit rules for your specific use case.

Параметр Описание Значение по умолчанию
Температура
temperature
Controls the degree of randomness in the response.
Lower temperatures result in more deterministic responses, and higher temperatures result in more diverse or creative responses.
Depends on the model
Топ-К
topK
Limits the number of highest probability words used in the generated content.
A top-K value of 1 means the next selected token should be the most probable among all tokens in the model's vocabulary, while a top-K value of n means that the next token should be selected from among the n most probable tokens (all based on the temperature that's set).
Depends on the model
Топ-П
topP
Controls diversity of generated content.
Tokens are selected from the most probable (see top-K above) to least probable until the sum of their probabilities equals the top-P value.
Depends on the model



Configure Imagen models

Click your Imagen API provider to view provider-specific content and code on this page.

This section shows you how to set up a configuration for use with Imagen models and provides a description of each parameter .

Настройка конфигурации модели ( Imagen )

The configuration is maintained for the lifetime of the instance. If you want to use a different config, create a new ImagenModel instance with that config.

Быстрый

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


import FirebaseAILogic

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
let config = ImagenGenerationConfig(
  negativePrompt: "frogs",
  numberOfImages: 2,
  aspectRatio: .landscape16x9,
  imageFormat: .jpeg(compressionQuality: 100),
  addWatermark: false
)

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `ImagenModel` instance
let model = FirebaseAI.firebaseAI(backend: .googleAI()).imagenModel(
  modelName: "IMAGEN_MODEL_NAME",
  generationConfig: config
)

// ...

Kotlin

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


// ...

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
val config = ImagenGenerationConfig {
    negativePrompt = "frogs",
    numberOfImages = 2,
    aspectRatio = ImagenAspectRatio.LANDSCAPE_16x9,
    imageFormat = ImagenImageFormat.jpeg(compressionQuality = 100),
    addWatermark = false
}

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `GenerativeModel` instance
val model = Firebase.ai(backend = GenerativeBackend.vertexAI()).imagenModel(
    modelName = "IMAGEN_MODEL_NAME",
    generationConfig = config
)

// ...

Java

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


// ...

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
ImagenGenerationConfig config = new ImagenGenerationConfig.Builder()
    .setNegativePrompt("frogs")
    .setNumberOfImages(2)
    .setAspectRatio(ImagenAspectRatio.LANDSCAPE_16x9)
    .setImageFormat(ImagenImageFormat.jpeg(100))
    .setAddWatermark(false)
    .build();

// Specify the config as part of creating the `ImagenModel` instance
ImagenModelFutures model = ImagenModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .imagenModel(
                    "IMAGEN_MODEL_NAME",
                    config
                );
);

// ...

Web

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


// ...

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

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
const generationConfig = {
  negativePrompt: "frogs",
  numberOfImages: 2,
  aspectRatio: ImagenAspectRatio.LANDSCAPE_16x9,
  imageFormat: ImagenImageFormat.jpeg(100),
  addWatermark: false
};

// Specify the config as part of creating the `ImagenModel` instance
const model = getImagenModel(ai, { model: "IMAGEN_MODEL_NAME", generationConfig });

// ...

Dart

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


// ...

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
final generationConfig = ImagenGenerationConfig(
  negativePrompt: 'frogs',
  numberOfImages: 2,
  aspectRatio: ImagenAspectRatio.landscape16x9,
  imageFormat: ImagenImageFormat.jpeg(compressionQuality: 100)
  addWatermark: false
);

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `ImagenModel` instance
final model = FirebaseAI.googleAI().imagenModel(
  model: 'IMAGEN_MODEL_NAME',
  config: generationConfig,
);

// ...

Единство

Set the values of the parameters in an ImagenGenerationConfig as part of creating an ImagenModel instance.


using Firebase.AI;

// Set parameter values in a `ImagenGenerationConfig` (example values shown here)
var config = new ImagenGenerationConfig(
  numberOfImages: 2,
  aspectRatio: ImagenAspectRatio.Landscape16x9,
  imageFormat: ImagenImageFormat.Jpeg(100)
);

// Initialize the Gemini Developer API backend service
// Specify the config as part of creating the `ImagenModel` instance
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetImagenModel(
  modelName: "imagen-4.0-generate-001",
  generationConfig: config
);

// ...

You can find a description of each parameter in the next section of this page.

Description of parameters ( Imagen )

Ниже представлен общий обзор доступных параметров, если таковые имеются. Полный список параметров и их значений можно найти в документации Google Cloud .

Параметр Описание Значение по умолчанию
Отрицательный вопрос
negativePrompt
A description of what you want to omit in generated images

This parameter is not yet supported by imagen-3.0-generate-002 .

---
Количество результатов
numberOfImages
The number of generated images returned for each request default is one image
Соотношение сторон
aspectRatio
The ratio of width to height of generated images default is square (1:1)
Формат изображения
imageFormat
Параметры вывода, такие как формат изображения (тип MIME) и уровень сжатия создаваемых изображений. default MIME type is PNG
По умолчанию степень сжатия составляет 75 (если MIME-тип установлен на JPEG).
Водяной знак
addWatermark
Whether to add a non-visible digital watermark (called a SynthID ) to generated images default is true
Person generation
personGeneration
Whether to allow generation of people by the model default depends on the model
Include safety attributes
includeSafetyAttributes
Whether to enable rounded Responsible AI scores for a list of safety attributes in responses for unfiltered input and output

Safety attribute categories: "Death, Harm & Tragedy" , "Firearms & Weapons" , "Hate" , "Health" , "Illicit Drugs" , "Politics" , "Porn" , "Religion & Belief" , "Toxic" , "Violence" , "Vulgarity" , "War & Conflict" .

default is false



Other options to control content generation

  • Learn more about prompt design so that you can influence the model to generate output specific to your needs.
  • Use safety settings to adjust the likelihood of getting responses that may be considered harmful, including hate speech and sexually explicit content.
  • Set system instructions to steer the behavior of the model. This feature is like a preamble that you add before the model gets exposed to any further instructions from the end user.
  • Pass a response schema along with the prompt to specify a specific output schema. This feature is most commonly used when generating JSON output , but it can also be used for classification tasks (like when you want the model to use specific labels or tags).