> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aihubmix.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Guías de Gemini

> Una guía completa de las llamadas a la API de Gemini en nuestra plataforma.

## Reenvío para los modelos de Gemini

Para la serie Gemini, ofrecemos **dos** métodos de invocación: llamadas a la API nativa y llamadas compatibles con OpenAI.\
Antes de empezar, asegúrate de instalar o actualizar la dependencia nativa ejecutando `pip install google-genai` o `pip install -U google-genai`.

1️⃣ Para la integración nativa, Gemini se encarga automáticamente de enrutar el tráfico entre AI Studio y VertexAI. Solo tienes que proporcionar tu **clave API de AIHubMix** y la **URL de solicitud** adecuada. Recuerda que esta URL es diferente del habitual `base_url`; sigue el ejemplo a continuación para asegurar una configuración correcta.

```python theme={null}
client = genai.Client(
    api_key="sk-***",  # Replace with the key you generated from AiHubMix
    http_options={"base_url": "https://aihubmix.com/gemini"},
)
```

2️⃣ Para los formatos compatibles con OpenAI, mantén el endpoint universal `v1`.

```py theme={null}
client = OpenAI(
    api_key="sk-***", # Replace with the key you generated from AiHubMix
    base_url="https://aihubmix.com/v1",
)
```

3️⃣ Para la serie 2.5, si necesitas mostrar el proceso de razonamiento, hay dos formas de hacerlo:

1. **Invocación nativa:** Pasa `include_thoughts=True`
2. **Método compatible con OpenAI:** Pasa `reasoning_effort`

Puedes consultar los ejemplos de código a continuación para conocer el uso detallado.

## Instrucciones de la vista previa de imágenes con **Gemini 3 Pro**

Gemini 3 Pro Image Preview (Nano Banana Pro Preview) está diseñado para la creación de recursos profesionales e instrucciones complejas. Este modelo ofrece las siguientes funciones:

* Usa Google Search para recuperar conocimiento del mundo en tiempo real
* Proceso de "razonamiento" integrado (optimiza la composición antes de generar)
* Puede generar imágenes con resoluciones de hasta **4K**

<Tip>
  <strong>Modo de streaming (`stream=True`)</strong>
  → solo la etapa de razonamiento\
  <strong>Modo sin streaming (`stream=False`)</strong>
  → generación final de la imagen

  Las imágenes generadas <strong>no se incluyen en las respuestas en streaming</strong>
  y deben recuperarse mediante una <strong>solicitud sin streaming</strong>
  .
</Tip>

**Ejemplos de uso en Python:**

