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

# Gemini-Leitfaden

> Ein umfassender Leitfaden zu Gemini-API-Aufrufen auf unserer Plattform.

## Weiterleitung für Gemini-Modelle

Für die Gemini-Serie bieten wir **zwei** Aufrufmethoden an: native API-Aufrufe und OpenAI-kompatible Aufrufe.\
Bevor Sie beginnen, stellen Sie sicher, dass Sie die native Abhängigkeit installieren oder aktualisieren, indem Sie entweder `pip install google-genai` oder `pip install -U google-genai` ausführen.

1️⃣ Bei der nativen Integration übernimmt Gemini das Routing des Datenverkehrs zwischen AI Studio und VertexAI automatisch. Stellen Sie einfach Ihren **AIHubMix API-Schlüssel** und die passende **Anfrage-URL** bereit. Beachten Sie, dass sich diese URL von der üblichen `base_url` unterscheidet – folgen Sie dem Beispiel unten, um die korrekte Einrichtung sicherzustellen.

```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️⃣ Für OpenAI-kompatible Formate behalten Sie den universellen `v1`-Endpunkt bei.

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

3️⃣ Für die 2.5-Serie gibt es zwei Möglichkeiten, den Denkprozess anzuzeigen:

1. **Nativer Aufruf:** Übergeben Sie `include_thoughts=True`
2. **OpenAI-kompatible Methode:** Übergeben Sie `reasoning_effort`

Detaillierte Verwendungshinweise finden Sie in den Codebeispielen unten.

## Hinweise zu **Gemini 3 Pro** Image Preview

Gemini 3 Pro Image Preview (Nano Banana Pro Preview) ist für die professionelle Asset-Erstellung und komplexe Anweisungen konzipiert. Dieses Modell bietet folgende Funktionen:

* Nutzt die Google-Suche, um aktuelles Weltwissen abzurufen
* Integrierter „Denkprozess“ (optimiert die Komposition vor der Generierung)
* Kann Bilder mit Auflösungen bis zu **4K** generieren

<Tip>
  <strong>Streaming-Modus (`stream=True`)</strong>
  → nur die Reasoning-Phase\
  <strong>Nicht-Streaming-Modus (`stream=False`)</strong>
  → finale Bildgenerierung

  Generierte Bilder sind <strong>nicht in Streaming-Antworten enthalten</strong>
  und müssen mit einer <strong>Nicht-Streaming-Anfrage</strong>
  abgerufen werden.
</Tip>

**Python-Anwendungsbeispiele:**

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

## Über die Gemini 2.5 Inferenzmodelle

1. Die gesamte 2.5-Serie besteht aus **Inferenzmodellen**.
2. **2.5 Flash** ist ein Hybridmodell, ähnlich wie Claude Sonnet 3.7. Sie können sein Reasoning-Verhalten durch Anpassung des Parameters `thinking_budget` für eine optimale Kontrolle feinjustieren.
3. **2.5 Pro** ist ein reines Inferenzmodell. Das Denken kann nicht deaktiviert werden, und `thinking_budget` sollte nicht explizit gesetzt werden.

**Python-Anwendungsbeispiele:**

<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: Unterstützung für schnelle Aufgaben

Beispiel für einen OpenAI-kompatiblen Aufruf:

<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. Setzen Sie für komplexe Aufgaben einfach die Modell-ID auf den Standardwert `gemini-2.5-flash-preview-04-17`, um das Denken zu aktivieren.
  2. Gemini 2.5 Flash steuert die Denktiefe über den Parameter `budget` im Bereich von 0 bis 16K. Das Standardbudget beträgt 1024, der optimale Grenzeffekt liegt bei 16K.
</Tip>

## Multimedia-Verständnis

* Für Multimedia-Dateien **unter 20 MB** (Bilder, Audio, Video) laden Sie diese mit `inline_data` hoch.
* Wenn eine Multimedia-Datei **größer als 20 MB** ist, müssen Sie die Files API verwenden.

### Dateien unter 20 MB

<Tip>
  Durch Hinzufügen des Parameters `EDIARESOLUTION_MEDIUM` können Sie die Bildauflösung anpassen, was die Eingabekosten erheblich reduziert und das Fehlerrisiko bei großen Bildern minimiert.

  **Unterstützte Werte für die Multimedia-Auflösung:**

  | Name                           | Beschreibung                                                               |
  | ------------------------------ | -------------------------------------------------------------------------- |
  | MEDIA\_RESOLUTION\_UNSPECIFIED | Multimedia-Auflösung wurde nicht gesetzt.                                  |
  | MEDIA\_RESOLUTION\_LOW         | Multimedia-Auflösung auf niedrig gesetzt (64 Token).                       |
  | MEDIA\_RESOLUTION\_MEDIUM      | Multimedia-Auflösung auf mittel gesetzt (256 Token).                       |
  | MEDIA\_RESOLUTION\_HIGH        | Multimedia-Auflösung auf hoch gesetzt (gezoomtes Reframing mit 256 Token). |
</Tip>

**Python-Anwendungsbeispiele:**

<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 kann verschiedene Arten von Eingabedaten gleichzeitig verarbeiten, darunter Text, Bilder und Audio. Wenn die Gesamtgröße der Anfrage (einschließlich Dateien, Texthinweisen, Systembefehlen usw.) **20 MB** überschreitet, müssen Sie unbedingt die Files API verwenden.

<Tip>
  * Das Auflisten hochgeladener Dateien wird nicht unterstützt.
  * Dateien werden nach 48 Stunden automatisch gelöscht, oder Sie können hochgeladene Dateien manuell löschen.
</Tip>

**Python-Anwendungsbeispiele:**

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

## Code-Ausführung

Die Code-Ausführungsfunktion ermöglicht es dem Modell, Python-Code zu generieren und auszuführen sowie iterativ aus den Ergebnissen zu lernen, bis es zu einer finalen Ausgabe gelangt. Sie können diese Code-Ausführungsfähigkeit nutzen, um Anwendungen zu entwickeln, die von codebasiertem Reasoning profitieren und Textausgaben erzeugen. Beispielsweise könnten Sie die Code-Ausführung in einer Anwendung verwenden, die Gleichungen löst oder Texte verarbeitet.

```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 ist die Gemini-Inferenzschnittstelle der naechsten Generation. Sie gibt strukturierte `Interaction`-Objekte zurueck und unterstuetzt Textgenerierung, native Bilderzeugung (Nano Banana) sowie mehrstufiges Reasoning. Derzeit wird der **synchrone Modus** (`interactions.create()`) unterstuetzt; der asynchrone Modus (Background Interactions) folgt in Kuerze.

