мышление

All the recent Gemini models use an internal "thinking process" that significantly improves their reasoning and multi-step planning abilities, making them highly effective for complex tasks such as coding, advanced mathematics, and data analysis.

Модели мышления предлагают следующие конфигурации и варианты:

  • Контролируйте количество размышлений.
    You can configure how much "thinking" that a model can do. This configuration is particularly important if reducing latency or cost is a priority. Also, review the comparison of task difficulties to decide how much a model might need its thinking capability.

    Управляйте этой конфигурацией либо с помощью уровней мышления (модели Gemini 3.x и более поздние) , либо с помощью бюджетов мышления (модели Gemini 2.5 ) .

  • Получите краткие обзоры мыслей
    You can enable thought summaries to include with the generated response. These summaries are synthesized versions of the model's raw thoughts and offer insights into the model's internal reasoning process.

  • Обработка сигнатур мыслей
    The Firebase AI Logic SDKs automatically handle thought signatures for you, which ensures that the model has access to the thought context from previous turns specifically when using function calling.

Обязательно ознакомьтесь с передовыми методами и рекомендациями по использованию моделей мышления.



Рекомендации и подсказки по использованию моделей мышления

We recommend testing your prompt in Google AI Studio or Agent Studio where you can view the full thinking process. You can identify any areas where the model may have gone astray so that you can refine your prompts to get more consistent and accurate responses.

Begin with a general prompt that describes the desired outcome, and observe the model's initial thoughts on how it determines its response. If the response isn't as expected, help the model generate a better response by using any of the following prompting techniques :

  • Предоставьте пошаговые инструкции.
  • Приведите несколько примеров пар «вход-выход».
  • Предоставьте рекомендации по формулировке и форматированию выходных данных и ответов.
  • Укажите конкретные этапы проверки.

Помимо подсказок, рассмотрите возможность использования следующих рекомендаций:

  • Set system instructions , which are like a "preamble" that you add before the model gets exposed to any further instructions from the prompt or end user. They let you steer the behavior of the model based on your specific needs and use cases.

  • Set a thinking level (or thinking budget for Gemini 2.5 models) to control how much thinking the model can do. If you set it high, then the model can think more, if needed. If you set it lower, then the model won't "overthink" its response, and it also reserves more of the total token output limit for the actual response and can help reduce latency and cost.

  • Enable AI monitoring in the Firebase console to monitor the count of thinking tokens and the latency of your requests that have thinking enabled. And if you have thought summaries enabled, they will display in the console where you can inspect the model's detailed reasoning to help you debug and refine your prompts.



Контролируйте количество размышлений.

Вы можете настроить, какой объем «размышлений» и рассуждений может выполнить модель, прежде чем вернуть ответ. Эта настройка особенно важна, если приоритетом является снижение задержки или стоимости.

Обязательно сравните сложность задач , чтобы определить, насколько сильно модели может потребоваться развитие мыслительных способностей. Вот несколько общих рекомендаций:

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

Управляйте этой конфигурацией либо с помощью уровней мышления (модели Gemini 3.x и более поздние) , либо с помощью бюджетов мышления (модели Gemini 2.5 ) .

Уровни мышления (модели Gemini 3.x и более поздние)

Чтобы контролировать объем мыслительной работы, которую может выполнить модель Gemini 3.x и более поздних версий для генерации ответа, можно задать уровень мышления , определяющий количество разрешенных ей мыслительных токенов.

Настройте уровень мышления

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

Agent

Set the thinking level in a GenerationConfig as part of creating the GenerativeModel instance. The configuration is maintained for the lifetime of the instance. If you want to use different thinking levels for different requests, then create GenerativeModel instances configured with each level.

Подробнее о поддерживаемых ценностях для уровня мышления вы узнаете позже в этом разделе.

Быстрый

Уровень мышления задается в параметре GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(thinkingLevel: .low)
)

// Specify the config as part of creating the `GenerativeModel` instance.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_3.x_MODEL_NAME",
  generationConfig: generationConfig
)

// ...

Kotlin

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


// ...

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      thinkingLevel = ThinkingLevel.LOW
  }
}

// Specify the config as part of creating the `GenerativeModel` instance.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
  modelName = "GEMINI_3.x_MODEL_NAME",
  generationConfig,
)

// ...

Java

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


