How to Build Your First App with the Gemini API

Human Verified

Share to: , and

A developer's desk at dusk: a laptop with a glowing code editor, screen blurred with no readable text, a notebook, a coffee cup and a small plant in warm lamp light. No readable text.

By Faheem R. Khattak | Facts checked 25 November 2026

How to Build Your First App with the Gemini API

You can build a working app with the Gemini API in about an hour, starting from nothing: one API key, one SDK install, one first call — and then, step by step, streaming, conversation memory, image input, JSON output, tools and error handling. That is the whole promise of this guide, and it is deliberately small: by the end you will have a real app that takes a question, answers it live as the words arrive, understands a photo you hand it, and returns clean JSON your code can use. Everything here was checked against Google’s own documentation on 25 November 2026, and the code samples are the ones Google’s own quickstart teaches — not copies from older tutorials. That last point matters more than it sounds, because the Gemini API has changed shape since most tutorials were written, and this guide teaches the current shape.

The change is this: Google’s quickstart now teaches the Interactions API. Your first call is client.interactions.create(...), not the older generateContent call that most blog posts still show. The older endpoint still exists — Google’s own thinking guide contrasts the two — but every current guide, from the quickstart to the safety settings page, teaches the Interactions API, so this guide teaches it too and says so plainly wherever the difference could confuse you. If you have followed an older Gemini tutorial before and the method names look unfamiliar, that is why. You are not behind; the docs moved.

Two warnings before you start, both about money and both dated. First, prices in this guide are as they stood on 25 November 2026, and two of them move within days of publication: Gemini 4 Carbon and Argon double in price on 1 December 2026, and Gemini 3.8 Flash doubles on 1 January 2027. The guide states both dates wherever the prices appear, so nothing here goes silently stale. Second, the app in this guide defaults to Gemini 4 Hydrogen, which has a free tier — your first calls cost nothing. The moment you switch to a paid model, every token is billed, including the model’s thinking tokens, so the pricing section is not optional reading; it is step 3 for a reason. Checked 25 November 2026.

A developer's desk at dusk: a laptop with a glowing code editor, screen blurred with no readable text, a notebook, a coffee cup and a small plant in warm lamp light. No readable text.

The short answer: your first app in about an hour

<img src="

A clear straight path through a garden maze leading to a small glowing doorway, warm daylight, minimal composition. No readable text.

” alt=”A clear straight path through a garden maze leading to a small glowing doorway, warm daylight, minimal composition. No readable text.”>

Here is the whole build in four moves. First, get an API key from Google AI Studio — it takes about two minutes and the studio creates a project and a key for you. Second, install the Google Gen AI SDK and make your first call with the model gemini-4-hydrogen, which is the current default in Google’s quickstart and has a free tier. Third, turn the one-off call into an app: stream the answer so it appears word by word, keep the conversation going across turns, and accept an image as well as text. Fourth, make the app trustworthy: get JSON back instead of prose, give the model a tool when it needs live facts, set the safety rules, and handle the errors that every real app hits — rate limits, bad keys, blocked content. Each step in this guide is one of those moves, in that order, and each one ends with working code you can run.

The app you will have at the end is small on purpose. It is a single program that asks Gemini a question, streams the answer to the screen, remembers what you said a moment ago, can look at a photo and describe it, and can answer in strict JSON when you need data rather than words. That is not a toy: those five abilities — text, streaming, memory, multimodal input, structured output — are the skeleton of almost every AI app in production, from support chatbots to document tools. The guide adds the two things that separate a demo from a product — tools and error handling — and then shows you how to ship it without leaking your key or getting a surprise bill. If you already know Python, you will move fast; if you do not, the guide shows the JavaScript version of every key call too, and the REST version wherever a raw HTTP call is clearer.

One more thing about scope. This guide does not re-explain the Gemini model family — which model is fastest, which is cheapest, which reasons deepest. That is a different question, and our guide to Gemini’s models answers it in full. What this guide does is teach you to build with the API, and it picks one default model for the worked examples (Hydrogen) and tells you exactly when to switch to another. The model-choice section gives you the prices and the free-tier facts you need to make that switch wisely, and then the guide gets back to building. If you want the full comparison first, read the models guide, then come back here; the two pieces are written to fit together.

A note on the code in this guide: every sample is taken from Google’s own documentation as it stood on 25 November 2026, shortened only where the docs themselves offer a shorter form. Where the docs show a Python sample, this guide shows the Python sample; where they show JavaScript and REST too, the guide shows those as well. Nothing here is invented, and nothing is copied from a third-party tutorial. If a detail is not in Google’s docs — a rate-limit number, a version number, a benchmark — this guide does not state it, and says so where the gap matters. That discipline is what makes the code runnable rather than merely plausible.

What the Gemini API actually is (and what it is not)

One central glowing hub with spokes connecting a phone, a laptop and a small server rack on a desk, soft blue light. No readable text, no legible branding.

The Gemini API is Google’s developer API for the Gemini models. You send it a request — text, an image, an audio clip, a document — and it returns the model’s response. That is the whole product at its core. Around that core sit the pieces this guide teaches: the Interactions API that organises each exchange, the SDKs that wrap it for Python, JavaScript, Java and Go, the Files API for large uploads, the built-in tools that let the model search the web or run code, and the safety and billing systems that govern all of it. What the API is not is equally important: it is not a chatbot app, it is not a hosted website, and it does not give you a user interface. You build the front end. The API gives you the intelligence; the app around it is yours.

The current shape of the API is the Interactions API, and it is worth understanding its shape before you write code. Each exchange is an interaction: you create one with a model name and an input, and you get back an object with an id, a status, a list of steps, and usage counts. The steps are the interesting part. A response is not one blob of text; it is a chronological list of steps — a thought step where the model reasons, a model_output step with the answer, a google_search_call step if it searched, a function_call step if it wants your code to do something. The SDK gives you shortcuts — interaction.output_text for the final text, interaction.output_image for a generated image — but the steps are always there underneath, and several sections of this guide (streaming, function calling, thinking) work with them directly. Learn the shape once and the rest of the API reads naturally.

Under the hood, the REST endpoint is https://generativelanguage.googleapis.com/v1beta/interactions. You POST JSON to it with two headers: x-goog-api-key carrying your key, and Api-Revision: 2026-05-20. The v1beta in the path matters: the Interactions API lives in the beta version of the API, and Google’s troubleshooting guide says plainly that a feature in beta is only available in the /v1beta version. The SDKs hide this from you — genai.Client() in Python and new GoogleGenAI({}) in JavaScript need no version argument for the calls in this guide — but if you ever use raw HTTP, the version is part of the URL and the revision header is part of the request. Keep both exactly as shown; a missing revision header is the kind of small mistake that produces a confusing error.

