Gemini 3 i Gemini 2.5 mogą korzystać z wewnętrznego „procesu myślowego”, który znacznie poprawia ich zdolności do rozumowania i planowania wieloetapowego, dzięki czemu są bardzo skuteczne w przypadku złożonych zadań, takich jak kodowanie, zaawansowana matematyka i analiza danych.
Modele myślowe oferują te konfiguracje i opcje:
Kontrolowanie ilości „myślenia”
Możesz skonfigurować, ile „myślenia” może wykonać model. Ta konfiguracja jest szczególnie ważna, jeśli priorytetem jest zmniejszenie opóźnienia lub kosztów. Zapoznaj się też z porównaniem trudności zadań, aby określić, w jakim stopniu model może potrzebować funkcji myślenia.Możesz kontrolować tę konfigurację za pomocą poziomów myślenia (modele Gemini 3 i nowsze) lub budżetów myślenia (modele Gemini 2.5).
Uzyskiwanie podsumowań myśli
Możesz włączyć podsumowania myśli, aby dołączać je do wygenerowanej odpowiedzi. Te podsumowania to zsyntetyzowane wersje surowych przemyśleń modelu, które pozwalają zrozumieć jego wewnętrzny proces rozumowania.Obsługa sygnatur myśli
Pakiety Firebase AI Logic SDK automatycznie obsługują sygnatury myśli, co zapewnia modelowi dostęp do kontekstu myśli z poprzednich tur, zwłaszcza podczas korzystania z wywoływania funkcji.
Zapoznaj się ze sprawdzonymi metodami i wskazówkami dotyczącymi promptów w przypadku korzystania z modeli myślowych.
Używanie modelu myślowego
Używaj modelu myślącego tak samo jak każdego innego modelu Gemini.
Aby w pełni wykorzystać potencjał modeli myślowych, zapoznaj się z sekcją Sprawdzone metody i wskazówki dotyczące promptów w przypadku modeli myślowych na tej stronie.
Modele obsługujące tę funkcję
Ta funkcja jest obsługiwana tylko przez modele Gemini 3 i Gemini 2.5.
gemini-3-pro-previewgemini-3-pro-image-preview(znany też jako „nano banana pro”)gemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Sprawdzone metody i wskazówki dotyczące promptów w przypadku korzystania z modeli myślowych
Zalecamy przetestowanie promptu w Google AI Studio lub Vertex AI Studio, gdzie możesz zobaczyć cały proces myślowy. Możesz zidentyfikować obszary, w których model mógł się pomylić, aby dopracować prompty i uzyskiwać bardziej spójne i dokładne odpowiedzi.
Zacznij od ogólnego prompta opisującego oczekiwany wynik i obserwuj wstępne przemyślenia modelu na temat tego, jak określa on odpowiedź. Jeśli odpowiedź nie jest zgodna z oczekiwaniami, pomóż modelowi wygenerować lepszą odpowiedź, korzystając z jednej z tych technik promptowania:
- podamy szczegółowe instrukcje;
- Podaj kilka przykładów par danych wejściowych i wyjściowych.
- Podaj wskazówki dotyczące sformułowania i formatowania danych wyjściowych oraz odpowiedzi.
- Podaj konkretne kroki weryfikacji
Oprócz promptów możesz też skorzystać z tych rekomendacji:
Ustaw instrukcje systemowe, które są jak „wstęp” dodawany przed tym, jak model zostanie poddany dalszym instrukcjom z promptu lub użytkownika końcowego. Pozwalają one sterować działaniem modelu w zależności od konkretnych potrzeb i przypadków użycia.
Ustaw poziom myślenia (lub budżet na myślenie w przypadku modeli Gemini 2.5), aby kontrolować, ile czasu model może poświęcić na myślenie. Jeśli ustawisz wysoki poziom, model będzie mógł w razie potrzeby dłużej myśleć. Jeśli ustawisz niższą wartość, model nie będzie „zbyt długo” zastanawiać się nad odpowiedzią, a także zarezerwuje więcej tokenów z całkowitego limitu na rzeczywistą odpowiedź, co może pomóc zmniejszyć opóźnienia i koszty.
Włącz monitorowanie AI w Firebasekonsoli, aby śledzić liczbę tokenów przetwarzania i opóźnienie żądań, w których włączono przetwarzanie. Jeśli masz włączone podsumowania myśli, będą one wyświetlane w konsoli, w której możesz sprawdzić szczegółowe uzasadnienie modelu, aby debugować i dopracowywać prompty.
Kontrolowanie ilości myślenia
Możesz skonfigurować, ile „myślenia” i wyciągania wniosków może wykonać model, zanim zwróci odpowiedź. Ta konfiguracja jest szczególnie ważna, jeśli priorytetem jest zmniejszenie opóźnienia lub kosztów.
Zapoznaj się z porównaniem trudności zadań, aby określić, w jakim stopniu model może potrzebować funkcji myślenia. Oto kilka ogólnych wskazówek:
- Ustaw niższą wartość myślenia w przypadku mniej złożonych zadań lub jeśli priorytetem jest dla Ciebie skrócenie czasu oczekiwania lub obniżenie kosztów.
- Ustaw wyższą wartość myślenia w przypadku bardziej złożonych zadań.
Możesz kontrolować tę konfigurację za pomocą poziomów myślenia (modele Gemini 3 i nowsze) lub budżetów myślenia (modele Gemini 2.5).
Poziomy myślenia (Gemini 3 modeli)
Aby kontrolować, ile czasu model Gemini 3 może poświęcić na myślenie w celu wygenerowania odpowiedzi, możesz określić poziom myślenia, czyli liczbę tokenów myślenia, których może użyć.
Ustawianie poziomu myślenia
|
Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod specyficzne dla tego dostawcy. |
Ustaw poziom myślenia w GenerationConfig podczas tworzenia instancji GenerativeModel dla modelu Gemini 3. Konfiguracja jest utrzymywana przez cały okres istnienia instancji. Jeśli chcesz używać różnych poziomów myślenia w przypadku różnych żądań, utwórz GenerativeModel instancje
skonfigurowane z każdym poziomem.
Więcej informacji o obsługiwanych wartościach poziomu myślenia znajdziesz w dalszej części tej sekcji.
Swift
Ustaw poziom myślenia w GenerationConfig podczas tworzenia instancji 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_MODEL_NAME",
generationConfig: generationConfig
)
// ...
Kotlin
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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_MODEL_NAME",
generationConfig,
)
// ...
Java
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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_MODEL_NAME",
/* generationConfig */ generationConfig
);
);
// ...
Web
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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_MODEL_NAME", generationConfig });
// ...
Dart
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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_MODEL_NAME',
config: generationConfig,
);
// ...
Unity
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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_MODEL_NAME",
generationConfig: generationConfig
);
// ...
Obsługiwane wartości poziomu myślenia
W tabeli poniżej znajdziesz wartości poziomu myślenia, które możesz ustawić dla każdego modelu, konfigurując jego thinkingLevel.
MINIMAL |
LOW |
MEDIUM |
HIGH |
|
|---|---|---|---|---|
|
|
|
|
|
| Gemini 3 Pro | (domyślnie) | |||
| Gemini 3 Pro Image („nano banana pro”) | (domyślnie) | |||
| Gemini 3 Flash | (domyślnie) |
Budżety na myślenie (modele Gemini 2.5)
Aby kontrolować, ile czasu Gemini 2.5 może poświęcić na myślenie w celu wygenerowania odpowiedzi, możesz określić budżet na myślenie, czyli liczbę tokenów, których może użyć.
Ustawianie budżetu na myślenie
|
Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod specyficzne dla tego dostawcy. |
Ustaw budżet na myślenie w GenerationConfig podczas tworzenia instancji GenerativeModel dla modelu Gemini 2.5. Konfiguracja jest utrzymywana przez cały okres istnienia instancji. Jeśli chcesz używać różnych budżetów na potrzeby różnych żądań, utwórz GenerativeModel instancje skonfigurowane z poszczególnymi budżetami.
Więcej informacji o obsługiwanych wartościach budżetu na myślenie znajdziesz w dalszej części tej sekcji.
Swift
Ustaw budżet na myślenie w GenerationConfig podczas tworzenia instancji 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
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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,
);
// ...
Unity
Ustaw wartości parametrów w sekcji GenerationConfig podczas tworzenia instancji 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
);
// ...
Obsługiwane wartości budżetu na myślenie
W tabeli poniżej znajdziesz wartości budżetu na myślenie, które możesz ustawić dla każdego modelu, konfigurując thinkingBudget modelu.
| Model | Wartość domyślna | Dostępny zakres budżetu na myślenie |
Wartość, która wyłącza myślenie |
Wartość, która włącza dynamiczne myślenie |
|
|---|---|---|---|---|---|
| Wartość minimalna | Wartość maksymalna | ||||
| Gemini 2.5 Pro | 8,192 |
128 |
32,768 |
Nie można wyłączyć | -1 |
| Gemini 2.5 Flash | 8,192 |
1 |
24,576 |
0 |
-1 |
| Gemini 2.5 Flash‑Lite | 0(myślenie jest domyślnie wyłączone) |
512 |
24,576 |
0(lub w ogóle nie konfiguruj budżetu na myślenie) |
-1 |
Złożoność zadań dla wszystkich modeli myślących
Proste zadania – myślenie nie jest tak konieczne
Proste prośby, które nie wymagają złożonego rozumowania, np. wyszukiwanie faktów lub klasyfikacja. Przykłady:- „Gdzie powstała firma DeepMind?”
- „Czy ten e-mail zawiera prośbę o spotkanie, czy tylko informacje?”
Umiarkowane zadania – wymagają pewnego zastanowienia
Typowe żądania, które wymagają pewnego stopnia przetwarzania krok po kroku lub głębszego zrozumienia. Przykłady:- „Utwórz analogię między fotosyntezą a dorastaniem”.
- „Porównaj samochody elektryczne i hybrydowe”.
Trudne zadania – może być konieczne maksymalne zaangażowanie myślowe
Naprawdę złożone wyzwania, takie jak rozwiązywanie skomplikowanych zadań matematycznych lub pisanie kodu. Tego typu zadania wymagają od modelu pełnego zaangażowania możliwości rozumowania i planowania, często obejmują wiele wewnętrznych kroków, zanim zostanie udzielona odpowiedź. Przykłady:- „Rozwiąż zadanie 1 z AIME 2025: znajdź sumę wszystkich podstaw całkowitych b > 9, dla których 17b jest dzielnikiem 97b”.
- „Napisz kod w Pythonie dla aplikacji internetowej, która wizualizuje dane z rynku akcji w czasie rzeczywistym, w tym uwierzytelnianie użytkowników. Zadbaj o jak największą wydajność”.
Podsumowania przemyśleń
Podsumowania myśli to zsyntetyzowane wersje surowych myśli modelu, które dostarczają informacji o wewnętrznym procesie rozumowania modelu.
Oto kilka powodów, dla których warto uwzględniać podsumowania myśli w odpowiedziach:
Podsumowanie przemyśleń możesz wyświetlać w interfejsie aplikacji lub udostępniać użytkownikom. Podsumowanie myśli jest zwracane jako osobna część odpowiedzi, dzięki czemu masz większą kontrolę nad sposobem jego wykorzystania w aplikacji.
Jeśli włączysz też monitorowanie AI w Firebasekonsoli, w konsoli będą wyświetlane podsumowania myśli, w których możesz sprawdzić szczegółowe uzasadnienie modelu, aby debugować i dopracowywać prompty.
Oto kilka najważniejszych informacji o podsumowaniach myśli:
Podsumowania myśli nie są kontrolowane przez budżety na myślenie (budżety mają zastosowanie tylko do surowych myśli modelu). Jeśli jednak myślenie jest wyłączone, model nie zwróci podsumowania myśli.
Podsumowania przemyśleń są traktowane jako część zwykłej odpowiedzi modelu w postaci wygenerowanego tekstu i są liczone jako tokeny wyjściowe.
Włącz podsumowania myśli
|
Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod specyficzne dla tego dostawcy. |
Podsumowania przemyśleń możesz włączyć, ustawiając w konfiguracji modelu wartość includeThoughts na true. Podsumowanie możesz wyświetlić, sprawdzając pole thoughtSummary w odpowiedzi.
Oto przykład, który pokazuje, jak włączyć i pobrać podsumowania myśli w odpowiedzi:
Swift
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
onse.")
}
print("Answer: \(text)")
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
println("Answer: $it")
}
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
}
}, MoreExecutors.directExecutor());
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
`Answer: ${text}`);
// ...
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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
swer: ${response.text}');
}
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
"Answer: {response.Text}");
}
// ...
// 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}");
}
Wyświetlanie podsumowań strumienia myśli
Możesz też wyświetlać podsumowania myśli, jeśli zdecydujesz się przesyłać strumieniowo odpowiedź za pomocą generateContentStream. Podczas generowania odpowiedzi będą zwracane bieżące, przyrostowe podsumowania.
Swift
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
r ---")
}
print(text)
answer += text
}
}
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
uot;)
}
print(it)
answer += it
}
}
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
}, throwable -> {
// Handle error
});
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
out.write(text) could be used.
console.log(text);
answer += text;
}
}
// ...
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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
39;);
}
answer += response.text!;
}
}
// ...
// 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
Włącz podsumowania myśli w GenerationConfig podczas tworzenia instancji GenerativeModel.
og(response.Text);
answer += response.Text;
}
}
// ...
// 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;
}
}
Podpisy myśli
Podczas korzystania z funkcji myślenia w interakcjach wieloetapowych model nie ma dostępu do kontekstu myślenia z poprzednich etapów. Jeśli jednak korzystasz z wywoływania funkcji, możesz używać sygnatur myśli, aby zachować kontekst myślowy w kolejnych turach. Podpisy myśli to zaszyfrowane reprezentacje wewnętrznego procesu myślowego modelu. Są one dostępne podczas korzystania z myślenia i wywoływania funkcji. Sygnatury myśli są generowane, gdy:
- Myślenie jest włączone i generowane są pomysły.
- Żądanie zawiera deklaracje funkcji.
Aby korzystać z sygnatur myśli, używaj wywoływania funkcji w normalny sposób.
Pakiety Firebase AI Logic SDK upraszczają ten proces, zarządzając stanem i automatycznie obsługując podpisy myśli. Zestawy SDK automatycznie przekazują wygenerowane sygnatury myśli między kolejnymi wywołaniami funkcji sendMessage lub sendMessageStream w ramach Chat sesji.
Ceny i zliczanie tokenów myślowych
Tokeny myślenia mają takie same ceny jak tokeny wyjściowe tekstu. Jeśli włączysz podsumowania myśli, będą one traktowane jako tokeny myśli i odpowiednio wyceniane.
Możesz włączyć monitorowanie AI w Firebasekonsoli, aby śledzić liczbę tokenów przetwarzania w przypadku żądań, w których włączono przetwarzanie.
Łączną liczbę tokenów myślenia możesz uzyskać z pola thoughtsTokenCount w atrybucie usageMetadata odpowiedzi:
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 Futu<reCallbackGenerateConte>ntResponse() {
@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}");
}
Więcej informacji o tokenach znajdziesz w przewodniku po tokenach.