Faccina che pensa

I modelli di pensiero vengono addestrati a generare il "processo di pensiero" che il modello segue come parte della sua risposta. Di conseguenza, i modelli di pensiero sono in grado di fornire risposte con ragionamenti più solidi rispetto ai modelli di base equivalenti.

Il processo di pensiero è attivo per impostazione predefinita. Quando utilizzi Vertex AI Studio, puoi visualizzare l'intero processo di pensiero insieme alla risposta generata dal modello.

Modelli supportati

Il pensiero è supportato nei seguenti modelli:

Usa il pensiero

Console

  1. Apri Vertex AI Studio > Crea prompt.
  2. Nel riquadro Modello, fai clic su Cambia modello e seleziona uno dei modelli supportati dal menu.
    • L'opzione Budget di pensiero è impostata su Automatico per impostazione predefinita quando il modello viene caricato (solo Gemini 2.5 Flash).
  3. (Facoltativo) Fornisci al modello alcune istruzioni dettagliate su come formattare le risposte nel campo Istruzioni di sistema.
  4. Inserisci un prompt nel campo Scrivi il tuo prompt.
  5. Fai clic su Esegui.

Gemini restituisce una risposta dopo che è stata generata. A seconda della complessità della risposta, la generazione può richiedere diversi secondi.

Puoi visualizzare il ragionamento riassunto del modello espandendo il riquadro Pensieri. Per disattivare la funzionalità, imposta Budget di pensiero su Off.

Gen AI SDK for Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.5-pro-preview-03-25",
    contents="solve x^2 + 4x + 4 = 0",
)
print(response.text)
# Example Response:
#     Okay, let's solve the quadratic equation x² + 4x + 4 = 0.
#
#     We can solve this equation by factoring, using the quadratic formula, or by recognizing it as a perfect square trinomial.
#
#     **Method 1: Factoring**
#
#     1.  We need two numbers that multiply to the constant term (4) and add up to the coefficient of the x term (4).
#     2.  The numbers 2 and 2 satisfy these conditions: 2 * 2 = 4 and 2 + 2 = 4.
#     3.  So, we can factor the quadratic as:
#         (x + 2)(x + 2) = 0
#         or
#         (x + 2)² = 0
#     4.  For the product to be zero, the factor must be zero:
#         x + 2 = 0
#     5.  Solve for x:
#         x = -2
#
#     **Method 2: Quadratic Formula**
#
#     The quadratic formula for an equation ax² + bx + c = 0 is:
#     x = [-b ± sqrt(b² - 4ac)] / (2a)
#
#     1.  In our equation x² + 4x + 4 = 0, we have a=1, b=4, and c=4.
#     2.  Substitute these values into the formula:
#         x = [-4 ± sqrt(4² - 4 * 1 * 4)] / (2 * 1)
#         x = [-4 ± sqrt(16 - 16)] / 2
#         x = [-4 ± sqrt(0)] / 2
#         x = [-4 ± 0] / 2
#         x = -4 / 2
#         x = -2
#
#     **Method 3: Perfect Square Trinomial**
#
#     1.  Notice that the expression x² + 4x + 4 fits the pattern of a perfect square trinomial: a² + 2ab + b², where a=x and b=2.
#     2.  We can rewrite the equation as:
#         (x + 2)² = 0
#     3.  Take the square root of both sides:
#         x + 2 = 0
#     4.  Solve for x:
#         x = -2
#
#     All methods lead to the same solution.
#
#     **Answer:**
#     The solution to the equation x² + 4x + 4 = 0 is x = -2. This is a repeated root (or a root with multiplicity 2).

Controllare il budget di pensiero

Solo per Gemini 2.5 Flash, puoi controllare quanto il modello riflette durante le risposte. Questo limite massimo è chiamato budget di pensiero e si applica all'intero processo di pensiero del modello. Per impostazione predefinita, il modello controlla automaticamente la quantità di pensiero fino a un massimo di 8192 token. Questo valore predefinito si applica sia a Gemini 2.5 Flash sia a Gemini 2.5 Pro.

