एजेंट बनाने और मैनेज करने की सुविधा के बारे में खास जानकारी

इस गाइड में, Gemini API पर मैनेज किए गए एजेंट बनाने और उनका इस्तेमाल करने का तरीका बताया गया है. इसके लिए, Antigravity एजेंट का इस्तेमाल किया गया है. आपको एजेंट से पहला कॉल करने, सिलसिलेवार बातचीत जारी रखने, जवाब रीयल टाइम में जनरेट होते हुए देखने की सुविधा, सैंडबॉक्स से फ़ाइलें डाउनलोड करने, और Antigravity के मैनेज किए गए एजेंट के साथ काम करने का मौका मिलेगा.

एजेंट के साथ पहला इंटरैक्शन करना

Interactions API को एक बार कॉल करने पर, Linux सैंडबॉक्स उपलब्ध कराया जाता है, एजेंट लूप चलाया जाता है, और नतीजा दिखाया जाता है. आपको तीन पैरामीटर तय करने होंगे:

  • agent को "antigravity-preview-09-2026", के तौर पर पास करें. यह पहले से तय और सामान्य मकसद के लिए मैनेज किए गए एजेंट का मौजूदा वर्शन है.
  • environment="remote" को तय करें, ताकि नया सैंडबॉक्स एनवायरमेंट उपलब्ध कराया जा सके.
  • एक इनपुट बनाएं और तय करें कि एजेंट को क्या काम करना है.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
    environment="remote",
)

# Print the agent's final output
print(f"Interaction ID: {interaction.id}")
print(f"Environment ID: {interaction.environment_id}")
print(f"Output: {interaction.output_text}")

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-09-2026",
    input: "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
    environment: "remote",
});

console.log(`Interaction ID: ${interaction.id}`);
console.log(`Environment ID: ${interaction.environment_id}`);

console.log(`Output: ${interaction.output_text}`);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateAgentInteraction params = CreateAgentInteraction.builder()
    .agent(AgentOption.of("antigravity-preview-09-2026"))
    .input(InteractionsInput.of("Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents."))
    .environment(CreateAgentInteractionEnvironment.of("remote"))
    .build();

Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

// Print the agent's final output
System.out.println("Interaction ID: " + interaction.id().orElse(""));
System.out.println("Environment ID: " + interaction.environmentId().orElse(""));
System.out.println("Output: " + interaction.outputText().orElse(""));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "antigravity-preview-09-2026",
    "input": [{"type": "text", "text": "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents."}],
    "environment": {"type": "remote"}
}'

जवाब में, एक Interaction ऑब्जेक्ट मिलता है. interaction.id और interaction.environment_id को सेव करें, ताकि उसी सैंडबॉक्स में बातचीत जारी रखी जा सके. एजेंट के आखिरी जवाब को ऐक्सेस करने के लिए, interaction.output_text का इस्तेमाल करें. interaction.steps में, एजेंट के हर चरण की जानकारी दी गई होती है. जैसे, गहराई से विश्लेषण, टूल कॉल, कोड एक्ज़ीक्यूशन.

सिलसिलेवार बातचीत जारी रखें

यह एपीआई, दो इंडिपेंडेंट स्टेट डाइमेंशन ट्रैक करता है:

  • बातचीत का कॉन्टेक्स्ट: चैट का इतिहास, तर्क का पता लगाना, टूल का इस्तेमाल करना, और previous_interaction_id का इस्तेमाल करना.
  • एनवायरमेंट की स्थिति: फ़ाइलें, इंस्टॉल किए गए पैकेज, और सैंडबॉक्स की स्थिति. इसके लिए, environment का इस्तेमाल किया जाता है.

फिर से शुरू करने के लिए, दोनों को उनकी जगह पर पास करें:

Python

interaction_2 = client.interactions.create(
    agent="antigravity-preview-09-2026",
    previous_interaction_id=interaction.id,
    environment=interaction.environment_id,
    input="Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
)

print(interaction_2.output_text)

JavaScript

const interaction2 = await client.interactions.create({
    agent: "antigravity-preview-09-2026",
    previous_interaction_id: interaction.id,
    environment: interaction.environment_id,
    input: "Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
}, { timeout: 300_000 });

