SPB Git

Repository Public

background-execution.md 18.8 KB 510 lines markdown

1For 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](https://ai.google.dev/gemini-api/docs/interactions-overview) provides **background execution** to run these tasks asynchronously.23To 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.45Background execution is supported for standard Gemini models (such as `gemini-3.8-flash` and `gemini-3.1-pro-preview`) and Managed Agents (such as `antigravity-preview-09-2026`).67## Create a background interaction89To start a background interaction, set the `background` parameter to `true` when creating the resource.1011### Python1213    from google import genai1415    client = genai.Client()1617    interaction = client.interactions.create(18        model="gemini-3.8-flash",19        input="Write a guide on space exploration.",20        background=True,21    )22    print(f"Created background interaction ID: {interaction.id}")2324### JavaScript2526    import { GoogleGenAI } from "@google/genai";2728    const client = new GoogleGenAI({});2930    const interaction = await client.interactions.create({31        model: "gemini-3.8-flash",32        input: "Write a guide on space exploration.",33        background: true,34    });35    console.log(`Created background interaction ID: ${interaction.id}`);3637### Java3839    import com.google.genai.Client;40    import com.google.genai.gaos.models.interactions.CreateModelInteraction;41    import com.google.genai.gaos.models.interactions.Interaction;42    import com.google.genai.gaos.models.interactions.InteractionsInput;43    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;4445    Client client = new Client();4647    CreateModelInteraction params =48        CreateModelInteraction.builder()49            .model("gemini-3.8-flash")50            .input(InteractionsInput.of("Write a guide on space exploration."))51            .background(true)52            .build();5354    Interaction interaction =55        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();56    System.out.println("Created background interaction ID: " + interaction.id().orElse(""));5758### REST5960    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \61      -H "x-goog-api-key: $GEMINI_API_KEY" \62      -H "Content-Type: application/json" \63      -H "Api-Revision: 2026-05-20" \64      -d '{65        "model": "gemini-3.8-flash",66        "input": "Write a guide on space exploration.",67        "background": true68      }'6970## How background execution works7172When you create a background interaction, the task runs asynchronously on the server. The interaction transitions through various execution states:7374- `in_progress`: The server is actively executing the interaction (such as running code or researching).75- `requires_action`: The interaction has paused and is waiting for client input (such as confirming a tool execution or answering a question).76- `completed`: The interaction finished successfully and the output is available.77- `failed`: An error occurred during execution (such as tool failure or rate limits).78- `cancelled`: A client request stopped the execution.7980> [!NOTE]81> **Note:** For the complete list of interaction states, see the [Interactions API Reference](https://ai.google.dev/api/interactions-api#Resource:Interaction).8283### Use cases8485Use background execution for:8687- **Agent executions:** Tasks requiring code execution, web browsing, or sub-agent orchestration (such as `antigravity-preview-09-2026`).8889- **Deep research:** Runs using `deep-research-preview-04-2026` or `deep-research-max-preview-04-2026` which take several minutes.9091- **Long reasoning:** Tasks where model thinking steps exceed standard HTTP connection limits.9293## Retrieve results9495Obtain background interaction results using either **polling** or **streaming**.9697### Polling pattern (non-blocking)9899Polling checks the interaction status periodically using non-blocking GET requests until it reaches a terminal state.100101### Python102103    import time104    from google import genai105106    client = genai.Client()107108    interaction = client.interactions.get(id="YOUR_INTERACTION_ID")109110    while interaction.status == "in_progress":111        time.sleep(5)112        interaction = client.interactions.get(id=interaction.id)113114    if interaction.status == "completed":115        print(interaction.output_text)116    else:117        print(f"Finished with status: {interaction.status}")118119### JavaScript120121    import { GoogleGenAI } from "@google/genai";122123    const client = new GoogleGenAI({});124125    let interaction = await client.interactions.get("YOUR_INTERACTION_ID");126127    while (interaction.status === "in_progress") {128        await new Promise(resolve => setTimeout(resolve, 5000));129        interaction = await client.interactions.get(interaction.id);130    }131132    if (interaction.status === "completed") {133        console.log(interaction.output_text);134    } else {135        console.log(`Finished with status: ${interaction.status}`);136    }137138### Java139140    import com.google.genai.Client;141    import com.google.genai.gaos.models.interactions.Interaction;142    import com.google.genai.gaos.models.interactions.InteractionStatus;143    import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;144145    Client client = new Client();146147    Interaction interaction =148        client.interactions149            .get(GetInteractionByIdRequest.builder().id("YOUR_INTERACTION_ID").build())150            .interaction()151            .get();152153    while (InteractionStatus.IN_PROGRESS.equals(interaction.status().orElse(null))) {154      Thread.sleep(5000);155      interaction =156          client.interactions157              .get(GetInteractionByIdRequest.builder().id(interaction.id().get()).build())158              .interaction()159              .get();160    }161162    if (InteractionStatus.COMPLETED.equals(interaction.status().orElse(null))) {163      System.out.println(interaction.outputText().orElse(""));164    } else {165      System.out.println(166          "Finished with status: " + interaction.status().map(InteractionStatus::value).orElse(""));167    }168169### REST170171    curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \172      -H "x-goog-api-key: $GEMINI_API_KEY" \173      -H "Api-Revision: 2026-05-20"174175### Streaming pattern176177If 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.178179### Python180181    import time182    from google import genai183184    client = genai.Client()185    interaction_id = "YOUR_INTERACTION_ID"186187    def stream_with_reconnect(interaction_id: str):188        last_event_id = None189        while True:190            try:191                # Retrieve the stream. If resuming, pass last_event_id192                stream = client.interactions.get(193                    id=interaction_id,194                    stream=True,195                    last_event_id=last_event_id196                )197198                for event in stream:199                    # Log event updates and capture event_id if present200                    if event.event_id:201                        last_event_id = event.event_id202203                    if event.event_type == "step.delta" and event.delta.type == "text":204                        print(event.delta.text, end="", flush=True)205206                    if event.event_type == "interaction.completed":207                        return208209            except Exception as e:210                print(f"\n[Connection lost: {e}. Reconnecting in 3s...]")211                time.sleep(3)212213    stream_with_reconnect(interaction_id)214215### JavaScript216217    import { GoogleGenAI } from "@google/genai";218219    const client = new GoogleGenAI({});220    const interactionId = "YOUR_INTERACTION_ID";221222    async function streamWithReconnect(id) {223        let lastEventId = undefined;224        while (true) {225            try {226                // Retrieve the stream. If resuming, pass last_event_id in options227                const stream = await client.interactions.get(id, {228                    stream: true,229                    last_event_id: lastEventId230                });231232                for await (const event of stream) {233                    // Capture event_id if present234                    const idVal = event.event_id || event.id;235                    if (idVal) {236                        lastEventId = idVal;237                    }238239                    if (event.event_type === "step.delta" && event.delta?.type === "text") {240                        process.stdout.write(event.delta.text);241                    }242243                    if (event.event_type === "interaction.completed") {244                        return;245                    }246                }247            } catch (error) {248                console.log(`\n[Connection lost: ${error.message}. Reconnecting in 3s...]`);249                await new Promise(resolve => setTimeout(resolve, 3000));250            }251        }252    }253254    await streamWithReconnect(interactionId);255256### Java257258    import com.google.genai.Client;259    import com.google.genai.gaos.models.interactions.InteractionCompletedEvent;260    import com.google.genai.gaos.models.interactions.InteractionSSEEvent;261    import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;262    import com.google.genai.gaos.models.interactions.StepDelta;263    import com.google.genai.gaos.models.interactions.TextDelta;264    import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;265    import com.google.genai.gaos.utils.EventStream;266267    Client client = new Client();268    String interactionId = "YOUR_INTERACTION_ID";269    String lastEventId = null;270    boolean completed = false;271272    while (!completed) {273      try (EventStream<InteractionSSEStreamEvent> stream =274          client.interactions275              .get(276                  GetInteractionByIdRequest.builder()277                      .id(interactionId)278                      .stream(true)279                      .lastEventId(lastEventId)280                      .build())281              .events()) {282        for (InteractionSSEStreamEvent streamEvent : stream) {283          InteractionSSEEvent event = streamEvent.data().orElse(null);284          if (event instanceof StepDelta) {285            StepDelta stepDelta = (StepDelta) event;286            if (stepDelta.eventId().isPresent()) {287              lastEventId = stepDelta.eventId().get();288            }289            if (stepDelta.delta().isPresent() && stepDelta.delta().get() instanceof TextDelta) {290              System.out.print(((TextDelta) stepDelta.delta().get()).text().orElse(""));291              System.out.flush();292            }293          } else if (event instanceof InteractionCompletedEvent) {294            completed = true;295            break;296          }297        }298      } catch (Exception e) {299        System.out.println("\n[Connection lost: " + e.getMessage() + ". Reconnecting in 3s...]");300        Thread.sleep(3000);301      }302    }303304### REST305306    curl -N -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID?stream=true&last_event_id=YOUR_LAST_EVENT_ID" \307      -H "x-goog-api-key: $GEMINI_API_KEY" \308      -H "Api-Revision: 2026-05-20"309310## Multi-turn conversations311312Subsequent interactions can chain to a background conversation using `previous_interaction_id`, subject to these constraints:3133141. **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.3152. **Environment Parameter for Managed Agents:** When chaining interactions for Managed Agents (such as `antigravity-preview-09-2026`), requests must include both `previous_interaction_id` and `environment`.316317The following examples show how to chain interactions:318319### Python320321    import time322    from google import genai323324    client = genai.Client()325    agent_model = "antigravity-preview-09-2026"326327    # First interaction: Provision sandbox environment and execute first instruction328    interaction1 = client.interactions.create(329        agent=agent_model,330        input="Create a folder named project/ and write hello.py inside.",331        environment="remote",332        background=True333    )334335    # Wait for completion336    while True:337        check = client.interactions.get(id=interaction1.id)338        if check.status != "in_progress":339            break340        time.sleep(2)341342    # Second interaction: Chain using previous_interaction_id and environment343    interaction2 = client.interactions.create(344        agent=agent_model,345        input="List all files in the project/ directory.",346        previous_interaction_id=interaction1.id,347        environment="remote",348        background=True349    )350351### JavaScript352353    import { GoogleGenAI } from "@google/genai";354355    const client = new GoogleGenAI({});356    const agentModel = "antigravity-preview-09-2026";357358    // First interaction: Provision sandbox environment and execute first instruction359    const interaction1 = await client.interactions.create({360        agent: agentModel,361        input: "Create a folder named project/ and write hello.py inside.",362        environment: "remote",363        background: true364    });365366    // Wait for completion367    while (true) {368        const check = await client.interactions.get(interaction1.id);369        if (check.status !== "in_progress") {370            break;371        }372        await new Promise(resolve => setTimeout(resolve, 2000));373    }374375    // Second interaction: Chain using previous_interaction_id and environment376    const interaction2 = await client.interactions.create({377        agent: agentModel,378        input: "List all files in the project/ directory.",379        previous_interaction_id: interaction1.id,380        environment: "remote",381        background: true382    });383384### Java385386    import com.google.genai.Client;387    import com.google.genai.gaos.models.interactions.CreateModelInteraction;388    import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;389    import com.google.genai.gaos.models.interactions.Interaction;390    import com.google.genai.gaos.models.interactions.InteractionStatus;391    import com.google.genai.gaos.models.interactions.InteractionsInput;392    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;393    import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;394395    Client client = new Client();396    String agentModel = "antigravity-preview-09-2026";397398    // First interaction: Provision sandbox environment and execute first instruction399    CreateModelInteraction params1 =400        CreateModelInteraction.builder()401            .model(agentModel)402            .input(InteractionsInput.of("Create a folder named project/ and write hello.py inside."))403            .environment(CreateModelInteractionEnvironment.of("remote"))404            .background(true)405            .build();406407    Interaction interaction1 =408        client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();409410    // Wait for completion411    while (true) {412      Interaction check =413          client.interactions414              .get(GetInteractionByIdRequest.builder().id(interaction1.id().get()).build())415              .interaction()416              .get();417      if (!InteractionStatus.IN_PROGRESS.equals(check.status().orElse(null))) {418        break;419      }420      Thread.sleep(2000);421    }422423    // Second interaction: Chain using previousInteractionId and environment424    CreateModelInteraction params2 =425        CreateModelInteraction.builder()426            .model(agentModel)427            .input(InteractionsInput.of("List all files in the project/ directory."))428            .previousInteractionId(interaction1.id().get())429            .environment(CreateModelInteractionEnvironment.of("remote"))430            .background(true)431            .build();432433    Interaction interaction2 =434        client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();435436### REST437438    # Chain second interaction (Make sure FIRST_INTERACTION_ID has status 'completed')439    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \440      -H "x-goog-api-key: $GEMINI_API_KEY" \441      -H "Content-Type: application/json" \442      -H "Api-Revision: 2026-05-20" \443      -d '{444        "agent": "antigravity-preview-09-2026",445        "input": "List all files in the project/ directory.",446        "previous_interaction_id": "FIRST_INTERACTION_ID",447        "environment": "remote",448        "background": true449      }'450451## Cancellation and deletion452453Control running executions and manage storage using cancel and delete requests:454455- **Cancel (`POST /interactions/{id}/cancel`):** Stops the running task. The status transitions to `cancelled`. Clean-up actions on the server can cause a slight delay before the status updates in GET requests.456- **Delete (`DELETE /interactions/{id}`):** Removes the interaction records from the server. Subsequent GET requests return a `404 Not Found` error.457458### Python459460    from google import genai461462    client = genai.Client()463464    # Cancel a running interaction465    client.interactions.cancel(id="YOUR_INTERACTION_ID")466467    # Delete the interaction record entirely468    client.interactions.delete(id="YOUR_INTERACTION_ID")469470### JavaScript471472    import { GoogleGenAI } from "@google/genai";473474    const client = new GoogleGenAI({});475476    // Cancel a running interaction477    await client.interactions.cancel("YOUR_INTERACTION_ID");478479    // Delete the interaction record entirely480    await client.interactions.delete("YOUR_INTERACTION_ID");481482### Java483484    import com.google.genai.Client;485486    Client client = new Client();487488    // Cancel a running interaction489    client.interactions.cancel("YOUR_INTERACTION_ID");490491    // Delete the interaction record entirely492    client.interactions.delete("YOUR_INTERACTION_ID");493494### REST495496    # Cancel the interaction497    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID/cancel" \498      -H "x-goog-api-key: $GEMINI_API_KEY" \499      -H "Api-Revision: 2026-05-20"500501    # Delete the interaction502    curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \503      -H "x-goog-api-key: $GEMINI_API_KEY" \504      -H "Api-Revision: 2026-05-20"505506## Next steps507508- Read the [Interactions API overview](https://ai.google.dev/gemini-api/docs/interactions-overview) to understand session and state management.509- See the [Streaming interactions](https://ai.google.dev/gemini-api/docs/streaming) guide for details on real-time event updates.510- Explore the [Managed agents quickstart](https://ai.google.dev/gemini-api/docs/managed-agents-quickstart) to build stateful multi-turn agents.
Files main
Menu

Theme