// ...

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setThinkingLevel(ThinkingLevel.LOW)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

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

// ...

Web

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


// ...

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

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
const generationConfig = {
  thinkingConfig: {
    thinkingLevel: ThinkingLevel.LOW
  }
};

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

// ...

Dart

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


// ...

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
final thinkingConfig = ThinkingConfig.withThinkingLevel(ThinkingLevel.low);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_3.x_MODEL_NAME',
  config: generationConfig,
);

// ...

Единство

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


// ...

// Set the thinking configuration.
// Use a thinking level value appropriate for your model (example value shown here).
var thinkingConfig = new ThinkingConfig(thinkingLevel: ThinkingLevel.Low);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

// ...

Значения уровня поддерживаемого мышления

В таблице ниже перечислены значения уровня мышления, которые можно установить для каждой модели, настроив thinkingLevel этой модели .

MINIMAL LOW MEDIUM HIGH

Модель использует минимальное количество токенов; практически не требует размышлений.

Задачи низкой сложности

Модель использует меньше токенов; минимизирует задержку и стоимость.

Простые задачи и задачи с высокой пропускной способностью

Модель использует сбалансированный подход.

Задачи средней сложности

Модель использует токены до максимального уровня.

Сложные задания, требующие глубокого логического мышления.

Gemini 3.x Pro
gemini-3.1-pro-preview
(по умолчанию)
Gemini 3.x Flash
gemini-3.8-flash
gemini-3.7-flash
gemini-3.6-flash
gemini-3.5-flash

не поддерживается gemini-3.8-flash или gemini-3.7-flash 1
(по умолчанию)
Gemini 3.x Flash‑Lite
gemini-3.5-flash-lite
gemini-3.1-flash-lite
(по умолчанию)
Образ Gemini 3.x Pro
gemini-3-pro-image
("Nano Banana Pro")
(по умолчанию)
Образ Gemini 3.x Flash
gemini-3.1-flash-image
("Нано-банан 2")
(по умолчанию)
Gemini 3.x Flash‑Lite Image
gemini-3.1-flash-lite-image
("Nano Banana 2 Lite")
(по умолчанию)

1. Версии gemini-3.8-flash и gemini-3.7-flash не поддерживают уровень мышления MINIMAL . Если вы установите уровень мышления на MINIMAL , запрос завершится ошибкой 400.



Расчет бюджета (модели Gemini 2.5 )

Чтобы контролировать объем мыслительной работы, которую модель Gemini 2.5 может выполнить для генерации ответа, вы можете задать « бюджет мышления» — количество мыслительных токенов, которые ей разрешено использовать.

Составьте бюджет для размышлений

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

Agent

Set the thinking budget in a GenerationConfig as part of creating the GenerativeModel instance for a Gemini 2.5 model. The configuration is maintained for the lifetime of the instance. If you want to use different thinking budgets for different requests, then create GenerativeModel instances configured with each budget.

Подробнее о поддерживаемых ценностях при планировании бюджета вы узнаете позже в этом разделе.

Быстрый

Задайте бюджет мышления в параметре GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(thinkingBudget: 1024)
)

// Specify the config as part of creating the `GenerativeModel` instance.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_2.5_MODEL_NAME",
  generationConfig: generationConfig
)

// ...

Kotlin

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


// ...

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      thinkingBudget = 1024
  }
}

// Specify the config as part of creating the `GenerativeModel` instance.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
  modelName = "GEMINI_2.5_MODEL_NAME",
  generationConfig,
)

// ...

Java

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


// ...

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setThinkingBudget(1024)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

// Specify the config as part of creating the `GenerativeModel` instance.
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "GEMINI_2.5_MODEL_NAME",
                  /* generationConfig */ generationConfig
                );
);

// ...

Web

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


// ...

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

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
const generationConfig = {
  thinkingConfig: {
    thinkingBudget: 1024
  }
};

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

// ...

Dart

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


// ...

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
final thinkingConfig = ThinkingConfig.withThinkingBudget(1024);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_2.5_MODEL_NAME',
  config: generationConfig,
);

// ...

Единство

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


// ...

// Set the thinking configuration.
// Use a thinking budget value appropriate for your model (example value shown here).
var thinkingConfig = new ThinkingConfig(thinkingBudget: 1024);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

// ...

Бюджетные значения, поддерживаемые мышлением