console.log(interaction2.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();
String interactionId = "INTERACTION_ID";
String environmentId = "ENVIRONMENT_ID";

CreateAgentInteraction params = CreateAgentInteraction.builder()
    .agent(AgentOption.of("antigravity-preview-09-2026"))
    .previousInteractionId(interactionId)
    .environment(CreateAgentInteractionEnvironment.of(environmentId))
    .input(InteractionsInput.of("Now plot the Fibonacci sequence as a line chart and save it as chart.png."))
    .build();

Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction2.outputText().orElse(""));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "antigravity-preview-09-2026",
    "previous_interaction_id": "interaction_id_from_step_1",
    "environment": "environment_id_from_step_1",
    "input": [{"type": "text", "text": "Now plot the Fibonacci sequence as a line chart and save it as chart.png."}]
}'

पहले टर्न (fibonacci.txt) की फ़ाइलें, दूसरे टर्न में भी मौजूद रहती हैं. एजेंट को बातचीत का कॉन्टेक्स्ट भी पता होता है.

इनको अलग-अलग तरीके से इस्तेमाल किया जा सकता है:

  • बातचीत मिटाएं, फ़ाइलें सेव रखें: previous_interaction_id को हटा दें. साथ ही, उसी वर्कस्पेस में नई बातचीत शुरू करने के लिए, environment का इस्तेमाल करके सिर्फ़ एनवायरमेंट आईडी पास करें.
  • बातचीत जारी रखें, नया फ़ाइल फ़ोल्डर: previous_interaction_id पास करें और नए सैंडबॉक्स के लिए environment="remote" सेट करें.

कॉन्टेक्स्ट को अपने-आप छोटा करने की सुविधा

लंबे समय तक चलने वाली और कई बार की जाने वाली बातचीत में, तर्क देने के चरणों, टूल कॉल, और बड़ी फ़ाइल के कॉन्टेंट का रॉ डेटा तेज़ी से बढ़ता है. इससे कॉन्टेक्स्ट के लिए उपलब्ध जगह काफ़ी कम हो जाती है. टोकन की सीमा से जुड़ी गड़बड़ियों को रोकने और एजेंट बनाने और मैनेज करने की सुविधा का फ़ोकस बनाए रखने (कॉन्टेक्स्ट रॉट को रोकने) के लिए, Managed Agents API में करीब 1,35,000 टोकन पर कॉन्टेक्स्ट कंपैक्शन का एक नेटिव चरण होता है. यह अपने-आप होता है.

जवाब को स्ट्रीम करना

ज़्यादा समय तक चलने वाले टास्क के लिए, जवाब को स्ट्रीम किया जा सकता है. इससे एजेंट को रीयल टाइम में काम करते हुए देखा जा सकता है:

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
    environment="remote",
    stream=True,
)

for event in stream:
    print(event)
    if event.event_type == "step.stop" and event.usage:
        print(event.usage)

JavaScript

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

const client = new GoogleGenAI({});

const stream = await client.interactions.create({
    agent: "antigravity-preview-09-2026",
    input: "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
    environment: "remote",
    stream: true,
});

for await (const event of stream) {
    console.log(event);
    if (event.event_type === "step.stop" && event.usage) {
        console.log(event.usage);
    }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.StepStop;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.gaos.utils.EventStream;

Client client = new Client();

CreateAgentInteraction params = CreateAgentInteraction.builder()
    .agent(AgentOption.of("antigravity-preview-09-2026"))
    .input(InteractionsInput.of("Read Hacker News, summarize the top 5 stories, and save the results as a PDF."))
    .environment(CreateAgentInteractionEnvironment.of("remote"))
    .stream(true)
    .build();

try (EventStream<InteractionSSEStreamEvent> stream =
    client.interactions.create(CreateInteractionRequestBody.of(params)).events()) {
  for (InteractionSSEStreamEvent event : stream) {
    System.out.println(event);
    if (event.data().isPresent() && event.data().get() instanceof StepStop stepStop) {
      stepStop.usage().ifPresent(System.out::println);
    }
  }
}

REST

curl -N -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "antigravity-preview-09-2026",
    "input": "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
    "environment": "remote",
    "stream": true
}'