<Warning>
  SDK-Versionsanforderung: `@google/genai` **>= 2.0.0** (JS/TS) oder `google-genai` **>= 2.0.0** (Python). Aeltere SDK-Versionen werden vom Google-Backend abgelehnt (`legacy Interactions schema no longer supported`).
</Warning>

### Textgenerierung

Rufen Sie `interactions.create()` auf, um eine Inferenz zu starten. Das zurueckgegebene `Interaction`-Objekt bietet die Komfort-Eigenschaft `output_text`.

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

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Ersetzen Sie dies durch Ihren bei AIHubMix generierten API Key
    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-***",  # Ersetzen Sie dies durch Ihren bei AIHubMix generierten API Key
      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>

### Native Bilderzeugung

Konfigurieren Sie die Ausgabemodalitaet ueber `response_format` auf Bild. Das zurueckgegebene `Interaction`-Objekt bietet die Komfort-Eigenschaft `output_image`.

<Tip>
  * Empfohlenes Modell: `gemini-3.1-flash-image` (Nano Banana 2, universelles Bildgenerierungsmodell).
  * Die Werte von `response_modalities` muessen **kleingeschrieben** sein: `['text', 'image']`; Grossbuchstaben sind die Schreibweise der `generateContent`-API und fuehren bei der Interactions API zu einem `400`-Fehler.
  * Uebergeben Sie nicht `delivery: 'inline'` (`400 Image delivery mode is not supported`) -- die Ergebnisse werden standardmaessig inline zurueckgegeben.
</Tip>

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

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // Ersetzen Sie dies durch Ihren bei AIHubMix generierten API Key
    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" },
  });

  // output_image-Komfort-Eigenschaft (letztes generiertes Bild)
  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-***",  # Ersetzen Sie dies durch Ihren bei AIHubMix generierten API Key
      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>

### Streaming-Ausgabe

Uebergeben Sie `stream: true`, um SSE-Streaming zu aktivieren. Inkrementeller Text wird ueber `event.delta.text` abgerufen.

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

> Die vollstaendige SDK-Integrationsanleitung (inkl. Embeddings, explizitem Caching CRUD, Funktionsmatrix usw.) finden Sie unter [Gemini Native SDK-Anbindung](/de/api/Gemini-SDK).

## Kontext-Caching