В таблице ниже приведены значения бюджета мышления, которые можно установить для каждой модели, настроив thinkingBudget этой модели .

Модель Значение по умолчанию Доступный ассортимент для тех, кто планирует бюджет. Ценность для
отключить мышление
Ценность для
способствовать динамичному мышлению
Минимальное значение Максимальное значение
Gemini 2.5 Pro 8,192 128 32,768 не может быть отключен -1
Вспышка Gemini 2.5 8,192 1 24,576 0 -1
Фонарь Gemini 2.5 Flash‑Lite 0
(мышление по умолчанию отключено)
512 24,576 0
(или вообще не стоит планировать бюджет)
-1



Сложность задачи для всех моделей мышления

  • Простые задачи — думать не так уж и нужно.
    Простые запросы, не требующие сложных рассуждений, например, поиск фактов или классификация. Примеры:

    • «Где была основана компания DeepMind?»
    • "В этом письме содержится просьба о встрече или просто предоставляется информация?"
  • Задачи средней сложности — потребуется некоторое размышление.
    Типичные запросы, которые выигрывают от поэтапной обработки или более глубокого понимания. Примеры:

    • «Проведите аналогию между фотосинтезом и взрослением».
    • «Сравните электромобили и гибридные автомобили».
  • Сложные задачи — может потребоваться максимальное обдумывание.
    Truly complex challenges, such as solving complex math problems or coding tasks. These types of tasks require the model to engage its full reasoning and planning capabilities, often involving many internal steps before providing an answer. Examples:

    • "Решите задачу 1 на AIME 2025: Найдите сумму всех целочисленных оснований b > 9, для которых 17b является делителем 97b."
    • «Напишите код на Python для веб-приложения, которое визуализирует данные фондового рынка в реальном времени, включая аутентификацию пользователей. Сделайте его максимально эффективным».



Краткие обзоры мыслей

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

Вот несколько причин, по которым стоит включать в ответы краткие изложения своих мыслей:

  • You can display the thought summary in your app's UI or make them accessible to your users. The thought summary is returned as a separate part in the response so that you have more control over how it's used in your app.

  • If you also enable AI monitoring in the Firebase console , then thought summaries display in the console where you can inspect the model's detailed reasoning to help you debug and refine your prompts.

Вот несколько ключевых моментов, касающихся кратких изложений мыслей:

  • Сводки мыслей не регулируются бюджетами мышления (бюджеты применяются только к исходным мыслям модели). Однако, если мышление отключено , модель не будет возвращать сводку мыслей.

  • Краткие изложения мыслей считаются частью обычного текстового ответа, генерируемого моделью, и учитываются как выходные токены.

Включить краткие изложения мыслей

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

Agent

Вы можете включить отображение кратких обзоров мыслей, установив параметр includeThoughts в значение true в конфигурации вашей модели. Затем вы сможете получить доступ к обзору, проверив поле thoughtSummary в ответе.

Вот пример, демонстрирующий, как включить и получить краткие изложения мыслей вместе с ответом:

Быстрый

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(includeThoughts: true)
)

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

let response = try await model.generateContent("solve x^2 + 4x + 4 = 0")

// Handle the response that includes thought summaries.
if let thoughtSummary = response.thoughtSummary {
  print("Thought Summary: \(thoughtSummary)")
}
guard let text = response.text else {
  fatalError("No text in response.")
}
print("Answer: \(text)")

Kotlin

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      includeThoughts = true
  }
}

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

val response = model.generateContent("solve x^2 + 4x + 4 = 0")

// Handle the response that includes thought summaries.
response.thoughtSummary?.let {
    println("Thought Summary: $it")
}
response.text?.let {
    println("Answer: $it")
}

Java

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setIncludeThoughts(true)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

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