Gemini 2.5 Flash ti consente di impostare manualmente il limite superiore per il numero di token in situazioni in cui potresti aver bisogno di più o meno token rispetto al budget per il pensiero predefinito. Puoi impostare un limite di token inferiore per le attività meno complesse o un limite superiore per quelle più complesse.

Il budget di pensiero massimo che puoi impostare è 24.576 token e il valore minimo che puoi impostare mantenendo attivo il pensiero è 1. Tuttavia, il valore minimo per il budget stimato è 1024 token, il che significa che qualsiasi valore impostato al di sotto di 1024 token viene reimpostato su 1024 nell'API.

Se imposti il budget di pensiero su 0, il pensiero viene disattivato.

Console

  1. Apri Vertex AI Studio > Crea prompt.
  2. Nel riquadro Modello, fai clic su Cambia modello e seleziona uno dei modelli supportati dal menu.
  3. Per il budget di pensiero (solo Gemini 2.5 Flash), impostalo su Manuale e poi utilizza il cursore per regolare il limite del budget di pensiero.

SDK IA generativa per Python

Utilizza il campo thinking_budget in ThinkingConfig per impostare il budget di pensiero.

response = client.models.generate_content(
  model=MODEL_ID,
  contents="PROMPT",
  config=GenerateContentConfig(
    thinking_config=ThinkingConfig(
        thinking_budget=THINKING_BUDGET,
    )
  )
)

print(response.text))
print(response.usage_metadata.thoughts_token_count) #Output thought token count
print(response.usage_metadata.total_token_count) #Output thought and response token count
       

Tecniche di impostazione di prompt per i modelli di pensiero

Un prompt efficace è fondamentale per massimizzare i vantaggi dei modelli di pensiero di Gemini. Questa sezione illustra alcune best practice per i prompt dei modelli di pensiero.

Per iniziare

Inizia con istruzioni generali che descrivono il risultato desiderato. Inizia con un prompt semplice e osserva le prime idee del modello su come affrontare la sfida.

Describe the most unusual or striking architectural feature you've ever seen in a building or structure.
  
<...>
The most unusual architectural feature that has truly stayed with me is the "floating roof" of the
  Heydar Aliyev Center in Baku, Azerbaijan, designed by Zaha Hadid Architects.

Visually, it's breathtaking. Imagine a vast, undulating landscape of pure white, seemingly draped
over the building. It's not just a roof in the traditional sense; it's an extension of the ground,
flowing seamlessly upwards and over the building's various spaces before curving back down to meet
the earth again. There are no sharp angles, no rigid lines. Instead, everything is fluid, organic,
and continuous. It resembles a giant, pristine white wave frozen in motion, or perhaps a sand dune
sculpted by an unseen wind.
<...>
  

Fornisci istruzioni dettagliate

Se il tentativo iniziale non produce il risultato desiderato, perfeziona il prompt fornendo istruzioni passo passo più esplicite per guidare Gemini nella procedura di risoluzione dei problemi per un approccio più mirato. In questo modo, puoi indirizzare la comprensione iniziale del modello dell'attività con suggerimenti e indicazioni espliciti.

Now imagine that architectural feature is not just for looks, but has a specific function or
purpose related to the building's environment or the people who use it. Explain what that
function could be and how it enhances the building's overall design and usability.
  
<...>
Let's imagine that the "floating roof" of the Heydar Aliyev Center is not purely aesthetic but
serves a crucial environmental and user-centric function: it's designed as a sophisticated climate
moderator and natural ventilation system for the Baku environment.

Here's how this function would work and enhance the building:

Function: Passive Climate Control and Natural Ventilation System