<CodeGroup>
  ```python Text-to-Image theme={null}
  import os
  from google import genai
  from google.genai import types

  API_KEY = "<YOUR AIHUBMIX API KEY>"  

  client = genai.Client(
      api_key=API_KEY,
      http_options={"base_url": "https://aihubmix.com/gemini"},  
  )

  prompt = (
      "Da Vinci style anatomical sketch of a dissected Monarch butterfly. "
      "Detailed drawings of the head, wings, and legs on textured parchment with notes in English."
  )

  # Optional parameters
  aspect_ratio = "1:1"   # Supported: "1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"
  resolution   = "4K"    # Default: 1K. Supported: "1K", "2K", "4K". Note: “K” must be uppercase.

  response = client.models.generate_content(
      model="gemini-3-pro-image-preview",
      contents=prompt,   
      config=types.GenerateContentConfig(
          response_modalities=['TEXT', 'IMAGE'],
          image_config=types.ImageConfig(
              aspect_ratio=aspect_ratio,
              image_size=resolution,
          ),
      ),
  )

  # Save image & print text
  for part in response.parts:
      if part.text:
          print(part.text)  
      elif image := part.as_image():
          image.save("butterfly.png")
          print("Image saved: butterfly.png")
  ```

  ```python Image-to-Image theme={null}
  from google import genai
  from PIL import Image

  API_KEY = "<YOUR AIHUBMIX API KEY>"

  client = genai.Client(
      api_key=API_KEY,
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  prompt = (
      "Create a picture of my cat eating a nano-banana "
      "in a fancy restaurant under the Gemini constellation."
  )

  image = Image.open("cat_image.jpg")

  response = client.models.generate_content(
      model="gemini-2.5-flash-image",
      contents=[prompt, image],
  )

  # Save image & print text
  for part in response.parts:
      if part.text is not None:
          print(part.text)
      elif part.inline_data is not None:
          image = part.as_image()
          image.save("generated_image.png")
  ```

  ```python Multiple Imag theme={null}
  from google import genai
  from google.genai import types
  from PIL import Image

  API_KEY = "<YOUR AIHUBMIX_API_KEY>"

  prompt = "An office group photo of these people, they are making funny faces."
  aspect_ratio = "5:4"
  resolution = "2K"

  client = genai.Client(
      api_key=API_KEY,
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-3-pro-image-preview",
      contents=[
          prompt,
          Image.open('person1.png'),
          Image.open('person2.png'),
          Image.open('person3.png'),
          Image.open('person4.png'),
          Image.open('person5.png'),
      ],
      config=types.GenerateContentConfig(
          response_modalities=['TEXT', 'IMAGE'],
          image_config=types.ImageConfig(
              aspect_ratio=aspect_ratio,
              image_size=resolution,
          ),
      )
  )

  # Save image & print text
  for part in response.parts:
      if part.text is not None:
          print(part.text)
      elif image := part.as_image():
          image.save("office.png")
  ```

  ```python Google Search theme={null}
  from google import genai
  from google.genai import types

  API_KEY = "<YOUR AIHUBMIX API KEY>"

  prompt = (
      "Visualize the current weather forecast for the next 5 days in Shanghai "
      "as a clean, modern weather chart. Add a visual showing what I should wear each day."
  ) # Display Shanghai’s five-day weather in a chart format

  aspect_ratio = "16:9"

  client = genai.Client(
      api_key=API_KEY,
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-3-pro-image-preview",
      contents=prompt,
      config=types.GenerateContentConfig(
          response_modalities=['TEXT', 'IMAGE'],
          image_config=types.ImageConfig(
              aspect_ratio=aspect_ratio,
          ),
          tools=[{"google_search": {}}]
      )
  )

  # Save image & print text
  for part in response.parts:
      if part.text is not None:
          print(part.text)
      elif image := part.as_image():
          image.save("weather.png")
  ```
</CodeGroup>

## Acerca de los modelos de inferencia de Gemini 2.5

1. Toda la serie 2.5 está formada por **modelos de inferencia**.
2. **2.5 Flash** es un modelo híbrido, similar a Claude Sonnet 3.7. Puedes afinar su comportamiento de razonamiento ajustando el parámetro `thinking_budget` para un control óptimo.
3. **2.5 Pro** es un modelo de inferencia puro. El razonamiento no se puede desactivar y `thinking_budget` no debe establecerse explícitamente.

**Ejemplos de uso en Python:**