There is also a command-line route. Google ships a gemini-api CLI: install it with the install script from Google’s repository, then gemini-api generate "Explain how AI works in a few words" makes a call without writing any code at all. The CLI is useful for quick checks — is my key working, does this model answer this prompt — and this guide mentions its flags where they match a section (streaming, background tasks, file upload). For the app itself, though, use an SDK. A CLI call is a one-off; an app needs the SDK’s objects, its streaming, and its error handling.

Finally, the older API. Before the Interactions API, Gemini developers used generateContent — in the Python SDK, client.models.generate_content. That endpoint still exists: Google’s troubleshooting guide names generateContent as an inference call, and the thinking guide explains that the two APIs handle the model’s internal reasoning differently (in the older API there are no dedicated thought blocks; in the Interactions API, thoughts are first-class steps). But every current guide teaches the Interactions API, the quickstart’s first call uses it, and the new features in this guide — stateful conversations, managed agents, background execution — are Interactions API features. This guide teaches the current API. If you inherit code that uses generateContent, it is not broken, but it is the previous generation, and the new features will not be available to it. For a first app, start where the docs start.

Step 1: Get your API key in Google AI Studio

A hand holding a brass key up to a glowing doorway lock, warm light, shallow depth of field. No readable text.

Everything starts in Google AI Studio, at aistudio.google.com. It is Google’s free browser playground for the Gemini API: you can try prompts there without writing code, and — more importantly for this guide — it is where your API key lives. For new users, AI Studio automatically creates a project and an API key. Open the API keys page, copy the key, and you are done with setup. If you need another key, click Create API key and follow the dialog to add a new key-project pair. There is no form to fill in, no waitlist, no approval step for a basic key. The whole step takes about two minutes, and it is the only step in this guide that happens in a browser rather than in your code.

Your key is a secret, and the rule for it is simple and absolute: never put it in client-side code, never commit it to a public repository, and never paste it into a chat or a screenshot. Set it as an environment variable on your own machine:

export GEMINI_API_KEY=<your key here>

Then your code reads it from the environment instead of containing it. The SDKs are built for this: after you set the variable, genai.Client() in Python and new GoogleGenAI({}) in JavaScript pick the key up with no arguments at all, which is exactly how the quickstart’s samples are written. If you ever see your key stop working, check the troubleshooting section first — Google proactively blocks keys it finds leaked in public, and a blocked key needs replacing in AI Studio, not debugging in your code.

Two things can complicate this simple step, and both are worth knowing now rather than discovering at midnight. First, some projects need verification before they can use the free tier: Google may ask you to verify your account with a mobile device in AI Studio, or you can set up billing instead, which skips the verification step. Second, free-tier eligibility is decided at the Google Cloud project level, not per key — if your project is restricted from the free tier, creating a new key in the same project will not fix it, and the fix is to upgrade that project to the paid tier by linking an active Cloud Billing account. Both facts come from Google’s own troubleshooting guide, and both save you from the most common first-hour dead end: a key that looks right and returns 403 PERMISSION_DENIED. The error section of this guide covers that code in full.

One distinction that confuses almost every beginner: the Gemini app is not the Gemini API. The Gemini app is the chatbot you talk to at gemini.google.com; the API is the developer interface this guide teaches. They share models, but they are different products with different billing — chatting in the app does not use your API key, and API calls do not appear in your app history. The same split applies inside Google’s own products: Gemini features inside Docs, Sheets, Slides and Gmail are the app side of Gemini, and our guide to Gemini in Workspace covers what those features actually do. For this guide, remember only the boundary: if you are writing code, you are on the API side, and your key is what connects the two.

Before you leave AI Studio, do one more useful thing: try a prompt in the playground. Type a question, pick the gemini-4-hydrogen model, and watch the answer. This is not strictly necessary — the code below does the same thing — but it tells you in thirty seconds whether your account, your key and the model all work, before you have written a line of code. If the playground answers, your key is good; if it does not, the problem is in AI Studio, not in your program, and you have saved yourself a debugging session. Then come back here and write the code.

Step 2: Install the SDK and make your first call

Close-up of hands typing a short command on a laptop keyboard, terminal glow, screen blurred and illegible. No readable text.

Install the SDK for your language. In Python it is one command:

pip install -U google-genai

In JavaScript it is one command too:

npm install @google/genai

The package name is the same idea in both languages — the Google Gen AI SDK — and the docs give the same treatment to Java and Go if those are your languages. Google does not publish a version number for the SDK in the quickstart, so this guide does not state one either; install the latest and the samples below will match, because they are written against the current SDK surface.

Now the first call. This is the Python version, exactly as Google’s quickstart teaches it:

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Explain how AI works in a few words"
)

print(interaction.output_text)

Four lines of real code. genai.Client() reads your key from the environment. client.interactions.create(...) sends the request. The model is gemini-4-hydrogen — the quickstart’s default, and the right default for a first app because it has a free tier. The input is a plain string. And interaction.output_text is the model’s answer, printed to your screen. Google’s own example answer to this prompt is: “AI learns patterns from data, then uses those patterns to make predictions or decisions on new data.” Run it and you should see something very much like that. If you see an error instead, do not guess — the error section of this guide maps the common ones to their fixes.

The JavaScript version is the same shape:

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Explain how AI works in a few words",
});

console.log(interaction.output_text);

And the raw REST version, for anyone who wants to see what the SDK is doing underneath:

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" 
  -H "x-goog-api-key: $GEMINI_API_KEY" 
  -H 'Content-Type: application/json' 
  -H "Api-Revision: 2026-05-20" 
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Explain how AI works in a few words"
  }'

Three things about that curl command deserve attention. The URL ends in /v1beta/interactions — the beta API version and the Interactions resource. The x-goog-api-key header carries the key, not the URL, so it does not leak into logs. And the Api-Revision: 2026-05-20 header pins the API revision the docs were written against. If you copy this command and it works, your key, your network and the API are all fine; everything after this is application logic, not setup.

Look at what comes back before you move on, because the shape of the response is the shape of everything that follows. The full interaction object has an id (something like v1_Chd...), a status (here completed), a usage block, and a steps array. In Google’s quickstart example, the usage block reads total_tokens: 197, total_input_tokens: 8, total_output_tokens: 12 — eight tokens in, twelve out, and the rest is the model’s internal thinking, which is also billed as output. The steps array holds a thought step (the model’s internal reasoning, with an encrypted signature) and then a model_output step with the text. You will rarely read the raw object in a finished app — output_text is the shortcut — but knowing it exists makes the streaming, tools and thinking sections far easier to follow. One caution from the docs: output_text returns the last text blocks joined together, and it does not include earlier text blocks separated by non-text content such as thoughts, images or tool calls. For complex or interleaved responses, iterate over steps yourself instead of trusting the shortcut.

That is the first call, and it is also the first version of your app: a program that takes a question and returns an answer. Everything from here on is an addition to this shape — streaming changes how the answer arrives, multi-turn changes what the model remembers, multimodal input changes what you can send, structured output changes what comes back, tools change what the model can do, and safety and error handling change what happens when things go wrong. None of them changes the call itself. Keep this four-line program open while you read the rest; every section adds one argument or one loop to it.