// Handle the response that includes thought summaries.
ListenableFuture responseFuture = model.generateContent("solve x^2 + 4x + 4 = 0");
Futures.addCallback(responseFuture, new FutureCallback() {
    @Override
    public void onSuccess(GenerateContentResponse response) {
        if (response.getThoughtSummary() != null) {
            System.out.println("Thought Summary: " + response.getThoughtSummary());
        }
        if (response.getText() != null) {
            System.out.println("Answer: " + response.getText());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        // Handle error
    }
}, MoreExecutors.directExecutor());

Web

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

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

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
const generationConfig = {
  thinkingConfig: {
    includeThoughts: true
  }
};

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

const result = await model.generateContent("solve x^2 + 4x + 4 = 0");
const response = result.response;

// Handle the response that includes thought summaries.
if (response.thoughtSummary()) {
    console.log(`Thought Summary: ${response.thoughtSummary()}`);
}
const text = response.text();
console.log(`Answer: ${text}`);

Dart

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
final thinkingConfig = ThinkingConfig(includeThoughts: true);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

final response = await model.generateContent('solve x^2 + 4x + 4 = 0');

// Handle the response that includes thought summaries.
if (response.thoughtSummary != null) {
  print('Thought Summary: ${response.thoughtSummary}');
}
if (response.text != null) {
  print('Answer: ${response.text}');
}

Единство

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
var thinkingConfig = new ThinkingConfig(includeThoughts: true);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

var response = await model.GenerateContentAsync("solve x^2 + 4x + 4 = 0");

// Handle the response that includes thought summaries.
if (response.ThoughtSummary != null) {
    Debug.Log($"Thought Summary: {response.ThoughtSummary}");
}
if (response.Text != null) {
    Debug.Log($"Answer: {response.Text}");
}

Краткие обзоры мыслей в потоке

Вы также можете просмотреть сводки мыслей, если решите передавать ответ в потоковом режиме с помощью generateContentStream . Это позволит получать скользящие, инкрементальные сводки в процессе генерации ответа.

Быстрый

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(includeThoughts: true)
)

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

let stream = try model.generateContentStream("solve x^2 + 4x + 4 = 0")

// Handle the streamed response that includes thought summaries.
var thoughts = ""
var answer = ""
for try await response in stream {
  if let thought = response.thoughtSummary {
    if thoughts.isEmpty {
      print("--- Thoughts Summary ---")
    }
    print(thought)
    thoughts += thought
  }

  if let text = response.text {
    if answer.isEmpty {
      print("--- Answer ---")
    }
    print(text)
    answer += text
  }
}

Kotlin

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      includeThoughts = true
  }
}

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

// Handle the streamed response that includes thought summaries.
var thoughts = ""
var answer = ""
model.generateContentStream("solve x^2 + 4x + 4 = 0").collect { response ->
    response.thoughtSummary?.let {
        if (thoughts.isEmpty()) {
            println("--- Thoughts Summary ---")
        }
        print(it)
        thoughts += it
    }
    response.text?.let {
        if (answer.isEmpty()) {
            println("--- Answer ---")
        }
        print(it)
        answer += it
    }
}

Java

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setIncludeThoughts(true)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

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

