Tinkering with Gemini API

In last article we started using Gemini programmatically. Now, let’s roll up our sleeves and do some tinkering to unlock more advanced capabilities of the google-genai SDK.

1. Listing Available Gemini Models

Before diving into specific tasks, it’s often helpful to programmatically inspect which models are currently available in your environment and filter them by their capabilities (such as text or content generation).

from google import genai

# Initialize the client
client = genai.Client(api_key="your_api_key")

print("Available Content Generation Models:\n" + "-" * 50)
for model in client.models.list():
    # Filter for models that support text/content generation
    if "generateContent" in model.supported_actions:
        print(f"Name         : {model.name}")
        print(f"Display Name : {model.display_name}")
        print("-" * 50)

2. Generating Images

Beyond text, the Gemini ecosystem lets you generate stunning visual assets directly through the API using state-of-the-art models.

Here is how you can generate and save an image programmatically:

from google import genai
from google.genai import types

client = genai.Client(api_key="your_api_key")

prompt_text = "A futuristic city with flying cars at sunset, digital art style"
print(f"Generating image for prompt: '{prompt_text}'...\n" + "-" * 50)

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=prompt_text,
    config=types.GenerateContentConfig(
        response_modalities=["IMAGE"],
        image_config=types.ImageConfig(aspect_ratio="1:1"),
    ),
)

saved = 0
for part in response.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        saved += 1
        filename = f"generated_image_{saved}.png"
        part.as_image().save(filename)
        print(f"Success! Image saved as: {filename}")

if saved == 0:
    print("No image returned. Check response.candidates[0].finish_reason / safety feedback.")

3. Harnessing the 1 Million+ Token Context Window

One of the most defining features of the Gemini ecosystem is its massive context window (supporting millions of tokens across flagship models). This allows you to pass an entire textbook, a massive codebase, or hours of audio directly into a single API call without needing complex chunking or external vector databases.

When dealing with large text documents, reading them into memory and passing them alongside your prompt is straightforward:

from google import genai

def analyze_large_context():
    client = genai.Client(api_key="your_api_key")

    # Ensure you have 'large_document.txt' in your workspace for testing
    try:
        with open("large_document.txt", "r", encoding="utf-8") as f:
            massive_text_data = f.read()
    except FileNotFoundError:
        print("Please create a 'large_document.txt' file to test large context windows.")
        return

    # Constructing a prompt that targets specific data buried in the context
    prompt = [
        massive_text_data,
        "\n\nTask: Based strictly on the exhaustive document provided above, extract all key information and list them in a Markdown table."
    ]

    print("Analyzing your document (this might take a few moments due to size)...")
    
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents=prompt
    )

    print("\n--- Deep Analysis Result ---")
    print(response.text)

if __name__ == "__main__":
    analyze_large_context()

4. Going Multimodal with the Files API

The massive context window isn’t restricted to text. If you want to analyze hours of audio, large PDFs, or video files, you can use the Files API (client.files.upload()) to upload the asset to Google’s servers temporarily, and then pass the file reference directly into contents alongside your text query.

Here is a quick example of how you can analyze a PDF report or audio file:

from google import genai
import time

client = genai.Client(api_key="your_api_key")

# 1. Upload a heavy file (e.g., a financial report PDF or audio recording)
print("Uploading file...")
file_ref = client.files.upload(file="financial_report.pdf")

# 2. Wait for processing if necessary, then query it
prompt = [
    file_ref,
    "Summarize the key financial highlights, revenue growth percentages, and identified audit risks from this document."
]

print("Generating analysis from file...")
response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents=prompt
)

print("\n--- Multimodal Analysis ---")
print(response.text)

# Optional: Clean up the file from Google's servers when done
client.files.delete(name=file_ref.name)
print("\nFile cleaned up from server.")

Leave a Comment