Step 3: Pick the right model for your app

Four glass beakers of different sizes on a workbench holding different coloured liquids, a comparison at a glance. No readable text.

Your first call used gemini-4-hydrogen because Google’s quickstart uses it and because it has a free tier. That is the right default for learning — but it is a choice, and the rest of the Gemini lineup exists because different apps need different trade-offs. The table below is the whole decision in one place, with prices as they stood on 25 November 2026. Read it as a picker, not a ranking: there is no best model, only a best model for a given job and budget.

ModelFree tierInput / 1M tokensOutput / 1M tokensBest for
Gemini 4 Hydrogen (gemini-4-hydrogen)Yes$1.50$7.50Everyday coding and agentic work; the default for a first app
Gemini 4 Neon (gemini-4-neon)No$3.00$15.00Frontier intelligence with fast end-to-end task completion
Gemini 4 Carbon (gemini-4-carbon)No$2.00 → $4.00 from 1 Dec 2026$10.00 → $20.00 from 1 Dec 2026The strongest reasoning: complex engineering, science, cybersecurity
Gemini 4 Argon (gemini-4-argon)No$2.00 → $4.00 from 1 Dec 2026$10.00 → $20.00 from 1 Dec 2026Frontier reasoning with faster responses and lower token spend per turn than Carbon
Gemini 3.1 Pro (gemini-3.1-pro-preview)No (testable free in AI Studio)$2.00 / $4.00 over 200K-token prompts$12.00 / $18.00 over 200K-token promptsMultimodal understanding, agentic work, vibe-coding
Gemini 3.8 Flash (gemini-3.8-flash)Yes$0.75 → $1.50 from 1 Jan 2027$3.75 → $7.50 from 1 Jan 2027Long-horizon coding and autonomous agents at Flash speed and cost

Three facts in that table do most of the work. First, Hydrogen and 3.8 Flash are the only current models in the table with a free tier — that is why a first app should start on one of them. Second, Carbon and Argon cost exactly the same on Google’s pricing page, $2.00 in and $10.00 out through 30 November 2026, doubling to $4.00 and $20.00 from 1 December 2026; the difference between them is not price but behaviour — Argon is built to give frontier reasoning with faster responses and lower token spend per turn. Third, 3.1 Pro is the only model in the table with prompt-size pricing: prompts up to 200,000 tokens cost $2.00 in and $12.00 out per million tokens, and prompts over 200,000 tokens cost $4.00 in and $18.00 out. If your app sends very long documents, that threshold is the first thing to check. For the full model-by-model comparison — including the Flash-Lite models for high-volume work and the question of what Google AI Ultra actually is — the models guide linked above covers the whole lineup in depth.

Neon deserves a sentence of its own, because it is new. Gemini 4 Neon did not exist in the lineup a fortnight ago: it is the fourth Gemini 4 model, described by Google as bringing “frontier-level intelligence with fast end-to-end task completion across complex software engineering, knowledge work, and science workflows”. It costs $3.00 in and $15.00 out per million tokens, has no free tier, and sits between Hydrogen and Carbon on price — more expensive than Carbon’s current $2.00/$10.00 intro price, cheaper than Carbon’s $4.00/$20.00 price from 1 December. Our report on the Neon launch covers what it is and where it fits; for a first app, the practical rule is simple: start on Hydrogen, and reach for Neon when Hydrogen’s answers are not good enough for the hardest tasks in your app rather than as a default.

Now the arithmetic, because token prices are abstract until you do it. Prices are per million tokens, and a token is roughly a word fragment — but this guide will not convert tokens to pages or words, because Google’s pages do not publish that conversion and any figure would be invented. Work in tokens. A heavy single session of 1 million input tokens and 100,000 output tokens costs $2.25 on Hydrogen ($1.50 + $0.75), $1.13 on 3.8 Flash ($0.75 + $0.38), and $5.80 on 3.1 Pro for a prompt over 200,000 tokens ($4.00 + $1.80). Your first call in this guide was far smaller: Google’s example response shows 8 input tokens and 12 output tokens, which on Hydrogen is a fraction of a cent. The lesson is not the exact figure — it is that short calls are nearly free on the free-tier models, and the bill only becomes real when you send long documents or generate long answers. That is why the thinking section later in this guide matters: the model’s internal reasoning tokens are billed as output, so a model that thinks hard costs more than its answer alone suggests.

Two price changes are already scheduled, and they land soon after this guide is published. Carbon and Argon double on 1 December 2026 — six days from the date this guide was checked — and 3.8 Flash doubles on 1 January 2027. If you are reading this after 1 December, Carbon and Argon cost $4.00 in and $20.00 out, not the $2.00 and $10.00 in the table. Our report on the Carbon price doubling covers that change in news form. The habit to build is to check the pricing page before you commit to a model for a production app, because Gemini prices move on announced dates and the docs always carry the current figure. And one cost control that is always available: the Batch API costs half the Standard price on every model above — Hydrogen Batch is $0.75 in and $3.75 out — for work that does not need an immediate answer.

How do you actually choose? Use the picker method in our guide to choosing an AI model — the decision framework is model-agnostic and it applies here directly — but the short version is: Hydrogen for your first app and for everyday coding and agents; 3.8 Flash when you want the cheapest capable model with a free tier for long-running or high-volume work; 3.1 Pro when the task is genuinely hard — deep multimodal reasoning or precise multi-step tool use — and you can pay for it; Carbon when you need the strongest reasoning Google offers; Argon when you want frontier reasoning but faster and cheaper per turn than Carbon; Neon when you want frontier intelligence with fast end-to-end completion and Hydrogen is not enough. Start cheap, measure what your app actually spends, and only then move up. A model is a one-word change in your code — model="gemini-3.8-flash" instead of model="gemini-4-hydrogen" — so the cost of experimenting is nearly zero.

Step 4: Stream the response so your app feels alive

Water flowing from a tap into a row of glasses, motion blur on the stream, bright kitchen light. No readable text.

Your first call waits for the whole answer before it prints anything. For a short answer that is fine. For a long one, it feels broken: the user stares at a blank screen for ten seconds, wonders if the app crashed, and clicks away. Streaming fixes that. Instead of waiting for the complete response, your app receives the answer as it is generated, piece by piece, and displays each piece the moment it arrives. It is the difference between a chatbot that types and a chatbot that thinks — and it is one argument in the call you already wrote.

Add stream=True to the Python call:

stream = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Explain how AI works",
    stream=True
)
for event in stream:
    print(event)