<CodeGroup>
  ```py StreamFalse theme={null}
  from google import genai
  from google.genai import types

  def generate():
      client = genai.Client(
          api_key="sk-***", # 🔑 Replace it by your AiHubMix Key
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.0-flash"
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How do I know I'm not wasting time?"""),
              ],
          ),
      ]

      print(client.models.generate_content(
          model=model,
          contents=contents,
      ))

  if __name__ == "__main__":
      generate()
  ```

  ```py 2.0 Series-Stream theme={null}
  from google import genai
  from google.genai import types

  def generate():
      client = genai.Client(
          api_key="sk-***", # 🔑 Replace it by your AiHubMix Key
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.0-flash"
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How do I know I'm not wasting time?"""),
              ],
          ),
      ]
      generate_content_config = types.GenerateContentConfig(
          response_mime_type="text/plain",
      )

      for chunk in client.models.generate_content_stream(
          model=model,
          contents=contents,
          config=generate_content_config,
      ):
          print(chunk.text, end="")

  if __name__ == "__main__":
      generate()
  ```

  ```py 2.5 Flash-Stream theme={null}
  from google import genai
  from google.genai import types

  def generate():
      client = genai.Client(
          api_key="sk-***", # 🔑 Replace it by your AiHubMix Key
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.5-flash-preview-04-17" #gemini-2.5-pro-preview-03-25、gemini-2.5-flash-preview-04-17
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How do I know I'm not wasting time?"""),
              ],
          ),
      ]
      generate_content_config = types.GenerateContentConfig(
          thinking_config = types.ThinkingConfig(
              thinking_budget=2048, #range: 0-16K。1024 as default，16000 for best performance
          ),
          response_mime_type="text/plain",
      )

      for chunk in client.models.generate_content_stream(
          model=model,
          contents=contents,
          config=generate_content_config,
      ):
          print(chunk.text, end="")

  if __name__ == "__main__":
      generate()
  ```

  ```py 2.5 Pro-Stream theme={null}
  from google import genai
  from google.genai import types

  def generate():
      client = genai.Client(
          api_key="sk-***", # 🔑 Replace it by your AiHubMix Key
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.5-pro-preview-03-25"
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How do I know I'm not wasting time?"""),
              ],
          ),
      ]
      generate_content_config = types.GenerateContentConfig(
          response_mime_type="text/plain",
      )

      for chunk in client.models.generate_content_stream(
          model=model,
          contents=contents,
          config=generate_content_config,
      ):
          print(chunk.text, end="")

  if __name__ == "__main__":
      generate()
  ```

  ```py 2.5 Show Thinking theme={null}
  from google import genai
  from google.genai import types

  def generate():
      client = genai.Client(
          api_key="sk-***", # 🔑 Replace it by your AiHubMix Key
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.5-pro-preview-05-06"
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How is the "Rule of 72" in finance derived?"""),
              ],
          ),
      ]
      generate_content_config = types.GenerateContentConfig(
          response_mime_type="text/plain",
          thinking_config=types.ThinkingConfig(
              include_thoughts=True  # Show Thinking Content
          ),
      )

      final_usage_metadata = None
      
      for chunk in client.models.generate_content_stream(
          model=model,
          contents=contents,
          config=generate_content_config,
      ):
          if chunk.candidates and len(chunk.candidates) > 0:
              for part in chunk.candidates[0].content.parts:
                  if part.text:
                      if part.thought:
                          print(part.text, end="")
                      else:
                          print(part.text, end="")

          if chunk.usage_metadata:
              final_usage_metadata = chunk.usage_metadata
      
      if final_usage_metadata:
          print(f"\n\n📊 Token Usage:")
          print(f"Thinking tokens: {getattr(final_usage_metadata, 'thoughts_token_count', '不可用')}")
          print(f"Output tokens: {getattr(final_usage_metadata, 'candidates_token_count', '不可用')}")
          print(f"Total: {final_usage_metadata}")

  if __name__ == "__main__":
      generate()
  ```
</CodeGroup>

## Gemini 2.5 Flash: Soporte para tareas rápidas

Ejemplo de invocación compatible con OpenAI:

<CodeGroup>
  ```py Python Disable thinking for rapid task theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="AIHUBMIX_API_KEY", # Replace with the key you generated in AiHubMix
      base_url="https://aihubmix.com/v1",
  )

  completion = client.chat.completions.create(
      model="gemini-2.5-flash-preview-04-17-nothink",
      messages=[
          {
              "role": "user",
              "content": "Explain the Occam's Razor concept and provide everyday examples of it"
          }
      ]
  )

  print(completion.choices[0].message.content)
  ```

  ```py Python Reasoning Effort theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-***", # Replace with the key you generated in AiHubMix
      base_url="https://aihubmix.com/v1",
  )

  completion = client.chat.completions.create(
      model="gemini-2.5-flash-preview-04-17",
      reasoning_effort="low", #"low", "medium", and "high", map to 1K, 8K, and 16K thinking token budgets
      messages=[
          {
              "role": "user",
              "content": "Explain the Occam's Razor concept and provide everyday examples of it"
          }
      ]
  )

  print(completion.choices[0].message.content)
  ```

  ```shell Curl-Basic theme={null}
  curl -X POST https://aihubmix.com/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer sk-***" \
    -d '{
      "model": "gemini-2.5-flash-preview-04-17-nothink",
      "messages": [
        {
          "role": "user",
          "content": "Explain the Occam'\''s Razor concept and provide an everyday example of it."
        }
      ]
    }'
  ```

  ```shell Curl-Show Thinking theme={null}
  curl https://aihubmix.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-***" \
  -d '{
    "model": "gemini-2.5-pro-preview-05-06",
    "messages": [
      {
        "role": "user",
        "content": "Explain the Occam'\''s Razor concept and provide an everyday example of it."
      }
    ],
    "reasoning_effort": "low"
  }'
  ```
