La API de Gemini (Interactions API) permite generar texto, imágenes, entender
contenido multimodal y conectar el modelo a tu código. Se usa con el SDK
google-genai y una sola llamada central:
client.interactions.create(...). A continuación dos casos de uso, del más
simple al más completo, y el grafo animado del ciclo.
El "hola mundo": una llamada para generar texto y su versión en streaming.
# pip install -U google-genai
# export GEMINI_API_KEY="tu-api-key"
from google import genai
# 1. Crear el cliente (lee GEMINI_API_KEY).
client = genai.Client()
# 2. Primera llamada: modelo + entrada (input).
interaction = client.interactions.create(
model="gemini-3.6-flash",
input="Explain how AI works in a few words"
)
# 3. El texto final está en output_text.
print(interaction.output_text)
# ---- Streaming: respuesta en tiempo real ----
stream = client.interactions.create(
model="gemini-3.6-flash",
input="Explain how AI works",
stream=True
)
for event in stream:
print(event) # cada evento = un fragmento (step.delta)
genai.Client() crea el cliente y autentica con GEMINI_API_KEY.interactions.create(model, input) envía la solicitud.Interaction con pasos (steps) y metadatos.output_text extrae el texto final; con stream=True se reciben eventos SSE.models.generate_content().
Más info: ai.google.dev/gemini-api/docs/interactions-overview.
Conecta el modelo a tu código: declaras una función, el modelo la invoca y tú ejecutas el resultado.
import json
from google import genai
client = genai.Client()
# 1. Declarar la herramienta (esquema de la función).
weather_tool = {
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name, e.g. San Francisco"},
},
"required": ["location"],
},
}
# 2. Funciones locales (el modelo NO las ejecuta; las ejecutas tú).
available_functions = {
"get_current_temperature": lambda location: {
"location": location, "temperature": "22", "unit": "celsius"
},
}
user_input = "What is the temperature in London?"
previous_id = None
# 3. Bucle: el modelo pide la función → la ejecutas → devuelves el resultado.
while True:
interaction = client.interactions.create(
model="gemini-3.6-flash",
input=user_input,
tools=[weather_tool],
previous_interaction_id=previous_id,
)
function_results = []
for step in interaction.steps:
if step.type == "function_call":
result = available_functions[step.name](**step.arguments)
print(f"Called {step.name}({step.arguments}) → {result}")
function_results.append({
"type": "function_result",
"name": step.name,
"call_id": step.id,
"result": [{"type": "text", "text": json.dumps(result)}],
})
if not function_results:
break # ya no hay más funciones que llamar
user_input = function_results
previous_id = interaction.id
print(interaction.output_text)
| Concepto | Qué es |
|---|---|
tools=[...] | Funciones que el modelo puede invocar |
step.type == "function_call" | El modelo solicita ejecutar una función |
step.arguments | Argumentos estructurados generados por el modelo |
function_result | Resultado que tú devuelves al modelo |
previous_interaction_id | Encadena turnos (estado en el servidor) |
El token 🟠 recorre el flujo en orden. Clic en el gráfico reinicia la animación.
| # | Caso | Qué enseña |
|---|---|---|
| 1 | Generación de texto | genai.Client, interactions.create, output_text, stream |
| 2 | Function calling | tools, function_call / function_result, previous_interaction_id |
C:\Users\TUF\Documents\librerías\local\ antes de instalar.
Instalación: pip install -U google-genai.
Docs: https://ai.google.dev/gemini-api/docs/get-started.