In JavaScript it is stream: true, and the loop is for await (const event of stream). Each event the stream yields is a step.delta event carrying a chunk of text — the docs’ own example shows deltas of “AI “, “works “, and so on, arriving one after another. Your job in the app is to take each delta’s text and append it to what the user sees. That is the whole mechanism. The full event sequence has a shape worth knowing: it opens with interaction.created, then a step.start for the thought step, a series of step.delta events, a step.stop, then a step.start for the model-output step, more deltas, another step.stop, and finally interaction.completed with the usage counts. You do not need to handle every event type in a first app — printing the text deltas is enough — but knowing the sequence exists will save you confusion when you look at a raw stream for the first time.

Over REST, streaming is a query parameter and a curl flag. Add ?alt=sse to the URL and --no-buffer to the curl command, and pass "stream": true in the JSON body:

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" 
  -H "x-goog-api-key: $GEMINI_API_KEY" 
  -H 'Content-Type: application/json' 
  -H "Api-Revision: 2026-05-20" 
  --no-buffer 
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Explain how AI works",
    "stream": true
  }'

The server answers with a stream of server-sent events (SSE), each event carrying a type and JSON data, in the same sequence as the SDK stream. The --no-buffer flag matters: without it, curl waits and collects the output before showing it, which defeats the entire purpose of streaming. If you test streaming from the command line and see nothing until the end, that flag is the first thing to check.

Two practical notes. First, streaming does not change what you pay: the same tokens are generated and billed whether they arrive all at once or piece by piece. It changes only the experience. Second, the deltas include the model’s thought steps as well as its output — the stream carries thought deltas with encrypted signatures before the answer deltas begin. In a finished app you display only the text deltas from the model_output step, and you ignore the thought deltas (or, if you enable thought summaries, you can show those separately — the thinking section covers that). Google’s streaming guide covers the detailed event handling; for this tutorial, the rule is: stream the text, ignore the rest, and your app will feel instant.

Step 5: Hold a conversation — multi-turn without losing the thread

Two people in conversation across a café table, one gesturing, notebooks on the table, warm light. No readable text.

A single call has no memory. Ask “I have 2 dogs in my house”, then in a new call ask “How many paws are in my house?”, and the model has no idea what you are talking about — each call starts from zero. A real app needs the second question to work, and the Interactions API gives you two ways to make it work. The first is the one you should use.

Stateful (recommended). Chain interactions by passing previous_interaction_id. The server keeps the full conversation history for you, including the model’s thought steps and their signatures, and it optimises caching along the way. The docs’ own example is the dogs:

interaction1 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="I have 2 dogs in my house.",
)

print("Response 1:", interaction1.output_text)

interaction2 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="How many paws are in my house?",
    previous_interaction_id=interaction1.id,
)

print("Response 2:", interaction2.output_text)

The second call returns “There are 8 paws in your house” — because the server remembered the first turn. In JavaScript the same parameter is previous_interaction_id: interaction1.id; over REST it is "previous_interaction_id" in the JSON body, and you pull the id out of the first response (for example with jq -r '.id'). The rule for a stateful app is simple: keep the last interaction’s id, pass it with the next input, and the conversation continues. That is how a chatbot remembers the user across messages, and it is one line of code per turn.

Stateless. Set store=false and manage the history yourself on the client. Every request then carries the full conversation: the original user input, every model step exactly as received — including the thought and function_call steps — and then the new user input. The docs are emphatic about the exactness: you must resend all thought blocks exactly as received, never remove or modify them, because they carry the signatures the model needs to continue its reasoning. If you switch models mid-session, still resend the previous model’s thought blocks; the backend manages compatibility. Built-in tool steps carry their own signatures too, and those must be resent as well. Stateless mode exists for apps that need to own their history — for privacy, for audit, or because the history lives in your database rather than on Google’s servers — but it is more work and more ways to break. The quickstart’s stateless example shows the shape: build a history list, append each interaction’s steps to it with history.append(step.model_dump()), append the new user input, and send the whole list as the next call’s input.

Which should you choose? Stateful, unless you have a specific reason not to. It is the recommended path in the docs, it handles the signatures for you, and it is less code. The one thing stateful mode costs you is control: the history lives on Google’s side. If your app’s privacy model requires the history to stay on your servers, or you need to store it in your own database for compliance, use stateless mode and accept the bookkeeping. Either way, do not mix the two casually inside one conversation — pick a mode per conversation and stay with it.

One more status to know. When the model wants your code to do something before it can answer — a function call — the interaction comes back with status requires_action instead of completed. That is not an error; it is the API telling you it is waiting on you. The function-calling section covers exactly what to do with it. The other statuses you will meet are in_progress (a background task, covered in the shipping section), failed (something went wrong — check the errors list), and incomplete (the model hit the output-token cap — covered in the thinking section). A finished app checks the status before it reads the answer; a demo that assumes every call completes is a demo that will break in production.

Step 6: Send images, audio and files — multimodal input

A desk with a photo print, a small microphone and a document arranged in a row, a laptop behind them. No readable text.

So far every call has sent text. But Gemini models understand images, audio, video and documents natively, and the Interactions API lets you pass media alongside text in a single request. This is the step that turns a chatbot into an app: a user uploads a photo of a broken appliance and asks what is wrong with it; a student uploads a lecture recording and asks for a summary; a shopkeeper uploads a PDF invoice and asks for the total. The mechanism is the same in each case — the input becomes a list of parts, one per piece of media, instead of a single string.

The quickstart’s example sends a local image and a remote audio file in one call:

import base64
from google import genai

client = genai.Client()

with open("sample.jpg", "rb") as f:
    image_bytes = f.read()

image_b64 = base64.b64encode(image_bytes).decode("utf-8")

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Compare this local image and this remote audio file."},
        {"type": "image", "data": image_b64, "mime_type": "image/jpeg"},
        {"type": "audio", "uri": "https://storage.googleapis.com/generativeai-downloads/data/sample.mp3", "mime_type": "audio/mp3"}
    ]
)

print(interaction.output_text)

Two patterns to notice. A local file is read, base64-encoded, and sent inline as a data field with its MIME type. A remote file is sent by reference, as a uri with its MIME type — the API fetches it. The same shapes work over REST, as JSON objects in the input array. In the docs’ example, the image is a pipe organ and the audio is a sample MP3, and the model compares the two. Your app will do something more useful with the same shape: describe the photo, transcribe the audio, extract the numbers from the document.

For larger files, use the Files API instead of inline base64. The rule from Google’s Files API guide is precise: always use the Files API when the total request size — files plus text prompt plus system instructions — is larger than 100 MB, and for PDF files the limit is 50 MB. The calls are simple:

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

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Describe this audio clip"},
        {"type": "audio", "uri": myfile.uri, "mime_type": myfile.mime_type}
    ]
)

client.files.upload returns a file object with a uri and a mime_type; you pass that URI into the interaction exactly as you would a remote URL. You can check the upload with client.files.get(name=file_name) and list everything you have uploaded with client.files.list(). File URIs work interchangeably across the v1 and v1beta API versions. One related feature worth knowing: the API can now slice files so you pay only for the part it reads — our report on the Gemini API’s file-slicing controls covers that in news form — but the mechanism above is the one to learn first; slicing is an optimisation, not a prerequisite.

