Skip to content
,

Gemini Interactions API Tutorial in Python (google-genai, 2026)

12โ€“18 minutes
Woman in a hijab in a home lab with a PC tower holding a tablet with a GEMINI API card, hook new Gemini API Interactions

Google now tells developers to build new Gemini apps on the Interactions API, not generateContent. It became generally available in June 2026, and the docs now open with client.interactions.create.

This guide shows you how to use it in Python with the google-genai SDK. We cover a first call, chat memory, streaming, tools, JSON output, prices, errors and a clean migration path.

TLDR

  • What it is: one endpoint for Gemini models and agents, called with client.interactions.create(model=..., input=...).
  • Why switch: Google calls generateContent “legacy” and says new capabilities will launch on Interactions first.
  • Chat memory: pass previous_interaction_id and the server keeps the history for you.
  • Read the answer: use interaction.output_text, or loop over interaction.steps for tools and thoughts.
  • SDK: google-genai 2.3.0 or later. We checked version 3.7.0 (2 Dec 2026), which needs Python 3.11+.
  • Price example: Gemini 4 Hydrogen costs $1.50 input and $7.50 output per 1M tokens on the paid tier.

What the Interactions API Is

The Interactions API is Google’s newer interface for talking to Gemini. Every request creates an Interaction, a stored record of one turn in a conversation or task.

Each Interaction holds a timeline of typed steps. That makes the response much easier to inspect than the old nested candidates and parts.

  • user_input: what you sent (shown when you fetch a stored interaction).
  • thought: the model’s reasoning step, with an encrypted signature and an optional summary.
  • function_call / function_result: a tool request from the model and the answer you send back.
  • google_search_call / google_search_result: server-side tool steps run by Google.
  • model_output: the final answer, which can hold text, images or audio.

The same endpoint also runs Google’s managed agents. You pass model= for a normal model call, or agent= for agents such as Deep Research or the Antigravity agent.

Why Google Now Recommends It

The official overview says the Interactions API has been Generally Available since June 2026 and is “the recommended interface for all new projects”. The old generateContent API is now labelled legacy, but it stays fully supported.

Google AI Studio docs page for the Interactions API saying it is Generally Available since June 2026 and generateContent is legacy
Official Gemini API docs Interactions API overview (checked 3 Dec 2026).

Here is what Google lists as the main reasons to move:

  • Server-side state: chain turns with previous_interaction_id instead of resending the full chat history.
  • Lower cost on long chats: stored state gives higher implicit cache hit rates across turns.
  • Observable steps: thoughts, tool calls and results come back as separate typed steps you can log or show in a UI.
  • Background runs: set background=True for long jobs and fetch the result later.
  • One API for models and agents: no separate endpoint for Deep Research or custom managed agents.
  • Where new things launch: Google says new capabilities beyond the core model family and new agent tools will launch on Interactions.

Note: Google’s GA blog post says generateContent will keep getting new mainline Gemini models “for the foreseeable future”. You do not have to rewrite working code today, but new projects should start on Interactions.

Prerequisites and Setup

You need three things before you write any code:

  • Python 3.11 or newer: the current google-genai 3.7.0 release requires it.
  • A Gemini API key: free from Google AI Studio. Our Google AI Studio guide shows where to click.
  • A model ID: this guide uses gemini-4-hydrogen, the model Google uses in its own Interactions examples.
  1. Create a virtual environment. Run python3 -m venv .venv, then activate it with source .venv/bin/activate (on Windows: .venv\Scripts\activate).
  2. Install the SDK. Run pip install -U google-genai. Interactions support starts at version 2.3.0, so older installs must be upgraded.
  3. Get your key. Open Google AI Studio, click Get API key, and create a key for your project.
  4. Store the key in an environment variable. Run export GEMINI_API_KEY="your-key". The SDK also reads GOOGLE_API_KEY, and if both are set it uses GOOGLE_API_KEY.
  5. Check the install. Run pip show google-genai and confirm the version is 2.3.0 or higher.

Warning: never paste your API key into code you commit. Keep it in an environment variable or a secrets manager, and use the old google-generativeai package for nothing new: Google marks it deprecated.

Your First Call in Python

A basic text request takes four lines. The client reads your key from the environment automatically.

from google import genai

client = genai.Client()  # reads GEMINI_API_KEY or GOOGLE_API_KEY

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Explain what an API rate limit is in two sentences.",
)

print(interaction.output_text)
print("Interaction ID:", interaction.id)
print("Status:", interaction.status)
print("Tokens used:", interaction.usage.total_tokens)

output_text joins the text blocks at the end of the model’s answer. For simple replies that is all you need.

Adding a system instruction and settings

