Los modelos de pensamiento se entrenan para generar el "proceso de pensamiento" que sigue el modelo como parte de su respuesta. Por lo tanto, los modelos de razonamiento pueden ofrecer respuestas con capacidades de razonamiento más sólidas que los modelos base equivalentes.
El proceso de reflexión está habilitado de forma predeterminada. Cuando usas Vertex AI Studio, puedes ver todo el proceso de reflexión junto con la respuesta generada por el modelo.
Modelos admitidos
La función Pensar está disponible en los siguientes modelos:
Usar un modelo de pensamiento
Para usar la función de reflexión con un modelo compatible, haz lo siguiente:
Consola
- Abre Vertex AI Studio > Crear petición.
- En el panel Modelo, haz clic en Cambiar modelo y selecciona uno de los modelos admitidos del menú.
- (Solo Gemini 2.5 Flash) La opción Presupuesto de reflexión se define como Automático de forma predeterminada cuando se carga el modelo.
- (Opcional) Da al modelo instrucciones detalladas sobre cómo debe dar formato a sus respuestas en el campo Instrucciones del sistema.
- Escribe una petición en el campo Escribe tu petición.
- Haz clic en Ejecutar.
Gemini devuelve una respuesta después de generarla. En función de la complejidad de la respuesta, la generación puede tardar varios segundos.
(Solo Gemini 2.5 Flash) Para desactivar el pensamiento, asigna el valor Desactivado a Presupuesto de pensamiento.
Python
Instalar
pip install --upgrade google-genai
Para obtener más información, consulta la documentación de referencia del SDK.
Define variables de entorno para usar el SDK de IA generativa 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
Go
Consulta cómo instalar o actualizar Go.
Para obtener más información, consulta la documentación de referencia del SDK.
Define variables de entorno para usar el SDK de IA generativa 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
Ver resúmenes de pensamientos
Los resúmenes de pensamientos son el resultado abreviado del proceso de pensamiento que ha seguido el modelo al generar su respuesta. Puedes ver resúmenes de reflexiones tanto en Gemini 2.5 Flash como en Gemini 2.5 Pro. Para ver resúmenes de reflexiones, sigue estos pasos:
Consola
Los resúmenes de reflexiones están habilitados de forma predeterminada en Vertex AI Studio. Para ver un resumen del proceso de reflexión del modelo, despliega el panel Reflexiones.
Python
Instalar
pip install --upgrade google-genai
Para obtener más información, consulta la documentación de referencia del SDK.
Define variables de entorno para usar el SDK de IA generativa 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
Recibir firmas de pensamientos
Las firmas de pensamiento son representaciones cifradas del proceso de pensamiento interno del modelo. El modelo devuelve firmas de pensamiento en el objeto de respuesta cuando se usa el pensamiento y la llamada de función está habilitada. Para asegurarte de que el modelo mantiene el contexto en varias interacciones de una conversación, debes devolver las firmas de pensamiento en tus solicitudes posteriores.
Recibirás firmas de pensamientos cuando:
- La función de pensamiento está habilitada y se generan pensamientos.
- La solicitud incluye declaraciones de funciones.
Aquí tienes un ejemplo de cómo usar la función de pensamiento con llamadas de declaración de funciones:
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 obtener más información, consulta la página Llamadas a funciones.
Otras limitaciones de uso que debes tener en cuenta al usar las llamadas a funciones son las siguientes:
- El modelo devuelve las firmas en otras partes de la respuesta, como las partes de llamada a función, texto, texto o resúmenes de ideas. Devuelve toda la respuesta con todas las partes al modelo en las siguientes interacciones.
- Las firmas no se pueden concatenar.
- Las firmas se envían en una secuencia de partes. Debes devolver esas partes en el mismo orden.
Controlar el presupuesto de pensamiento
Puedes controlar cuánto piensa el modelo durante sus respuestas. Este límite superior se denomina presupuesto de reflexión y se aplica a todo el proceso de reflexión del modelo. De forma predeterminada, el modelo controla automáticamente la cantidad que cree que puede generar,hasta un máximo de 8192 tokens.
Puedes definir manualmente el límite superior del número de tokens en situaciones en las que necesites más o menos tokens que el presupuesto de reflexión predeterminado. Puedes definir un límite de tokens inferior para tareas menos complejas o un límite superior para tareas más complejas.
En la siguiente tabla se muestran los importes mínimos y máximos que puede asignar al presupuesto de tokens de cada modelo admitido:
Modelo | Importe mínimo de tokens | Cantidad 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 |
Si asignas un presupuesto de reflexión de 0
al usar Gemini 2.5 Flash y Gemini 2.5 Flash-Lite, la reflexión se desactivará. No se puede desactivar la reflexión en Gemini 2.5 Pro.
Si quieres que el modelo controle el presupuesto de reflexión al usar la API, asigna el valor -1
al presupuesto de reflexión.
Consola
- Abre Vertex AI Studio > Crear petición.
- En el panel Modelo, haz clic en Cambiar modelo y selecciona uno de los modelos admitidos del menú.
- Selecciona Manual en el menú desplegable Presupuesto de reflexión y, a continuación, usa el control deslizante para ajustar el límite del presupuesto de reflexión.
Python
Instalar
pip install --upgrade google-genai
Para obtener más información, consulta la documentación de referencia del SDK.
Define variables de entorno para usar el SDK de IA generativa 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
Técnicas de peticiones
Para maximizar las ventajas de los modelos de razonamiento de Gemini, es fundamental crear peticiones eficaces. En esta sección se describen algunas prácticas de peticiones para modelos de pensamiento.
Empieza con instrucciones generales que describan el resultado que quieres obtener. Empieza con una petición sencilla y observa las primeras ideas del modelo sobre cómo 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. <...> |
Proporcionar instrucciones detalladas
Si el primer intento no da el resultado deseado, perfecciona tu petición proporcionando instrucciones paso a paso más explícitas para guiar a Gemini en el proceso de resolución de problemas y así conseguir un enfoque más específico. De esta forma, puedes dirigir la comprensión inicial de la tarea por parte del modelo con sugerencias y orientación explícitas.
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. <...> |
Peticiones de varios intentos con reflexión
Las peticiones de varios pasos junto con el pensamiento pueden mejorar aún más la comprensión de Gemini y la precisión de sus respuestas. Proporciona varios ejemplos de pares de entrada-salida que demuestren el comportamiento y el formato de salida deseados en tu petición.
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 la salida y el comportamiento
Cuando crees una aplicación en la que los usuarios interactúen directamente con el modelo, puede que quieras proporcionar directrices sobre el tono y el formato de las respuestas y los resultados de Gemini.
Instrucciones del sistema
Las instrucciones del sistema son un conjunto de instrucciones que el modelo procesa antes de procesar las peticiones. Se recuerdan cada vez que se le pide algo al modelo y le indican cómo quieres que se comporte y responda. Por ejemplo, puedes incluir aspectos como el rol o el perfil, información contextual e instrucciones de formato.
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. |
Verificación y reflexión
Incluye pasos de verificación específicos en las instrucciones del sistema o directamente en tus peticiones. Por ejemplo, puedes pedirle a Gemini que verifique sus fuentes, revise su razonamiento, identifique posibles errores y compruebe su respuesta 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. |
Depuración y control
Vertex AI Studio ofrece a los desarrolladores acceso a las reflexiones del modelo en la interfaz de usuario. Esto resulta útil para los desarrolladores que revisan sus peticiones al depurar:
Analizar el proceso de pensamiento
Revisa detenidamente el proceso de reflexión de Gemini para identificar las áreas en las que se haya desviado. Este análisis puede proporcionarte información valiosa para mejorar tus peticiones y obtener la respuesta esperada de forma constante en tu aplicación.
Ejemplo: Si el proceso de reflexión de Gemini muestra que no ha entendido un paso de una instrucción compleja, puedes modificar la petición para aclarar ese paso concreto.
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 |
Aprovechar al máximo las respuestas largas y el pensamiento extenso
Pensar genera "pensamientos" como parte de la salida de tokens que muestra el razonamiento detallado de Gemini. Para sacar el máximo partido a estos resultados, sigue estos pasos:
Revisa los motivos
Presta mucha atención al proceso de razonamiento de Gemini (disponible en la interfaz de usuario de Vertex AI Studio), a cómo ha desglosado la tarea y a las decisiones que ha tomado para generar el resultado. Esto puede ayudarte a entender cómo ha llegado a esa conclusión.
Proporcionar orientación en el razonamiento
Si quieres que el resultado sea especialmente largo, puedes proporcionar más instrucciones en tu petición para limitar la cantidad de razonamiento necesaria para llevar a cabo la tarea presentada en la petición. De esta forma, puedes reservar más tokens para tu respuesta.
*Ejemplo: Para obtener un informe detallado, puedes especificar secciones y subsecciones en tu petición para guiar el proceso de reflexión de Gemini y estructurar el 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... <...> |
Siguientes pasos
Prueba a usar un modelo de pensamiento con nuestro notebook de Colab o abre la consola de Vertex AI y prueba a pedirle algo al modelo.