</CodeGroup>

<Tip>
  1. Para tareas complejas, basta con establecer el ID de modelo en el predeterminado `gemini-2.5-flash-preview-04-17` para activar el razonamiento.
  2. Gemini 2.5 Flash usa el parámetro `budget` para controlar la profundidad del razonamiento, en un rango de 0 a 16K. El presupuesto predeterminado es 1024 y el efecto marginal óptimo se obtiene con 16K.
</Tip>

## Comprensión multimedia

* Para los archivos multimedia **inferiores a 20 MB** (imágenes, audio, vídeo), súbelos usando `inline_data`.
* Cuando el archivo multimedia es **mayor de 20 MB**, debes usar la Files API.

### Archivos menores de 20 MB

<Tip>
  Añadiendo el parámetro `EDIARESOLUTION_MEDIUM` puedes ajustar la resolución de la imagen, lo que reduce considerablemente los costos de entrada y minimiza el riesgo de errores con imágenes grandes.

  **Valores admitidos para la resolución multimedia:**

  | Nombre                         | Descripción                                                                   |
  | ------------------------------ | ----------------------------------------------------------------------------- |
  | MEDIA\_RESOLUTION\_UNSPECIFIED | La resolución multimedia no se ha establecido.                                |
  | MEDIA\_RESOLUTION\_LOW         | Resolución multimedia establecida en baja (64 tokens).                        |
  | MEDIA\_RESOLUTION\_MEDIUM      | Resolución multimedia establecida en media (256 tokens).                      |
  | MEDIA\_RESOLUTION\_HIGH        | Resolución multimedia establecida en alta (reencuadre con zoom y 256 tokens). |
</Tip>

**Ejemplos de uso en Python:**

<CodeGroup>
  ```python Image theme={null}
  from google import genai
  from google.genai import types

  file_path = "yourpath/file.jpeg"
  with open(file_path, "rb") as f:
      file_bytes = f.read()

  client = genai.Client(
      api_key="sk-***", # Replace with the key you generated in AiHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-2.5-flash",
      contents=types.Content(
          parts=[
              types.Part(
                  inline_data=types.Blob(
                      data=file_bytes,
                      mime_type="image/jpeg"
                  )
              ),
              types.Part(
                  text="Describe the image."
              )
          ]
      ),
      config=types.GenerateContentConfig(
          system_instruction="You are a helpful assistant that can describe images.",
          max_output_tokens=768,
          temperature=0.1,
          thinking_config=types.ThinkingConfig(
              thinking_budget=0, include_thoughts=False
          ),
          media_resolution=types.MediaResolution.MEDIA_RESOLUTION_MEDIUM # 256 tokens
      )
  )

  print(response.text)
  ```

  ```python Audio theme={null}
  from google import genai
  from google.genai import types

  file_path = "yourpath/file.m4a"
  with open(file_path, "rb") as f:
      file_bytes = f.read()

  client = genai.Client(
      api_key="sk-***", # Replace with the key you generated in AiHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-2.0-flash",
      contents=types.Content(
          parts=[
              types.Part(
                  inline_data=types.Blob(
                      data=file_bytes,
                      mime_type="audio/m4a"
                  )
              ),
              types.Part(
                  text="Transcribe the audio to text."
              )
          ]
      )
  )

  print(response.text)
  ```

  ```python Video theme={null}
  from google import genai
  from google.genai import types

  file_path = "yourpath/file.mp4"
  with open(file_path, "rb") as f:
      file_bytes = f.read()

  client = genai.Client(
      api_key="sk-***", # Replace with the key you generated in AiHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-2.0-flash",
      contents=types.Content(
          parts=[
              types.Part(
                  inline_data=types.Blob(
                      data=file_bytes,
                      mime_type="video/mp4"
                  )
              ),
              types.Part(
                  text="Summarize this video. Then create a quiz with an answer key based on the information in this video."
              )
          ]
      )
  )

  print(response.text)
  ```

  ```python Youtube URL theme={null}
  from google import genai
  from google.genai import types

  client = genai.Client(
      api_key="sk-***", # Replace with the key you generated in AiHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"}
  )

  response = client.models.generate_content(
      model="gemini-2.0-flash",
      contents=types.Content(
          parts=[
              types.Part(
                  file_data=types.FileData(
                      file_uri="https://www.youtube.com/watch?v=OoU7PwNyYUw"
                  )
              ),
              types.Part(
                  text="Please summarize the video in 3 sentences."
              )
          ]
      )
  )

  print(response.text)
  ```
