• Tech Dev NotesTech Dev Notes
Apps
  • App lookup
  • App compare
Market movement
  • App charts
  • App rankings
Visual proof
  • App screens
  • App listing screenshots
  • App icons
Build intelligence
  • App tech stacks
  • Tool releases
  • Developers
More
  • X feature flags
  • Grokipedia
  • Blog
  • Follow on X
Skip to content
All content/ filesChangelog

gemini-docs/latest/content · Jun 26, 14:03 UTC

pages/background-execution.txt

TXT·10.5 KB·184 lines

content/

  • pages

    • agent-environment.txt
    • agents.txt
    • ai-studio-quickstart.txt
    • aistudio-agents.txt
    • aistudio-android.txt
    • aistudio-build-mode.txt
    • aistudio-deploying.txt
    • aistudio-fullstack.txt
    • antigravity-agent.txt
    • api-key.txt
    • api-versions.txt
    • audio.txt
    • available-regions.txt
    • background-execution.txt
    • batch-api.txt
    • billing.txt
    • caching.txt
    • changelog.txt
    • code-execution.txt
    • coding-agents.txt
    • computer-use.txt
    • crewai-example.txt
    • custom-agents.txt
    • deep-research.txt
    • deprecations.txt
    • document-processing.txt
    • embeddings.txt
    • feedback-policies.txt
    • file-input-methods.txt
    • file-search.txt
    • files.txt
    • flex-inference.txt
    • function-calling.txt
    • gemini-3.txt
    • gemini-for-research.txt
    • get-started.txt
    • google-search.txt
    • image-generation.txt
    • image-understanding.txt
    • imagen.txt
    • index.txt
    • interactions-breaking-changes-may-2026.txt
    • interactions-overview.txt
    • langgraph-example.txt
    • learnlm.txt
    • libraries.txt
    • live-api.txt
    • llama-index.txt
    • logs-datasets.txt
    • logs-policy.txt
    • long-context.txt
    • managed-agents-quickstart.txt
    • maps-grounding.txt
    • media-resolution.txt
    • migrate-to-cloud.txt
    • migrate-to-interactions.txt
    • migrate.txt
    • model-tuning.txt
    • models.txt
    • music-generation.txt
    • oauth.txt
    • openai.txt
    • optimization.txt
    • partner-integration.txt
    • pricing.txt
    • priority-inference.txt
    • prompting-strategies.txt
    • rate-limits.txt
    • realtime-music-generation.txt
    • robotics-overview.txt
    • safety-guidance.txt
    • safety-settings.txt
    • speech-generation.txt
    • streaming.txt
    • structured-output.txt
    • temporal-example.txt
    • text-generation.txt
    • thinking.txt
    • thought-signatures.txt
    • tokens.txt
    • tool-combination.txt
    • tools.txt
  • pages/generate-content

    • api-key.txt
    • audio.txt
    • caching.txt
    • code-execution.txt
    • computer-use.txt
    • document-processing.txt
    • file-input-methods.txt
    • file-search.txt
    • files.txt
    • flex-inference.txt
    • function-calling.txt
    • gemini-3.txt
    • get-started.txt
    • google-search.txt
    • image-generation.txt
    • image-understanding.txt
    • maps-grounding.txt
    • media-resolution.txt
    • music-generation.txt
    • priority-inference.txt
    • speech-generation.txt
    • structured-output.txt
    • text-generation.txt
    • thinking.txt
    • thought-signatures.txt
    • tokens.txt
    • tool-combination.txt
    • url-context.txt
    • video-understanding.txt
    • webhooks.txt
    • whats-new-gemini-3.5.txt
  • pages/live-api

    • best-practices.txt
    • capabilities.txt
    • ephemeral-tokens.txt
    • get-started-sdk.txt
    • get-started-websocket.txt
    • live-translate.txt
    • session-management.txt
    • tools.txt
  • pages/models

    • antigravity-preview-05-2026.txt
    • deep-research-max-preview-04-2026.txt
    • deep-research-preview-04-2026.txt
    • deep-research-pro-preview-12-2025.txt
    • gemini-2.0-flash-lite.txt
    • gemini-2.0-flash.txt
    • gemini-2.5-computer-use-preview-10-2025.txt
    • gemini-2.5-flash-image.txt
    • gemini-2.5-flash-lite-preview-09-2025.txt
    • gemini-2.5-flash-lite.txt
    • gemini-2.5-flash-native-audio-preview-12-2025.txt
    • gemini-2.5-flash-preview-09-2025.txt
    • gemini-2.5-flash-preview-tts.txt
    • gemini-2.5-flash.txt
    • gemini-2.5-pro-preview-tts.txt
    • gemini-2.5-pro.txt
    • gemini-3-flash-preview.txt
    • gemini-3-pro-image.txt
    • gemini-3-pro-preview.txt
    • gemini-3.1-flash-image.txt
    • gemini-3.1-flash-lite-preview.txt
    • gemini-3.1-flash-lite.txt
    • gemini-3.1-flash-live-preview.txt
    • gemini-3.1-flash-tts-preview.txt
    • gemini-3.1-pro-preview.txt
    • gemini-3.5-flash.txt
    • gemini-3.5-live-translate-preview.txt
    • gemini-embedding-001.txt
    • gemini-embedding-2-preview.txt
    • gemini-embedding-2.txt
    • gemini-robotics-er-1.5-preview.txt
    • gemini-robotics-er-1.6-preview.txt
    • imagen.txt
    • lyria-3-clip-preview.txt
    • lyria-3-pro-preview.txt
    • lyria-realtime-exp.txt
    • veo-2.0-generate-001.txt
    • veo-3.1-generate-preview.txt
    • veo-3.1-lite-generate-preview.txt