Shading and Solar Heat Mitigation: The undulating curves of the white GFRC roof are strategically
shaped and oriented to provide optimal shading throughout the day, year-round. Baku experiences
intense sun, especially during the summer. The overhanging curves, acting like giant brise-soleils,
would block direct sunlight from hitting the building's glass facade, significantly reducing solar
heat gain. The varying heights and depths of the curves would create dynamic shade patterns, ensuring
that different parts of the building are shaded at different times of the day, optimizing comfort
and reducing the need for excessive air conditioning. The white color of the GFRC further enhances
this by reflecting a large portion of the solar radiation.
<...>
  

Prompting multishot con Thinking

I prompt con più foto in combinazione con il pensiero possono migliorare ulteriormente la comprensione di Gemini e la precisione delle sue risposte. Fornisci diversi esempi di coppie di input-output che dimostrino il comportamento e il formato di output desiderati nel prompt.

Example 1:
User: What is the tallest mountain in the world?
Assistant: Mount Everest

Example 2:
User: What is the largest ocean?
Assistant: Pacific Ocean

User: What is the longest river in the world?
Assistant:
  
Amazon River
  

Definizione di output e comportamento

Quando crei un'applicazione in cui gli utenti interagiranno direttamente con il modello, ti consigliamo di fornire indicazioni su come verranno formattate e su come verranno pronunciate le risposte e l'output di Gemini.

Istruzioni di sistema

Le istruzioni di sistema sono un insieme di istruzioni che il modello elabora prima di elaborare i prompt. Vengono richiamati ogni volta che viene richiesto al modello di rispondere e indicano al modello come vuoi che si comporti e risponda. Ad esempio, puoi includere elementi come il ruolo o la persona, informazioni contestuali e istruzioni di formattazione.

System Instruction: You are a helpful and concise coding tutor. Always provide code examples and explain them briefly.

User Prompt: Explain what is a closure in Javascript and give an example.
  
    function outerFunction(outerVar) {
      function innerFunction(innerVar) {
        console.log(outerVar); // Accessing outerVar from outerFunction's scope
        console.log(innerVar);
      }
      return innerFunction;
    }

    const closureExample = outerFunction('I am from outer');
    closureExample('I am from inner');

Explanation:

A closure is created when a function (innerFunction in this example) is defined inside another function
(outerFunction) and the inner function remembers and has access to the variables from the outer
function's scope, even after the outer function has finished executing.

In the example:

outerFunction is called with 'I am from outer' and returns innerFunction.

closureExample now holds a reference to innerFunction.

When closureExample('I am from inner') is called, innerFunction executes.

Even though outerFunction has already finished, innerFunction can still access and use outerVar
(which is 'I am from outer') because of the closure.

In essence, the innerFunction "closes over" the variables of its outer function's scope, creating
a closure.
  

Verifica e riflessione

Includi passaggi di verifica specifici nelle istruzioni di sistema o direttamente nei prompt. Ad esempio, chiedi a Gemini di verificare le sue fonti, rivedere il suo ragionamento, identificare potenziali errori e controllare la sua risposta finale.

    Verify the following statement and provide your sources: The capital of Brazil is Rio de Janeiro.
  
The statement "The capital of Brazil is Rio de Janeiro" is incorrect.

The current capital of Brazil is Brasília.

Rio de Janeiro was the capital of Brazil for a significant period, from 1763 to 1960. However, the
capital was moved to Brasília in 1960 as part of a plan to develop the country's interior and create
a more centrally located capital.

Verification and Sources:

You can easily verify this information from numerous reliable sources:

Encyclopedias:

Britannica: Searching for "Brazil" on Britannica will clearly state Brasília as the capital.

https://www.britannica.com/place/Brazil (Look for the "Capital" information in the introductory summary or "Geography" section)

Wikipedia: The Wikipedia article for "Brazil" also states Brasília as the capital.

https://en.wikipedia.org/wiki/Brazil (Look in the infobox or introductory section)

Government and Official Sources:

CIA World Factbook: This is a highly reliable source for country information. Searching for "Brazil"
will list Brasília as the capital.

https://www.cia.gov/the-world-factbook/countries/brazil/ (Look under "Government" > "Capital")

Official Website of the Brazilian Government (if accessible and in English): While navigating official
government websites can sometimes be complex, they would definitively list Brasília as the capital.

Geographic Resources:

National Geographic: Their website and publications will confirm Brasília as the capital of Brazil.

Atlases and Geography Textbooks: Any modern atlas or geography textbook will list Brasília as the capital.

Why the confusion?

The confusion might arise because:

Rio de Janeiro is a very famous Brazilian city: It's a major tourist destination, known for its
beaches, Carnival, and iconic landmarks like Christ the Redeemer. Its past status as capital adds
to its historical significance and public recognition.

Historical context: Rio de Janeiro was the capital for a long time. People who learned about Brazil
in the past might remember it as the capital.

In conclusion, the statement is false. The capital of Brazil is Brasília, not Rio de Janeiro. Rio
de Janeiro was the former capital but is no longer the current capital.

You can confidently use the sources listed above to verify this information.
  

Debug e gestione

Google AI Studio fornisce agli sviluppatori l'accesso ai pensieri del modello nell'interfaccia utente. Questo è utile per gli sviluppatori che esaminano il prompt durante il debug:

Analizza il processo di pensiero

Esamina attentamente il ragionamento di Gemini per identificare eventuali aree in cui potrebbe aver sbagliato. Questa analisi può fornire indizi preziosi per perfezionare i prompt e ottenere la risposta prevista in modo coerente nella tua applicazione.

Scenario di esempio: se il processo di pensiero di Gemini mostra che non ha compreso un passaggio di un'istruzione complessa, puoi perfezionare il prompt per chiarire quel passaggio specifico.

Step 1: Summarize the following article about quantum physics.
Step 2: Translate the summary into Spanish.
Step 3: Extract the key entities from the Spanish summary.

Article: ... [Article Text] ...
The user wants me to process an article about Google's new quantum chip called Willow in three steps:
Step 1: Summarize the article.
Step 2: Translate the summary into Spanish.
Step 3: Extract the key entities from the Spanish summary.

Let's break down each step.

Step 1: Summarize the article.
I need to read the article and identify the main points. The article is about Google's new quantum
chip, Willow, and its achievements. The key achievements are:

Exponential error reduction as qubits scale up.

Outperforming supercomputers in a benchmark computation (RCS).

Willow is a step towards commercially relevant quantum computing.

It's the first system below threshold for quantum error correction.

It achieved a benchmark computation in under 5 minutes that would take a supercomputer 10 septillion years.

It was fabricated in a new facility.

It has state-of-the-art performance and high quality qubits.

Google is looking towards real-world applications with Willow.

Quantum computing will benefit AI.

I will synthesize these points into a concise summary.

Step 2: Translate the summary into Spanish.
Once I have the summary in English, I will translate it into Spanish. I need to ensure the translation
is accurate and natural-sounding in Spanish.

Step 3: Extract the key entities from the Spanish summary.
After translating the summary, I will identify and extract the key entities. Key entities are typically
nouns or noun phrases that represent important objects, concepts, or actors. In this context, they
will likely include:

Names of chips (Willow, Sycamore)

Companies/Organizations (Google Quantum AI, Google Research)

Technologies (quantum chip, quantum computer, qubits, quantum error correction, superconducting
quantum system, classical computers, supercomputers, AI)

Benchmarks (random circuit sampling, RCS)

People (Julian Kelly, Peter Shor, David Deutsch, Sergio Boixo, Hartmut Neven, John Preskill)

Concepts (exponential error reduction, below threshold, beyond breakeven, state-of-the-art performance,
commercially relevant applications, quantum mechanics, multiverse, T1 times, system benchmarks,
algorithmic benchmarks)