What the text models cannot do is generate images. If your app needs a picture out, not just a picture in, you call an image model instead: gemini-3.1-flash-image (Nano Banana 2) is the one in the quickstart, and the generated image comes back base64-encoded in interaction.output_image.data, which you decode and save as a PNG. The newer Nano Banana 2.1 (gemini-nano-banana-2.1) costs $1.50 per million input tokens and $30.00 per million image-output tokens — about $0.0336 per 1K image. Do not ask a text model for an image and do not ask an image model for a chat answer; the model catalogue separates them for a reason, and using the wrong one is the most common beginner mistake after the wrong API version. For what each model can and cannot do, the models guide is the reference; this tutorial sticks to the text models and mentions image generation only so you know where it lives.

Step 7: Get JSON back, not prose — structured output

A tidy filing tray with neatly sorted blank cards and a small wooden box, seen from above. No readable text.

Prose is for humans; apps need data. If your app asks the model for a recipe and gets back a friendly paragraph, your code cannot reliably extract the ingredients, the quantities and the cooking time. Structured output solves that: you define a JSON schema, and the model returns JSON that matches it exactly. The docs’ promise is blunt — “the output text block contains a valid JSON string conforming exactly to the requested schema” — and it is one of the most useful features in the whole API for a first app, because it is what lets your code trust the answer.

The mechanism is a response_format argument on the call. In Python, with Pydantic:

from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional

class Recipe(BaseModel):
    recipe_name: str = Field(description="Name of the recipe.")
    ingredients: List[str] = Field(description="List of ingredients.")
    prep_time_minutes: Optional[int] = Field(description="Prep time in minutes.")

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Give me a recipe for banana bread",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Recipe.model_json_schema()
    },
)

recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)

In JavaScript the same idea uses Zod: build a JSON schema object, convert it with z.fromJSONSchema, pass it as the response_format schema, then parse the output with recipeSchema.parse(JSON.parse(interaction.output_text)). Over REST, the response_format object goes in the JSON body with the same three fields: type: "text", mime_type: "application/json", and your schema. The shape is identical across all three routes, which is the point of the Interactions API: one request shape, every language.

The docs’ example answer is a complete banana-bread recipe as JSON — name, eight ingredients with quantities, fifteen minutes of prep — and the key line is the last one in the Python sample: Recipe.model_validate_json(interaction.output_text). Validate before you trust it. Structured output makes invalid JSON rare, but “rare” is not “never”, and a production app parses defensively: validate the JSON against the schema, and if validation fails, retry the call or fall back to asking again with a clearer prompt. Never feed unvalidated model output straight into your database or your user interface. The schema is a contract with the model, and validation is how you enforce it.

When should you use structured output? Whenever your code needs to act on the answer rather than display it: extracting fields from a document, classifying a message, returning a list of items, filling a form, producing data for a chart. When the answer is for a human to read, leave the format alone and let the model write prose. A useful rule of thumb: if you find yourself writing a regular expression to pull a number out of the model’s reply, stop and use a schema instead. The model is better at filling a schema than your regex is at parsing a paragraph, and the result is code you can maintain.

Step 8: Give the model tools — Search grounding and your own functions

A workbench with a magnifier, a small globe and a calculator arranged together, warm workshop light. No readable text.

A model on its own knows only what it was trained on, and its training has a cut-off date. Give it tools and it can do more: search the web for today’s facts, run code to check its own arithmetic, call your functions to reach your data. The Interactions API has two kinds of tools — built-in tools that Google provides, and function calling, where you declare your own functions and the model decides when to call them. Both are passed in the same tools argument, and both change the shape of the response, because the model may now answer in stages: search, then answer; call a function, then answer with the result.

The simplest built-in tool is Google Search grounding. One argument turns a stale model into a current one:

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}]
)

print(interaction.output_text)

The API searches, processes the results, and returns the answer with citations — Spain won Euro 2024, beating England 2-1 in the final, in the docs’ example. The citations are not decoration: they arrive as url_citation annotations on the text content blocks, each with a title and a url, and the docs show how to print them by walking the interaction’s steps and looking for model_output steps whose text blocks carry annotations. In the step history you will also see the search itself: a google_search_call step with the queries the model ran (“UEFA Euro 2024 winner”), and a google_search_result step with what came back. Grounding is billed separately from tokens — 5,000 free search requests a month shared across all Gemini 3 and newer models, then $14 per 1,000 requests, with a daily cap of 1,500 requests per project — so a grounding-heavy app needs that line in its budget. The same grounding idea extends to Google Maps, which grounds answers in real-world location data; our guide to Google Maps AI features covers what Maps grounding is useful for on the product side.

Code execution is the other built-in tool a first app is likely to use. Pass a code-execution tool and the model can run Python in a secure sandboxed environment to check its own work — the quickstart’s example asks it to calculate the 20th Fibonacci number and verify whether it is prime, and the steps show the generated code and its execution output alongside the answer. The tool does not run your code; it runs code the model writes, in Google’s sandbox, and returns the result. That distinction matters for security: model-written code runs in the sandbox, your code runs on your machine, and the two never mix.

Function calling is where the API meets your app. You declare a function — its name, a description, and its parameters as a JSON schema — and the model decides when to call it, returning structured arguments. You run the function locally and send the result back. The docs’ example is a weather function:

