Empezar a pensar con REST
Copyright 2026 Google LLC.
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Modelos Gemini 3: Si solo te interesan los nuevos niveles de pensamiento de Gemini 3, ve directamente a la sección dedicada al final de este notebook, que también incluye una guía de migración.
Todos los modelos Gemini de la generación 2.5 y la nueva generación Gemini 3 están entrenados para realizar un proceso de pensamiento (o razonamiento) antes de llegar a una respuesta final. Como resultado, estos modelos son capaces de tener mayores capacidades de razonamiento en sus respuestas que los modelos anteriores.
Verás ejemplos de esas capacidades de razonamiento con problemas de comprensión de código, geometría y matemáticas.
Como verás, el modelo expone sus pensamientos para que puedas ver su razonamiento y cómo llegó a sus conclusiones.
Entendiendo los modelos de pensamiento
Los modelos de pensamiento están optimizados para tareas complejas que necesitan múltiples rondas de estrategia y resolución iterativa.
Al hacer llamadas a la API REST, controlas el comportamiento de pensamiento incluyendo un objeto thinkingConfig dentro de generationConfig en tu carga útil de solicitud JSON.
Gemini 3.7 Flash, en particular, ofrece la flexibilidad de usar thinkingBudget, un parámetro que proporciona un control preciso sobre el número máximo de tokens que un modelo puede generar mientras piensa. Alternativamente, puedes designar una asignación precisa de tokens para la etapa de "pensamiento" mediante el ajuste del parámetro thinkingBudget. Esta asignación puede variar entre 0 y 24576 tokens para 2.5 Flash.
Para obtener más información sobre todos los modelos Gemini, consulta la documentación para obtener información ampliada sobre cada uno de ellos.
En este notebook, la mayoría de los ejemplos usan el parámetro thinkingBudget, ya que es compatible con las generaciones de modelos 2.5 y 3. Para obtener más información sobre el uso de thinkingBudget con el modelo de pensamiento Gemini, consulta la documentación.
NUEVO: niveles de pensamiento: Gemini 3 Pro introdujo una nueva y más fácil forma de gestionar el presupuesto de pensamiento estableciendo un thinkingLevel que está documentado en la sección de esta guía dedicada a Gemini 3.
Configura tu clave de API
Para ejecutar la siguiente celda, tu clave de API debe estar almacenada en un Secreto de Colab llamado GEMINI_API_KEY. Si aún no tienes una clave de API, o no estás seguro de cómo crear un Secreto de Colab, consulta Autenticación
para ver un tutorial.
from google.colab import userdata
GEMINI_API_KEY=userdata.get('GEMINI_API_KEY')
import json
import requests
MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}url = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_ID}:generateContent?key={GEMINI_API_KEY}"
Ejemplos
Aquí tienes algunos ejemplos bastante complejos de lo que el modelo thinking de Gemini puede resolver.
En cada uno de ellos puedes seleccionar diferentes modelos para ver cómo se compara este nuevo modelo con sus predecesores.
En algunos casos, seguirás obteniendo la respuesta correcta de los otros modelos; en ese caso, vuelve a ejecutarlo un par de veces y verás que Gemini 2.5 thinking es más consistente gracias a su paso de pensamiento.
Ejemplo #1: Acertijo con pensamiento
Puedes empezar pidiéndole al modelo que explique un concepto y ver cómo razona antes de responder.
Comenzando con el thinkingBudget adaptativo, que es el predeterminado cuando no especificas un presupuesto, el modelo ajustará dinámicamente el presupuesto en función de la complejidad de la solicitud.
includeThoughts le dice al modelo que incluya sus pensamientos en la salida.
prompt = """
You are playing the 20 question game. You know that what you are looking for
is a aquatic mammal that doesn't live in the sea, and that's smaller than a
cat. What could that be and how could you make sure?
"""
# The animal I'm thinking of is a platipus
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**Here's how I'm thinking about this:**
Okay, so we've got an aquatic mammal, freshwater, smaller than a cat. My mind immediately starts running through the usual suspects. I'm going through the marine mammals first, ruling them out: whales, dolphins, sea lions... nope, definitely not. Manatees and dugongs, too big. Then, I start on the freshwater side. Otters are a possibility, though some are much bigger. Beavers? Too big. Muskrat and Mink are looking promising, and I'm adding platypus because it's aquatic and I need to be inclusive. Water voles, various shrews, and a quick check on the hippo (nope, obviously).
Now, refining based on size, the really strong candidates emerge: the water shrew and vole are ideal. The platypus, being unique, is a great fit. Mink also look good. Muskrat... borderline but possible. I'll include it to show I thought it through.
Based on the information, I'll go with the Water Shrew, Water Vole, Platypus, and Mink, as distinct options. They cover the space and show I've done a proper job.
Now, how would I confirm this? I start formulating those 20-questions style questions. The Platypus gets a special question: "Does it lay eggs?" because it's the most unusual. I'd ask a yes/no question to differentiate the different candidates and confirm the key features. I want to narrow down the options with each question, so I'm thinking about webbed feet, tail type, habitat, and overall size. I need to design the best strategy with the fewest questions.
OUTPUT:
This is a fun one! Let's break down the clues:
1. **Aquatic mammal:** Lives in or around water, has fur, breathes air, nurses young.
2. **Doesn't live in the sea:** Exclusively freshwater (rivers, lakes, ponds, swamps).
3. **Smaller than a cat:** A domestic cat is generally 8-10 lbs (3.6-4.5 kg) and about 18-24 inches (45-60 cm) long including the tail.
Given these clues, here are a few strong possibilities:
---
### What could that be?
1. **Water Shrew:**
* **Fits:** These are very small (much smaller than a cat, often only a few inches long), highly aquatic (excellent swimmers and divers), feed on aquatic insects and small fish, and live in freshwater habitats across many continents.
2. **Water Vole:**
* **Fits:** Roughly the size of a large rat (smaller than most cats), strong swimmers, live in freshwater rivers, streams, and ponds, primarily herbivorous but will eat insects. Common in Europe and parts of Asia.
3. **Platypus:**
* **Fits:** Unique semi-aquatic mammal (monotreme, meaning it lays eggs), found exclusively in eastern Australia (freshwater rivers and lakes), and is smaller than a cat (typically 12-15 inches/30-38 cm long, not including the tail).
4. **Mink:**
* **Fits:** A semi-aquatic weasel, smaller than a cat (body length usually 12-18 inches/30-45 cm), excellent swimmers and hunters of fish, frogs, and other small prey in freshwater environments.
---
### How could you make sure? (20 Questions style - Yes/No answers)
To narrow it down and confirm, you'd ask questions that target the specific characteristics of these animals:
1. **Is it native to Australia?** (Yes = Platypus)
* *If yes, you've likely found it. If no, proceed...*
2. **Does it have webbed feet?** (Yes = Platypus, Water Shrew, Mink (partially), some Water Voles have fringed feet)
* *This helps rule out things like land mammals that just drink from water.*
3. **Does it belong to the rodent family?** (Yes = Water Vole, Muskrat - if considering muskrat)
* *This would rule out shrews, minks, and platypus.*
4. **Is its diet primarily insects and small invertebrates?** (Yes = Water Shrew, Platypus to some extent)
* *This would lean away from the more herbivorous water vole or the more generalist mink.*
5. **Does it have a long, pointed snout with whiskers?** (Yes = Water Shrew)
* *Distinctive feature of shrews.*
6. **Does it have a short, blunt snout and round ears almost hidden in its fur?** (Yes = Water Vole)
* *Distinguishes it from shrews and minks.*
7. **Is it known for being a skilled hunter of fish and frogs?** (Yes = Mink, Water Shrew)
* *Mink are formidable predators.*
8. **Is its body typically less than 6 inches (15 cm) long (excluding the tail)?** (Yes = Water Shrew)
* *This is a size check that firmly places it as very small.*
9. **Does it belong to the weasel family?** (Yes = Mink)
* *A direct family identification.*
10. **Is it active year-round, even in freezing conditions?** (Many of these are, but can be a differentiator for specific species behavior).
11. **Does it spend a significant amount of time burrowing in riverbanks?** (Yes = Water Vole, Platypus, Mink (for dens))
12. **Is it generally considered solitary?** (Many small aquatic mammals are).
By asking these types of questions, you'd quickly narrow down whether it's a water shrew, water vole, platypus, or mink, or another similar small freshwater aquatic mammal.
print(response)
{'error': {'code': 400, 'message': 'Invalid JSON payload received. Unknown name "includeThoughts" at \'generation_config\': Cannot find field.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'generation_config', 'description': 'Invalid JSON payload received. Unknown name "includeThoughts" at \'generation_config\': Cannot find field.'}]}]}}
Inspeccionando los metadatos de la respuesta: Después de hacer la llamada REST, el JSON de la respuesta contiene usageMetadata. Este objeto proporciona información sobre el recuento de tokens de la solicitud. Busca el campo thoughtsTokenCount dentro de usageMetadata para ver cuántos tokens consumió el proceso de pensamiento para esta solicitud. También verás promptTokenCount, candidatesTokenCount (para la salida final) y totalTokenCount. Como puedes ver aquí, el modelo usó un número significativo de tokens en los pasos de pensamiento.
print("Prompt tokens:",response["usageMetadata"]["promptTokenCount"])
print("Thoughts tokens:",response["usageMetadata"]["thoughtsTokenCount"])
print("Output tokens:", response["usageMetadata"]["candidatesTokenCount"])
print("Total tokens:", response["usageMetadata"]["totalTokenCount"])
Prompt tokens: 58
Thoughts tokens: 1477
Output tokens: 820
Total tokens: 2355
Desactivando los pasos de pensamiento
Puedes desactivar explícitamente los pasos de pensamiento incluyendo el objeto thinkingConfig en el generationConfig y configurando el parámetro thinkingBudget en 0 en la carga útil JSON. Esto le indica al modelo que no realice ningún paso de razonamiento interno antes de generar la salida final. Es probable que veas que, en este caso, el modelo no considera al ornitorrinco como una posible respuesta.
Ten en cuenta que no puedes desactivar el pensamiento en los modelos Pro.
if "-pro" not in MODEL_ID:
prompt = """
You are playing the 20 question game. You know that what you are looking for
is a aquatic mammal that doesn't live in the sea, and that's smaller than a
cat. What could that be and how could you make sure?
"""
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
],
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 0,
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print(response['candidates'][0]['content']['parts'][0]['text'])
else
print("You can't disable thinking for pro models.")
This is a fun challenge! Let's break it down.
**The Object:** A aquatic mammal that doesn't live in the sea, and that's smaller than a cat.
**Possible Candidate:** The most likely candidate that fits all those criteria is a **river otter pup**.
**Why a River Otter Pup?**
* **Aquatic Mammal:** Yes, otters are well-known aquatic mammals.
* **Doesn't Live in the Sea:** While some otters live in coastal areas, river otters specifically inhabit freshwater environments like rivers, lakes, and marshes.
* **Smaller than a Cat:** An adult river otter is definitely larger than a cat. However, a newborn or very young **pup** (baby otter) would be significantly smaller than a domestic cat. They are born blind and helpless, and quite tiny.
**How to Make Sure (Your 20 Questions Strategy):**
To confirm this, you'd use your 20 questions to narrow down the possibilities. Here's a possible line of questioning, aiming to eliminate other options and pinpoint the river otter pup:
1. **Is it an animal?** (Yes - establishes the category)
2. **Is it a mammal?** (Yes - narrows it significantly)
3. **Is it aquatic?** (Yes - crucial qualifier)
4. **Does it primarily live in freshwater?** (Yes - this eliminates sea mammals like dolphins, seals, whales, sea otters, etc., and focuses on rivers, lakes, ponds)
5. **Is it native to North America?** (Yes - helps narrow down specific species of freshwater aquatic mammals)
6. **Does it have fur?** (Yes - separates it from some amphibians or fish if there was confusion)
7. **Is it known for being playful?** (Yes - strong hint towards otters)
8. **Does it belong to the weasel family (Mustelidae)?** (Yes - This is a powerful question as it directly points to otters, badgers, minks, ferrets, etc. among aquatic mammals, otters are the obvious choice here)
9. **Does it eat fish, crustaceans, and amphibians?** (Yes - typical otter diet)
10. **Does it build dens called "holts"?** (Yes - confirms it's an otter, not a beaver or muskrat)
11. **Is an adult of this species typically larger than a domestic cat?** (Yes - this is key to setting up the next question)
12. **Are we referring to a *baby* or *juvenile* of this species?** (Yes - This is the crucial question that explains why it's "smaller than a cat" despite the adult being larger.)
13. **Is it born helpless and blind?** (Yes - characteristic of otter pups)
14. **Does it learn to swim from its mother?** (Yes - typical otter pup behavior)
15. **Is it called a "pup"?** (Yes - common term for baby otters)
At this point, you've almost certainly confirmed it's a river otter pup. You could ask a few more specific questions if you wanted to be absolutely sure, but the combination of freshwater aquatic mammal, Mustelidae family, playful, and specifically being a *baby* when the adult is larger, makes the river otter pup an incredibly strong fit.
**Other Less Likely but Possible Considerations (and why they're not as good):**
* **Muskrat pup:** Muskrats are aquatic, freshwater, and pups are smaller than a cat. However, they are rodents, not typically considered "playful," and less commonly thought of as a primary "aquatic mammal" in the same way an otter is (though technically correct). Your questions about the weasel family would eliminate them.
* **Mink pup:** Minks are also Mustelids, aquatic, and pups are small. But they are often found in coastal areas as well as freshwater, and are generally more terrestrial than an otter.
* **Water Shrew:** These are *very* small, aquatic, and freshwater. However, they are insectivores, not often thought of as "mammals" in the common sense when people play 20 questions (though they are), and don't fit the "playful" stereotype. Also, they're so small, calling them "smaller than a cat" is an understatement.
* **Platypus pup (if you're thinking globally):** Fits the description, but "doesn't live in the sea" is a bit ambiguous as they live in rivers that lead to the sea. The "mammal" part is also tricky as they are monotremes. Your "native to North America" question would eliminate it quickly.
Given the common knowledge and typical scope of 20 questions, the **river otter pup** is by far the strongest and most elegant answer.
Ahora puedes ver que la respuesta es más rápida, ya que el modelo no realizó ningún paso de pensamiento. También puedes ver que no se usaron tokens para el paso de pensamiento:
print("Prompt tokens:",response["usageMetadata"]["promptTokenCount"])
print("Thoughts tokens:",response["usageMetadata"]["thoughtsTokenCount"] if "thoughtsTokenCount" in response["usageMetadata"] else "None")
print("Output tokens:", response["usageMetadata"]["candidatesTokenCount"])
print("Total tokens:", response["usageMetadata"]["totalTokenCount"])
Prompt tokens: 59
Thoughts tokens: None
Output tokens: 786
Total tokens: 845
Ejemplo #2: Problema de física
Ahora, intenta con un ejemplo simple de comprensión de física. Primero puedes desactivar el thinkingBudget para ver cómo se desempeña el modelo:
if "-pro" not in MODEL_ID:
prompt = """
A cantilever beam of length L=3m has a rectangular cross-section (width b=0.1m, height h=0.2m) and is made of steel (E=200 GPa).
It is subjected to a uniformly distributed load w=5 kN/m along its entire length and a point load P=10 kN at its free end.
Calculate the maximum bending stress (σ_max).
"""
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
],
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 0
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print(response['candidates'][0]['content']['parts'][0]['text'])
else
print("You can't disable thinking for pro models.")
Here's how to calculate the maximum bending stress for the cantilever beam:
**1. Define Given Parameters:**
* Length (L) = 3 m
* Width (b) = 0.1 m
* Height (h) = 0.2 m
* Modulus of Elasticity (E) = 200 GPa = 200 * 10^9 Pa
* Uniformly distributed load (w) = 5 kN/m = 5000 N/m
* Point load (P) = 10 kN = 10000 N
**2. Calculate the Moment of Inertia (I) for a Rectangular Cross-Section:**
The formula for the moment of inertia for a rectangular cross-section about the neutral axis is:
I = (b * h^3) / 12
I = (0.1 m * (0.2 m)^3) / 12
I = (0.1 m * 0.008 m^3) / 12
I = 0.0008 m^4 / 12
I = 6.6667 * 10^-5 m^4
**3. Determine the Maximum Bending Moment (M_max):**
For a cantilever beam, the maximum bending moment occurs at the fixed end. We need to consider the contribution from both the uniformly distributed load and the point load.
* **Bending moment due to uniformly distributed load (M_w):**
M_w = (w * L^2) / 2
M_w = (5000 N/m * (3 m)^2) / 2
M_w = (5000 N/m * 9 m^2) / 2
M_w = 45000 Nm / 2
M_w = 22500 Nm
* **Bending moment due to point load (M_P):**
M_P = P * L
M_P = 10000 N * 3 m
M_P = 30000 Nm
* **Total Maximum Bending Moment (M_max):**
Since both loads create bending moments in the same direction (causing tension on the top surface and compression on the bottom surface at the fixed end for standard upward loading, or vice-versa), we add them:
M_max = M_w + M_P
M_max = 22500 Nm + 30000 Nm
M_max = 52500 Nm
**4. Calculate the Distance from the Neutral Axis to the Outermost Fiber (c):**
For a rectangular cross-section, the neutral axis is at the geometric center, so:
c = h / 2
c = 0.2 m / 2
c = 0.1 m
**5. Calculate the Maximum Bending Stress (σ_max):**
The bending stress formula is:
σ_max = (M_max * c) / I
σ_max = (52500 Nm * 0.1 m) / (6.6667 * 10^-5 m^4)
σ_max = 5250 Nm^2 / (6.6667 * 10^-5 m^4)
σ_max = 78749375 Pa
**6. Convert to more convenient units (MPa):**
σ_max = 78749375 Pa / (10^6 Pa/MPa)
σ_max = 78.75 MPa (approximately)
**Therefore, the maximum bending stress in the cantilever beam is approximately 78.75 MPa.**
Metadatos (pensamiento deshabilitado): Como se esperaba, el usageMetadata para esta solicitud debería mostrar un thoughtsTokenCount de 0 o su ausencia, ya que el pensamiento se deshabilitó explícitamente en la carga útil de la solicitud.
print("Prompt tokens:",response["usageMetadata"]["promptTokenCount"])
print("Thoughts tokens:",response["usageMetadata"]["thoughtsTokenCount"] if "thoughtsTokenCount" in response["usageMetadata"] else "None")
print("Output tokens:", response["usageMetadata"]["candidatesTokenCount"])
print("Total tokens:", response["usageMetadata"]["totalTokenCount"])
Prompt tokens: 95
Thoughts tokens: None
Output tokens: 761
Total tokens: 856
Luego, establece un presupuesto máximo fijo (e.g., thinkingBudget=4096) para el paso de pensamiento incluyendo el objeto thinkingConfig con thinkingBudget configurado en la carga útil JSON. Observa cómo cambia la salida del modelo.
prompt = """
A cantilever beam of length L=3m has a rectangular cross-section (width b=0.1m, height h=0.2m) and is made of steel (E=200 GPa).
It is subjected to a uniformly distributed load w=5 kN/m along its entire length and a point load P=10 kN at its free end.
Calculate the maximum bending stress (σ_max).
"""
thinkingBudget = 4096 # @param {type:"slider", min:0, max:24576, step:1}
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
"thinkingBudget": thinkingBudget
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**Solving for Maximum Bending Stress in a Cantilever Beam**
Alright, let's break this down. The goal is clear: find the maximum bending stress in that cantilever beam. The key here, as always, is understanding where the maximum stress will occur. With a cantilever, it's a no-brainer – it's at the fixed support, where the bending moment is the greatest.
First, I need to have the bending stress formula at my fingertips: $\sigma = \frac{M y}{I}$. $M$ is the bending moment, $y$ is the distance to the fiber, and $I$ is the moment of inertia. I'll need to calculate those.
Since it's a rectangular cross-section (b = 0.1 m, h = 0.2 m), the moment of inertia is straightforward. $I = \frac{b h^3}{12}$, giving me $I = \frac{0.1 \times 0.2^3}{12} = \frac{1}{15000} m^4$. For a rectangle, the distance to the extreme fiber, *c*, is just half the height, or 0.1 m. I've got my section properties sorted.
Now for the moment. There are two loads: a point load at the free end and a uniformly distributed load along the entire length. I need to calculate the moment each load creates at the fixed support (x=0). The point load, with a magnitude of 10 kN at 3 m, creates a moment of $M_P = P \times L = 30 \text{ kNm}$. The distributed load of 5 kN/m is essentially an equivalent concentrated load of 15 kN located 1.5 m from the fixed support. So, the moment from that is $M_w = \frac{wL^2}{2} = 22.5 \text{ kNm}$.
Since they both bend the beam in the same sense, they add. The total maximum moment, then, is $M_{max} = 30 + 22.5 = 52.5 \text{ kNm}$.
Now it's just plugging into the bending stress formula. $\sigma_{max} = \frac{(52.5 \times 10^3 Nm) \times 0.1 m}{1/15000 m^4} $. Working through the math (making sure to convert to consistent units!), I get $\sigma_{max} = 78.75 \text{ MPa}$.
Finally, a quick sanity check. The Young's Modulus was given but it's not needed for *stress* here. That's for deflection, which wasn't asked for. The calculated stress of 78.75 MPa sounds reasonable for a steel beam, being below typical yield strengths. Done.
OUTPUT:
Okay, let's calculate the maximum bending stress for this cantilever beam.
**1. Identify Given Parameters:**
* Length of beam, L = 3 m
* Width of cross-section, b = 0.1 m
* Height of cross-section, h = 0.2 m
* Young's Modulus, E = 200 GPa (not needed for stress calculation, only for deflection/strain)
* Uniformly distributed load, w = 5 kN/m
* Point load at free end, P = 10 kN
**2. Calculate Section Properties:**
* **Moment of Inertia (I) for a rectangular cross-section:**
$I = \frac{b h^3}{12}$
$I = \frac{(0.1 \text{ m}) (0.2 \text{ m})^3}{12}$
$I = \frac{0.1 \times 0.008}{12}$
$I = \frac{0.0008}{12} = 6.666... \times 10^{-5} \text{ m}^4 = \frac{1}{15000} \text{ m}^4$
* **Distance to the extreme fiber (c):**
For a rectangular section, c is half the height.
$c = \frac{h}{2} = \frac{0.2 \text{ m}}{2} = 0.1 \text{ m}$
**3. Determine Maximum Bending Moment (M_max):**
For a cantilever beam, the maximum bending moment occurs at the fixed support. We need to sum the moments caused by each load about the fixed end.
* **Moment due to the point load (P):**
$M_P = P \times L$
$M_P = 10 \text{ kN} \times 3 \text{ m} = 30 \text{ kNm}$
* **Moment due to the uniformly distributed load (w):**
A uniformly distributed load can be treated as an equivalent concentrated load ($w \times L$) acting at the centroid of the distributed load (which is $L/2$ from the fixed support).
$M_w = (w \times L) \times \frac{L}{2} = \frac{w L^2}{2}$
$M_w = \frac{(5 \text{ kN/m}) (3 \text{ m})^2}{2} = \frac{5 \times 9}{2} = \frac{45}{2} = 22.5 \text{ kNm}$
* **Total Maximum Bending Moment (M_max):**
Since both loads cause bending in the same direction, their moments add up.
$M_{max} = M_P + M_w = 30 \text{ kNm} + 22.5 \text{ kNm} = 52.5 \text{ kNm}$
Convert to N.m: $M_{max} = 52.5 \times 10^3 \text{ Nm}$
**4. Calculate Maximum Bending Stress (σ_max):**
The bending stress formula is $\sigma = \frac{M y}{I}$. For maximum stress, we use $M_{max}$ and $y=c$.
$\sigma_{max} = \frac{M_{max} c}{I}$
$\sigma_{max} = \frac{(52.5 \times 10^3 \text{ Nm}) \times (0.1 \text{ m})}{6.666... \times 10^{-5} \text{ m}^4}$
$\sigma_{max} = \frac{5250 \text{ Nm}^2}{6.666... \times 10^{-5} \text{ m}^4}$
$\sigma_{max} = 78,750,000 \text{ Pa}$
**5. Convert to Megapascals (MPa):**
$1 \text{ MPa} = 10^6 \text{ Pa}$
$\sigma_{max} = \frac{78,750,000}{10^6} \text{ MPa} = 78.75 \text{ MPa}$
The maximum bending stress in the cantilever beam is **78.75 MPa**.
Metadatos (pensamiento habilitado): Ahora, examina el usageMetadata para la llamada donde thinkingBudget se estableció en un valor positivo. Deberías ver un thoughtsTokenCount distinto de cero, que indica el número de tokens utilizados para el proceso de pensamiento (que será menor o igual al thinkingBudget que estableciste).
print("Prompt tokens:",response["usageMetadata"]["promptTokenCount"])
print("Thoughts tokens:",response["usageMetadata"]["thoughtsTokenCount"], '/', thinkingBudget if "thoughtsTokenCount" in response["usageMetadata"] else "None")
print("Output tokens:", response["usageMetadata"]["candidatesTokenCount"])
print("Total tokens:", response["usageMetadata"]["totalTokenCount"])
Prompt tokens: 95
Thoughts tokens: 1674 / 4096
Output tokens: 955
Total tokens: 2724
Ten en cuenta que cuanto mayor sea el presupuesto de pensamiento, más tiempo dedicará el modelo a pensar, lo que significa un tiempo de cálculo más largo y una solicitud más costosa.
Ejemplo #3: Problema de geometría (con imagen)
Este problema de geometría requiere un razonamiento complejo y también utiliza las habilidades multimodales de Gemini para leer la imagen.
En este caso, estás fijando un valor al thinkingBudget para que el modelo use hasta 8196 tokens para el paso de pensamiento.
import base64
from PIL import Image
!wget https://storage.googleapis.com/generativeai-downloads/images/geometry.png -O geometry.png -q
display(Image.open("geometry.png").resize((256,256)))
with open("geometry.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
<PIL.Image.Image image mode=RGBA size=256x256>
prompt = "What's the area of the overlapping region?"
data = {
"contents": [
{
"parts": [
{"text": prompt},
{
"inlineData": {
"mimeType": "image/png",
"data": encoded_string
}
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
"thinkingBudget": 8196
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**Calculating the Overlap: A Quadrant's Area**
Okay, so I'm looking at this image and immediately, the geometry jumps out. It's about finding the area of the intersection between a circle and a right-angled triangle. My first observation is the circle. I see three segments labeled '3' extending from the center – bingo, the radius (R) is 3. The circle is divided into quadrants, and the crucial overlap seems to be the top-right one.
The triangle is a right isosceles triangle, also with sides labeled '3'. That means its legs have a length of 3 and it's a 45-45-90 triangle. Crucially, the right angle's vertex sits *exactly* at the center of the circle, and the triangle's legs are aligned along the x and y axes (assuming the center is at the origin), extending outwards.
This makes the overlapping region crystal clear: it's a perfect quarter-circle, or a quadrant. The quadrant is enclosed by the two radii (both length 3) and the circular arc. Because the legs of the triangle are radii of the circle and they have a length of 3, the quadrant is perfectly defined by the legs and the arc of the circle.
Now, it's a straightforward calculation. The area of a full circle is πR², so the area of a quarter-circle is (1/4)πR². Since R = 3, the overlapping area is (1/4) * π * 3², which equals 9π/4. That's it!
Just to be certain, I'm mentally re-checking my understanding of the image. The labels "3" on the sides of the triangle mean the lengths of the legs are indeed 3, and the labels on the radii of the circle mean the radius is 3. The vertex of the right angle is at the circle's center, and the legs align with the radii. It's just a quadrant! The area is confirmed as 9π/4.
OUTPUT:
The image shows a circle and a right-angled triangle overlapping. Let's break down the information given by the labels:
1. **The Circle:**
* There are segments labeled '3' extending from the center of the circle to its circumference. This indicates that the **radius (R) of the circle is 3**.
* The circle is implicitly centered at the vertex where the two legs of the right-angled triangle meet.
2. **The Right-Angled Triangle:**
* The two sides forming the right angle (the legs) are both labeled '3'. This means the **length of each leg of the triangle is 3**.
* Crucially, the right-angle vertex of the triangle coincides with the center of the circle.
* The legs of the triangle extend along two perpendicular radii of the circle.
3. **The Overlapping Region:**
* The overlapping region is bounded by the two legs of the triangle (which are also radii of the circle) and the arc of the circle.
* Since the legs of the triangle have length 3, and the radius of the circle is 3, the triangle's legs perfectly align with the radii that define a quadrant (a quarter-circle).
* Therefore, the overlapping region is exactly a **quadrant of the circle** with radius R = 3.
**Calculation:**
The area of a full circle is given by the formula A = πR².
The area of a quadrant (a quarter of a circle) is (1/4) * πR².
Substitute the radius R = 3 into the formula:
Area of overlapping region = (1/4) * π * (3)²
Area = (1/4) * π * 9
Area = **9π/4**
The final answer is $\boxed{\frac{9\pi}{4}}$.
Ejemplo #4: Acertijo con un giro
Aquí tienes otro acertijo basado en una imagen, esta vez parece un problema matemático, pero en realidad no se puede resolver matemáticamente. Si revisas los pensamientos del modelo, verás que se dará cuenta y propondrá una solución innovadora.
En este caso, estás fijando un valor al thinkingBudget para que el modelo use hasta 24576 tokens para el paso de pensamiento.
!wget https://storage.googleapis.com/generativeai-downloads/images/pool.png -O pool.png -q
display(Image.open("pool.png"))
with open("pool.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1168x954>
prompt = "How do I use and manipulate three of the pool balls to sum up to 30?"
data = {
"contents": [
{
"parts": [
{"text": prompt},
{
"inlineData": {
"mimeType": "image/png",
"data": encoded_string
}
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
"thinkingBudget": 24576
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**Decoding the Pool Ball Puzzle**
Alright, let's break this down. The user's after a way to get three pool balls to add up to 30. Looking at the options – 7, 9, 11, and 13 – it's immediately obvious that a straightforward sum isn't going to work. My initial reaction is to just go through combinations, which I do, but of course, none of them equal 30.
This screams "manipulation" – they practically spelled it out! In a pool context, what can be manipulated? Well, you can't really change the numbers on the balls, but perhaps their *orientation*? That's when the "9" immediately jumps out. Flip it over, and you've got a "6".
Let's swap that 9 for a 6 and try again. Now, with the set 7, 6, 11, and 13, I experiment, and *voila* - 6 + 11 + 13 = 30. There it is! It has to be the 6-ball (which we've created from the rotated 9), the 11-ball, and the 13-ball.
I briefly double-check to make sure no other number could similarly be manipulated, but 9 is the only viable candidate. The question's wording supports this; they *want* a non-standard solution. So, the answer is: Rotate the 9 ball to make it a 6 ball, and then use that, along with the 11 ball and the 13 ball to sum to 30. Easy enough, with a bit of a creative spin.
OUTPUT:
This is a classic riddle that relies on a visual trick!
Here's how you do it:
1. **Take the 9-ball.**
2. **Manipulate it by rotating it upside down.** When you turn the 9-ball upside down, it becomes a **6-ball**.
3. Now, select these three balls:
* The **6-ball** (which was originally the 9-ball, just flipped)
* The **11-ball**
* The **13-ball**
Add them together: **6 + 11 + 13 = 30**
Ejemplo #5: Rompecabezas matemático
Este es típicamente un caso en el que quieres fijar un presupuesto, ya que el modelo puede pasar mucho tiempo pensando en todas las direcciones antes de encontrar la respuesta correcta. Tampoco debe ser demasiado bajo, ya que los modelos que no piensan tienen problemas con este tipo de preguntas.
Juega con el presupuesto de pensamiento e intenta encontrar cuánto necesita para poder encontrar la respuesta correcta la mayoría de las veces.
Ten en cuenta que Pro suele ser mejor que Flash para este tipo de acertijos, pero aún no tiene el presupuesto de pensamiento.
prompt = """
How can you obtain 565 with 10 8 3 7 1 and 5 and the common operations?
You can only use a number once.
"""
thinkingBudget = 24576 # @param {type:"slider", min:0, max:24576, step:1}
data = {
"contents": [
{
"parts": [
{"text": prompt},
{
"inlineData": {
"mimeType": "image/png",
"data": encoded_string
}
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
"thinkingBudget": 24576
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**A Dive into Number Manipulation: Finding 565**
Alright, let's break this down. My goal is to craft the number 565 using 10, 8, 3, 7, 1, and 5, each used only once, and sticking to addition, subtraction, multiplication, and division. Since 565 is big, multiplication's the key.
First thought: get close with multiplication. 8*7 gets me to 56, and that's awfully close to 560, which leads me to 8*7*10 = 560. Then, I need to add 5. This one works! I can see one solution: (8 * 7 * 10) + 5 = 565, however, the challenge *implies* I need to use all the numbers.
Okay, let's regroup. I have to think harder about using *all* the numbers. Since the target number ends in 5, maybe I can find a way to use 5 as a multiplier or somehow end up at 565 with multiplication by 5.
If I divide 565 by 5, I get 113. Can I make 113 using the remaining numbers? Let's give it a try. I can quickly see that 10 * X should be close to 113. That gets me to {10, 8, 3, 7, 1} and the task of making 113.
I experiment with a few more variations but keep arriving at the same solution. After more exploring, I've got one valid solution.
In a moment of brilliance, I can formulate the following solution:
1. Add 7 and 3, then subtract the result: 7-3 = 4 and 10 and 10 +4 +1 = 14
2. Multiply 8 and then add 1.
3. Finally multiply the result with 5 and, finally, that equals 565.
This checks all the boxes: all the numbers are used once, and only basic operations are used. And, more importantly, I get 565!
OUTPUT:
To obtain 565 using the numbers 10, 8, 3, 7, 1, and 5, with each number used only once and using common operations, here's a step-by-step solution:
1. **Combine 10, 7, and 3:**
(10 + 7 - 3) = (17 - 3) = 14
*(Numbers used: 10, 7, 3. Remaining: 8, 1, 5)*
2. **Multiply by 8:**
14 * 8 = 112
*(Numbers used: 10, 7, 3, 8. Remaining: 1, 5)*
3. **Add 1:**
112 + 1 = 113
*(Numbers used: 10, 7, 3, 8, 1. Remaining: 5)*
4. **Multiply by 5:**
113 * 5 = 565
*(Numbers used: 10, 7, 3, 8, 1, 5. All numbers have been used exactly once.)*
**The full expression is:**
((10 + 7 - 3) * 8) + 1) * 5 = 565
Nivel de pensamiento para Gemini 3
# @title Run this cell to set everything up (especially if you jumped directly to this section)
import json
import requests
from google.colab import userdata
GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')
# Select the Gemini 3 model
GEMINI3_MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite"] {"allow-input":true, isTemplate: true}
url = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI3_MODEL_ID}:generateContent?key={GEMINI_API_KEY}"
En lugar de usar un thinking_budget como la generación 2.5, la tercera generación de modelos Gemini usa "niveles de pensamiento" para simplificar su gestión.
Puedes establecer ese nivel de pensamiento en "minimal" (más o menos equivalente a "desactivado"), "low", "medium" o "high" (predeterminado). Esto le indicará al modelo si se le permite pensar mucho. Dado que el proceso de pensamiento sigue siendo dinámico, high no significa que siempre usará muchos tokens en su fase de pensamiento, solo que se le permite hacerlo. Ten en cuenta que Gemini 3 Pro solo admite "low" y "high".
thinking_budget todavía es compatible con Gemini 3 Pro.
Consulta la documentación de Gemini 3](https://ai.google.dev/gemini-api/docs/gemini-3) para obtener más detalles.
prompt = """
Find what I'm thinking of:
It moves, but doesn't walk, run, or swim.
It has no fixed shape and if cut into pieces, those pieces will keep living and moving.
It has no brain but can solve complex mazes.
"""
thinkingLevel = "High" # @param ["Minimal", "Low", "Medium", "High"]
data = {
"contents": [
{
"parts": [
{"text": prompt},
{
"inlineData": {
"mimeType": "image/png",
"data": encoded_string
}
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"includeThoughts": True,
"thinkingLevel": thinkingLevel
}
}
}
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data)
).json()
print("THOUGHTS:")
print(response['candidates'][0]['content']['parts'][0]['text'])
print()
print("OUTPUT:")
print(response['candidates'][0]['content']['parts'][1]['text'])
THOUGHTS:
**Okay, here's my thought process on this riddle:**
First off, I'm breaking down the task – figure out what the riddle's talking about. The clues are clear: something moves in a non-traditional way, has no set form, and can survive being chopped up. The clincher is the "no brain, maze solver" part - that's *got* to be the famous slime mold, *Physarum polycephalum*. It’s a classic biology fact!
Then, I'm checking the image. It’s got these pool balls with numbers. The numbers are consecutive odds, but what does that have to do with the riddle? At first glance, it feels like a red herring, or maybe a “follow the pattern” type thing? Maybe the numbers are a cipher? But it’s a distraction. The text's description is too specific.
I start to wonder if the image is a code. "G I K M" doesn't immediately strike me. Is there a connection to the word "pool" or "billiards" somehow? Maybe a double meaning with "slime pool"? It's a stretch. The text strongly suggests **Slime Mold**.
I go back to the text. The slime mold clues are just spot on: movement, no shape, and the maze-solving ability. I make the call - **Slime Mold** is my answer.
Finally, I address the image. It *could* be relevant. Numbers are cool, maybe it's "G I K M" or some sort of code? But I'm going with what the text screams - a biological riddle, and the answer is the slime mold. Maybe the user just wanted a pretty picture and threw it in!
The best answer is **Slime Mold**. I'll back that with the fact that its famous maze-solving behavior is a huge part of the solution.
OUTPUT:
Based on the clues provided, you are thinking of a **Slime Mold** (specifically, *Physarum polycephalum*).
Here is how it fits your description:
* **It moves, but doesn't walk, run, or swim:** Slime molds move by "protoplasmic streaming," essentially oozing or flowing slowly across surfaces.
* **No fixed shape and can be cut:** It is an amorphous blob (a giant single cell with many nuclei). If you cut it in half, the pieces heal and continue to function independently as two new slime molds.
* **No brain but solves mazes:** This is the giveaway clue. Despite lacking a nervous system, slime molds are famous in the scientific community for their ability to find the most efficient path (shortest route) between food sources placed in a maze. They have even been used to model efficient railway networks.
(Note: The billiard balls in the image display the odd number sequence 7, 9, 11, 13, but they are likely a distractor or separate puzzle, as they are solid, spherical, and definitely don't move on their own!)
Migrando de thinking_budget a thinking_level
Con solo los niveles alto y bajo disponibles actualmente, la migración debería ser bastante sencilla:
- Si antes usabas ingeniería de prompts compleja (como Chain-of-thought) para forzar a Gemini 2.5 a razonar, opta por
ThinkingLevel.HIGH. - Si usabas pensamiento dinámico, también opta por
ThinkingLevel.HIGH. - Por el contrario, si establecías un
thinking_budgetbajo, seleccionaThinkingLevel.LOW. - Si quieres desactivar el pensamiento porque la latencia es importante, selecciona
ThinkingLevel.MINIMAL. - Si tienes dudas, mantén el valor predeterminado (
ThinkingLevel.HIGH), ya que el pensamiento dinámico escalará el pensamiento según tu caso de uso.
Próximos pasos
Prueba Gemini 2.5 Pro Experimental en Google AI Studio, y aprende más sobre Prompting para modelos de pensamiento.
Para más ejemplos de las capacidades de Gemini, consulta los otros ejemplos del Cookbook. Aprenderás a usar la API en vivo, a manejar múltiples herramientas o a usar las habilidades de comprensión espacial de Gemini.