מדריך למתחילים בנושא ניהול סוכנים

במדריך הזה נסביר איך ליצור סוכנים מנוהלים ב-Gemini API ולהשתמש בהם, באמצעות סוכן Antigravity. תבצעו את השיחה הראשונה עם סוכן, תמשיכו שיחה רב-שלבית, תצפו בתשובה באופן שוטף, תורידו קבצים מהארגז חול ותעבדו עם הסוכן המנוהל Antigravity.

הפעלת אינטראקציה ראשונה עם נציג

קריאה יחידה ל-Interactions API מספקת ארגז חול של Linux, מריצה את לולאת הסוכן ומחזירה את התוצאה. תגדירו שלושה פרמטרים:

  • מעבירים את agent בתור "antigravity-preview-05-2026",, שהיא הגרסה הנוכחית של הסוכן המנוהל שלנו שמוגדר מראש ומתאים למטרות כלליות.
  • מגדירים את environment="remote" כדי להקצות סביבת ארגז חול חדשה ורעננה.
  • יוצרים קלט ומגדירים מה רוצים שהסוכן יעשה.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-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-05-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.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(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-05-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 מפרטת כל שלב שהסוכן ביצע (חשיבה רציונלית, קריאות לכלים, הרצת קוד).

המשך השיחה (רב-שלבית)

ממשק ה-API עוקב אחרי שני מימדים עצמאיים של מצב:

  • הקשר של השיחה: היסטוריית הצ'אט, מעקב אחר תהליך החשיבה, שימוש בכלי, שימוש ב-previous_interaction_id.
  • מצב הסביבה: קבצים, חבילות מותקנות ומצב ארגז החול, באמצעות environment.

צריך להזין את שניהם במקום המתאים כדי להמשיך:

Python

interaction_2 = client.interactions.create(
    agent="antigravity-preview-05-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-05-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.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(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-05-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."}]
}'

קבצים מפנייה 1 (fibonacci.txt) נשמרים בפנייה 2. הסוכן גם שומר את ההקשר של השיחה.

אפשר לשלב בין האפשרויות האלה באופן עצמאי:

  • ניקוי השיחה, שמירת הקבצים: לא כוללים את previous_interaction_id, מעבירים רק את מזהה הסביבה באמצעות environment כדי ליצור שיחה חדשה באותו מרחב.
  • שמירת השיחה, סביבת עבודה חדשה: מעבירים את previous_interaction_id ומגדירים את environment="remote" לסביבת ארגז חול חדשה.

דחיסה אוטומטית של ההקשר

בשיחות ארוכות עם כמה תורות, ההיסטוריה הגולמית של שלבי הנימוקים, קריאות הכלים ותוכן הקבצים הגדולים יכולה לגדול במהירות ולתפוס נפח משמעותי של הקשר. כדי למנוע שגיאות שקשורות למגבלת הטוקנים ולשמור על המיקוד של הסוכן (ולמנוע 'הידרדרות ההקשר'), ב-API של ניהול סוכנים יש שלב דחיסה של ההקשר המקורי, בסביבות 135,000 טוקנים. פעולה זו מתבצעת באופן אוטומטי.

הצגת התשובה באופן שוטף

במשימות ארוכות, אפשר להזרים את התשובה כדי לראות את הסוכן פועל בזמן אמת:

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    agent="antigravity-preview-05-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-05-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.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(interaction.outputText().orElse(""));

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-05-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 עם בקשת HTTP ישירה (עדיין אין שיטה ב-SDK):

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 com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(interaction.outputText().orElse(""));

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-05-2026" ויכולים להעביר agent_config עם model שבחרתם בדיוק כמו ב-interactions.create. אתם גם מגדירים base_environment (ממקורות או על ידי יצירת עותק של סביבה קיימת). הסוכן ישתמש בסביבה הזו ובהגדרות המודל האלה לכל אינטראקציה חדשה.

ממקורות: הגדרת מקורות בשורה או ממקורות אחרים כמו GitHub או Cloud Storage.

Python

agent = client.agents.create(
    id="fibonacci-analyst",
    base_agent="antigravity-preview-05-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-05-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.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(interaction.outputText().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-05-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.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();

CreateModelInteraction req =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Summarize the project structure."))
        .environment(CreateModelInteractionEnvironment.of("remote"))
        .build();

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

System.out.println(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": "fibonacci-analyst",
    "environment": "remote",
    "input": "Generate the first 50 prime numbers, plot their distribution, and save a PDF report."
}'

המאמרים הבאים