</CodeGroup>

### Files API

Gemini puede gestionar simultáneamente varios tipos de datos de entrada, incluidos texto, imágenes y audio. Cuando el tamaño total de la solicitud (incluidos archivos, prompts de texto, comandos del sistema, etc.) supere los **20 MB**, asegúrate de usar la Files API.

<Tip>
  * No se admite listar los archivos subidos.
  * Los archivos se eliminarán automáticamente después de 48 horas, o puedes eliminar manualmente los archivos subidos.
</Tip>

**Ejemplos de uso en Python:**

<CodeGroup>
  ```python Upload a file theme={null}
  from google import genai

  client = genai.Client(
      api_key="sk-****",   
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )

  myfile = client.files.upload(file="path/to/sample.mp3")

  response = client.models.generate_content(
      model="gemini-2.5-flash", contents=["Describe this audio clip", myfile]
  )

  print(response.text)
  ```

  ```python Get metadata for a file theme={null}
  from google import genai

  client = genai.Client(
      api_key="sk-****",   
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )

  myfile = client.files.upload(file='path/to/sample.mp3')
  file_name = myfile.name
  myfile = client.files.get(name=file_name)
  print(myfile)
  ```

  ```python Delete uploaded files theme={null}
  from google import genai

  client = genai.Client()

  myfile = client.files.upload(file='path/to/sample.mp3')
  client.files.delete(name=myfile.name)
  ```
</CodeGroup>

## Ejecución de código

La función de ejecución de código permite al modelo generar y ejecutar código Python y aprender de los resultados de manera iterativa hasta llegar a una salida final. Puedes usar esta capacidad para construir aplicaciones que se beneficien del razonamiento basado en código y que produzcan salida de texto. Por ejemplo, podrías usar la ejecución de código en una aplicación que resuelva ecuaciones o procese texto.

```py Python theme={null}
from google import genai
from google.genai import types

file_path = "yourpath/file.csv"
with open(file_path, "rb") as f:
    file_bytes = f.read()

client = genai.Client(
    api_key="sk-***", # Replace with the key you generated in AiHubMix
    http_options={"base_url": "https://aihubmix.com/gemini"}
)

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=types.Content(
        parts=[
            types.Part(
                inline_data=types.Blob(
                    data=file_bytes,
                    mime_type="text/csv"
                )
            ),
            types.Part(
                text="Please analyze this CSV and summarize the key statistics. Use code execution if needed."
            )
        ]
    ),
    config=types.GenerateContentConfig(
        tools=[types.Tool(
            code_execution=types.ToolCodeExecution
        )]
    )
)

for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    if getattr(part, "executable_code", None) is not None:
        print("Generated code:\n", part.executable_code.code)
    if getattr(part, "code_execution_result", None) is not None:
        print("Execution result:\n", part.code_execution_result.output)
```

## Interactions API

Interactions es la interfaz de inferencia de nueva generacion de Gemini. Devuelve objetos `Interaction` estructurados y admite generacion de texto, generacion nativa de imagenes (Nano Banana) y razonamiento en multiples pasos. Actualmente se admite el **modo sincrono** (`interactions.create()`); el modo asincrono (Background Interactions) estara disponible proximamente.

<Warning>
  Requisito de version del SDK: `@google/genai` **>= 2.0.0** (JS/TS) o `google-genai` **>= 2.0.0** (Python). Las versiones anteriores del SDK seran rechazadas por el backend de Google (`legacy Interactions schema no longer supported`).
</Warning>

### Generacion de texto

Llama a `interactions.create()` para iniciar una inferencia. El objeto `Interaction` devuelto proporciona la propiedad de conveniencia `output_text`.