Geminis native API **aktiviert implizites Kontext-Caching standardmäßig** – keine Einrichtung erforderlich. Für jede `generate_content`-Anfrage cacht das System automatisch den Eingabeinhalt. Wenn eine nachfolgende Anfrage exakt denselben Inhalt, dasselbe Modell und dieselben Parameter verwendet, gibt das System sofort das vorherige Ergebnis zurück, was die Antwortzeit erheblich beschleunigt und möglicherweise die Kosten für Eingabe-Token reduziert.

* **Caching erfolgt automatisch – keine manuelle Konfiguration erforderlich.**
* Der Cache wird nur getroffen, wenn Inhalt, Modell und alle Parameter exakt übereinstimmen; jede Abweichung führt zu einem Cache-Miss.
* Die Cache-Lebensdauer (TTL) kann vom Entwickler festgelegt oder ungesetzt gelassen werden (Standard: 1 Stunde). Google erzwingt keine minimale oder maximale TTL. Die Kosten hängen von der Anzahl der gecachten Token und der Cache-Dauer ab.
  * Während Google die TTL nicht beschränkt, **unterstützen wir als Weiterleitungsplattform nur einen begrenzten TTL-Bereich**. Bei Anforderungen, die über die Grenzen unserer Plattform hinausgehen, kontaktieren Sie uns bitte.

### Hinweise

* **Keine garantierten Kosteneinsparungen:** Cache-Token werden mit 25 % des Standard-Eingabepreises abgerechnet – theoretisch kann Caching also bis zu 75 % der Kosten für Eingabe-Token einsparen. Allerdings garantiert die [offizielle Google-Dokumentation](https://ai.google.dev/gemini-api/docs/caching?lang=python) keine Kosteneinsparungen; der tatsächliche Effekt hängt von Ihrer Cache-Trefferquote, den Token-Typen und der Speicherdauer ab.
* **Bedingungen für Cache-Treffer:** Um die Cache-Effektivität zu maximieren, platzieren Sie wiederholbaren Kontext am Anfang Ihrer Eingabe und dynamische Inhalte (wie Benutzereingaben) am Ende.
* **So erkennen Sie Cache-Treffer:** Wenn eine Antwort aus dem Cache stammt, enthält `response.usage_metadata` das Feld `cache_tokens_details` und `cached_content_token_count`. Damit können Sie die Cache-Nutzung feststellen.\
  Beispielfelder bei einem Cache-Treffer:

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

**Codebeispiel:**

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

> Bei einem Cache-Treffer enthält `response.usage_metadata`:
>
> ```
> cache_tokens_details=[ModalityTokenCount(modality=<MediaModality.TEXT: 'TEXT'>, token_count=2003)]
> cached_content_token_count=2003
> ```

**Kernfazit:** Implizites Caching erfolgt automatisch und liefert eindeutige Rückmeldung zu Cache-Treffern. Entwickler können `usage_metadata` auf den Cache-Status prüfen. **Kosteneinsparungen sind nicht garantiert** – der tatsächliche Nutzen hängt von der Anfragestruktur und den Cache-Trefferquoten ab.

## Function Calling

Wenn Sie Geminis Function Calling über die OpenAI-kompatible Methode aufrufen, müssen Sie `tool_choice="auto"` im Anfragetext übergeben, andernfalls wird ein Fehler gemeldet.

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

**Ausgabebeispiel:**

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

## Token-Verbrauch einfach nachverfolgen

1. **Gemini** verfolgt den Token-Verbrauch über `usage_metadata`. Hier ist, was jedes Feld bedeutet:

   * `prompt_token_count`: Anzahl der Eingabe-Token
   * `candidates_token_count`: Anzahl der Ausgabe-Token
   * `thoughts_token_count`: Token, die während des Reasonings verwendet werden (zählen ebenfalls als Ausgabe)
   * `total_token_count`: Gesamte verwendete Token (Eingabe + Ausgabe)

   Weitere Details finden Sie in der [offiziellen Dokumentation](https://ai.google.dev/gemini-api/docs/tokens?lang=python).
2. Für APIs im **OpenAI-kompatiblen Format** wird der Token-Verbrauch unter `.usage` mit den folgenden Feldern verfolgt:
   * `usage.completion_tokens`: Anzahl der Eingabe-Token
   * `usage.prompt_tokens`: Anzahl der Ausgabe-Token (einschließlich Reasoning)
   * `usage.total_tokens`: Gesamter Token-Verbrauch

***

**So verwenden Sie es im Code:**

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

***

Zuletzt aktualisiert: 2026-07-07
