Zum Inhalt springen

Lektion 19 · The Gemini API

Structured Output and Multimodal Input

Get JSON that follows a schema from the Gemini API, validate it in your code, and send images, PDFs, audio and video inline or through the Files API.

Programs need predictable data, not free-form paragraphs. And many tasks start from a picture, a PDF or a recording. This lesson covers structured output and multimodal input with the Interactions API. Facts are as of December 2026.

Ask for JSON that follows a schema

Describe the shape with a JSON Schema and pass it in response_format:

Python
# Read-only.
schema = {
    "type": "object",
    "properties": {
        "category": {"type": "string", "enum": ["billing", "delivery", "other"]},
        "urgent": {"type": "boolean"},
        "summary": {"type": "string"},
    },
    "required": ["category", "urgent", "summary"],
}

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Classify: 'My parcel is a week late and I need it tomorrow.'",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": schema,
    },
)
print(interaction.output_text)   # JSON text

In Python you can also build the schema from a Pydantic model with Model.model_json_schema() and parse the reply with Model.model_validate_json(...).

Shape is not truth

Structured output aims to give you syntactically valid JSON in the requested shape. Google's documentation also lists constraints that are not enforced and are silently removed, including minLength, maxLength and uniqueItems. It says minItems and maxItems are enforced. Very complex schemas can be rejected with an error. So validate every reply in your own code, and check that the values make sense. "urgent": true can be valid JSON and still the wrong judgment.

Python Stand-in: validate a JSON reply

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When validation fails, you might retry once and include the error, then fall back to a safe path such as human review. Do not loop forever. A reply cut off by an output limit or an error also fails validation, so handle that too.

Send images and PDFs inline

For small, one-off files, send base64 data in an input block:

Python
# Read-only.
import base64

with open("report.pdf", "rb") as f:
    data = base64.b64encode(f.read()).decode("utf-8")

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "document", "data": data, "mime_type": "application/pdf"},
        {"type": "text", "text": "List the three main risks with page numbers."},
    ],
)

Images use a block with "type": "image". Google's image guide lists PNG, JPEG, WEBP, HEIC and HEIF. With a single image and a text prompt, that guide suggests putting the text first.

The Files API

For large files, or files that you will reuse, upload them first:

Python
# Read-only.
uploaded = client.files.upload(file="meeting.mp3")
# Large media may need processing before use: see the Files and video guides.

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "audio", "uri": uploaded.uri, "mime_type": uploaded.mime_type},
        {"type": "text", "text": "List the decisions."},
    ],
)

Google's documentation gives these figures: use the Files API when a request would exceed 100 MB (the image guide gives a lower limit of 20 MB for requests with inline images). Uploaded files are deleted after 48 hours, a file can be up to 2 GB and a project can store up to 20 GB. A PDF is limited to 50 MB and 1,000 pages. Limits differ between guides and tiers, so check the page for your file type.

Video

You can upload video, or send small clips inline. Google's video guide also supports public YouTube links as video input (a preview feature at the time of writing, with its own limits). You can ask about moments with MM:SS timestamps. By default, about one frame per second is sampled, so fast action can be missed. The guide describes settings for the frame rate and for processing only part of a video.

Estimate size before sending

Google's rough rule is about four characters per token for English text. Image cost depends on the image size and resolution settings. For a count before sending, the SDK offers client.models.count_tokens(...), and interaction.usage reports what a request used.

Python Choose inline or upload by size

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This rule deliberately uses a cautious limit. Each format also has its own limits.

Privacy for uploads

An upload sends the whole content to the service. Remove data that you do not need, check that you have permission and delete uploads you no longer need.

Design a helpful schema

A good schema makes the correct answer easy to express.

  • Use enums for fixed choices, and include an "other" or "unknown" value so the model is not forced to guess.
  • Make it possible to say that data is missing. If every field is required and has no empty option, a model may invent a value.
  • Use clear field names and add descriptions, such as the unit for an amount or the format for a date.
  • Keep the structure flat unless nesting adds real meaning.
  • Version your schema, so that stored results can be traced to the shape that produced them.

For document extraction, you can add a field for the page number or the supporting quote. Then your program or a reviewer can check the value against the source. Test with a document that lacks a field, one that contains two possible values and a blurry scan. These cases show whether your schema gives the model an honest way out.

Common mistake: trusting schema-valid JSON as correct data. A well-formed "total": 900 may not match the invoice. Compare important values with the source.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does structured output help guarantee?

    You must still validate your rules and check the values.
  2. 2. How should you handle a schema constraint such as maxLength?

    Google lists several constraints that are silently removed.
  3. 3. When is the Files API a good choice?

    Uploading avoids sending large data again and handles big files.

Summary

  • Use response_format with a JSON Schema, then validate in your code.
  • Send small files inline, and upload large or reused ones.
  • Check limits and retention on the official pages.
  • Count tokens, and protect the data that you upload.

Next: Function Calling and Built-In Tools

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.