Ekzekutimi në sfond

Për detyra që ekzekutohen për një kohë të gjatë, si kërkime të thella, arsyetime komplekse ose ekzekutime agjentësh me shumë hapa, skadimet e kohës së lidhjes mund të ndërpresin kërkesat standarde HTTP (të cilat zakonisht mbyllen pas 60 sekondash). API-ja e Ndërveprimeve ofron ekzekutim në sfond për të ekzekutuar këto detyra në mënyrë asinkrone.

Për ta lënë bashkëveprimin të funksionojë derisa të përfundojë detyra në server, vendosni "background": true kur krijoni bashkëveprimin. API-ja kthen menjëherë një ID bashkëveprimi, të cilin aplikacionet e klientit mund ta përdorin për të pyetur për statusin, progresin e transmetimit ose për t'u rilidhur me një transmetim të shkëputur.

Ekzekutimi në sfond mbështetet për modelet standarde Gemini (siç janë gemini-3.5-flash dhe gemini-3.1-pro-preview ) dhe Agjentët e Menaxhuar (siç është antigravity-preview-05-2026 ).

Krijo një ndërveprim në sfond

Për të filluar një bashkëveprim në sfond, vendosni parametrin e backgroundtrue kur krijoni burimin.

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}`);

PUSHTIM

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
  }'

Si funksionon ekzekutimi në sfond

Kur krijoni një bashkëveprim në sfond, detyra ekzekutohet në mënyrë asinkrone në server. Ndërveprimi kalon nëpër gjendje të ndryshme ekzekutimi:

  • in_progress : Serveri po ekzekuton në mënyrë aktive bashkëveprimin (si p.sh. po ekzekuton kod ose po bën kërkime).
  • requires_action : Ndërveprimi është ndalur dhe është duke pritur për të dhëna nga klienti (si p.sh. konfirmimi i ekzekutimit të një mjeti ose përgjigjja e një pyetjeje).
  • completed : Ndërveprimi përfundoi me sukses dhe rezultati është i disponueshëm.
  • failed : Ndodhi një gabim gjatë ekzekutimit (siç është dështimi i mjetit ose kufizimet e shpejtësisë).
  • cancelled : Një kërkesë e klientit ndaloi ekzekutimin.

Rastet e përdorimit

Përdorni ekzekutimin në sfond për:

  • Ekzekutimet e agjentëve: Detyrat që kërkojnë ekzekutimin e kodit, shfletimin e uebit ose orkestrimin e nën-agjentëve (si p.sh. antigravity-preview-05-2026 ).

  • Hulumtim i thellë: Ekzekutohet duke përdorur deep-research-preview-04-2026 ose deep-research-max-preview-04-2026 të cilat zgjasin disa minuta.

  • Arsyetim i gjatë: Detyra ku hapat e të menduarit model tejkalojnë kufijtë standardë të lidhjes HTTP.

Merrni rezultatet

Merrni rezultatet e ndërveprimit në sfond duke përdorur sondazhe ose transmetim .

Modeli i votimit (jo-bllokues)

Sondazhi kontrollon statusin e ndërveprimit periodikisht duke përdorur kërkesa GET jo-bllokuese derisa të arrijë në një gjendje terminale.

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}`);
}

PUSHTIM

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"

Modeli i transmetimit

Nëse një ndërprerje e rrjetit shkëput një transmetim, transmetimi mund të rifillojë nga ngjarja e fundit e marrë. Çdo delta përmban një event_id unik në ngarkesën e saj. Kalimi i këtij ID si last_event_id rifillon transmetimin nga ajo ngjarje.

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);

PUSHTIM

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"

Biseda me shumë kthesa

Ndërveprimet pasuese mund të lidhen me një bisedë në sfond duke përdorur previous_interaction_id , në varësi të këtyre kufizimeve:

  1. Ekzekutimet aktive bllokohen: Lidhja zinxhir e një bashkëveprimi pasues me një me status in_progress kthen një gabim 400 Bad Request . Prisni që bashkëveprimi të arrijë gjendjen completed përpara se të filloni atë tjetër.
  2. Parametri i Mjedisit për Agjentët e Menaxhuar: Kur lidhni zinxhir ndërveprimet për Agjentët e Menaxhuar (siç është antigravity-preview-05-2026 ), kërkesat duhet të përfshijnë si previous_interaction_id ashtu edhe environment .

Shembujt e mëposhtëm tregojnë se si të zinxhirohen ndërveprimet:

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 instruction
const interaction1 = await client.interactions.create({
    model: agentModel,
    input: "Create a folder named project/ and write hello.py inside.",
    environment: "remote",
    background: true
});

// Wait for completion
while (true) {
    const check = await client.interactions.get(interaction1.id);
    if (check.status !== "in_progress") {
        break;
    }
    await new Promise(resolve => setTimeout(resolve, 2000));
}

// Second interaction: Chain using previous_interaction_id and environment
const interaction2 = await client.interactions.create({
    model: agentModel,
    input: "List all files in the project/ directory.",
    previous_interaction_id: interaction1.id,
    environment: "remote",
    background: true
});

PUSHTIM

# Chain second interaction (Make sure FIRST_INTERACTION_ID has status 'completed')
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": "antigravity-preview-05-2026",
    "input": "List all files in the project/ directory.",
    "previous_interaction_id": "FIRST_INTERACTION_ID",
    "environment": "remote",
    "background": true
  }'

Anulimi dhe fshirja

Kontrolloni ekzekutimet në ekzekutim dhe menaxhoni hapësirën e ruajtjes duke përdorur kërkesat për anulim dhe fshirje:

  • Anulo ( POST /interactions/{id}/cancel ): Ndalon detyrën që po ekzekutohet. Statusi kalon në cancelled . Veprimet e pastrimit në server mund të shkaktojnë një vonesë të vogël përpara përditësimeve të statusit në kërkesat GET.
  • Fshij ( DELETE /interactions/{id} ): Heq të dhënat e ndërveprimit nga serveri. Kërkesat pasuese GET kthejnë një gabim 404 Not Found .

Python

from google import genai

client = genai.Client()

# Cancel a running interaction
client.interactions.cancel(id="YOUR_INTERACTION_ID")

# Delete the interaction record entirely
client.interactions.delete(id="YOUR_INTERACTION_ID")

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

// Cancel a running interaction
await client.interactions.cancel("YOUR_INTERACTION_ID");

// Delete the interaction record entirely
await client.interactions.delete("YOUR_INTERACTION_ID");

PUSHTIM

# Cancel the interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID/cancel" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20"

# Delete the interaction
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20"

Hapat e ardhshëm