Settings such as temperature and thinking depth live in generation_config. The system prompt is a top-level system_instruction string.

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    system_instruction="You are a concise Python tutor. Answer in plain English.",
    input="What does a list comprehension do?",
    generation_config={
        "temperature": 0.4,
        "max_output_tokens": 400,
        "thinking_level": "low",   # minimal, low, medium, high or xhigh
    },
)

print(interaction.output_text)

Tip: thinking tokens are billed as output tokens. Use "thinking_level": "low" or "minimal" for simple tasks to keep costs down.

Multi-Turn Chat With Server-Side State

This is the biggest change from generateContent. You no longer build a history list yourself. You pass the ID of the last interaction and the server fills in the context.

from google import genai

client = genai.Client()
MODEL = "gemini-4-hydrogen"

turn1 = client.interactions.create(
    model=MODEL,
    input="Hi, my name is Priya and I run a small bakery.",
)
print("Gemini:", turn1.output_text)

turn2 = client.interactions.create(
    model=MODEL,
    previous_interaction_id=turn1.id,
    input="Suggest a name for my new sourdough loaf. Use my name.",
)
print("Gemini:", turn2.output_text)

A simple chat loop

from google import genai

client = genai.Client()
last_id = None

while True:
    user_text = input("You: ").strip()
    if user_text.lower() in {"quit", "exit"}:
        break
    reply = client.interactions.create(
        model="gemini-4-hydrogen",
        input=user_text,
        previous_interaction_id=last_id,
    )
    print("Gemini:", reply.output_text)
    last_id = reply.id

Keep two rules in mind with chained turns:

  • Only history carries over: tools, system_instruction and generation_config apply to one interaction only. Send them again on every turn that needs them.
  • Storage must be on: chaining needs store=True, which is the default. With store=False you must send the full history yourself.

Streaming Responses

Streaming uses the same endpoint with stream=True. You get Server-Sent Events instead of one final object.

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Write a 5-line poem about debugging at midnight.",
    stream=True,
)

for event in stream:
    if event.event_type == "step.delta" and event.delta.type == "text":
        print(event.delta.text, end="", flush=True)
    elif event.event_type == "interaction.completed":
        usage = event.interaction.usage
        print(f"\n\nDone. Total tokens: {usage.total_tokens}")
    elif event.event_type == "error":
        print("\nStream error:", event.error)

Every stream follows the same event order:

  1. interaction.created: the ID, model and starting status.
  2. step.start: a new step begins, such as thought, model_output or function_call.
  3. step.delta: pieces of that step, such as text, thought_summary or arguments_delta.
  4. step.stop: the step is finished.
  5. interaction.completed: final status and token usage.

To see a summary of the model’s reasoning while it streams, add generation_config={"thinking_summaries": "auto"} and print the thought_summary deltas.

Note: Google says new event and delta types may be added over time. Log and skip any type you do not recognise rather than raising an error.

Tools: Google Search and Function Calling

Tools are a flat list of objects with a type. You can mix built-in tools and your own functions in one request.

from google import genai

client = genai.Client()

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

for step in interaction.steps:
    if step.type == "model_output":
        text_block = step.content[0]
        print("Answer:", text_block.text)
        for anno in text_block.annotations or []:
            print("Source:", anno.title, anno.uri)

Citations now sit inside the text block as annotations. You no longer map character indexes from a separate grounding metadata object.

Function calling, step by step

The Interactions API does not run Python functions for you yet. Automatic function calling in Python is listed as a generateContent-only feature, so you run the function and send the result back.

import json
from google import genai

client = genai.Client()
MODEL = "gemini-4-hydrogen"

weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "City name, e.g. Paris"}
        },
        "required": ["city"],
    },
}

def get_weather(city: str) -> dict:
    # Replace with a real weather API call
    return {"city": city, "temp_c": 22, "sky": "sunny"}

first = client.interactions.create(
    model=MODEL,
    input="Should I take an umbrella in Paris today?",
    tools=[weather_tool],
)

results = []
for step in first.steps:
    if step.type == "function_call" and step.name == "get_weather":
        data = get_weather(**step.arguments)
        results.append({
            "type": "function_result",
            "call_id": step.id,
            "name": step.name,
            "result": json.dumps(data),
        })

if results:
    final = client.interactions.create(
        model=MODEL,
        previous_interaction_id=first.id,
        input=results,
        tools=[weather_tool],
    )
    print(final.output_text)
else:
    print(first.output_text)

When the model asks for a function, the interaction status becomes requires_action. Your function_result must use the same call_id as the call step. For the full tool guide, see our Gemini function calling tutorial.

Structured JSON Output