स्ट्रीमिंग, इंक्रीमेंटल अपडेट के साथ चरण के डेल्टा दिखाती है. जब कोई चरण पूरा हो जाता है, तो step.stop इवेंट में इस्तेमाल से जुड़े आंकड़े शामिल होते हैं. ज़्यादा जानने के लिए, स्ट्रीमिंग गाइड देखें.

एनवायरमेंट से फ़ाइलें डाउनलोड करना

जब एजेंट, सैंडबॉक्स में फ़ाइलें बनाता है. इन्हें सीधे एचटीटीपी अनुरोध (अब तक कोई एसडीके तरीका नहीं है) के साथ Files API का इस्तेमाल करके डाउनलोड करें:

Python

import os
import requests
import tarfile

env_id = interaction.environment_id
api_key = os.environ["GEMINI_API_KEY"]

response = requests.get(
    f"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download",
    params={"alt": "media"},
    headers={"x-goog-api-key": api_key},
    allow_redirects=True,
)

with open("snapshot.tar", "wb") as f:
    f.write(response.content)

with tarfile.open("snapshot.tar") as tar:
    tar.extractall(path="extracted_snapshot")

JavaScript

import fs from "fs";
import { execSync } from "child_process";

const envId = interaction.environment_id;
const apiKey = process.env.GEMINI_API_KEY || "";

const url = `https://generativelanguage.googleapis.com/v1beta/files/environment-${envId}:download?alt=media`;
const response = await fetch(url, {
    headers: {
        "x-goog-api-key": apiKey,
    },
});

if (!response.ok) {
    throw new Error(`Failed to download file: ${response.statusText}`);
}

const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync("snapshot.tar", buffer);

if (!fs.existsSync("extracted_snapshot")) {
    fs.mkdirSync("extracted_snapshot");
}
execSync("tar -xf snapshot.tar -C extracted_snapshot");

console.log(fs.readdirSync("extracted_snapshot"));

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;

String envId = "ENVIRONMENT_ID";
String apiKey = System.getenv("GEMINI_API_KEY");

HttpClient httpClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://generativelanguage.googleapis.com/v1beta/files/environment-" + envId + ":download?alt=media"))
    .header("x-goog-api-key", apiKey)
    .GET()
    .build();

HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
Files.write(Paths.get("snapshot.tar"), response.body());
System.out.println("Saved snapshot to snapshot.tar");

REST

ENV_ID="your_environment_id_here"

curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o snapshot.tar

mkdir -p extracted_snapshot
tar -xf snapshot.tar -C extracted_snapshot

मैनेज किए जा रहे एजेंट को सेव करना

पिछले चरणों में, हमने डिफ़ॉल्ट Antigravity एजेंट का इस्तेमाल किया था और उसे इनलाइन तरीके से पसंद के मुताबिक बनाया था. कॉन्फ़िगरेशन (निर्देश, स्किल, मॉडल का चुनाव, और एनवायरमेंट) में बदलाव करने के बाद, इसे मैनेज किए जा सकने वाले ऐसे एजेंट के तौर पर सेव किया जा सकता है जिसे बार-बार इस्तेमाल किया जा सकता है. इससे कॉन्फ़िगरेशन को दोहराए बिना, आईडी के ज़रिए इसे लागू किया जा सकता है.

किसी एजेंट को सेव करते समय, इनलाइन इंटरैक्शन के साथ आर्किटेक्चरल सिमिट्री पर ध्यान दें: आपको base_agent: "antigravity-preview-09-2026" तय करना होता है और अपने चुने हुए model के साथ agent_config पास करना होता है. ऐसा ही आपको interactions.create पर करना होता है. आपको base_environment भी तय करना होता है. इसके लिए, सोर्स से या किसी मौजूदा एनवायरमेंट को फ़ोर्क करके तय किया जा सकता है. एजेंट, हर नई बातचीत के लिए इस एनवायरमेंट और मॉडल कॉन्फ़िगरेशन का इस्तेमाल करेगा.