<CodeGroup>
  ```js JavaScript theme={null}
  import { GoogleGenAI } from "@google/genai";

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Reemplaza con tu API Key generada en AIHubMix
    httpOptions: { baseUrl: "https://aihubmix.com/gemini" },
  });

  const interaction = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "Explain quantum computing in one sentence",
  });

  console.log(interaction.output_text);
  console.log(interaction.usage);
  // { total_tokens, total_input_tokens, total_output_tokens, ... }
  ```

  ```py Python theme={null}
  from google import genai

  client = genai.Client(
      api_key="sk-***",  # Reemplaza con tu API Key generada en AIHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )

  interaction = client.interactions.create(
      model="gemini-3.5-flash",
      input="Explain quantum computing in one sentence",
  )

  print(interaction.output_text)
  ```
</CodeGroup>

### Generacion nativa de imagenes

Configura la modalidad de salida como imagen mediante `response_format`. El objeto `Interaction` devuelto proporciona la propiedad de conveniencia `output_image`.

<Tip>
  * Modelo recomendado: `gemini-3.1-flash-image` (Nano Banana 2, modelo universal de generacion de imagenes).
  * Los valores de `response_modalities` deben estar en **minusculas**: `['text', 'image']`; las mayusculas son la sintaxis de la API `generateContent` y devuelven un `400` en la Interactions API.
  * No envies `delivery: 'inline'` (`400 Image delivery mode is not supported`) -- los resultados se devuelven en modo inline por defecto.
</Tip>

<CodeGroup>
  ```js JavaScript theme={null}
  import { GoogleGenAI } from "@google/genai";
  import fs from "node:fs";

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Reemplaza con tu API Key generada en AIHubMix
    httpOptions: { baseUrl: "https://aihubmix.com/gemini" },
  });

  const interaction = await ai.interactions.create({
    model: "gemini-3.1-flash-image",
    input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
    response_modalities: ["text", "image"],
    response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
  });

  // Propiedad de conveniencia output_image (ultima imagen generada)
  if (interaction.output_image?.data) {
    fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
  }
  ```

  ```py Python theme={null}
  import base64
  from google import genai

  client = genai.Client(
      api_key="sk-***",  # Reemplaza con tu API Key generada en AIHubMix
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )

  interaction = client.interactions.create(
      model="gemini-3.1-flash-image",
      input="A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
      response_format={
          "type": "image",
          "aspect_ratio": "1:1",
          "image_size": "1K",
      },
  )

  if interaction.output_image:
      with open("output.png", "wb") as f:
          f.write(base64.b64decode(interaction.output_image.data))
  ```
</CodeGroup>

### Salida en streaming

Pasa `stream: true` para habilitar streaming SSE. El texto incremental se obtiene mediante `event.delta.text`.

```js JavaScript theme={null}
const stream = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "Write a haiku about the moon",
  stream: true,
});

for await (const event of stream) {
  if (event.event_type === "step.delta" && event.delta?.type === "text") {
    process.stdout.write(event.delta.text);
  }
  if (event.event_type === "interaction.completed") {
    console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
  }
}
```

> La guia completa de integracion con el SDK (incluyendo Embeddings, CRUD de cache explicito, matriz de capacidades, etc.) esta disponible en [Integracion con SDK nativo de Gemini](/es/api/Gemini-SDK).

## Caché de contexto

La API nativa de Gemini **habilita la caché de contexto implícita por defecto**: no se requiere configuración. Para cada solicitud de `generate_content`, el sistema almacena automáticamente en caché el contenido de entrada. Si una solicitud posterior utiliza exactamente el mismo contenido, modelo y parámetros, el sistema devolverá al instante el resultado previo, acelerando enormemente el tiempo de respuesta y reduciendo potencialmente los costos de tokens de entrada.

* **El almacenamiento en caché es automático; no se necesita configuración manual.**
* La caché solo se acierta cuando el contenido, el modelo y todos los parámetros son exactamente iguales; cualquier diferencia resultará en un fallo de caché.
* La duración de la caché (TTL) puede ser establecida por el desarrollador o dejarse sin definir (por defecto, 1 hora). Google no impone un TTL mínimo ni máximo. Los costos dependen del número de tokens en caché y de la duración de la caché.
  * Aunque Google no impone restricciones al TTL, como plataforma de reenvío, **solo admitimos un rango limitado de TTL**. Para requisitos que excedan los límites de nuestra plataforma, contáctanos.

