> ## 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.

# Guias do Gemini

> Um guia completo para chamadas da API Gemini na nossa plataforma.

## Encaminhamento para Modelos Gemini

Para a série Gemini, fornecemos **dois** métodos de invocação: chamadas nativas da API e chamadas compatíveis com OpenAI.\
Antes de começar, certifique-se de instalar ou atualizar a dependência nativa executando `pip install google-genai` ou `pip install -U google-genai`.

1️⃣ Para integração nativa, o Gemini cuida automaticamente do roteamento de tráfego entre AI Studio e VertexAI. Basta fornecer sua **chave de API AIHubMix** e a **URL de requisição** apropriada. Lembre-se de que esta URL é diferente da `base_url` usual — siga o exemplo abaixo para garantir a configuração correta.

```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 formatos compatíveis com OpenAI, mantenha o 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 a série 2.5, se você precisa exibir o processo de raciocínio, existem duas maneiras de fazer isso:

1. **Invocação nativa:** Passe `include_thoughts=True`
2. **Método compatível com OpenAI:** Passe `reasoning_effort`

Você pode consultar os exemplos de código abaixo para uso detalhado.

## Instruções do **Gemini 3 Pro** Image Preview

O Gemini 3 Pro Image Preview (Nano Banana Pro Preview) foi projetado para criação profissional de ativos e instruções complexas. Este modelo oferece os seguintes recursos:

* Usa o Google Search para recuperar conhecimento mundial em tempo real
* Processo "thinking" integrado (otimiza a composição antes da geração)
* Pode gerar imagens com resoluções de até **4K**

<Tip>
  <strong>Modo Streaming (`stream=True`)</strong>
  → apenas estágio de raciocínio\
  <strong>Modo Não-Streaming (`stream=False`)</strong>
  → geração final da imagem

  As imagens geradas <strong>não são incluídas nas respostas em streaming</strong>
  e devem ser recuperadas usando uma <strong>requisição sem streaming</strong>
  .
</Tip>

**Exemplos de uso em 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>

## Sobre os Modelos de Inferência Gemini 2.5

1. A série 2.5 inteira consiste em **modelos de inferência**.
2. **2.5 Flash** é um modelo híbrido, similar ao Claude Sonnet 3.7. Você pode ajustar fino seu comportamento de raciocínio ajustando o parâmetro `thinking_budget` para controle ideal.
3. **2.5 Pro** é um modelo de inferência puro. O thinking não pode ser desabilitado, e `thinking_budget` não deve ser definido explicitamente.

**Exemplos de uso em 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: Suporte a Tarefas Rápidas

Exemplo para invocação compatível com 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 tarefas complexas, basta definir o id do modelo como o padrão `gemini-2.5-flash-preview-04-17` para habilitar o thinking.
  2. O Gemini 2.5 Flash usa o parâmetro `budget` para controlar a profundidade do thinking, variando de 0 a 16K. O budget padrão é 1024, e o efeito marginal ideal é 16K.
</Tip>

## Compreensão de Mídia

* Para arquivos multimídia **com menos de 20MB** (imagens, áudio, vídeo), envie-os usando `inline_data`.
* Quando um arquivo multimídia for **maior que 20MB**, você deve usar a Files API.

### Arquivos Abaixo de 20MB

<Tip>
  Adicionando o parâmetro `EDIARESOLUTION_MEDIUM`, você pode ajustar a resolução da imagem, o que reduz significativamente os custos de entrada e minimiza o risco de erros com imagens grandes.

  **Valores de resolução de mídia suportados:**

  | Nome                           | Descrição                                                                        |
  | ------------------------------ | -------------------------------------------------------------------------------- |
  | MEDIA\_RESOLUTION\_UNSPECIFIED | A resolução de mídia não foi definida.                                           |
  | MEDIA\_RESOLUTION\_LOW         | Resolução de mídia definida como baixa (64 tokens).                              |
  | MEDIA\_RESOLUTION\_MEDIUM      | Resolução de mídia definida como média (256 tokens).                             |
  | MEDIA\_RESOLUTION\_HIGH        | Resolução de mídia definida como alta (reenquadramento com zoom com 256 tokens). |
</Tip>

**Exemplos de uso em 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

O Gemini pode lidar com vários tipos de dados de entrada simultaneamente, incluindo texto, imagens e áudio. Quando o tamanho total da requisição (incluindo arquivos, dicas de texto, comandos de sistema, etc.) excede **20 MB**, certifique-se de usar a Files API.

<Tip>
  * Listar arquivos enviados não é suportado.
  * Os arquivos serão automaticamente excluídos após 48 horas, ou você pode excluir manualmente os arquivos enviados.
</Tip>

**Exemplos de uso em 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>

## Execução de Código

O recurso de execução de código permite que o modelo gere e execute código Python e aprenda iterativamente com os resultados até chegar a uma saída final. Você pode usar essa capacidade de execução de código para construir aplicações que se beneficiam de raciocínio baseado em código e produzem saída de texto. Por exemplo, você poderia usar a execução de código em uma aplicação que resolve equações ou processa 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 e a interface de inferencia de nova geracao do Gemini. Ela retorna objetos `Interaction` estruturados e suporta geracao de texto, geracao nativa de imagens (Nano Banana) e raciocinio em multiplas etapas. Atualmente o **modo sincrono** (`interactions.create()`) e suportado; o modo assincrono (Background Interactions) estara disponivel em breve.

<Warning>
  Requisito de versao do SDK: `@google/genai` **>= 2.0.0** (JS/TS) ou `google-genai` **>= 2.0.0** (Python). Versoes anteriores do SDK serao rejeitadas pelo backend do Google (`legacy Interactions schema no longer supported`).
</Warning>

### Geracao de texto

Chame `interactions.create()` para iniciar uma inferencia. O objeto `Interaction` retornado fornece a propriedade de conveniencia `output_text`.

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

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Substitua pela sua API Key gerada no 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-***",  # Substitua pela sua API Key gerada no 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>

### Geracao nativa de imagens

Configure a modalidade de saida como imagem via `response_format`. O objeto `Interaction` retornado fornece a propriedade de conveniencia `output_image`.

<Tip>
  * Modelo recomendado: `gemini-3.1-flash-image` (Nano Banana 2, modelo universal de geracao de imagens).
  * Os valores de `response_modalities` devem estar em **minusculas**: `['text', 'image']`; maiusculas sao a sintaxe da API `generateContent` e retornam um `400` na Interactions API.
  * Nao envie `delivery: 'inline'` (`400 Image delivery mode is not supported`) -- os resultados sao retornados em modo inline por padrao.
</Tip>

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

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Substitua pela sua API Key gerada no 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" },
  });

  // Propriedade de conveniencia output_image (ultima imagem gerada)
  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-***",  # Substitua pela sua API Key gerada no 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>

### Saida em streaming

Passe `stream: true` para habilitar streaming SSE. O texto incremental e obtido via `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));
  }
}
```

> O guia completo de integracao com o SDK (incluindo Embeddings, CRUD de cache explicito, matriz de capacidades, etc.) esta disponivel em [Integracao com SDK nativo do Gemini](/pt/api/Gemini-SDK).

## Cache de Contexto

A API nativa do Gemini **habilita o cache de contexto implícito por padrão** — sem necessidade de configuração. Para cada requisição `generate_content`, o sistema cacheia automaticamente o conteúdo de entrada. Se uma requisição subsequente usar exatamente o mesmo conteúdo, modelo e parâmetros, o sistema retornará instantaneamente o resultado anterior, acelerando drasticamente o tempo de resposta e potencialmente reduzindo os custos de tokens de entrada.

* **O cache é automático — sem necessidade de configuração manual.**
* O cache só é acertado quando o conteúdo, modelo e todos os parâmetros são exatamente os mesmos; qualquer diferença resultará em cache miss.
* O time-to-live (TTL) do cache pode ser definido pelo desenvolvedor, ou deixado sem definição (padrão: 1 hora). Não há TTL mínimo ou máximo imposto pelo Google. Os custos dependem do número de tokens cacheados e da duração do cache.
  * Embora o Google não imponha restrição ao TTL, como uma plataforma de encaminhamento, **suportamos apenas uma faixa limitada de TTL**. Para requisitos além dos limites da nossa plataforma, entre em contato conosco.

### Observações

* **Sem garantia de economia de custos:** Tokens de cache são cobrados a 25% do preço padrão de entrada — então teoricamente, o cache pode economizar até 75% dos custos de tokens de entrada. No entanto, a [documentação oficial do Google](https://ai.google.dev/gemini-api/docs/caching?lang=python) não garante economia de custos; o efeito real depende da sua taxa de acerto de cache, tipos de tokens e duração do armazenamento.
* **Condições de acerto de cache:** Para maximizar a eficácia do cache, coloque o contexto repetível no início da entrada e o conteúdo dinâmico (como entrada do usuário) no final.
* **Como detectar acertos de cache:** Se uma resposta vier do cache, `response.usage_metadata` incluirá o campo `cache_tokens_details` e `cached_content_token_count`. Você pode usá-los para determinar o uso do cache.\
  Exemplo de campos quando um acerto de cache ocorre:

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

**Exemplo 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()
```