सोर्स से: सोर्स को इनलाइन या GitHub या Cloud Storage जैसे अन्य सोर्स से तय करें.

Python

agent = client.agents.create(
    id="fibonacci-analyst",
    base_agent="antigravity-preview-09-2026",
    agent_config={
        "type": "antigravity",
        "model": "gemini-3.8-flash",
    },
    system_instruction="You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always include a chart and a summary table in your reports.",
            },
            {
                "type": "repository",
                "source": "https://github.com/your-org/skills",
                "target": ".agents/skills"
            }
        ],
    },
)

print(f"Saved agent: {agent.id}")

JavaScript

const agent = await client.agents.create({
    id: "fibonacci-analyst",
    base_agent: "antigravity-preview-09-2026",
    agent_config: {
        type: "antigravity",
        model: "gemini-3.8-flash",
    },
    system_instruction: "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "Always include a chart and a summary table in your reports.",
            },
            {
                type: "repository",
                source: "https://github.com/your-org/skills",
                target: ".agents/skills"
            }
        ],
    },
});

console.log(`Saved agent: ${agent.id}`);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.agents.Agent;
import com.google.genai.gaos.models.agents.AgentConfig;
import com.google.genai.gaos.models.agents.BaseEnvironment;
import com.google.genai.gaos.models.interactions.AntigravityAgentConfig;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.Source;
import com.google.genai.gaos.models.interactions.SourceType;
import java.util.List;

Client client = new Client();

Environment env = Environment.builder()
    .sources(List.of(
        Source.builder()
            .type(SourceType.INLINE)
            .target(".agents/AGENTS.md")
            .content("Always include a chart and a summary table in your reports.")
            .build(),
        Source.builder()
            .type(SourceType.REPOSITORY)
            .source("https://github.com/your-org/skills")
            .target(".agents/skills")
            .build()
    ))
    .build();

Agent agentParams = Agent.builder()
    .id("fibonacci-analyst")
    .baseAgent("antigravity-preview-09-2026")
    .agentConfig(AgentConfig.of(
        AntigravityAgentConfig.builder()
            .model("gemini-3.8-flash")
            .build()
    ))
    .systemInstruction("You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.")
    .baseEnvironment(BaseEnvironment.of(env))
    .build();

Agent agent = client.agents.create(agentParams).agent().get();
System.out.println("Saved agent: " + agent.id().orElse(""));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/agents" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "id": "fibonacci-analyst",
    "base_agent": "antigravity-preview-09-2026",
    "agent_config": {
        "type": "antigravity",
        "model": "gemini-3.8-flash"
    },
    "system_instruction": "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    "base_environment": {
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always include a chart and a summary table in your reports."
            },
            {
                "type": "repository",
                "source": "https://github.com/your-org/skills",
                "target": ".agents/skills"
            }
        ]
    }
}'

मैनेज किए जा रहे एजेंट को चालू करना

मैनेज किए गए एजेंट को सेव करने के बाद, उसे आईडी से शुरू किया जा सकता है. हर इनवोकेशन, बेस एनवायरमेंट को फ़ोर्क करता है. इसलिए, हर रन क्लीन तरीके से शुरू होता है:

Python

result = client.interactions.create(
    agent="fibonacci-analyst",
    input="Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
    environment="remote",
)

print(result.output_text)

JavaScript

const result = await client.interactions.create({
    agent: "fibonacci-analyst",
    input: "Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
    environment: "remote",
}, {
    timeout: 300_000,
});

console.log(result.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateAgentInteraction params = CreateAgentInteraction.builder()
    .agent(AgentOption.of("fibonacci-analyst"))
    .input(InteractionsInput.of("Generate the first 50 prime numbers, plot their distribution, and save a PDF report."))
    .environment(CreateAgentInteractionEnvironment.of("remote"))
    .build();

Interaction result = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(result.outputText().orElse(""));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "fibonacci-analyst",
    "environment": "remote",
    "input": "Generate the first 50 prime numbers, plot their distribution, and save a PDF report."
}'

आगे क्या करना है