weather_tool = {
    "type": "function",
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

available_functions = {
    "get_current_temperature": lambda location: {
        "location": location, "temperature": "22", "unit": "celsius"
    },
}

The call loop is the part to learn carefully. You send the user’s question with the tool declared. If the model wants the temperature, the interaction comes back with status requires_action and a function_call step naming the function and its arguments (call_abc123, get_current_temperature, {"location": "London"} in the docs’ example). You run your local function with those arguments, then send the result back as a function_result step — with the same name and call_id — in a new call chained with previous_interaction_id, re-sending the full tools array, because the API does not store tool declarations between requests. Loop until no function_call steps remain, then read interaction.output_text: “The temperature in London is currently 22°C.” The model never executes your code and never sees your database — it only returns the call, and you decide what runs.

Three discipline points, all from the docs. First, resend the full tools array on every request in the chain, including chained requests — if you forget, the model may stop finding the tools or call functions the request does not declare. Second, describe the function well: the description and the parameter descriptions are what the model uses to decide when to call it and what arguments to pass, so a vague description produces vague calls. Third, treat function arguments as untrusted input — validate them before your code acts on them, exactly as you would validate any user input, because the model can pass a surprising value and your function is the one that will run it. Function calling is also the bridge to the wider API world: our guide to the OpenAI API shows how the same idea works on the other side of the fence, and the shape is deliberately similar — declare, call, return, answer — so what you learn here transfers.

Step 9: Control the thinking — quality, speed and cost in one dial

A person thinking at a desk with a chessboard, chin resting on one hand, soft window light. No readable text.

Gemini models think before they answer. They reason internally — working through a problem step by step — and that reasoning is what makes them good at coding, mathematics and multi-step planning. It also costs you: thinking generates tokens, thinking tokens are billed as output tokens, and thinking takes time. The Interactions API gives you one dial for all of it, called thinking_level, and this section is about setting it deliberately instead of accepting the default blindly.

The levels are low, medium, high, xhigh and minimal, and each model has its own default. The table from Google’s thinking guide is the whole story:

Thinking levelToken useWhen to use itDefault on
lowFewest tokens, lowest latencyCost- and latency-sensitive work: fast chat, high-throughput processing—
mediumLower token use, faster responsesInteractive coding, live UI prototyping, latency-sensitive tool callsCarbon, Argon, 3.8 Flash, 3.6 Flash
highBalanced intelligence and speedMost tasks, including complex coding, agents, tool calling, multimodal workNeon, Hydrogen (maximum depth on Carbon, Argon, Gemini 3)
xhighMost tokens, deepest reasoningHard multi-step coding and agentic problems where high falls short— (supported on Neon and Hydrogen only)
minimalNear-off thinking, lowest latencySimple extraction and classification3.5/3.1 Flash-Lite (also supported on 3.6 Flash and 3 Flash preview; not on Gemini 4 or 3.8 Flash)

Set the level in the generation config:

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Audit this payment retry queue for race conditions and rewrite the lock acquisition logic.",
    generation_config={
        "thinking_level": "xhigh"
    }
)

For a simple list — “Provide a list of 3 famous physicists and their key contributions” — the docs use "thinking_level": "low" on the same model. That contrast is the method: start with the default, and only raise the level when the task is hard enough to need it. Google’s own advice is to run your evaluations at all the levels with a high output cap, then pick the lowest level that meets your quality bar. xhigh can overthink simple prompts and even exhaust the output cap on tasks like text or JSON extraction, so reserving it for genuinely hard problems is not caution — it is the documented guidance.

Thinking has two limits you need to understand, because they produce the two most confusing failures in a first app. The first is max_output_tokens. It is a hard cutoff enforced by the infrastructure, and it counts thinking tokens as well as answer tokens. If the model hits the cap while still reasoning, it stops with status incomplete and returns truncated or empty output — while still billing you for the thinking tokens it generated. The fix is not a bigger cap by default; it is a lower thinking level. Google says this directly: to reduce cost or latency without truncating responses, lower thinking_level instead of setting a small max_output_tokens. The second limit is the context window. On Gemini 4 models, input, thinking and output tokens share a single 1-million-token window (1,048,576 tokens exactly). If your input plus your output cap exceeds it, the API caps the output to whatever space remains. The default synchronous output cap is 65,536 tokens — 32,768 for non-streaming calls on Carbon and Argon — and reaching beyond 65,536 tokens up to the full million is called long decode, which needs max_output_tokens above 65,536 with background=True or client-side continuation.

Two more facts complete the picture. First, you can see the thinking: the Interactions API surfaces reasoning as thought steps in the steps array, each with an encrypted signature and an optional summary. Enable summaries with generation_config={"thinking_summaries": "auto"} and read the summary arrays on the thought steps. Second, the counts are visible in usage: interaction.usage.total_thought_tokens and interaction.usage.total_output_tokens tell you exactly how much of your bill was thinking. Check those two numbers the first time your app runs a hard task; they are the most honest measure of what a thinking level costs you.

And one thing you must not do on current models: do not set temperature, top_p or top_k. On Gemini 4 and Gemini 3.6 and newer, the API ignores custom values for all three and returns deprecation warning headers — and Google says it will return 400 errors for them in a future release. Remove them from your request configs entirely. The old sampling knobs belong to the previous generation of models; the current generation is controlled with thinking_level and max_output_tokens, and with system instructions, which are covered in the next sections’ companion material. If you copy a code sample from an older tutorial that sets temperature=0.7, delete that line — it does nothing today and will break tomorrow.

Step 10: Safety settings — what gets blocked and what to do about it

A garden gate with a soft brass lock at dusk, warm light spilling through the gap, calm and friendly. No readable text.

Every Gemini API call passes through safety filters, and your app needs to know what they do — because the first time one fires, it looks like your app is broken. It is not broken. The request was blocked, the API told you why, and your code is supposed to handle it. This section is the whole of that handling.

The filters cover five categories: harassment (abusive, threatening, bullying content), hate_speech, sexually_explicit, dangerous_content (content that promotes, facilitates or enables dangerous activities), and jailbreak (prompts designed to bypass the safety filters). On top of those, built-in protections against core harms — such as content endangering child safety — are always blocked and cannot be adjusted at all. You set the adjustable filters per category, one setting each, as a safety_settings list on the call:

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Some potentially unsafe prompt.",
    safety_settings=[
        {
            "type": "hate_speech",
            "threshold": "block_low_and_above",
        }
    ],
)

The thresholds are four: off (the filter is off), block_only_high (block only when the probability of unsafe content is high), block_medium_and_above (block at medium or high), and block_low_and_above (block at low, medium or high — the strictest). Here is the fact most developers get wrong: the default is Off for Gemini 2.5 and later models. The adjustable filters are off unless you turn them on, because the model’s own built-in safety covers most cases, and Google’s guide says plainly to adjust the settings only if your application consistently requires it. Do not turn everything to maximum strictness “to be safe” — you will block legitimate answers, and the guide’s own example is a video game whose dialogue needs the dangerous-content filter loosened. Set the filters for your use case, test them with real prompts, and leave the rest off.

When a filter blocks a request, the interaction fails with an HTTP 400 error and the blocked content is not returned. The error code tells you why: safety means the input or the response was blocked by a safety filter; jailbreak, prohibited_content or blocklist mean the input was blocked for that reason, and the message starts with Input blocked:. Google’s example error body is:

{
  "error": {
    "code": "safety",
    "message": "Request blocked due to safety violations (harmful content). Please modify your input and retry."
  }
}

For background interactions the same code and message appear in the errors list with the status set to failed; when streaming, the error arrives as an error event. Note the blocking rule itself: the API rates the probability of content being unsafe — high, medium, low or negligible — and blocks on probability, not on severity. Google’s own example is two sentences about a robot: “The robot punched me” might score a higher probability of being unsafe than “The robot slashed me up”, even though the second sounds more severe. Test carefully, says the guide, to find the level that supports your use case while minimising harm to your users. That is the whole philosophy in one sentence: blocking is a probability judgement, and your job is to tune it, not to assume it.

