Short answer. Your first call to the Gemini API needs three things: a key, which you put in the environment variable GEMINI_API_KEY; the SDK (pip install -U google-genai for Python, npm install @google/genai for JavaScript, both at version 3.3.0 on the registries on 12 November 2026); and a call to client.interactions.create with a model and a text. Today's official guide uses the Interactions API, which the documentation names as the recommended interface for all new projects; the old generateContent remains supported, but is described as "legacy". The difference that matters to you is not in the syntax: Interactions keep the conversation on Google's servers by default, for one day on the free tier and for 55 days in paid projects, unless you turn it off with store=false.
This is the second article in the series, and it picks up the choice of model from the first: here I write gemini-4-hydrogen, the one that today's quickstart uses in its examples. I am not affiliated with Google. Sources opened on 13 November 2026. No listing calls the API, because I used no keys and no accounts: the ones that show the shape of a call are declared "schema to adapt", checked only for syntax, and the ones that run check requests, expiry dates and rules against a local fake that I declare as such.
Step 1: the key, and where not to put it
According to the quickstart, Google AI Studio automatically creates a project and a key for new users, which you copy from the keys page; to get another one you choose "Create API key". Additional projects, or ones imported from Google Cloud, may require a project verification before they can use the free tier. The documentation sets the key like this: export GEMINI_API_KEY="YOUR_KEY", and to raise the limits you link billing from the same page. The client reads the variable on its own: the key never appears in the code.
Two non-negotiable rules. The key does not go in the code that runs in the browser of whoever visits your site: anyone who opens the developer tools copies it and spends on your project. The call is made from your server, which in turn authenticates the user and limits the requests. Second rule: the key does not go in a repository, not even a private one, and not in an example file. An environment variable or a secrets manager is enough to start with. The script below is a startup check: if the variable is missing the service does not start, and the value is never printed, not even partly, because logs end up in places you do not control.
"""Startup check: is the key there? I never print it, not even partly."""
def read_key(environment: dict) -> str:
key = environment.get("GEMINI_API_KEY", "").strip()
if not key:
raise SystemExit("GEMINI_API_KEY not set: the service does not start")
return key
for name, environment in (("without the variable", {}), ("with the variable", {"GEMINI_API_KEY": "test-key-value"})):
try:
key = read_key(environment)
print(f"{name}: ok, {len(key)} characters (the value is not printed)")
except SystemExit as error:
print(f"{name}: {error}")
# Output:
# without the variable: GEMINI_API_KEY not set: the service does not start
# with the variable: ok, 14 characters (the value is not printed)
The script runs twice, with an empty environment and with a test value, because the function read_key receives the dictionary instead of reading os.environ: that way the output is the same on every machine. In a real service you would call it with os.environ. The strip() line avoids the most trivial and most frustrating case, a variable with a space or a newline at the end, a trivial and frequent error when the key is copied by hand. One detail that changes how you organise keys: the limits page says that limits apply per project, not per key. Three keys in the same project share the same quota. If you want to isolate two applications, you need one project for each.
Step 2: the first call, with a conversation
The Python listing creates a client with no arguments, which takes the key from the environment, and makes two calls. The first, client.interactions.create with model and input, returns an Interaction object: a complete turn, which contains a sequence of "steps" (steps) with the model's thoughts, any tool calls and the final output, plus an id. The output_text property is the shortcut for the final text. The second call passes previous_interaction_id with the id of the first, and the server retrieves the history: you do not resend it. The constant MODELLO is the one from article 1: a single point to change. The prompts in the listing are in Italian ("Explain how a B-tree index works in three sentences." and "When is a B-tree index worse than a full scan?"); the listing is a schema to adapt, so I left it identical to the Italian original and translated only the comments.
from google import genai
MODELLO = "gemini-4-hydrogen" # a single constant, with the date of the choice beside it
client = genai.Client() # reads GEMINI_API_KEY from the environment
turno1 = client.interactions.create(
model=MODELLO,
input="Spiega come funziona un indice B-tree in tre frasi.",
)
print(turno1.output_text)
turno2 = client.interactions.create(
model=MODELLO,
input="Quando un indice B-tree è peggio di una scansione completa?",
previous_interaction_id=turno1.id, # the server retrieves the history
)
print(turno2.output_text)
This is a schema to adapt, not executed: it needs a key. I compared it with the quickstart and with the Interactions page, and I checked it on two things without the network. The file compiles (python3 -m py_compile), and in SDK 3.3.0, installed in an isolated environment, client.interactions.create exists and the type that describes the request has 19 fields, as the last listing in this article shows. The same schema in JavaScript uses ai.interactions.create with an object, and is identical in shape.
import { GoogleGenAI } from "@google/genai";
const MODELLO = "gemini-4-hydrogen";
const ai = new GoogleGenAI({}); // reads GEMINI_API_KEY from the environment
const turno1 = await ai.interactions.create({
model: MODELLO,
input: "Spiega come funziona un indice B-tree in tre frasi.",
});
console.log(turno1.output_text);
const turno2 = await ai.interactions.create({
model: MODELLO,
input: "Quando un indice B-tree è peggio di una scansione completa?",
previous_interaction_id: turno1.id,
});
console.log(turno2.output_text);
The JavaScript file passes Node's syntax check (node --check) and in @google/genai 3.3.0 the functions interactions.create, interactions.get and interactions.delete exist; I did not make a real call. Note that the field is called previous_interaction_id in snake case in JavaScript too, as in the documentation's example: copy the field names exactly as they are written, without adapting them to the habits of the language.
What is remembered and what is not
The Interactions page says that previous_interaction_id keeps only the history (inputs and outputs). Three other parameters are tied to the single interaction and must be redeclared at every turn: tools, system_instruction and generation_config (with thinking_level, temperature and the like). The consequence is concrete: if at turn two you do not put back the function the model could call, the model no longer sees it, and no error warns you. The next script builds the requests with a function create, sends them to a local fake and applies three documented rules: store=false does not combine with background=true, an unsaved turn cannot be used as a starting point, and tools are not inherited.
"""Builds and checks Interactions API requests locally, without sending them.
The "server" below is a FAKE written by me for testing: it is not Google and does not answer like Google.
The rules it applies are those of the Interactions API page (2026-11-13)."""
import json
from datetime import date, timedelta
MODEL = "gemini-4-hydrogen"
REST_HEADERS = {"x-goog-api-key": "$GEMINI_API_KEY", "Content-Type": "application/json", "Api-Revision": "2026-05-20"}
RETENTION = {"free": 1, "paid": 55} # days, defaults
PAID_WINDOWS = (7, 14, 28, 55) # days configurable in paid projects
def create(input, *, previous_interaction_id=None, store=True, background=False,
tools=None, system_instruction=None, generation_config=None):
if background and not store:
raise ValueError("store=false is incompatible with background=true")
body = {"model": MODEL, "input": input}
if previous_interaction_id:
body["previous_interaction_id"] = previous_interaction_id
if not store:
body["store"] = False # the default is true: no need to write it
if background:
body["background"] = True
if tools:
body["tools"] = tools
if system_instruction:
body["system_instruction"] = system_instruction
if generation_config:
body["generation_config"] = generation_config
return body
class FakeServer:
def __init__(self):
self.saved = {}
self.counter = 0
def send(self, body):
previous = body.get("previous_interaction_id")
if previous and previous not in self.saved:
raise LookupError(f"{previous}: interaction not saved (store=false) or expired")
self.counter += 1
ident = f"fake_{self.counter}"
if body.get("store", True):
self.saved[ident] = body
return {"id": ident, "status": "completed"}
def forgotten_settings(previous_body, body):
"""tools, system_instruction and generation_config apply only to the interaction that sets them."""
if "previous_interaction_id" not in body:
return []
return [k for k in ("tools", "system_instruction", "generation_config")
if k in previous_body and k not in body]
def expires_on(created: date, plan: str, paid_days: int = 55) -> date:
if plan == "paid" and paid_days not in PAID_WINDOWS:
raise ValueError(f"window not allowed: {paid_days}")
return created + timedelta(days=paid_days if plan == "paid" else RETENTION["free"])
s = FakeServer()
lamp = [{"type": "function", "name": "set_light", "description": "Sets the brightness.",
"parameters": {"type": "object", "properties": {"level": {"type": "integer"}}, "required": ["level"]}}]
t1 = create("Dim the lights.", tools=lamp)
r1 = s.send(t1)
t2 = create("A little less.", previous_interaction_id=r1["id"])
print("1) turn 2 with state on the server:", json.dumps(t2, ensure_ascii=False))
print(" tools not redeclared:", forgotten_settings(t1, t2))
s.send(t2)
stateless = s.send(create("Summarise.", store=False))
try:
s.send(create("And in two lines?", previous_interaction_id=stateless["id"]))
except LookupError as e:
print("2) chain on an unsaved turn:", e)
try:
create("Long task.", store=False, background=True)
except ValueError as e:
print("3) combination rejected:", e)
print("4) expiry for a turn created on 2026-11-13:")
print(" free ->", expires_on(date(2026, 11, 13), "free"))
print(" paid (default) ->", expires_on(date(2026, 11, 13), "paid"))
print(" paid (7 days) ->", expires_on(date(2026, 11, 13), "paid", 7))
try:
expires_on(date(2026, 11, 13), "paid", 30)
except ValueError as e:
print(" paid (30) ->", e)
print("5) REST request for t2 (key as a variable, not the value):")
print(json.dumps({"headers": REST_HEADERS, "body": t2}, ensure_ascii=False, indent=2))
# Output:
# 1) turn 2 with state on the server: {"model": "gemini-4-hydrogen", "input": "A little less.", "previous_interaction_id": "fake_1"}
# tools not redeclared: ['tools']
# 2) chain on an unsaved turn: fake_3: interaction not saved (store=false) or expired
# 3) combination rejected: store=false is incompatible with background=true
# 4) expiry for a turn created on 2026-11-13:
# free -> 2026-11-14
# paid (default) -> 2027-01-07
# paid (7 days) -> 2026-11-20
# paid (30) -> window not allowed: 30
# 5) REST request for t2 (key as a variable, not the value):
# {
# "headers": {
# "x-goog-api-key": "$GEMINI_API_KEY",
# "Content-Type": "application/json",
# "Api-Revision": "2026-05-20"
# },
# "body": {
# "model": "gemini-4-hydrogen",
# "input": "A little less.",
# "previous_interaction_id": "fake_1"
# }
# }
Read the output line by line. Line 1 shows the body of turn two: it contains the id, but not the tools, and forgotten_settings flags it. Line 2 is the effect of store=false on the following turn: the fake rejects the chain, and that is behaviour I wrote following the documentation, not the real server's error, which I do not know. Line 3 is the forbidden combination. Line 4 calculates the expiry dates with the periods in the documentation (one day and 55 days, or 7, 14, 28 and 55 in paid projects); the value 30 is rejected because it is not among those allowed. Line 5 shows what the REST request looks like, with the Api-Revision header that the quickstart's example reports; the key appears as a variable, not as a value.
The next check answers a different question: are the field names you write the right ones? The type with which the SDK builds an interaction request has 19 fields, and the script compares the keys of a request against them, including a deliberate typo, stor. It serves a real case: the SDK type does not reject unknown keys (I tried it with model_validate; what create does with an unknown key I have not verified), and a typo on store would mean keeping on the server data you thought you were not keeping. The script requires the SDK to be installed, but opens no connections.
"""Compares the top-level keys of a request with the fields of the type that the
google-genai SDK (3.3.0) uses to create an interaction. It opens no connection."""
from google.genai import interactions
FIELDS = set(interactions.CreateModelInteraction.model_fields)
request = {
"model": "gemini-4-hydrogen",
"input": "A little less.",
"previous_interaction_id": "test-id",
"store": False,
"tools": [],
"system_instruction": "Answer in English.",
"generation_config": {"thinking_level": "high"},
"stor": False, # deliberate typo
}
for key in request:
print(f"{key:24} {'recognised' if key in FIELDS else 'NOT among the type fields'}")
print("type fields:", len(FIELDS))
# Output:
# model recognised
# input recognised
# previous_interaction_id recognised
# store recognised
# tools recognised
# system_instruction recognised
# generation_config recognised
# stor NOT among the type fields
# type fields: 19
The result is proof that the check is needed: seven keys out of eight are recognised, and the eighth is not. The test does not guarantee that the value of each field is allowed, because it checks only the top-level names. For values, the documentation applies: for example, thinking_level is low, medium, high, and for Hydrogen also xhigh. The 3.3.0 type does not reject an invented level such as ultra, I tried it, so the check of values stays in your code.
The choice: state on the server, or not
Interactions are saved by default (store=true). The documentation indicates 55 days for paid projects and one day for free ones; paid projects can reduce the window to 7, 14, 28 or 55 days from the AI Studio logs page, and every interaction can be deleted with the delete method, which requires the id. When the period ends, the data is deleted automatically. With store=false you work without state: you resend the history with every request, and you lose two things, previous_interaction_id for the following turns and background execution (background=true).
| With state (store=true, default) | Without state (store=false) | |
|---|---|---|
| Code | Shorter: you pass an id | Longer: you maintain and resend the history, including thought and tool steps |
| Data at Google | Kept 1 day (free) or 55 days (paid, reducible) | The interaction is not saved |
| Background execution | Yes | No, incompatible |
| Observability | Steps can be re-read with interactions.get and in the AI Studio logs (paid projects) | Only in the response |
| Implicit cache | Supported; with state it kicks in more easily | Supported |
The row that most often decides is the second. Neither of the two modes is better than the other: what changes is your data processing. With state you write less code and get the cache, but every turn stays at Google for up to 55 days, and this must be declared in the privacy notice if the texts contain personal data. Without state you manage the history yourself, and the price is more code and more tokens resent. In the unpaid services the terms also say that Google may use the content to improve its products and that human reviewers may read it: on the free tier do not send third-party data.
There is also a recent change. The changelog of 26 October 2026 reports "Generate Content API storage on by default": new paid projects that use generateContent and its variants now keep requests by default, like Interactions; existing projects keep their current setting. You can refuse per request with store=false or by switching off logging from the "Logs and Datasets" panel. The entry does not say for how long they are kept: I do not know and I do not write it. If your project is new and still uses generateContent, read the original entry before sending customer data.
Two hypothetical decisions
These are scenarios I built myself, without figures, to show how the choice changes with the task. First scenario: a support chat with many turns per customer. Here state is really needed, and it is worth switching it on and choosing on the logs page the shortest window that supports your use (for example 7 days). Keep the id of each interaction together with the customer it belongs to: deletion on request goes through the delete method, which asks for the id, and without that table you would not know which turns to delete.
Second scenario: a service that labels incoming messages ("urgent", "documents", "information"). Each message is an independent request, the memory of the conversation is of no use, and keeping the text of each message for 55 days is extra processing with no benefit. Here store=false removes the problem at the root. The rule I draw from it is simple: state is switched on by choice, when there is a conversation to remember, not by inertia because it is the default.
What you can do now
You can put the key where it belongs and check for it at startup, you can write the first call and chain two turns, and you know that tools and instructions must be redeclared at every turn. You also know why the store setting is a data decision and not a technical detail. In practice, in this order:
- Create the key in AI Studio, put it in
GEMINI_API_KEYand run the startup check. - Decide explicitly whether you need state; if every request is independent, write
store=false. - Write in the README the date you consulted the documentation and the model used.
- Before passing third-party data, read article 5 on tiers, limits and privacy.
The order is not random: the key check comes before everything, because a service that starts without a key fails at the first user and not at the first test; the decision about state comes before the first real call, because afterwards there is already saved data. The next step in the series is tools: in article 3 the model proposes a function and you run it.
What I have not verified
- No real call: the Python and JavaScript listings are schemas checked for syntax and method names, not executed.
- Passing files and images to the API, and streaming: the quickstart covers them, but I did not reread them for this article.
- What is kept, and for how long, with
generateContentin new paid projects. - The exact error the server returns when you chain an unsaved turn: in the script a fake simulates it.
These are limits declared so that the reader does not have to discover them: each concerns a point where the code or the text should be reconfirmed with a real key before going into production. If you have no key, the shortest route is to try the schemas in the AI Studio playground and compare the field names with the ones reported here.
The series
- Gemini for Developers: Models and Pricing
- This article: key, SDK and Interactions API.
- Gemini: functions, JSON and Google Search
- Gemini: 1M-token context, thinking, caching
- Gemini API: tiers, limits and data privacy
- After Gemini CLI: Antigravity and gemini-api
If you are interested in the protocol these models use to connect to external tools, there is the introduction to the Model Context Protocol on this site: the function calling of article 3 is the basic mechanism on which the servers that implement it also rely.
Frequently asked questions
Do I have to migrate from generateContent to Interactions?
Not necessarily. The documentation of 13 November 2026 says generateContent remains fully supported, but names Interactions as the recommended interface for new projects and says new models and tools will arrive there first.
Do my conversations stay saved on Google's server?
With Interactions yes, by default (store=true): one day on the free tier, 55 days in paid projects, reducible to 7, 14 or 28. You switch it off with store=false, which however rules out previous_interaction_id in the following turns and background execution.
Does the API key go in the site's code?
Never in code that runs in the browser. The key authorises the project's spending: keep it in an environment variable on the server, such as GEMINI_API_KEY, and make the call from your backend.
Sources
- Gemini API, Getting started - key in AI Studio, environment variable, SDK installation, first call, conversation with previous_interaction_id, Api-Revision header; consulted on 2026-11-13
- Interactions API - state on the server, parameters tied to the single interaction, retention of 1 and 55 days, store, delete, background; consulted on 2026-11-13
- Gemini API, Release notes - entry of 26 October 2026 on retention for generateContent; consulted on 2026-11-13
- Gemini API, Rate limits - limits per project and not per key; consulted on 2026-11-13
- Gemini API Additional Terms of Service - use of content in the free and paid services; consulted on 2026-11-13
- PyPI registry, google-genai - version 3.3.0 published on 2026-11-12; consulted on 2026-11-13
- npm registry, @google/genai - version 3.3.0 published on 2026-11-12; consulted on 2026-11-13
Commenti
Caricamento commenti...
Sign in to comment