Traditional LLM integrations turn developers into state managers. You keep a growing history array, you persist it across services, and you write the glue that runs tools and feeds their results back. The Gemini Interactions API moves that state to the server. Each request creates an interaction with its own ID, and the next request continues from it with previous_interaction_id.
In this codelab you build an on-call agent for Orbital 7, an ageing space station that has just lost main power. The agent has to work out what is wrong from telemetry it cannot fully trust, recover from hardware that fails when it is used, spend limited coolant and power wisely, and decide when to hand over to a human. Nothing in the tools tells it the order of operations: it has to reason.
What you'll learn
- Run a multi-step tool loop with
client.interactions, typedfunction_callsteps andfunction_resultinputs matched by call ID. - Design tools that make a model reason: typed arguments, enums, limited resources and errors it can recover from.
- Read the agent's thought summaries, and measure what each turn sends compared with what the model reads.
- Get a machine-readable incident report with structured output, and check the agent's claims against ground truth.
- Resume a session from a different process using only its interaction ID.
- Branch a session from an earlier turn to test how the agent handles a different failure.
- Apply production practices and know the trade-offs of server-side state.
What you'll need
- A modern web browser.
- A Google Account and Google Cloud project, used only to open Cloud Shell (no billing required on your project).
- A Gemini API key:
- At a live workshop: Provided by your facilitator, you do not need to open Google AI Studio or set up billing.
- Self-paced: Create a key in Google AI Studio (
gemini-3.8-flashis available on the Free Tier for individual use, or via a Paid Tier project with a minimum $5 Prepay credit balance).
- Intermediate Python: functions, dictionaries, classes and reading JSON.
Billing does not need to be enabled on your Google Cloud project. Cloud Shell is only the coding environment, and all Interactions API requests authenticate directly with the Gemini API key. At the live workshop, use the key provided by your facilitator.
Workshop plan (90 minutes)
| Block | Time | Steps |
|---|---|---|
| The Interactions API model | 10 min | Overview, Understand the Interactions API |
| Setup | 10 min | Set up your environment, project structure |
| Build the agent | 25 min | Station simulator, tools, agent loop, first run |
| Trust, but verify | 10 min | Structured incident report, scenarios 2 and 3 |
| State in action | 25 min | Measure, resume from a new process, branch the timeline |
| Production and wrap-up | 10 min | Production practices, trade-offs, clean up |
With generateContent, every request is independent. To hold a conversation, your code keeps the history and sends all of it, every turn, in the exact order the model expects. With the Interactions API, each call to client.interactions.create() produces an interaction resource that is stored on the server (store defaults to True). The response holds the new steps the model produced: thoughts, function calls and its output. To continue, you send only the new input and the ID of the interaction to continue from.
Stateless vs stateful
| Feature | generateContent | Interactions API |
|---|---|---|
| Where history lives | In your code | On the server, linked by interaction ID |
| What you send each turn | The whole history, every time | Only the new input or tool results |
| What the model reads | The whole history | The whole history too, loaded on the server, with implicit caching |
| Tool calls and results | functionCall and functionResponse parts | function_call steps and function_result inputs matched by call_id |
| Response shape | Candidates with parts | Typed steps: thought, function_call, model_output |
| Status | Finish reason | completed, requires_action, in_progress, failed, cancelled, incomplete |
What carries over, and what does not
previous_interaction_id carries over the conversation history only. The model, tools, system_instruction and generation_config apply to a single interaction, so you send them on every request. Forgetting this is the most common bug: the agent quietly loses its instructions after the first turn.
The Interactions API needs the Google Gen AI SDK (google-genai) version
2.0.0 or later. Older 1.x versions use a retired response format. This codelab
uses gemini-3.8-flash, which Google recommends for new projects.
The trade-offs
- Retention: Stored interactions are kept for 1 day on the free tier and up to 55 days on paid tiers. Long-lived sessions need a plan.
- Opting out:
store=Falsekeeps nothing on the server, but it also turns offprevious_interaction_idand background execution. - Context still costs: The model still reads the full history on every turn. You stop managing it, and implicit caching lowers the cost, but long sessions still grow.
- Your environment is still yours: The server remembers the conversation, not the state of the systems your tools change. You will see why this matters when you branch a session.
When continuing a session with previous_interaction_id, what is automatically carried over by the server?
You will work entirely in Google Cloud Shell, a free browser-based Linux terminal with Python, the google-genai SDK and an editor already installed. Nothing needs to be installed on your machine.
Launch Cloud Shell
- Open the Google Cloud Console.
- Select your project in the top-left dropdown.
- Click the Activate Cloud Shell icon (
>_) in the top-right toolbar. If you are asked to authorise the terminal, click Authorize.
Upgrade the Google Gen AI SDK
The google-genai SDK is pre-installed in Cloud Shell. Upgrade it directly via pip so you are on the latest release:
Then check the SDK version:
You should see 2.0.0 or later.
Configure your Gemini API key
Your facilitator provides the Gemini API key. Copy that key and run the
export command below in Cloud Shell — you do not need to open Google AI
Studio.
If you are completing this codelab on your own (self-paced):
- Open Google AI Studio in a new browser tab and sign in.
- Click Create API key and copy the key (
gemini-3.8-flashworks on the Free Tier for single-user pace, or on a Paid Tier project with a minimum $5 Prepay credit balance).
In Cloud Shell, export your API key so the google-genai SDK reads GEMINI_API_KEY automatically:
Environment variables are cleared when Cloud Shell restarts or when you open a
new tab. If you see an authentication error later, run the export command
again.
Project Structure
Create a folder for the project and the files you will fill in:
simulator.py: The station. It holds the true state, the hidden faults and averdict()method that reports ground truth. In production, this is your infrastructure.tools.py: The tool declarations the model sees, and a dispatcher that runs them and turns failures into results the model can read.agent.py: The model configuration, the orchestration loop and the structured incident report.main.py: Runs an incident from start to finish and saves the session tosession.json.resume.py: A separate process that continues a stored session using only its ID.branch.py: Rewinds a session to an earlier turn and replays it with a different outcome.
To edit the files, click Open Editor in the Cloud Shell toolbar and open the orbital7-agent folder.
Orbital 7's reactor overheated and its breakers cut main power. The scrubbers stopped, so oxygen is falling, and the telemetry array went dark. The simulator models this incident with problems the agent has to discover for itself:
- Stale telemetry: With no power, the dashboard replays its last sync. It shows a safe core temperature and healthy oxygen, and both are wrong.
- A jammed valve: One of the two coolant valves does not respond. The agent only finds out by trying it.
- Limited coolant: There is enough for two vents, which is exactly what the core needs. A wasted vent cannot be undone.
- An overloaded configuration: The power settings saved before the blackout ask for 100 MW, more than the reactor can supply. Restarting the bus as it is will trip it again.
- A clock: Every action takes time, and oxygen drops by 1% per action until the scrubbers restart. Below 65% the station is lost.
- Trade-offs: Life support, telemetry and the hydroponics algae farm all need power, and the algae freeze if they stay unpowered for too long. Something has to be shed.
You can run the simulator with one of three scenarios: 1 (Thermal Trip), 2 (Ghost Sensor, which adds a faulty oxygen sensor) and 3 (random faults, reproducible with --seed).
How simulator.py works
Before copying the simulator code, note how the Station class models the environment and its traps:
- Scenario configuration (
SCENARIOSand__init__): Each scenario configures which coolant valve is jammed ("A"or"B"), whether the oxygen sensor is stuck at97.0%, and the reactor's maximum output (60–70MW). The station starts at1040°C(SAFE_CORE_TEMPis800°C), with100%coolant reserve,84.0%true oxygen, and a pre-blackout sector allocation totaling100MW. - The ticking clock (
_advance_timeand_gate): Every public tool method callsself._gate()first. Unless the session has already ended,_gate()calls_advance_time(), incrementingself.tick, droppingself.oxygenby1.0%per action while life support is offline, and incrementingself.hydroponics_unpowered_ticks(freezing the algae permanently if unpowered for more than 15 actions). - Dashboard vs local diagnostics (
get_station_statusvsrun_diagnostic): While the power bus is offline orcommshas less than10MW,get_station_status()returns a"DEGRADED"snapshot with stale values (790°Cand95.0%oxygen). By contrast,run_diagnostic(subsystem)reads local battery-backed sensors for a single subsystem (reactor,power,life_support, orcomms)—includingo2_sensor_self_test("FAIL"when the O2 sensor is faulty) andco2_ppm(which rises as true oxygen falls). - Physical constraints (
vent_coolant,set_sector_power,restart_power_bus,restart_life_support): Each successful coolant vent uses40%coolant and drops the core temperature by180°C, so two vents bring the reactor from1040°Cdown to680°C(below the800°Cbreaker lock). Violating any physical constraint raises aValueErrororRuntimeErrorwith a descriptive message. - Ground truth (
verdict): Theverdict()method is never exposed to the agent as a tool. It inspects the station's true internal state at the end of a run so you can verify whether the agent's report matches reality.
Add the simulator code
Because simulator.py is pure Python environment logic with no Gemini API calls, copy the complete file at once. Open simulator.py, paste the following code, and save the file:
If a tool description says "run this before that", the model follows instructions instead of reasoning. In tools.py, you will build the bridge between the model and the simulator in two parts: first the tool declarations (what the model sees), and then the tool executor (what runs in Python).
Part 1: Declare the tool schemas (TOOL_DECLARATIONS)
When you pass tools=TOOL_DECLARATIONS to client.interactions.create(), the model inspects each tool's name, description, and JSON Schema parameters. Notice how these seven declarations are structured:
- Describe capability and constraints, never order: Each
descriptionstates what the tool does and its trade-offs—for example,get_station_statusnotes that "the array needs power to give live data", whilerun_diagnosticreads "one subsystem directly from its local sensors, on battery power". - Constrain inputs with
enumand numeric bounds: Strict"enum"lists (["reactor", "power", "life_support", "comms"],["A", "B"]) and bounds ("minimum": 0, "maximum": 60) stop the model from inventing invalid subsystem or sector names. - Give the agent a safe exit (
escalate_to_human): Providing an explicit escalation tool lets the model hand over control when both coolant valves fail rather than guessing or looping forever.
The Interactions API uses explicit JSON Schema dictionaries ("type": "function") rather than automatic Python function introspection, giving you exact control over the contract exposed to the model.
Open tools.py and paste Part 1:
Part 2: Gate tool calls and turn exceptions into observations (execute_tool)
Next, add the execution wrapper that runs a model-requested tool call against your Station instance:
- Allowlist (
TOOL_NAMES): Builds a set of valid tool names fromTOOL_DECLARATIONS. Checkingif name not in TOOL_NAMESbeforegetattr(station, name)ensures the model can never invoke internal helper methods like_advance_timeorverdict. - Errors as data, not crashes (
execute_tool): When an action fails in the simulator—for example, when Valve A is jammed or the power bus trips on overload—Stationraises aRuntimeErrororValueError. Instead of letting that exception crash your Python process,execute_tool()catches it and returns(f"ERROR: {error}", True). Your agent loop will send that text back to the model with"is_error": Trueso the model can read why the action failed and adapt its plan.
Append Part 2 to the bottom of tools.py and save the file:
agent.py holds everything that talks to the model. You will assemble it in three top-level blocks:
- Client & request configuration (
SYSTEM_INSTRUCTIONandREQUEST_CONFIG) - Thought summaries & the stateful orchestration loop (
print_thoughtsandrun_agent) - Structured incident reporting (
IncidentReportandgenerate_report)
Part 1: Configure the client, operating principles, and REQUEST_CONFIG
Before adding the first block of agent.py, look at two critical design choices:
- Principles, not steps (
SYSTEM_INSTRUCTION): The system instruction tells the agent how to behave—verify telemetry with diagnostics, conserve coolant and power, protect life support first, never repeat a failed action unchanged, and escalate when no safe path remains—without hardcoding which sequence of tools to call. - Why
REQUEST_CONFIGis sent on every turn: In the Interactions API,previous_interaction_idcarries over the conversation history, butmodel,system_instruction,tools, andgeneration_configare interaction-scoped. Grouping them inREQUEST_CONFIGlets you unpack**REQUEST_CONFIGon everyclient.interactions.create()call so the model keeps the same tools, instructions, and"thinking_summaries": "auto"setting across every turn.
Open agent.py and paste Part 1:
Part 2: Read thought summaries and run the stateful loop (print_thoughts & run_agent)
Next, add the functions that inspect the model's reasoning and drive the multi-turn tool loop:
- Thought summaries (
print_thoughts): BecauseREQUEST_CONFIGsets"thinking_summaries": "auto",interaction.stepsincludes"thought"steps.print_thoughts()iterates overstep.summaryblocks and prints the model's internal reasoning (💭) before executing its tool calls. - Checking
interaction.status: On each turn,run_agent()checks whether the interaction reached"completed"(the agent finished and produced a final answer ininteraction.output_text) or"requires_action"(the model paused and is waiting for tool results). Any other status exits the loop cleanly. - One
function_resultperfunction_call: Acreateresponse contains only this turn's newly generated steps, so everyfunction_callininteraction.stepsis new. For each call, the loop runsexecute_tool(), logs the call insession["turns"], and builds a"function_result"dictionary linked bycall_idandname. - Chaining the next turn (
previous_interaction_id=interaction.id): Instead of appending to a localmessageslist, the loop sends onlyinput=resultsandprevious_interaction_id=interaction.id. It also recordspayload_bytesalongsideusage.total_input_tokensandusage.total_cached_tokensso you can compare what your code sent over the network with what the model read on the server.
Append Part 2 to agent.py:
Part 3: Define the structured incident report (IncidentReport & generate_report)
Once the agent finishes stabilising the station, you want a machine-readable post-incident report—not free-form prose—that you can compare against the simulator's ground truth:
- Pydantic schema (
IncidentReport): Defines the exact structure required:title,root_cause, a step-by-steptimeline(action,observation,reasoning),final_state,sectors_shed,open_risks, andescalated_to_human. - Chaining a structured output turn (
generate_report): Callsclient.interactions.create()withprevious_interaction_idpointing to the completed session andresponse_format={"type": "text", "mime_type": "application/json", "schema": IncidentReport.model_json_schema()}. Because the server already holds the entire incident history underprevious_interaction_id, you only send a one-line prompt to get back schema-valid JSON, whichIncidentReport.model_validate_json()parses into a typed Python object.
Append Part 3 to the bottom of agent.py and save the file:
main.py wires the simulator and the agent together in two parts: first starting the incident session and running the tool loop, and then auditing the agent's report against the simulator's ground truth.
Part 1: Start Turn 1 and run the orchestration loop
The first half of main.py sets up the run and kicks off the interaction chain:
- Initialise the environment and audit log: Parses
--scenario(1,2, or3) and--seed, creates theStationinstance, and initialises thesessiondictionary that will be saved tosession.jsonfor later steps. - Start Turn 1: Calls
client.interactions.create(input=first_input, **REQUEST_CONFIG)with the initial blackout alert. Because this is the first turn of the session, there is noprevious_interaction_idyet—the server creates a brand-new interaction ID and returns the model's initial thought summary and tool calls. - Hand off to
run_agent(): Passes the firstinteractionintorun_agent(), which loops until the agent stabilises the station or escalates, and savesfinal_interaction_idtosession.json.
Open main.py and paste Part 1:
Part 2: Chain the incident report, verify ground truth, and inspect token usage
The second half of main.py audits what happened once the loop finishes:
- Chain the structured report (
generate_report(interaction.id)): If the session reached"completed", it passesinteraction.idtogenerate_report()to request the typedIncidentReportfrom the same server-side conversation history. - Compare with
station.verdict(): Prints the simulator's ground-truth verdict (which the agent never sees) right below the agent's report so you can check whether the agent's claims match reality. - Print
PAYLOAD VS CONTEXT: Summarises the bytes your code sent on each turn alongside the total and cached input tokens read by the model on the server.
Append Part 2 to the bottom of main.py and save the file:
Run scenario 1
Watch the 💭 lines as well as the actions. As you watch, look for the answers to these questions:
- Did the agent trust the stale dashboard, or did it check with a diagnostic first?
- What did it do when a valve failed? Did it retry the same valve or switch?
- Did it notice the saved power configuration before restarting the bus, or did it learn from the trip?
- Which sector did it shed, and did it explain why?
- Did it confirm the result with diagnostics before declaring success?
The model decides its own path, so every run can take a slightly different sequence of diagnostics and actions to reach stability.
At the end of the run, generate_report() asks the same session for an incident report. It sets response_format to a JSON Schema generated from the IncidentReport Pydantic model, so interaction.output_text is valid JSON that IncidentReport.model_validate_json() turns into a typed object. Downstream systems, such as a ticketing tool, can consume it directly.
Valid JSON is not the same as true JSON. main.py prints the agent's report and then the simulator's verdict, which the agent never sees. Compare final_state in the report with the checks and true_oxygen_percent in the verdict.
Run the Ghost Sensor scenario
In this scenario the oxygen sensor is faulty and always reads 97%. The life_support diagnostic shows the self-test failing and CO2 rising. Did the agent notice the contradiction? Does the oxygen figure in its report match true_oxygen_percent?
Try random faults
Treat an agent's report as a claim. Check the facts that matter against your own systems before you act on it.
Why does main.py compare the Pydantic IncidentReport against station.verdict()?
At the end of each run, main.py prints a table of what your code sent on each turn and what the model read. Look closely at the 📊 PAYLOAD VS CONTEXT output in your terminal—you should see two distinct trends:
- Sent stays small: Each turn sends only the latest tool results, a few hundred bytes, however long the session gets.
- Read keeps growing: The model's input tokens grow every turn, because it still reads the whole history. A large share of it should show as cached, which lowers the cost.
Compare the cached token count on Turn 1 with the final turn of your run. Notice how the server-side history grows with each step while implicit caching reuses the prefix from earlier turns.
This is the honest version of the stateful benefit. The Interactions API removes history management from your code and keeps requests small, which matters when many services or slow networks are involved. It does not make the model's context free. For very long sessions, you still need a strategy, such as summarising and starting a new session from the summary.
Your loop keeps no history. Everything the agent knows lives on the server, linked to an interaction ID, so any process that has the ID can continue: another terminal, another container or another service. Prove it with a script that has no simulator, no tools and no local state.
How resume.py works
Before pasting resume.py, notice what makes cross-process resumption possible:
- Zero local dependencies:
resume.pydoes not importsimulator,tools, oragent. It creates a freshgenai.Client()in an isolated Python process. - Looking up the interaction ID: It reads either an interaction ID passed on the command line (
sys.argv[1]) or the latest ID stored insession.json(report_interaction_idorfinal_interaction_id). - Continuing the server-side chain: Passing
previous_interaction_id=interaction_idtoclient.interactions.create()loads the entire multi-turn incident history on the server—every diagnostic reading, valve failure, thought summary, and power adjustment—so the model can answer follow-up questions about its decisions and returns a new interaction ID (follow_up.id).
Add the code
Open resume.py, paste the following code and save the file:
Run it in a separate process
Open a new Cloud Shell tab with the + icon. It is a new shell session, so export your key again, then run the script. By default it continues from the last interaction saved in session.json; you can also pass any interaction ID as an argument.
Try questions such as "Which reading did you distrust, and why?" or "What would you do differently with one more valve failure?". The agent answers from the stored session.
In production, this is how a web request, a worker or a Cloud Run instance continues the same agent session: store the interaction ID next to your own record, such as an incident ticket, and pass it back with the next request.
Because every interaction is stored, you can continue from any earlier one, not just the latest. branch.py goes back to the turn where a coolant vent succeeded and changes history: this time that valve jams too. With both valves gone, the core cannot be cooled, and the right answer is to escalate.
There is a catch, and it is the most important architecture lesson in this codelab: the server restores the conversation, but not the station. You will build branch.py in two parts to see why.
Part 1: Locate the branch point and replay environment state
When you point previous_interaction_id to an earlier turn (target_turn["interaction_id"]), the server rewinds the model's conversation memory to that exact moment. However, your local Station object is separate from the API. To put the simulator in the exact state it had right before target_turn ran:
- Locate the branch point (
target_index): Scans the savedturnsinsession.jsonto find the first turn wherevent_coolantsucceeded (not c["is_error"]). - Replay earlier tool calls (
original["turns"][:target_index]): Instantiates a freshStationwith the original scenario and seed, then replays every tool call from earlier turns sostationreaches the exact tick, oxygen level, and configuration it had at that moment.
Open branch.py and paste Part 1:
Part 2: Inject the new fault and fork the interaction
Now that station is synchronised with target_turn, you can alter what happens on that turn and fork a new timeline on the server:
- Inject the new failure (
station.jammed_valves.add): Before executing the tool calls intarget_turn, jam the valve that previously worked. Whenexecute_tool()runsvent_coolant, it now returns an actuator fault (is_error = True) linked to the originalcall_id. - Fork the conversation (
previous_interaction_id=target_turn["interaction_id"]): Callclient.interactions.create()pointing back totarget_turn["interaction_id"]with the new error result, and hand the forked interaction torun_agent(). The original session insession.jsonremains untouched, while the alternate timeline is saved tobranch.json.
Append Part 2 to the bottom of branch.py and save the file:
Run the branch
Watch whether the agent tries to recover, recognises that it cannot, and escalates. The verdict shows escalated set to true. You can branch the same turn as many times as you like: each branch is a new interaction, and the original session is unchanged.
When branching from an earlier interaction ID, why does branch.py replay prior tool calls against a fresh Station instance first?
This workshop runs everything in Cloud Shell so you can focus on the API. When you move a stateful agent into a real Google Cloud architecture, apply these practices:
- Store interaction IDs, not history: Save the latest interaction ID with your own record, for example in Firestore against an incident ID. Any instance of your service can then continue the session, so the service itself stays stateless and scales out on Cloud Run.
- Record what your tools did: Keep your own log of tool calls and results, as
session.jsondoes here. You need it to rebuild, audit or branch, because the server does not know the state of your systems. - Send configuration on every call: Keep the model, tools, system instruction and generation settings in one place, as
REQUEST_CONFIGdoes, and send them with every request. - Design tools for reasoning and safety: Typed arguments, enums, clear errors and an escalation path. Put destructive actions behind a human approval step.
- Bound the loop: Keep a turn limit, and treat any status other than
completedorrequires_actionas a stop condition. - Verify before you act: Validate structured output, and check the agent's claims against your own systems.
- Plan for retention and privacy: Know your retention window, use
store=Falsewhere data must not be stored, and delete interactions you no longer need. - Protect the key: Keep the API key in Secret Manager and inject it at runtime.
- Observe with steps: Export
interaction.steps, including thought summaries, to your logging system as an audit trail.
Clean Up
-
Clear the environment variable:
Cloud Shell / Terminal❯unset GEMINI_API_KEY -
Revoke the API key: If you created your own key for this codelab, open the API keys page in Google AI Studio and delete it. If your facilitator gave you a key, there is nothing to do: it is revoked after the workshop.
-
Stored interactions: Interactions from this workshop expire on their own: after 1 day on the free tier, and up to 55 days on paid tiers. To remove them sooner, call
client.interactions.delete(id=...)for the IDs insession.jsonandbranch.json. -
Close Cloud Shell: Type
exitor close the Cloud Shell pane. Yourorbital7-agentfolder stays in your Cloud Shell home directory if you want to come back to it.
Summary
You built an agent that diagnoses and recovers from a cascading failure with incomplete information, and you used the Interactions API to run, inspect, resume and branch its sessions.
What you covered:
- A tool loop built on typed
function_callsteps andfunction_resultinputs matched by call ID. - Tools that make a model reason, and errors it can recover from.
- Interaction-scoped configuration, and what
previous_interaction_iddoes and does not carry over. - Thought summaries, and the difference between what you send and what the model reads.
- Structured incident reports, checked against ground truth.
- Resuming a session from a new process, and branching it from an earlier turn while rebuilding your own environment state.
Next steps:
- Add a human approval step before destructive tools, and return a rejected action as a
function_result. - Stream the agent's thoughts and actions live with
stream=True. - Run long incidents with
background=Trueand poll them withclient.interactions.get(). - Hand the finished session to the Deep Research agent for a postmortem, chained with
previous_interaction_id. - Replace the simulator with real Cloud Monitoring and Compute Engine calls.
Orbital 7 Complete Reference Repository
Browse or clone the complete end-to-end Orbital 7 source code (simulator.py, tools.py, agent.py, main.py, resume.py, and branch.py) on GitHub.
Learn more: