Os modelos Gemini 2.5 podem usar um "processo de pensamento" interno que melhora significativamente as habilidades de raciocínio e planejamento de várias etapas, tornando-os altamente eficazes para tarefas complexas, como programação, matemática avançada e análise de dados.
Os modelos de pensamento oferecem as seguintes configurações e opções:
Orçamento de pensamento: você pode configurar o quanto um modelo pode "pensar" usando um orçamento de pensamento. Essa configuração é especialmente importante se a prioridade for reduzir a latência ou o custo. Além disso, confira a comparação de dificuldades das tarefas para decidir o quanto um modelo pode precisar da capacidade de raciocínio.
Resumos de ideias: você pode ativar os resumos de ideias para incluir na resposta gerada. Esses resumos são versões sintetizadas dos pensamentos brutos do modelo e oferecem insights sobre o processo de raciocínio interno dele.
Assinaturas de pensamento: os SDKs do Firebase AI Logic processam automaticamente as assinaturas de pensamento para você, o que garante que o modelo tenha acesso ao contexto de pensamento de interações anteriores, principalmente ao usar a chamada de função.
Confira as práticas recomendadas e orientações de comandos para usar modelos de pensamento.
Usar um modelo de pensamento
Use um modelo de pensamento da mesma forma que usaria qualquer outro modelo Gemini
(inicialize o provedor Gemini API escolhido, crie uma instância GenerativeModel
etc.).
Esses modelos podem ser usados para tarefas de geração de texto ou código, como
gerar saída estruturada
ou analisar entrada multimodal (como
imagens,
vídeo,
áudio,
ou
PDFs).
Você pode até usar modelos de pensamento ao transmitir a saída.
Modelos compatíveis com esse recurso
Apenas os modelos Gemini 2.5 são compatíveis com essa capacidade.
gemini-2.5-pro
gemini-2.5-flash
gemini-2.5-flash-lite
Práticas recomendadas e orientações de comandos para usar modelos de pensamento
Recomendamos testar o comando no Google AI Studio ou no Vertex AI Studio para conferir todo o processo de raciocínio. Você pode identificar áreas em que o modelo pode ter se desviado para refinar seus comandos e receber respostas mais consistentes e precisas.
Comece com um comando geral que descreva o resultado desejado e observe os primeiros pensamentos do modelo sobre como ele determina a resposta. Se a resposta não for o esperado, ajude o modelo a gerar uma resposta melhor usando uma das seguintes técnicas de comando:
- Fornecer instruções detalhadas
- Forneça vários exemplos de pares de entrada e saída
- Forneça orientações sobre como a saída e as respostas devem ser formuladas e formatadas.
- Fornecer etapas específicas de verificação
Além de comandos, considere usar estas recomendações:
Defina instruções do sistema, que são como um "preâmbulo" que você adiciona antes que o modelo seja exposto a outras instruções do comando ou do usuário final. Elas permitem orientar o comportamento do modelo com base nas suas necessidades e casos de uso específicos.
Defina um orçamento de pensamento para configurar o quanto o modelo pode pensar. Se você definir um orçamento baixo, o modelo não vai "pensar demais" na resposta. Se você definir um orçamento alto, o modelo poderá pensar mais, se necessário. Definir um orçamento de pensamento também reserva mais do limite total de saída de tokens para a resposta real.
Ative o monitoramento de IA no console do Firebase para monitorar a contagem de tokens de pensamento e a latência das suas solicitações que têm o pensamento ativado. Se você tiver os resumos de ideias ativados, eles vão aparecer no console, onde é possível inspecionar o raciocínio detalhado do modelo para ajudar a depurar e refinar seus comandos.
Controlar o orçamento de pensamento
Para controlar o quanto o modelo pode pensar para gerar uma resposta, especifique o número de tokens de orçamento de pensamento que ele pode usar.
Você pode definir manualmente o orçamento de pensamento em situações em que precisar de mais ou menos tokens do que o padrão. Confira orientações mais detalhadas sobre complexidade da tarefa e orçamentos sugeridos mais adiante nesta seção. Confira algumas orientações gerais:
- Defina um orçamento de pensamento baixo se a latência for importante ou para tarefas menos complexas
- Definir um orçamento de pensamento alto para tarefas mais complexas
Definir o orçamento de pensamento
Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página. |
Defina o orçamento de pensamento em um GenerationConfig
como parte da criação da instância GenerativeModel
. A configuração é mantida durante todo o ciclo de vida da instância. Se você quiser usar orçamentos de pensamento diferentes para solicitações diferentes, crie instâncias GenerativeModel
configuradas com cada orçamento.
Saiba mais sobre os valores de orçamento de pensamento compatíveis nesta seção.
Swift
Defina o orçamento de pensamento em um
GenerationConfig
como parte da criação de uma instância 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_MODEL_NAME",
generationConfig: generationConfig
)
// ...
Kotlin
Defina os valores dos parâmetros em um
GenerationConfig
como parte da criação de uma instância 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_MODEL_NAME",
generationConfig,
)
// ...
Java
Defina os valores dos parâmetros em um
GenerationConfig
como parte da criação de uma instância 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_MODEL_NAME",
/* generationConfig */ generationConfig
);
);
// ...
Web
Defina os valores dos parâmetros em um
GenerationConfig
como parte da criação de uma instância 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_MODEL_NAME", generationConfig });
// ...
Dart
Defina os valores dos parâmetros em um
GenerationConfig
como parte da criação de uma instância GenerativeModel
.
// ...
// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
final thinkingConfig = ThinkingConfig(thinkingBudget: 1024);
final generationConfig = GenerationConfig(
thinkingConfig: thinkingConfig
);
// Specify the config as part of creating the `GenerativeModel` instance
final model = FirebaseAI.googleAI().generativeModel(
model: 'GEMINI_MODEL_NAME',
config: generationConfig,
);
// ...
Unity
Defina os valores dos parâmetros em um
GenerationConfig
como parte da criação de uma instância 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_MODEL_NAME",
generationConfig: generationConfig
);
// ...
Valores de limite de orçamento de pensamento aceitos
A tabela a seguir lista os valores de orçamento de pensamento que podem ser definidos para cada modelo ao configurar o thinkingBudget
do modelo.
Modelo | Valor padrão | Intervalo disponível para o orçamento de pensamento |
Valor para desativar o pensamento |
Valor para ativar o pensamento dinâmico |
|
---|---|---|---|---|---|
Valor mínimo | Valor máximo | ||||
Gemini 2.5 Pro | 8,192 |
128 |
32,768 |
não pode ser desativado | -1 |
Gemini 2.5 Flash | 8,192 |
1 |
24,576 |
0 |
-1 |
Gemini 2.5 Flash‑Lite | 0 (o pensamento está desativado por padrão) |
512 |
24,576 |
0 (ou não configure o orçamento de pensamento) |
-1 |
Desativar raciocínio
Para algumas tarefas mais fáceis, a capacidade de raciocínio não é necessária, e a inferência tradicional é suficiente. Ou, se reduzir a latência for uma prioridade, talvez você não queira que o modelo leve mais tempo do que o necessário para gerar uma resposta.
Nessas situações, você pode desativar (ou desligar) o pensamento:
- Gemini 2.5 Pro: o pensamento não pode ser desativado
- Gemini 2.5 Flash: defina
thinkingBudget
como0
tokens - Gemini 2.5 Flash‑Lite: o pensamento está desativado por padrão
Incentivar o pensamento dinâmico
Você pode deixar o modelo decidir quando e quanto ele pensa (chamado de
pensamento dinâmico) definindo thinkingBudget
como -1
. O modelo pode usar quantos tokens achar adequado, até o valor máximo listado acima.
Complexidade da tarefa
Tarefas fáceis: o pensamento pode ser desligado
Solicitações simples em que não é necessário um raciocínio complexo, como recuperação ou classificação de fatos. Exemplos:- "Onde a DeepMind foi fundada?"
- "Este e-mail está pedindo uma reunião ou apenas fornecendo informações?"
Tarefas médias: orçamento padrão ou algum orçamento adicional de reflexão necessário
Solicitações comuns que se beneficiam de um grau de processamento gradual ou compreensão mais profunda. Exemplos:- "Crie uma analogia entre a fotossíntese e o crescimento."
- "Compare e contraste carros elétricos e híbridos."
Tarefas difíceis: pode ser necessário um orçamento máximo de pensamento
Desafios realmente complexos, como resolver problemas de matemática complexos ou tarefas de programação. Esses tipos de tarefas exigem que o modelo use todas as suas capacidades de raciocínio e planejamento, muitas vezes envolvendo várias etapas internas antes de fornecer uma resposta. Exemplos:- "Resolva o problema 1 da AIME 2025: encontre a soma de todas as bases inteiras b > 9 para as quais 17b é um divisor de 97b."
- "Escreva um código Python para um aplicativo da Web que visualize dados do mercado de ações em tempo real, incluindo autenticação de usuários. Faça com que seja o mais eficiente possível."
Incluir resumos de pensamento nas respostas
Os resumos de ideias são versões sintetizadas dos pensamentos brutos do modelo e oferecem insights sobre o processo de raciocínio interno dele.
Confira alguns motivos para incluir resumos de pensamento nas respostas:
Você pode mostrar o resumo de ideias na interface do seu app ou disponibilizá-lo para os usuários. O resumo é retornado como uma parte separada na resposta para que você tenha mais controle sobre como ele é usado no seu app.
Se você também ativar o monitoramento de IA no console do Firebase, os resumos de ideias vão aparecer no console, onde você pode inspecionar o raciocínio detalhado do modelo para ajudar a depurar e refinar seus comandos.
Confira algumas observações importantes sobre os resumos de ideias:
Os resumos de pensamento não são controlados por orçamentos de pensamento (os orçamentos se aplicam apenas aos pensamentos brutos do modelo). No entanto, se o pensamento estiver desativado, o modelo não vai retornar um resumo.
Os resumos de ideias são considerados parte da resposta regular de texto gerado do modelo e contam como tokens de saída.
Ativar resumos de ideias
Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página. |
Para ativar os resumos de ideias, defina includeThoughts
como "true" na configuração do modelo. Para acessar o resumo, verifique o campo
thoughtSummary
na resposta.
Confira um exemplo de como ativar e recuperar resumos de ideias com a resposta:
Swift
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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}');
}
Unity
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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}");
}
Resumos de pensamento em streaming
Você também pode ver resumos de ideias se escolher transmitir uma resposta usando
generateContentStream
. Isso vai retornar resumos incrementais e contínuos durante
a geração da resposta.
Swift
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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!;
}
}
Unity
Ative os resumos de ideias no
GenerationConfig
ao criar uma instância do 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;
}
}
Entender as assinaturas de pensamento
Ao usar o pensamento em interações de várias interações, o modelo não tem acesso ao contexto de pensamento de interações anteriores. No entanto, se você estiver usando a chamada de função, poderá aproveitar as assinaturas de pensamento para manter o contexto do pensamento em várias interações. As assinaturas de pensamento são representações criptografadas do processo de pensamento interno do modelo e estão disponíveis ao usar a chamada de função de pensamento e. Especificamente, as assinaturas de pensamento são geradas quando:
- O recurso de pensamento está ativado e as ideias são geradas.
- A solicitação inclui declarações de função.
Para aproveitar as assinaturas de pensamento, use a chamada de função normalmente.
Os SDKs do Firebase AI Logic simplificam o processo gerenciando o estado e processando automaticamente as assinaturas de pensamento para você. Os SDKs transmitem automaticamente todas as assinaturas de pensamento geradas entre as chamadas subsequentes de sendMessage
ou sendMessageStream
em uma sessão Chat
.
Preços e contagem de tokens de pensamento
Os tokens de pensamento usam a mesma tabela de preços dos tokens de saída de texto. Se você ativar os resumos de ideias, eles serão considerados tokens de pensamento e terão o preço adequado.
É possível ativar o monitoramento de IA no console do Firebase para monitorar a contagem de tokens de pensamento em solicitações que têm esse recurso ativado.
Você pode receber o número total de tokens de pensamento do campo thoughtsTokenCount
no atributo usageMetadata
da resposta:
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}");
}
Saiba mais sobre tokens no guia de contagem de tokens.