Думающая

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

Для моделей рассуждения доступны следующие конфигурации и параметры:

  • Управление объемом рассуждений
    Вы можете настроить уровни рассуждений, чтобы контролировать, сколько "думает" модель. Эта настройка особенно важна, если для вас приоритетно сокращение задержки или расходов. Также ознакомьтесь со сравнением сложности задач, чтобы решить, насколько модели может понадобиться способность рассуждать.

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

  • Обработка подписей мыслей
    SDK Firebase AI Logic автоматически обрабатывают подписи мыслей, чтобы у модели был доступ к контексту мыслей из предыдущих шагов, особенно при вызове функций.

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



Рекомендации и советы по созданию запросов для моделей с рассуждением

Рекомендуем протестировать запрос в Google AI Studio или Agent  Studio, где можно посмотреть весь процесс рассуждения. Вы можете определить области, в которых модель могла ошибиться, и уточнить свои запросы, чтобы получить более последовательные и точные ответы.

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

  • Предоставим вам пошаговые инструкции по работе с функцией.
  • Предоставьте несколько примеров пар входных и выходных данных.
  • Укажите, как должны быть сформулированы и отформатированы выходные данные и ответы.
  • Предоставьте подробные инструкции по проверке

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

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

  • Задайте уровень мышления, чтобы контролировать, сколько времени модель может тратить на рассуждения. Если вы установите высокий уровень, модель сможет думать дольше, когда это необходимо. Если вы установите меньшее значение, модель не будет "слишком долго думать" над ответом, а также зарезервирует большее количество токенов для фактического ответа, что может помочь снизить задержку и стоимость.

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



Управляйте временем на размышление

Вы можете настроить уровни рассуждения, чтобы контролировать, сколько времени модель тратит на рассуждения, прежде чем дать ответ. Такая конфигурация особенно важна, если приоритетом является снижение задержки или стоимости.

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

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

Уровни мышления

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

Как настроить уровень рассуждений

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

Задайте уровень мышления в GenerationConfig при создании экземпляра GenerativeModel. Конфигурация сохраняется в течение всего времени существования экземпляра. Если вы хотите использовать разные уровни рассуждения для разных запросов, создайте экземпляры GenerativeModel, настроенные для каждого уровня.

Подробнее о поддерживаемых значениях для уровня мышления…

Swift

Задайте уровень рассуждений в 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',
  generationConfig: generationConfig,
);

// ...

Unity

Задайте значения параметров в 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 4 Argon
gemini-4-argon
1 (по умолчанию)
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 Nano Banana 2.1
gemini-nano-banana-2.1
(по умолчанию)
Gemini Nano Banana 2
gemini-3.1-flash-image
(по умолчанию)
Gemini Nano Banana 2 Lite
gemini-3.1-flash-lite-image
(по умолчанию)
Gemini Nano Banana Pro
gemini-3-pro-image
(по умолчанию)

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



Модели мышления Gemini 2.5

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



Сложность задач для всех думающих моделей

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

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

    • "Проведи аналогию между фотосинтезом и взрослением".
    • «Сравните электромобили и гибридные автомобили».
  • Сложные задачи – может потребоваться максимальное время на размышление
    По-настоящему сложные задачи, например решение сложных математических задач или написание кода. Для выполнения таких задач модели необходимо задействовать все свои возможности рассуждения и планирования, что часто включает множество внутренних шагов перед предоставлением ответа. Примеры:

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



Краткие пересказы рассуждений

Сводки рассуждений – это обобщенные версии необработанных рассуждений модели, которые дают представление о ее внутреннем процессе мышления.

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

  • Вы можете показывать краткий пересказ рассуждений в интерфейсе приложения или сделать его доступным для пользователей. Краткое изложение мыслей возвращается в ответе как отдельная часть, чтобы вы могли лучше контролировать, как оно используется в вашем приложении.

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

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

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

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

Включить сводки мыслей

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

Чтобы включить краткий пересказ мыслей, задайте для параметра includeThoughts значение true в конфигурации модели. После этого вы сможете получить доступ к сводке, проверив поле thoughtSummary в ответе.

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

Swift

Включите краткие пересказы мыслей в 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([Content.text('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}');
}

Unity

Включите краткие пересказы мыслей в 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. В этом случае во время генерации ответа будут возвращаться скользящие дополнительные сводки.

Swift

Включите краткие пересказы мыслей в 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([Content.text('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!;
  }
}

Unity

Включите краткие пересказы мыслей в 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;
    }
}



Подписи мыслей

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

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

Чтобы воспользоваться преимуществами подписей мыслей, используйте вызов функций как обычно. SDK Firebase AI Logic упрощают этот процесс, управляя состоянием и автоматически обрабатывая подписи мыслей. SDK автоматически передают все сгенерированные подписи мыслей между последующими вызовами sendMessage или sendMessageStream в сеансе Chat.



Цены и подсчет токенов мышления

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

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

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

Swift

// ...

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}");
}

Unity

// ...

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

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

Подробнее о токенах рассказывается в руководстве по подсчету токенов.