> Quando ocorre um acerto de cache, `response.usage_metadata` conterá:
>
> ```
> cache_tokens_details=[ModalityTokenCount(modality=<MediaModality.TEXT: 'TEXT'>, token_count=2003)]
> cached_content_token_count=2003
> ```

**Conclusão principal:** O cache implícito é automático e fornece feedback claro de acerto de cache. Os desenvolvedores podem verificar usage\_metadata para o status do cache. **A economia de custos não é garantida** — o benefício real depende da estrutura da requisição e das taxas de acerto de cache.

## Function calling

Ao usar a forma compatível com OpenAI para chamar a function calling do Gemini, você precisa passar `tool_choice="auto"` no corpo da requisição, caso contrário ele relatará um erro.

<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>

**Exemplo de Saída:**

```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)
```

## Rastreamento Simplificado de Uso de Tokens

1. O **Gemini** rastreia o uso de tokens usando `usage_metadata`. Veja o que cada campo significa:

   * `prompt_token_count`: número de tokens de entrada
   * `candidates_token_count`: número de tokens de saída
   * `thoughts_token_count`: tokens usados durante o raciocínio (também contados como saída)
   * `total_token_count`: total de tokens usados (entrada + saída)

   Para mais detalhes, consulte a [documentação oficial](https://ai.google.dev/gemini-api/docs/tokens?lang=python).
2. Para APIs usando o **formato compatível com OpenAI**, o uso de tokens é rastreado em `.usage` com os seguintes campos:
   * `usage.completion_tokens`: número de tokens de entrada
   * `usage.prompt_tokens`: número de tokens de saída (incluindo raciocínio)
   * `usage.total_tokens`: uso total de tokens

***

**Veja como usá-lo no 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 atualização: 2026-07-07