### Notas

* **No se garantizan ahorros de costo:** Los tokens en caché se facturan al 25 % del precio estándar de entrada, por lo que, teóricamente, el almacenamiento en caché puede ahorrarte hasta el 75 % en costos de tokens de entrada. Sin embargo, la [documentación oficial de Google](https://ai.google.dev/gemini-api/docs/caching?lang=python) no garantiza el ahorro de costos; el efecto real depende de tu tasa de aciertos de caché, los tipos de tokens y la duración del almacenamiento.
* **Condiciones de acierto de caché:** Para maximizar la eficacia de la caché, coloca el contexto repetible al principio de tu entrada y el contenido dinámico (como la entrada del usuario) al final.
* **Cómo detectar aciertos de caché:** Si una respuesta proviene de la caché, `response.usage_metadata` incluirá el campo `cache_tokens_details` y `cached_content_token_count`. Puedes usarlos para determinar el uso de la caché.\
  Ejemplo de campos cuando se produce un acierto de caché:

  ```
  cache_tokens_details=[ModalityTokenCount(modality=<MediaModality.TEXT: 'TEXT'>, token_count=2003)]
  cached_content_token_count=2003
  ```

**Ejemplo de código:**

```python theme={null}
from google import genai

client = genai.Client(
    http_options={"base_url": "https://aihubmix.com/gemini"},
    api_key="sk-***",  # Replace with your AiHubMix API key
)

prompt = """
        <the entire contents of 'Pride and Prejudice'>
"""

def generate_content_sync():
    response = client.models.generate_content(
        model="gemini-2.5-flash-preview-05-20",
        contents=prompt + "Analyze the major themes in 'Pride and Prejudice'.",
    )
    print(response.usage_metadata)  # When cache is hit, cache_tokens_details and cached_content_token_count will appear
    return response

generate_content_sync()
```

> Cuando se produce un acierto de caché, `response.usage_metadata` contendrá:
>
> ```
> cache_tokens_details=[ModalityTokenCount(modality=<MediaModality.TEXT: 'TEXT'>, token_count=2003)]
> cached_content_token_count=2003
> ```

**Conclusión clave:** La caché implícita es automática y ofrece comentarios claros sobre los aciertos de caché. Los desarrolladores pueden comprobar usage\_metadata para conocer el estado de la caché. **No se garantizan ahorros de costos**: el beneficio real depende de la estructura de la solicitud y de las tasas de acierto de la caché.

## Llamadas a funciones (Function calling)

Al usar la forma compatible con OpenAI para invocar las llamadas a funciones de Gemini, debes pasar `tool_choice="auto"` en el cuerpo de la solicitud; de lo contrario, se producirá un error.

<CodeGroup>
  ```py Python theme={null}
  from openai import OpenAI

  # Define the function declaration for the model
  schedule_meeting_function = {
      "name": "schedule_meeting",
      "description": "Schedules a meeting with specified attendees at a given time and date.",
      "parameters": {
          "type": "object",
          "properties": {
              "attendees": {
                  "type": "array",
                  "items": {"type": "string"},
                  "description": "List of people attending the meeting.",
              },
              "date": {
                  "type": "string",
                  "description": "Date of the meeting (e.g., '2024-07-29')",
              },
              "time": {
                  "type": "string",
                  "description": "Time of the meeting (e.g., '15:00')",
              },
              "topic": {
                  "type": "string",
                  "description": "The subject or topic of the meeting.",
              },
          },
          "required": ["attendees", "date", "time", "topic"],
      },
  }

  # Configure the client
  client = OpenAI(
      api_key="AIHUBMIX_API_KEY", # Replace with the key you generated in AiHubMix
      base_url="https://aihubmix.com/v1",
  )

  # Send request with function declarations using OpenAI compatible format
  response = client.chat.completions.create(
      model="gemini-2.0-flash",
      messages=[
          {"role": "user", "content": "Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning."}
      ],
      tools=[{"type": "function", "function": schedule_meeting_function}],
      tool_choice="auto" ## 📍 Added Aihubmix compatibility, more stable request method
  )

  # Check for a function call
  if response.choices[0].message.tool_calls:
      tool_call = response.choices[0].message.tool_calls[0]
      function_call = tool_call.function
      print(f"Function to call: {function_call.name}")
      print(f"Arguments: {function_call.arguments}")
      print(response.usage)
      #  In a real app, you would call your function here:
      #  result = schedule_meeting(**json.loads(function_call.arguments))
  else:
      print("No function call found in the response.")
      print(response.choices[0].message.content)
  ```
</CodeGroup>

**Ejemplo de salida:**

```bash theme={null}
Function to call: schedule_meeting
Arguments: {"attendees":["Bob","Alice"],"date":"2025-03-14","time":"10:00","topic":"Q3 planning"}
CompletionUsage(completion_tokens=28, prompt_tokens=111, total_tokens=139, completion_tokens_details=None, prompt_tokens_details=None)
```

## Seguimiento sencillo del uso de tokens

1. **Gemini** realiza el seguimiento del uso de tokens mediante `usage_metadata`. Esto es lo que significa cada campo:

   * `prompt_token_count`: número de tokens de entrada
   * `candidates_token_count`: número de tokens de salida
   * `thoughts_token_count`: tokens utilizados durante el razonamiento (también se cuentan como salida)
   * `total_token_count`: total de tokens utilizados (entrada + salida)

   Para más detalles, consulta su [documentación oficial](https://ai.google.dev/gemini-api/docs/tokens?lang=python).
2. Para las API que usan el **formato compatible con OpenAI**, el uso de tokens se rastrea en `.usage` con los siguientes campos:
   * `usage.completion_tokens`: número de tokens de entrada
   * `usage.prompt_tokens`: número de tokens de salida (incluido el razonamiento)
   * `usage.total_tokens`: uso total de tokens

***

**A continuación, cómo usarlo en código:**

<CodeGroup>
  ```py Gemini native theme={null}
  from google import genai
  from google.genai import types
  import time

  def generate():
      client = genai.Client(
          api_key="sk-***", # Replace this with your key from AiHubMix
          http_options={"base_url": "https://aihubmix.com/gemini"},
      )

      model = "gemini-2.5-pro-preview-03-25"
      contents = [
          types.Content(
              role="user",
              parts=[
                  types.Part.from_text(text="""How is the "Rule of 72" derived in the financial world?"""),
              ],
          ),
      ]
      generate_content_config = types.GenerateContentConfig(
          response_mime_type="text/plain",
      )

      final_usage_metadata = None
      
      for chunk in client.models.generate_content_stream(
          model=model,
          contents=contents,
          config=generate_content_config,
      ):
          print(chunk.text, end="")
          if chunk.usage_metadata:
              final_usage_metadata = chunk.usage_metadata
      
      # Once all chunks are processed, print the full token usage
      if final_usage_metadata:
          print(f"\nUsage: {final_usage_metadata}")

  if __name__ == "__main__":
      generate()
  ```

  ```py OpenAI compatible theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-***", # Replace this with your key from AiHubMix
      base_url="https://aihubmix.com/v1",
  )

  completion = client.chat.completions.create(
      model="gemini-2.5-flash-preview-04-17",
      reasoning_effort="low", #"low", "medium", and "high", which behind the scenes we map to 1K, 8K, and 24K thinking token budgets. If you want to disable thinking, you can set the reasoning effort to "none".
      messages=[
          {
              "role": "user",
              "content": "How is the "Rule of 72" derived in the financial world?"
          }
      ],
      stream=True
  )

  #print(completion.choices[0].message.content)

  for chunk in completion:
      print(chunk.choices[0].delta)
      # Only print token usage info on the last chunk (which includes full usage data)
      if chunk.usage and chunk.usage.completion_tokens > 0:
          print(f"Output tokens: {chunk.usage.completion_tokens}")
          print(f"Input tokens: {chunk.usage.prompt_tokens}")
          print(f"Total tokens: {chunk.usage.total_tokens}")
  ```
</CodeGroup>

***

Última actualización: 2026-07-07