JSON settings moved to a top-level response_format field. A Pydantic model gives you the schema and the parser in one go.

from google import genai
from pydantic import BaseModel

client = genai.Client()

class Recipe(BaseModel):
    recipe_name: str
    prep_minutes: int
    ingredients: list[str]

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

recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe.recipe_name, recipe.prep_minutes, recipe.ingredients)

You can also pass a list of formats, such as [{"type": "text"}, {"type": "image"}], on image models to get text and pictures in one reply. Our structured outputs guide compares this with Claude and OpenAI.

The Same Call With curl

The SDK talks to https://generativelanguage.googleapis.com/v1/interactions by default and sends your key in the x-goog-api-key header.

curl -X POST "https://generativelanguage.googleapis.com/v1/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Explain what an API rate limit is in two sentences."
  }'

Add "stream": true to the JSON body to stream. Unlike generateContent, there is no separate streaming URL.

Interactions API vs generateContent

Feature generateContent (legacy) Interactions API
Python call client.models.generate_content() client.interactions.create()
Prompt field contents input
Response shape candidates, content, parts typed steps timeline
Quick text access response.text interaction.output_text
Chat history You resend it, or use client.chats previous_interaction_id (server-side)
Settings Nested in config generation_config, plus top-level system_instruction and tools
JSON output response_mime_type + response_schema in config Top-level response_format
Streaming Separate streamGenerateContent endpoint Same endpoint, stream=True
Search citations Separate grounding metadata with indexes Inline annotations on the text
Background jobs No Yes, background=True
Agents (Deep Research, Antigravity) No Yes, agent=
Batch API Yes Not yet
Explicit context caching Yes Not yet (implicit caching only)
Automatic function calling (Python) Yes Not yet
Quick answer: use the Interactions API for every new project. Stay on generateContent for now only if you depend on the Batch API, explicit caches or Python automatic function calling.

How to Migrate From generateContent

Google offers a coding-agent skill that can do much of this for you. If you prefer to do it by hand, follow these steps.

  1. Upgrade the SDK. Run pip install -U google-genai and confirm version 2.3.0 or later.
  2. Swap the call. Change client.models.generate_content(model=..., contents=...) to client.interactions.create(model=..., input=...).
  3. Swap the reader. Replace response.text with interaction.output_text. Replace any candidates[0].content.parts parsing with a loop over interaction.steps.
  4. Flatten the config. Move system_instruction and tools to the top level. Put temperature, token limits and thinking settings in generation_config.
  5. Replace chat history. Drop client.chats or your manual contents list and pass previous_interaction_id each turn.
  6. Rewrite tool declarations. Each function becomes {"type": "function", "name": ..., "description": ..., "parameters": ...}, and Google Search becomes {"type": "google_search"}.
  7. Rewrite function results. Send a function_result item with the matching call_id instead of a Part.from_function_response.
  8. Move JSON settings. Replace response_mime_type and response_schema with a top-level response_format object.
  9. Update streaming. Replace generate_content_stream with stream=True and handle step.delta events.
  10. Decide on storage. Keep the default store=True for chaining, or set store=False for stateless calls with sensitive data.
  11. Test, then switch traffic. Compare outputs and token usage on a sample of real prompts before you remove the old path.

Tip: if you use a coding agent, Google’s docs suggest installing the gemini-api-dev skill and asking it to “migrate my app to the interactions api”. Review every diff it makes.

Pricing and a Worked Cost Example

The Interactions API itself has no extra fee. You pay the normal per-token price of the model you call, and Google notes that thinking tokens and tool system instructions are billed too.

Model (ID) Free tier Input / 1M tokens Output / 1M tokens Cached input / 1M
Gemini 4 Carbon (gemini-4-carbon) Not available $4.00 $20.00 $0.20
Gemini 4 Neon (gemini-4-neon) Not available $3.00 $15.00 $0.15
Gemini 4 Hydrogen (gemini-4-hydrogen) Yes $1.50 $7.50 $0.075
Gemini 3.8 Flash (gemini-3.8-flash) Yes $0.75* $3.75* $0.075*
Gemini 3.5 Flash-Lite (gemini-3.5-flash-lite) Yes $0.30 $2.50 $0.03

Standard tier, paid prices from the official pricing page on 3 Dec 2026. *Gemini 3.8 Flash prices are listed “through December 31, 2026”. Output prices include thinking tokens.

Official Gemini API pricing table for Gemini 4 Hydrogen showing 1.50 dollars input, 7.50 dollars output and 0.075 dollars cached per 1M tokens
Official Gemini Developer API pricing page, Gemini 4 Hydrogen standard tier (checked 3 Dec 2026).

