Tutti i modelli Gemini utilizzano un "processo di pensiero" interno che migliora significativamente le loro capacità di ragionamento e pianificazione in più passaggi, rendendoli altamente efficaci per attività complesse come la programmazione, la matematica avanzata e l'analisi dei dati.
I modelli di ragionamento offrono le seguenti configurazioni e opzioni:
Controlla la quantità di ragionamento
Puoi configurare i livelli di ragionamento per controllare quanto "ragionamento" può fare un modello. Questa configurazione è particolarmente importante se la riduzione della latenza o dei costi è una priorità. Inoltre, consulta il confronto delle difficoltà delle attività per decidere quanto un modello potrebbe aver bisogno della sua capacità di ragionamento.Ricevi riepiloghi dei pensieri
Puoi attivare i riepiloghi dei pensieri da includere nella risposta generata. Questi riepiloghi sono versioni sintetizzate dei pensieri non elaborati del modello e offrono insight sul processo di ragionamento interno del modello.Gestisci le firme di pensiero
Gli SDK Firebase AI Logic gestiscono automaticamente le firme di pensiero, il che garantisce che il modello abbia accesso al contesto di pensiero dei turni precedenti, in particolare quando si utilizza la chiamata di funzione.
Assicurati di leggere le best practice e le indicazioni per i prompt per l'utilizzo dei modelli di ragionamento.
Best practice e suggerimenti per i prompt per l'utilizzo dei modelli di ragionamento
Ti consigliamo di testare il prompt in Google AI Studio o Agent Studio dove puoi visualizzare l'intero processo di ragionamento. Puoi identificare le aree in cui il modello potrebbe aver commesso errori, in modo da perfezionare i prompt per ottenere risposte più coerenti e accurate.
Inizia con un prompt generale che descrive il risultato desiderato e osserva i pensieri iniziali del modello su come determina la sua risposta. Se la risposta non è quella prevista, aiuta il modello a generare una risposta migliore utilizzando una delle seguenti tecniche di prompting:
- Fornisci istruzioni passo passo
- Fornisci diversi esempi di coppie input-output
- Fornisci indicazioni su come formulare e formattare l'output e le risposte
- Fornisci passaggi di verifica specifici
Oltre ai prompt, valuta la possibilità di utilizzare questi suggerimenti:
Imposta le istruzioni di sistema, che sono come un "preambolo" che aggiungi prima che il modello venga esposto a ulteriori istruzioni del prompt o dell'utente finale. Ti consentono di indirizzare il comportamento del modello in base alle tue esigenze e ai tuoi casi d'uso specifici.
Imposta un livello di ragionamento per controllare quanto può ragionare il modello. Se lo imposti su un valore elevato, il modello può ragionare di più, se necessario. Se imposti un valore inferiore, il modello non "penserà troppo" alla risposta e riserverà anche una parte maggiore del limite totale di token di output per la risposta effettiva, il che può contribuire a ridurre la latenza e i costi.
Attiva il monitoraggio AI nella console Firebase per monitorare il numero di token di ragionamento e la latenza delle tue richieste con il ragionamento abilitato. Se hai attivato i riepiloghi dei pensieri, questi verranno visualizzati nella console, dove potrai esaminare il ragionamento dettagliato del modello per aiutarti a eseguire il debug e perfezionare i prompt.
Controlla la quantità di ragionamento
Puoi configurare i livelli di ragionamento per controllare quanto "ragionamento" può fare un modello prima di restituire una risposta. Questa configurazione è particolarmente importante se la riduzione della latenza o dei costi è una priorità.
Assicurati di esaminare il confronto delle difficoltà delle attività per decidere quanto un modello potrebbe aver bisogno della sua capacità di ragionamento. Ecco alcune indicazioni generali:
- Imposta un valore di ragionamento inferiore per le attività meno complesse o se la riduzione della latenza o dei costi è una priorità per te.
- Imposta un valore di ragionamento più alto per le attività più complesse.
Livelli di ragionamento
Per controllare quanto ragionamento può fare un modello per generare la sua risposta, puoi specificare un livello di ragionamento per la quantità di token di ragionamento che può utilizzare.
Imposta il livello di ragionamento
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Imposta il livello di pensiero in un GenerationConfig durante la creazione dell'istanza GenerativeModel. La configurazione viene mantenuta per tutta la durata dell'istanza. Se vuoi utilizzare livelli di ragionamento diversi per richieste diverse, crea istanze GenerativeModel configurate con ciascun livello.
Scopri di più sui valori supportati per il livello di ragionamento più avanti in questa sezione.
Swift
Imposta il livello di ragionamento in un
GenerationConfig
durante la creazione di un'istanza 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
Imposta i valori dei parametri in un
GenerationConfig
durante la creazione di un'istanza 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
Imposta i valori dei parametri in un
GenerationConfig
durante la creazione di un'istanza 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
Imposta i valori dei parametri in un
GenerationConfig
durante la creazione di un'istanza 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
Imposta i valori dei parametri in un
GenerationConfig
durante la creazione di un'istanza 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
Imposta i valori dei parametri in un
GenerationConfig
durante la creazione di un'istanza 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
);
// ...
Valori del livello di ragionamento supportati
La seguente tabella elenca i valori del livello di ragionamento che puoi impostare per ogni modello configurando il thinkingLevel del modello.
MINIMAL |
LOW |
MEDIUM |
HIGH |
|
|---|---|---|---|---|
|
Il modello utilizza il minor numero possibile di token; quasi nessun pensiero Attività a bassa complessità |
Il modello utilizza meno token; riduce al minimo la latenza e i costi Attività semplici e attività con throughput elevato |
Il modello utilizza un approccio equilibrato Attività di complessità moderata |
Il modello utilizza i token fino al livello massimo Prompt complessi che richiedono un ragionamento approfondito |
|
Gemini 4 Argongemini-4-argon
|
1 | (valore predefinito) | ||
Gemini 3.x Progemini-3.1-pro-preview
|
(valore predefinito) | |||
Gemini 3.x Flashgemini-3.8-flashgemini-3.7-flashgemini-3.6-flashgemini-3.5-flash
|
non supportato da gemini-3.8-flashgemini-3.7-flash |
(valore predefinito) | ||
Gemini 3.x Flash‑Litegemini-3.5-flash-litegemini-3.1-flash-lite
|
(valore predefinito) | |||
Gemini Nano Banana 2.1gemini-nano-banana-2.1
|
(valore predefinito) | |||
Gemini Nano Banana 2gemini-3.1-flash-image |
(valore predefinito) | |||
Gemini Nano Banana 2 Litegemini-3.1-flash-lite-image |
(valore predefinito) | |||
Gemini Nano Banana Progemini-3-pro-image
|
(valore predefinito) |
1 gemini-4-argon, gemini-3.8-flash
e gemini-3.7-flash non supportano il
livello di ragionamento MINIMAL. Se imposti il livello di ragionamento su
MINIMAL, la richiesta non andrà a buon fine e restituirà un errore 400.
Budget di pensiero (Gemini 2.5 modelli)
Per controllare la quantità di ragionamento che un modello Gemini 2.5 può eseguire per generare la sua risposta, puoi specificare un budget di ragionamento per la quantità di token di ragionamento che può utilizzare.
Complessità delle attività per tutti i modelli di ragionamento
Attività semplici: non è necessario pensare
Richieste semplici che non richiedono un ragionamento complesso, come il recupero di informazioni o la classificazione. Esempi:- "Dove è stata fondata DeepMind?"
- "Questa email richiede una riunione o fornisce solo informazioni?"
Attività moderate: è probabile che sia necessario un po' di ragionamento
Richieste comuni che traggono vantaggio da un certo livello di elaborazione passo passo o da una comprensione più approfondita. Esempi:- "Crea un'analogia tra la fotosintesi e la crescita."
- "Confronta e contrapponi le auto elettriche e le auto ibride."
Attività difficili: potrebbe essere necessario il massimo livello di ragionamento
Sfide davvero complesse, come la risoluzione di problemi matematici complessi o attività di programmazione. Questi tipi di attività richiedono al modello di utilizzare tutte le sue capacità di ragionamento e pianificazione, spesso coinvolgendo molti passaggi interni prima di fornire una risposta. Esempi:- "Risolvi il problema 1 di AIME 2025: trova la somma di tutte le basi intere b > 9 per cui 17b è un divisore di 97b."
- "Scrivi il codice Python per un'applicazione web che visualizza i dati del mercato azionario in tempo reale, inclusa l'autenticazione utente. Rendilo il più efficiente possibile."
Riepiloghi del pensiero
I riepiloghi dei pensieri sono versioni sintetizzate dei pensieri non elaborati del modello e offrono informazioni sul processo di ragionamento interno del modello.
Ecco alcuni motivi per includere i riepiloghi dei ragionamenti nelle risposte:
Puoi visualizzare il riepilogo dei pensieri nell'interfaccia utente della tua app o renderlo accessibile ai tuoi utenti. Il riepilogo del ragionamento viene restituito come parte separata nella risposta, in modo da darti un maggiore controllo su come viene utilizzato nella tua app.
Se attivi anche il monitoraggio AI nella console Firebase, i riepiloghi dei pensieri vengono visualizzati nella console, dove puoi esaminare il ragionamento dettagliato del modello per aiutarti a eseguire il debug e perfezionare i prompt.
Ecco alcune note chiave sui riepiloghi dei pensieri:
I riepiloghi dei ragionamenti non sono controllati dai budget di ragionamento (i budget si applicano solo ai ragionamenti grezzi del modello). Tuttavia, se il ragionamento è disattivato, il modello non restituirà un riepilogo del ragionamento.
I riepiloghi dei pensieri sono considerati parte della normale risposta di testo generato dal modello e vengono conteggiati come token di output.
Abilita i riepiloghi dei pensieri
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Puoi attivare i riepiloghi dei pensieri impostando includeThoughts su true nella configurazione del modello. Puoi quindi accedere al riepilogo controllando il campo thoughtSummary della risposta.
Ecco un esempio che mostra come attivare e recuperare i riepiloghi dei pensieri con la risposta:
Swift
Abilita i riepiloghi dei pensieri in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi dei pensieri in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi dei pensieri in GenerationConfig nell'ambito della creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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}");
}
Riepiloghi del pensiero in streaming
Puoi anche visualizzare i riepiloghi dei pensieri se scegli di trasmettere in streaming una risposta utilizzando
generateContentStream. In questo modo, verranno restituiti riepiloghi incrementali e continui durante la generazione della risposta.
Swift
Abilita i riepiloghi dei pensieri in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi dei pensieri in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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
Abilita i riepiloghi dei pensieri in GenerationConfig nell'ambito della creazione di un'istanza 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
Abilita i riepiloghi del pensiero in
GenerationConfig
durante la creazione di un'istanza 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;
}
}
Firme del pensiero
Quando utilizzi il ragionamento nelle interazioni a più turni, il modello non ha accesso al contesto del ragionamento dei turni precedenti. Tuttavia, se utilizzi la chiamata di funzione, puoi sfruttare le firme di pensiero per mantenere il contesto del pensiero tra i turni. Le firme di pensiero sono rappresentazioni criptate del processo di pensiero interno del modello e sono disponibili quando si utilizzano il ragionamento e la chiamata di funzione. In particolare, le firme dei pensieri vengono generate quando:
- Il ragionamento è abilitato e i pensieri vengono generati.
- La richiesta include dichiarazioni di funzione.
Per sfruttare le firme di pensiero, utilizza la chiamata di funzione come di consueto.
Gli SDK Firebase AI Logic semplificano il processo gestendo lo stato e gestendo automaticamente le firme dei pensieri. Gli SDK passano automaticamente
le firme di pensiero generate tra le chiamate sendMessage o
sendMessageStream successive in una sessione Chat.
Prezzi e conteggio dei token di ragionamento
I token di ragionamento utilizzano gli stessi prezzi dei token di output di testo. Se attivi i riepiloghi dei pensieri, questi vengono considerati token di ragionamento e il loro prezzo viene calcolato di conseguenza.
Puoi attivare il monitoraggio AI nella console Firebase per monitorare il conteggio dei token di ragionamento per le richieste con il ragionamento abilitato.
Puoi ottenere il numero totale di token di ragionamento dal campo thoughtsTokenCount
nell'attributo usageMetadata della risposta:
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}");
}
Scopri di più sui token nella guida al conteggio dei token.