route: /gemini-api/docs/background-execution
title: Background execution
description: Run long-running background tasks and agents using background=true in the Interactions API.

For long-running tasks like deep research, complex reasoning, or multi-step agent executions, connection timeouts can interrupt standard HTTP requests (which typically close after 60 seconds). The Interactions API provides background execution to run these tasks asynchronously.
To let the interaction run until it completes the task on the server, set "background": true when creating the interaction. The API immediately returns an interaction ID, which client applications can use to poll for status, stream progress, or reconnect to a disconnected stream.
Background execution is supported for standard Gemini models (such as gemini-3.5-flash and gemini-3.1-pro-preview) and Managed Agents (such as antigravity-preview-05-2026).
Create a background interaction
To start a background interaction, set the background parameter to true when creating the resource.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Write a guide on space exploration.",
background=True,
)
print(f"Created background interaction ID: {interaction.id}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.5-flash",
input: "Write a guide on space exploration.",
background: true,
});
console.log(`Created background interaction ID: ${interaction.id}`);
REST
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-3.5-flash",
"input": "Write a guide on space exploration.",
"background": true
}'
How background execution works
When you create a background interaction, the task runs asynchronously on the server. The interaction transitions through various execution states:
in_progress: The server is actively executing the interaction (such as running code or researching).
requires_action: The interaction has paused and is waiting for client input (such as confirming a tool execution or answering a question).
completed: The interaction finished successfully and the output is available.
failed: An error occurred during execution (such as tool failure or rate limits).
cancelled: A client request stopped the execution.
Note: For the complete list of interaction states, see the
Interactions API Reference.
Use cases
Use background execution for:
Agent executions: Tasks requiring code execution, web browsing, or sub-agent orchestration (such as antigravity-preview-05-2026).
Deep research: Runs using deep-research-preview-04-2026 or deep-research-max-preview-04-2026 which take several minutes.
Long reasoning: Tasks where model thinking steps exceed standard HTTP connection limits.
Retrieve results
Obtain background interaction results using either polling or streaming.
Polling pattern (non-blocking)
Polling checks the interaction status periodically using non-blocking GET requests until it reaches a terminal state.
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.get(id="YOUR_INTERACTION_ID")
while interaction.status == "in_progress":
time.sleep(5)
interaction = client.interactions.get(id=interaction.id)
if interaction.status == "completed":
print(interaction.output_text)
else:
print(f"Finished with status: {interaction.status}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
let interaction = await client.interactions.get("YOUR_INTERACTION_ID");
while (interaction.status === "in_progress") {
await new Promise(resolve => setTimeout(resolve, 5000));
interaction = await client.interactions.get(interaction.id);
}
if (interaction.status === "completed") {
console.log(interaction.output_text);
} else {
console.log(`Finished with status: ${interaction.status}`);
}
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
Streaming pattern
If a network interruption disconnects a stream, streaming can resume from the last received event. Each delta contains a unique event_id in its payload. Passing this ID as last_event_id resumes the stream from that event.
Python
import time
from google import genai
client = genai.Client()
interaction_id = "YOUR_INTERACTION_ID"
def stream_with_reconnect(interaction_id: str):
last_event_id = None
while True:
try:
# Retrieve the stream. If resuming, pass last_event_id
stream = client.interactions.get(
id=interaction_id,
stream=True,
last_event_id=last_event_id
)
for event in stream:
# Log event updates and capture event_id if present
if event.event_id:
last_event_id = event.event_id
if event.event_type == "step.delta" and event.delta.type == "text":
print(event.delta.text, end="", flush=True)
if event.event_type == "interaction.completed":
return
except Exception as e:
print(f"\n[Connection lost: {e}. Reconnecting in 3s...]")
time.sleep(3)
stream_with_reconnect(interaction_id)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interactionId = "YOUR_INTERACTION_ID";
async function streamWithReconnect(id) {
let lastEventId = undefined;
while (true) {
try {
// Retrieve the stream. If resuming, pass last_event_id in options
const stream = await client.interactions.get(id, {
stream: true,
last_event_id: lastEventId
});
for await (const event of stream) {
// Capture event_id if present
const idVal = event.event_id || event.id;
if (idVal) {
lastEventId = idVal;
}
if (event.event_type === "step.delta" && event.delta?.type === "text") {
process.stdout.write(event.delta.text);
}
if (event.event_type === "interaction.completed") {
return;
}
} catch (error) {
console.log(`\n[Connection lost: ${error.message}. Reconnecting in 3s...]`);
await new Promise(resolve => setTimeout(resolve, 3000));
}
await streamWithReconnect(interactionId);
REST
curl -N -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID?stream=true&last_event_id=YOUR_LAST_EVENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
Multi-turn conversations
Subsequent interactions can chain to a background conversation using previous_interaction_id, subject to these constraints:
Active executions are blocked: Chaining a subsequent interaction to one with in_progress status returns a 400 Bad Request error. Wait for the interaction to reach the completed state before starting the next one.
Environment Parameter for Managed Agents: When chaining interactions for Managed Agents (such as antigravity-preview-05-2026), requests must include both previous_interaction_id and environment.
The following examples show how to chain interactions:
Python
import time
from google import genai
client = genai.Client()
agent_model = "antigravity-preview-05-2026"
# First interaction: Provision sandbox environment and execute first instruction
interaction1 = client.interactions.create(
model=agent_model,
input="Create a folder named project/ and write hello.py inside.",
environment="remote",
background=True
)
# Wait for completion
while True:
check = client.interactions.get(id=interaction1.id)
if check.status != "in_progress":
break
time.sleep(2)
# Second interaction: Chain using previous_interaction_id and environment
interaction2 = client.interactions.create(
model=agent_model,
input="List all files in the project/ directory.",
previous_interaction_id=interaction1.id,
environment="remote",
background=True
)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const agentModel = "antigravity-preview-05-2026";
// First interaction: Provision sandbox environment and execute first ins
…
Previouspages/available-regions.txtNextpages/batch-api.txt

© 2026 Tech Dev Notes

RSSAboutAPIPrivacyTermsSitemap@techdevnotes