Worked example: a support chatbot on Hydrogen

  • Per request: 2,000 input tokens and 800 output tokens (thinking included).
  • Input cost: 2,000 / 1,000,000 x $1.50 = $0.003.
  • Output cost: 800 / 1,000,000 x $7.50 = $0.006.
  • Total: about $0.009 per request, or about $90 for 10,000 requests.

On long chats, chained turns can hit the implicit cache, and cached input on Hydrogen costs $0.075 per 1M tokens. Google also offers Flex (about 50% cheaper, slower) and Priority tiers through the service_tier field. See our Gemini API pricing guide for the full list.

Limits and Data Retention

Item What the docs say
Storage default store=True; set store=False to opt out
Retention, paid tier 55 days (can be shortened to 7, 14, 28 or 55 days in AI Studio)
Retention, free tier 1 day
store=False side effects No previous_interaction_id chaining and no background execution
Context window (Gemini 4 models) 1M tokens, with long decode past 64K output tokens
Not yet supported Batch API, explicit caching, Python automatic function calling
Remote MCP Not supported on Gemini 3 models yet
Rate limits Per project and per model; see the Rate limits page in AI Studio

You can delete a stored interaction at any time with client.interactions.delete(interaction_id), and fetch one with client.interactions.get(interaction_id). Paid-tier calls with storage on also appear on the AI Studio Logs page.

Troubleshooting: Common Errors and Fixes

The Python SDK raises status-based exceptions such as BadRequestError or RateLimitError for interaction calls. Each error carries a status_code and a message.

import time
from google import genai

client = genai.Client()

def ask(prompt, retries=4):
    for attempt in range(retries):
        try:
            return client.interactions.create(model="gemini-4-hydrogen", input=prompt)
        except Exception as e:
            code = getattr(e, "status_code", None)
            if code in (429, 500, 503, 504) and attempt < retries - 1:
                time.sleep(2 ** attempt)  # 1, 2, 4 seconds
                continue
            raise

print(ask("Say hello").output_text)
Error you see Code Likely cause Fix
API key not valid. Please pass a valid API key. 400 (API_KEY_INVALID) Wrong, revoked or empty key Check GEMINI_API_KEY; make sure GOOGLE_API_KEY is not set to an old key
authentication 401 Key missing or expired Create a new key in AI Studio
payment_required 402 Prepay credit balance is empty Add credits or turn on auto-reload; do not retry
permission_denied 403 Key lacks access, or project needs verification or billing Check project verification and billing status
model_not_found 404 Typo or retired model ID Use an ID from the supported models list, such as gemini-4-hydrogen
parameter_unknown 400 Old generateContent field like contents or config Rename to input and generation_config
rate_limit_exceeded / too_many_requests 429 Per-minute request or token limit hit Retry with exponential backoff
quota_exceeded 429 Daily quota used up Wait for reset or request more quota
service_unavailable 503 Model overloaded Back off and retry, or try a lighter model
deadline_exceeded 504 Request took too long Raise your client timeout, or use background=True
Follow-up turn forgets context none First turn used store=False, or you dropped the ID Keep store=True and pass previous_interaction_id
Tools or system prompt ignored on turn 2 none These settings do not carry over Send tools, system_instruction and generation_config on every turn

Blocked output returns codes such as safety, recitation or prohibited_content. Change the input and try again. Our Gemini API errors guide covers more cases.

Frequently Asked Questions

Is generateContent being shut down?

No. Google calls it legacy but says it remains fully supported and will keep getting new mainline Gemini models for the foreseeable future. New agent features will increasingly land only on the Interactions API.

Which google-genai version do I need for the Interactions API?

Version 2.3.0 or later. The latest release we checked, 3.7.0 from 2 December 2026, requires Python 3.11 or newer.

Does the Interactions API cost more than generateContent?

No. You pay the same per-token model prices. Chained turns can be cheaper because server-side state improves implicit cache hits.

How do I keep conversation memory without storing data on Google’s servers?

Set store=False and send the full conversation in input each time. You lose previous_interaction_id chaining and background execution in that mode.

Can I use the free tier with the Interactions API?

Yes, on models that have a free tier, such as Gemini 4 Hydrogen and Gemini 3.8 Flash. Gemini 4 Carbon and Neon are paid only, and free-tier interactions are kept for just 1 day.

Does the Interactions API run my Python functions automatically?

Not yet. Automatic function calling in Python is still a generateContent feature, so you run the function and send a function_result back yourself.

Can I use the Batch API with interactions?

Not yet. Google lists the Batch API as supported by generateContent only, so keep batch jobs on the legacy path for now.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a hijab in a home lab with a PC tower holding a tablet with a GEMINI API card, hook new Gemini API Interactions