// Streaming with Java is complex and depends on the async library used.
// This is a conceptual example using a reactive stream.
Flowable responseStream = model.generateContentStream("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries
StringBuilder thoughts = new StringBuilder();
StringBuilder answer = new StringBuilder();

responseStream.subscribe(response -> {
    if (response.getThoughtSummary() != null) {
        if (thoughts.length() == 0) {
            System.out.println("--- Thoughts Summary ---");
        }
        System.out.print(response.getThoughtSummary());
        thoughts.append(response.getThoughtSummary());
    }
    if (response.getText() != null) {
        if (answer.length() == 0) {
            System.out.println("--- Answer ---");
        }
        System.out.print(response.getText());
        answer.append(response.getText());
    }
}, throwable -> {
    // Handle error
});

Web

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

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

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
const generationConfig = {
  thinkingConfig: {
    includeThoughts: true
  }
};

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

const result = await model.generateContentStream("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries.
let thoughts = "";
let answer = "";
for await (const chunk of result.stream) {
  if (chunk.thoughtSummary()) {
    if (thoughts === "") {
      console.log("--- Thoughts Summary ---");
    }
    // In Node.js, process.stdout.write(chunk.thoughtSummary()) could be used
    // to avoid extra newlines.
    console.log(chunk.thoughtSummary());
    thoughts += chunk.thoughtSummary();
  }

  const text = chunk.text();
  if (text) {
    if (answer === "") {
      console.log("--- Answer ---");
    }
    // In Node.js, process.stdout.write(text) could be used.
    console.log(text);
    answer += text;
  }
}

Dart

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
final thinkingConfig = ThinkingConfig(includeThoughts: true);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

final responses = model.generateContentStream('solve x^2 + 4x + 4 = 0');

// Handle the streamed response that includes thought summaries.
var thoughts = '';
var answer = '';
await for (final response in responses) {
  if (response.thoughtSummary != null) {
    if (thoughts.isEmpty) {
      print('--- Thoughts Summary ---');
    }
    thoughts += response.thoughtSummary!;
  }
  if (response.text != null) {
    if (answer.isEmpty) {
      print('--- Answer ---');
    }
    answer += response.text!;
  }
}

Единство

Включите отображение кратких изложений мыслей в GenerationConfig при создании экземпляра GenerativeModel .


// ...

// Set the thinking configuration.
// Optionally enable thought summaries in the generated response (default is false).
var thinkingConfig = new ThinkingConfig(includeThoughts: true);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

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

var stream = model.GenerateContentStreamAsync("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries.
var thoughts = "";
var answer = "";
await foreach (var response in stream)
{
    if (response.ThoughtSummary != null)
    {
        if (string.IsNullOrEmpty(thoughts))
        {
            Debug.Log("--- Thoughts Summary ---");
        }
        Debug.Log(response.ThoughtSummary);
        thoughts += response.ThoughtSummary;
    }
    if (response.Text != null)
    {
        if (string.IsNullOrEmpty(answer))
        {
            Debug.Log("--- Answer ---");
        }
        Debug.Log(response.Text);
        answer += response.Text;
    }
}



Мыслительные подписи

При использовании мыслительного процесса в многоходовых взаимодействиях модель не имеет доступа к контексту мыслей из предыдущих ходов. Однако, если вы используете вызов функций , вы можете воспользоваться сигнатурами мыслей для сохранения контекста мыслей между ходами. Сигнатуры мыслей — это зашифрованные представления внутреннего мыслительного процесса модели, и они доступны при использовании мыслительного процесса и вызова функций. В частности, сигнатуры мыслей генерируются, когда:

  • Мышление получает возможность развиваться, и мысли генерируются.
  • Запрос включает объявления функций.

To take advantage of thought signatures, use function calling as normal. The Firebase AI Logic SDKs simplify the process by managing the state and automatically handling thought signatures for you. The SDKs automatically pass any generated thought signatures between subsequent sendMessage or sendMessageStream calls in a Chat session.



Оценка и подсчет жетонов мышления

Токены для размышлений имеют ту же ценовую политику, что и токены для текстового вывода. Если вы включите отображение кратких обзоров мыслей , они будут считаться токенами для размышлений и иметь соответствующую цену.

В консоли Firebase можно включить мониторинг ИИ , чтобы отслеживать количество токенов мышления для запросов, в которых включено мышление.

Общее количество токенов, содержащих мыслительные запросы, можно получить из поля thoughtsTokenCount в атрибуте usageMetadata ответа:

Быстрый

// ...

let response = try await model.generateContent("Why is the sky blue?")

if let usageMetadata = response.usageMetadata {
  print("Thoughts Token Count: \(usageMetadata.thoughtsTokenCount)")
}

Kotlin

// ...

val response = model.generateContent("Why is the sky blue?")

response.usageMetadata?.let { usageMetadata ->
    println("Thoughts Token Count: ${usageMetadata.thoughtsTokenCount}")
}

Java

// ...

ListenableFuture<GenerateContentResponse> response =
    model.generateContent("Why is the sky blue?");

Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String usageMetadata = result.getUsageMetadata();
        if (usageMetadata != null) {
            System.out.println("Thoughts Token Count: " +
                usageMetadata.getThoughtsTokenCount());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

// ...

const response = await model.generateContent("Why is the sky blue?");

if (response?.usageMetadata?.thoughtsTokenCount != null) {
    console.log(`Thoughts Token Count: ${response.usageMetadata.thoughtsTokenCount}`);
}

Dart

// ...

final response = await model.generateContent(
  Content.text("Why is the sky blue?"),
]);

if (response?.usageMetadata case final usageMetadata?) {
  print("Thoughts Token Count: ${usageMetadata.thoughtsTokenCount}");
}

Единство

// ...

var response = await model.GenerateContentAsync("Why is the sky blue?");

if (response.UsageMetadata != null)
{
    UnityEngine.Debug.Log($"Thoughts Token Count: {response.UsageMetadata?.ThoughtsTokenCount}");
}

Подробнее о токенах можно узнать в руководстве по подсчету токенов .