In AI Studio you can adjust the same filters without code: click Safety settings under Advanced settings in the Run settings panel, and use the sliders per category. A blocked request there shows a “Content blocked” message, with the category and the probability on hover. One warning from the docs belongs in any production plan: applications that use less restrictive safety settings may be subject to review under the Terms of Service. Loosening a filter is a decision with a paper trail — make it deliberately, document why, and keep the default wherever you do not have a reason to change it.

When it breaks: errors, rate limits and retries

A person calmly fixing a bicycle chain with tools spread on a cloth, daylight, practical and unhurried. No readable text.

Every app breaks. The difference between a demo and a product is that the product knows what broke and what to do about it. The Gemini API’s errors fall into a small number of buckets, and this section maps each one to its fix. Learn the map now; you will use it on the first day your app has real users.

Start with the retry rule, because it is the one developers get backwards most often. Retry only transient errors: 429 (rate limit), 503 (service unavailable), and other 5xx or 408 errors. Do not retry client errors — 400, 402, 403 — because retrying them changes nothing: they mean an invalid API key, depleted prepay credits, or bad syntax, and the same request will fail the same way a hundred times. When you do retry, use exponential backoff with jitter: wait a short time before the first retry (about 1 second), then increase the delay exponentially (2 seconds, 4 seconds, 8 seconds), add a random jitter so all your clients do not retry at the same instant, and set a maximum number of attempts so a retry loop can never run forever. The good news is that you may not need to write this at all: the official SDKs include automatic retry with exponential backoff by default for transient errors, and the Python SDK retries them up to four times with an initial delay of about 1 second and a maximum delay of 60 seconds. If you use the SDK, transient errors are handled for you; if you use raw REST, the backoff above is your implementation.

Rate limits are the most common 429. They are measured in three dimensions — requests per minute (RPM), tokens per minute of input (TPM), and requests per day (RPD) — and your usage is checked against each one separately, so exceeding any single dimension triggers the error even if the others are fine. Three facts about them matter for a first app. First, limits are applied per project, not per API key — creating more keys does not buy more quota. Second, the daily (RPD) quotas reset at midnight Pacific time. Third, the per-model RPM and TPM numbers are not published on the public docs pages; they live on the AI Studio rate-limit page for your project, and this guide will not invent them. What the public docs do publish is the spend-based limit: on a rolling 10-minute window, Tier 1 projects are capped at $10 of spend, and Tier 2 and Tier 3 at $200. Hit one and you get a 429 RESOURCE_EXHAUSTED; the fix is to wait and retry, to reduce the rate of expensive requests (smaller contexts, shorter outputs), or to request a limit increase. Grounding has its own cap: Google Search grounding on Gemini 3 and newer models is limited to 1,500 requests a day per project by default.

Usage tiers are how limits grow. A project starts on the Free tier; link an active billing account and it becomes Tier 1 (spend cap $250); once it has paid $100 and three days have passed since the first successful payment, it becomes Tier 2 (cap $2,000); once it has paid $1,000 and thirty days have passed, Tier 3 (cap $20,000 to $100,000+). Upgrades are automatic when the criteria are met — Free to Tier 1 typically takes effect instantly, later upgrades within 10 minutes — and you can check your tier on the Projects page in AI Studio. The practical meaning for a first app: your free-tier limits are real but modest, and the moment your app has users, set up billing. Billing does not just raise limits; it moves you to the paid tier, where your content is not used to improve Google’s products.

Then the 403. A 403 PERMISSION_DENIED with “Your project has been denied access” has four common causes, and each has a different fix. Verification required: verify your account with a mobile device in AI Studio, or set up billing to skip verification. Free tier unavailable: your project is not eligible for the free tier — remember, eligibility is at the project level, so a new key in the same project will not help; upgrade the project to the paid tier. Payment needed: your Cloud Billing account has a past-due balance — resolve it in the AI Studio billing page or the Cloud Billing console, and access returns automatically. Leaked or blocked key: Google found your key exposed in public and blocked it — generate a new key in AI Studio and fix the leak, because the old key will never work again. One trap the docs call out explicitly: a 200 OK from models.list (GET /v1beta/models) only proves your key exists. It does not check your project’s tier or billing status, so it does not prove that inference calls will work. Test with a real call, not with the list endpoint.

Finally, the errors that are not HTTP codes at all. A 400 with code safety is a blocked request — covered in the safety section, and the fix is to change the input, not to retry. An interaction with status incomplete hit the output-token cap — covered in the thinking section, and the fix is a lower thinking level, not a bigger hammer. A response that stops mid-sentence because of recitation (the output resembled training data too closely) is fixed by making the prompt more unique. And repeated tokens — the same phrase looping — are usually fixed by clearer instructions in the prompt or system instruction, not by sampling settings, because the sampling knobs no longer work on current models. The pattern across all of these is the same: read the status or the code, find the bucket it belongs to, and apply that bucket’s fix. Guessing wastes the hour that the map saves.

From tutorial to real app: shipping it without regret

A small shopfront at dusk with warm lights on, a blank signboard with no readable text, a person opening the door. No readable text.

You now have a working app. Shipping it means protecting three things: your key, your bill, and your users’ patience. Each one is a short checklist, and this section is that checklist plus the next steps worth taking once the basics are solid.

First, the key. It stays on the server, in an environment variable, never in client-side code and never in a repository. That rule was in step 1 and it bears repeating here because shipping is when it gets broken: the temptation is to paste the key into a front-end JavaScript file so the browser can call the API directly. Do not do it. Anyone who opens your page can read the key, call the API as you, and spend your money. The correct shape is a small back end — your server holds the key, the browser talks to your server, your server talks to Gemini. If a key does leak, Google will block it, and you will generate a new one in AI Studio and rotate it. Keys issued in AI Studio are now by default limited to AI Studio only, which limits the damage a leaked key can do — but the back-end rule is still the rule.

Second, the bill. Set up billing before your app has users, watch the spend-based limits, and know your tier. A first app on Hydrogen’s free tier costs nothing while you learn; the moment it has traffic, the paid tier’s higher limits and the not-used-for-training guarantee are worth the setup. Keep an eye on the two numbers that drive cost: input tokens (long documents, long histories, repeated tool declarations) and thinking tokens (high thinking levels on hard tasks). The Batch API halves the price for anything that does not need an immediate answer — nightly summaries, bulk classification, backfills — so use it for those jobs and keep the Standard tier for live requests. And remember the two price changes coming up: Carbon and Argon double on 1 December 2026, Flash doubles on 1 January 2027. If your app defaults to one of those models, re-check the pricing page when the date passes.

Third, your users’ patience. Long tasks should run in the background instead of blocking the request. Set background=True on the call and poll for the result with client.interactions.get(interaction.id) — the first response comes back immediately with status in_progress, and you poll every few seconds until it reads completed or failed. Over REST the same idea is "background": true in the request body and a GET on /v1beta/interactions/{id}. Background execution is how a real app handles the jobs that take minutes: a long report, a big document, a research task. Pair it with streaming for the jobs that take seconds, and your app will feel fast in both cases.

