Os modelos de raciocínio são preparados para gerar o "processo de raciocínio" pelo qual o modelo passa como parte da sua resposta. Como resultado, os modelos de raciocínio são capazes de ter capacidades de raciocínio mais fortes nas suas respostas do que os modelos base equivalentes.
O processo de reflexão está ativado por predefinição. Quando usa o Vertex AI Studio, pode ver o processo de raciocínio completo juntamente com a resposta gerada do modelo.
Modelos suportados
O raciocínio é suportado nos seguintes modelos:
Use um modelo de pensamento
Para usar o raciocínio com um modelo suportado, faça o seguinte:
Consola
- Abra o Vertex AI Studio > Criar comando.
- No painel Modelo, clique em Mudar modelo e selecione um dos modelos suportados no menu.
- (Apenas Gemini 2.5 Flash) O orçamento de raciocínio está definido como Automático por predefinição quando o modelo é carregado.
- (Opcional) Dê ao modelo algumas instruções detalhadas sobre como deve formatar as respetivas respostas no campo Instruções do sistema.
- Introduza um comando no campo Escreva o seu comando.
- Clique em Executar.
O Gemini devolve uma resposta após a geração da mesma. Dependendo da complexidade da resposta, a geração pode demorar vários segundos.
(Apenas no Gemini 2.5 Flash) Para desativar o raciocínio, defina o Orçamento de raciocínio como Desativado.
Python
Instalação
pip install --upgrade google-genai
Para saber mais, consulte a documentação de referência do SDK.
Defina variáveis de ambiente para usar o SDK de IA generativa com o 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
Go
Saiba como instalar ou atualizar o Go.
Para saber mais, consulte a documentação de referência do SDK.
Defina variáveis de ambiente para usar o SDK de IA generativa com o 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
Veja resumos de pensamentos
Os resumos de ideias são o resultado abreviado do processo de raciocínio que o modelo seguiu ao gerar a respetiva resposta. Pode ver resumos de raciocínio no Gemini 2.5 Flash e no Gemini 2.5 Pro. Para ver os resumos de ideias, faça o seguinte:
Consola
Os resumos de reflexões estão ativados por predefinição no Vertex AI Studio. Pode ver o processo de raciocínio resumido do modelo expandindo o painel Ideias.
Python
Instalação
pip install --upgrade google-genai
Para saber mais, consulte a documentação de referência do SDK.
Defina variáveis de ambiente para usar o SDK de IA generativa com o 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
Receba assinaturas de pensamentos
As assinaturas de pensamento são representações encriptadas do processo de pensamento interno do modelo. O modelo devolve assinaturas de raciocínio no objeto de resposta quando usa o raciocínio e a chamada de funções está ativada. Para garantir que o modelo mantém o contexto em várias interações de uma conversa, tem de devolver as assinaturas de reflexão nos pedidos subsequentes.
Recebe assinaturas de pensamentos quando:
- O pensamento está ativado e são gerados pensamentos.
- O pedido inclui declarações de funções.
Segue-se um exemplo de como usar o raciocínio com chamadas de declaração de funções:
Python
# Create user friendly response with function result and call the model again # ...Create a function response part (No change) # Append thought signatures, function call and result of the function execution to contents function_call_content = response.candidates[0].content # Append the model's function call message, which includes thought signatures contents.append(function_call_content) contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response final_response = client.models.generate_content( model="gemini-2.5-flash", config=config, contents=contents, ) print(final_response.text)
Para mais informações, consulte a página Chamada de funções.
Outras limitações de utilização a ter em conta com a Chamada de funções:
- As assinaturas são devolvidas pelo modelo noutras partes da resposta, por exemplo, partes de chamadas de funções ou de texto, texto ou resumos de pensamentos. Devolver toda a resposta com todas as partes ao modelo em interações subsequentes.
- Não é possível concatenar assinaturas.
- As assinaturas são enviadas numa sequência de partes. Tem de devolver essas peças pela mesma ordem.
Controle o orçamento de reflexão
Pode controlar o nível de reflexão do modelo durante as respetivas respostas. Este limite superior chama-se orçamento de reflexão e aplica-se ao processo de reflexão completo do modelo. Por predefinição, o modelo controla automaticamente a quantidade de texto que pensa,até um máximo de 8192 tokens.
Pode definir manualmente o limite superior do número de tokens em situações em que pode precisar de mais ou menos tokens do que o orçamento de reflexão predefinido. Pode definir um limite de tokens inferior para tarefas menos complexas ou um limite superior para tarefas mais complexas.
A tabela seguinte mostra os valores mínimos e máximos que pode definir para o orçamento de tokens para cada modelo suportado:
Modelo | Valor mínimo do token | Quantidade máxima de tokens |
---|---|---|
Gemini 2.5 Flash | 1 | 24 576 |
Gemini 2.5 Pro | 128 | 32 768 |
Gemini 2.5 Flash-Lite | 512 | 24 576 |
Se definir o orçamento de raciocínio como 0
quando usar o Gemini 2.5 Flash e o Gemini 2.5 Flash-Lite, o raciocínio é desativado. Não é possível desativar o raciocínio para o Gemini 2.5 Pro.
Se quiser que o modelo controle o orçamento de raciocínio quando usar a API, defina o orçamento de raciocínio como -1
.
Consola
- Abra o Vertex AI Studio > Criar comando.
- No painel Modelo, clique em Mudar modelo e selecione um dos modelos suportados no menu.
- Selecione Manual no seletor pendente Orçamento de ponderação e, em seguida, use o controlo de deslize para ajustar o limite do orçamento de ponderação.
Python
Instalação
pip install --upgrade google-genai
Para saber mais, consulte a documentação de referência do SDK.
Defina variáveis de ambiente para usar o SDK de IA generativa com o 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
Técnicas de interação
Os comandos eficazes são essenciais para maximizar as vantagens dos modelos de raciocínio do Gemini. Esta secção descreve algumas práticas de pedidos para modelos de raciocínio.
Comece com instruções gerais que descrevam o resultado pretendido. Comece com um comando simples e observe as ideias iniciais do modelo sobre como responder.
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. <...> |
Oferecer instruções passo a passo
Se a tentativa inicial não produzir o resultado desejado, refine o comando: dê instruções passo a passo mais explícitas para orientar o Gemini no processo de resolução de problemas para uma abordagem mais focada. Isto permite-lhe orientar a compreensão inicial da tarefa por parte do modelo com sugestões explícitas e orientações.
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. <...> |
Comandos multishot com raciocínio
Os comandos de vários exemplos em conjunto com o raciocínio podem melhorar ainda mais a compreensão do Gemini e a precisão das respetivas respostas. Forneça vários exemplos de pares de entrada-saída, demonstrando o comportamento e o formato de saída desejados no seu comando.
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 |
Definir a saída e o comportamento
Quando cria uma aplicação em que os utilizadores vão interagir diretamente com o modelo, pode querer fornecer orientações sobre o som e a formatação do resultado e das respostas do Gemini.
Instruções do sistema
As instruções do sistema são um conjunto de instruções que o modelo processa antes de processar comandos. São relembradas sempre que o modelo recebe um comando e indicam ao modelo como quer que se comporte e responda. Por exemplo, pode incluir elementos como a função ou a personagem, informações contextuais e instruções de formatação.
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. |
Validação e reflexão
Inclua passos de validação específicos nas instruções do sistema ou nos seus comandos diretamente. Por exemplo, peça ao Gemini para validar as respetivas fontes, rever o raciocínio, identificar potenciais erros e verificar a resposta final.
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. |
Depuração e direcionamento
O Vertex AI Studio dá aos programadores acesso aos pensamentos do modelo na IU. Isto é útil para um programador que reveja o seu comando durante a depuração:
Analise o processo de raciocínio
Reveja cuidadosamente o processo de raciocínio do Gemini para identificar áreas onde possa ter-se desviado. Esta análise pode fornecer pistas valiosas para refinar os seus comandos e receber a resposta esperada de forma consistente na sua aplicação.
Exemplo de cenário: se o processo de raciocínio do Gemini mostrar que não compreendeu um passo numa instrução complexa, pode refinar o comando para esclarecer esse passo específico.
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 the 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 |
Tirar o máximo partido dos resultados longos e do raciocínio de formato longo
O pensamento gera "pensamentos" como parte da saída de tokens que apresenta o raciocínio detalhado do Gemini. Para tirar o máximo partido destes resultados:
Reveja o raciocínio
Preste muita atenção ao processo de raciocínio do Gemini (disponível na IU do Vertex AI Studio), à forma como dividiu a tarefa e às escolhas que fez para o seu resultado. Isto pode ajudar a compreender como chegou à sua conclusão.
Fornecer orientações no raciocínio
Se quiser que o resultado seja particularmente longo, é recomendável dar mais orientações no comando para restringir a quantidade de reflexão necessária para realizar a tarefa apresentada no comando. Isto permite-lhe reservar mais da saída de tokens para a sua resposta.
*Exemplo: para um relatório detalhado, pode especificar secções e subsecções no comando para orientar o raciocínio do Gemini e estruturar o resultado de forma eficiente.
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... <...> |
O que se segue?
Experimente usar um modelo de raciocínio por si com o nosso notebook do Colab ou abra a consola da Vertex AI e experimente pedir ao modelo por si.