I will need to carefully review the Spanish summary to identify these entities and list them out.

Provide Corrective Feedback

If you observe errors or inconsistencies in Gemini's reasoning, provide corrective feedback in your prompt and/or System Instructions to anticipate where the model's response may deviate from your desired outcome.

You are an expert in botany. When asked to identify a plant, focus on leaf shape, flower structure, and stem characteristics.

Identify this plant based on these characteristics: ... [Plant Characteristics Description] ...

Previous incorrect response focused on habitat only. Please disregard habitat and focus on morphology.
Previous incorrect response focused on habitat only. Please disregard habitat and focus on morphology.
Tabebuia vellosoi

Sfruttare al meglio i contenuti lunghi e il pensiero in formato lungo

Il pensiero genera "pensieri" nell'ambito dell'output del token che mostra il ragionamento dettagliato di Gemini. Per ottenere il massimo da questi output:

Esamina il ragionamento

Presta molta attenzione al processo di ragionamento di Gemini (disponibile nell'interfaccia utente di Google AI Studio), a come ha suddiviso l'attività e alle scelte che ha fatto per l'output. In questo modo puoi capire come è arrivata a questa conclusione.

Fornire indicazioni per il ragionamento

Se il risultato desiderato deve essere particolarmente lungo, ti consigliamo di fornire ulteriori indicazioni nel prompt per limitare la quantità di pensiero necessaria per completare l'attività presentata nel prompt. In questo modo puoi riservare più dell'output del token per la tua risposta.

Esempio: per un report dettagliato, puoi specificare sezioni e sottosezioni nel prompt per guidare il ragionamento di Gemini e strutturare l'output in modo efficiente.

Generate a detailed report on the impact of climate change on coastal ecosystems.

Report Structure:

Introduction

Rising Sea Levels
2.1. Impact on Mangroves
2.2. Impact on Coral Reefs

Ocean Acidification
3.1. Impact on Shellfish
3.2. Impact on Plankton

Extreme Weather Events
4.1. Increased Storm Intensity
4.2. Coastal Erosion

Conclusion

Provide detailed analysis within each section.
<...>
Climate Change Impact on Coastal Ecosystems: A Detailed Report

1. Introduction

Coastal ecosystems, the dynamic interface between land and sea, are among the most productive and
biodiverse environments on Earth. They provide crucial ecosystem services, including coastal protection,
fisheries, carbon sequestration, and support for a vast array of species. However, these vital
ecosystems are increasingly threatened by the multifaceted impacts of climate change. Driven by
anthropogenic greenhouse gas emissions, climate change is manifesting in several interconnected ways
that are profoundly altering the physical and chemical conditions of coastal environments. This report
will delve into the key impacts of climate change on coastal ecosystems, focusing on rising sea levels,
ocean acidification, and extreme weather events, and their specific consequences for critical habitats
like mangroves and coral reefs, and key organisms like shellfish and plankton. Understanding these
impacts is crucial for developing effective conservation and management strategies to mitigate the
damage and enhance the resilience of these invaluable ecosystems.

2. Rising Sea Levels

Rising sea levels are a direct and significant consequence of global warming, driven by thermal
expansion of seawater and the melting of land ice (glaciers and ice sheets). This phenomenon poses a
direct threat to low-lying coastal ecosystems by inundating habitats, altering salinity regimes, and
increasing erosion rates. The rate of sea level rise is accelerating, and projections for the 21st
century indicate a continued upward trend, with potentially devastating consequences for coastal
environments.

2.1. Impact on Mangroves

Mangrove forests are unique coastal ecosystems found in tropical and subtropical intertidal zones.
They provide numerous benefits, including coastal protection against storms, nursery grounds for
fish and invertebrates, and significant carbon sequestration...
<...>

Passaggi successivi

Prova a utilizzare un modello di pensiero con il nostro notebook Colab, o apri la console Vertex AI e prova a chiedere al modello di pensare per te.