Once the checklist is done, the next step is agents. The Interactions API can run a managed agent instead of a plain model: pass an agent instead of a model and set environment="remote", and the agent runs in a remote sandbox with code execution and file management — Google’s example uses agent="antigravity-preview-09-2026" to write a Fibonacci script, save it to a file, read the file back and print it, all in one call. You can also define custom agents with your own instructions, skills and data sources, and there is a Deep Research agent for autonomous multi-step research. Agents are the natural sequel to this tutorial: everything you learned — interactions, tools, function calling, background execution — is the substrate agents run on, and our guide to AI agents explains what an agent is and when one is the right tool before you build with it. File search, which this guide mentioned in passing, is the other natural sequel: index your documents once, then let the model search them — the concepts behind it are the retrieval ideas in our explainer on BERT, Llama, Whisper and RAG.

What should you build next? Three ideas, each using only the features this guide taught. First, a document question-answerer: upload a PDF through the Files API, ask questions about it, return the answers as structured JSON with a source-page field. Second, a photo describer with a twist: take an image, ask for a description, then ask for the same description as JSON with fixed fields (subject, colours, mood) so another program can use it. Third, a grounded news summariser: take a topic, ground the answer with Google Search so it is current, print the citations alongside the summary, and stream the whole thing to the screen. Each one is an afternoon’s work from the code in this guide, and each one exercises a different combination of the steps: files, structured output, tools, streaming. Build one, ship it behind a back end that holds your key, and you will have gone from first call to real app.

The Gemini API rewards the developer who reads the docs over the one who copies a tutorial — and this guide was written to be the docs, in order, with the working code attached. The API you learned here is the Interactions API as it stands on 25 November 2026: the key from AI Studio, the first call on Hydrogen, streaming, memory, multimodal input, JSON output, tools, thinking, safety and errors. The models and the prices will move — Carbon and Argon on 1 December, Flash on 1 January — and the docs will move with them. Re-check the pricing page and the model catalogue when you ship, keep your key on the server, and build the next thing. Checked 25 November 2026.

Sources

  • Google — “Getting started” / Gemini API quickstart (ai.google.dev/gemini-api/docs/quickstart): the Interactions API end to end — API key setup, first call (Python, JavaScript, Java, Go, REST, CLI), streaming, multi-turn conversations (stateful and stateless), multimodal understanding, image generation, structured output, Google Search grounding, function calling, managed agents, background execution. Read in full, 25 November 2026.
  • Google — “Gemini Developer API pricing” (ai.google.dev/gemini-api/docs/pricing): Free / Paid / Enterprise tiers; Standard, Batch, Flex, Priority and Contributor pricing per model — Gemini 4 Carbon, Neon, Hydrogen, Argon; Gemini 3.1 Pro, 3.8 Flash, 3.6 Flash and others; grounding, context-caching and Batch (50% off) prices; price-change dates 1 Dec 2026 and 1 Jan 2027. Read in full, 25 November 2026.
  • Google — “Models” (ai.google.dev/gemini-api/docs/models): the current lineup — Gemini 4 Carbon, Neon, Hydrogen, Argon; Gemini 3 models incl. 3.8 Flash, 3.6 Flash, 3.1 Pro; max output 64K / 1M tokens for Gemini 4; Gemini 2.5 Flash deprecation and 1 Dec 2026 auto-routing to Gemini 3.5 Flash-Lite. Read in full, 25 November 2026.
  • Google — “Text generation” (ai.google.dev/gemini-api/docs/text-generation): basic text generation with the Interactions API; interaction.output_text behaviour; thinking enabled by default; generation_config thinking levels; system_instruction parameter. Read in full, 25 November 2026.
  • Google — “Gemini thinking” (ai.google.dev/gemini-api/docs/thinking): thinking levels table (low / medium / high / xhigh / minimal) and per-model defaults; shared 1M-token context window (1,048,576 tokens); default synchronous output cap 65,536 tokens (32,768 non-streaming on Carbon/Argon); long decode up to 1M tokens; max_output_tokens hard cutoff and incomplete status; usage.total_thought_tokens; thought steps and signatures. Read in full, 25 November 2026.
  • Google — “Safety settings” (ai.google.dev/gemini-api/docs/safety-settings): adjustable safety filters (harassment, hate_speech, sexually_explicit, dangerous_content, jailbreak); thresholds off / block_only_high / block_medium_and_above / block_low_and_above; default Off for Gemini 2.5 and later; blocked requests fail with HTTP 400 (codes safety, jailbreak, prohibited_content, blocklist); AI Studio safety panel. Read in full, 25 November 2026.
  • Google — “Rate limits” (ai.google.dev/gemini-api/docs/rate-limits): RPM / TPM / RPD dimensions; limits per project, not per key; RPD reset at midnight Pacific; spend-based limits per 10-minute window (Tier 1 $10, Tier 2/3 $200); usage tiers and qualifications; grounding 1,500 requests/day; Batch API limits. Read in full, 25 November 2026.
  • Google — “Troubleshooting guide” (ai.google.dev/gemini-api/docs/troubleshooting): retry strategy (exponential backoff, jitter; retry 429/408/5xx only, never 400/402/403); Python SDK auto-retry (up to four times, ~1s initial, 60s max); temperature / top_p / top_k ignored on Gemini 3.6+ and 4; candidate count unsupported on Gemini 3 and 4; 403 PERMISSION_DENIED causes (verification, free-tier unavailability, payment needed, leaked key); the models.list 200 trap. Read in full, 25 November 2026.
  • Google — “Files API” (ai.google.dev/gemini-api/docs/files): client.files.upload / files.get / files.list; use the Files API when the total request exceeds 100 MB (PDFs 50 MB); file URIs interchangeable across v1 and v1beta. Read in full, 25 November 2026.
  • Internal research base: C6 brief (~/workspace/ger-evergreen/c6-gemini/BRIEF.md, 13 Nov 2026) — model and pricing facts re-verified live against Google’s pages on 25 November 2026; all prices confirmed unchanged except the addition of Gemini 4 Neon.
  • Site sources linked in the article: the Gemini models explainer (post 5588); the Gemini in Workspace guide (post 4219); the AI model picker (post 4081); the Neon launch report; the Carbon price-doubling report; the Gemini API file-slicing report; the OpenAI API explainer (post 4638); the Google Maps AI features guide (post 6530); the AI agents explainer (post 6248); the BERT, Llama, Whisper and RAG explainer (post 4889). All verified HTTP 200 on 25 November 2026.

Share to: , and

Faheem R. Khattak

Senior automation engineer and AI marketing journo covering LLMs, algorithms, analytics, core updates, Bing search, and technical SEO.

0 Comments

Leave a Reply

Optional Take Tag:

🛡️ Spam protection: Honeypot + Time-Trap Active

This site uses Akismet to reduce spam. Learn how your comment data is processed.