관리 에이전트 빠른 시작

이 가이드에서는 Antigravity 에이전트를 사용하여 Gemini API에서 관리형 에이전트를 만들고 사용하는 방법을 안내합니다. 첫 번째 에이전트 호출을 하고, 여러 턴으로 구성된 대화를 이어가고, 응답을 스트리밍하고, 샌드박스에서 파일을 다운로드하고, 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}`);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-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.idinteraction.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);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-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를 사용하여 환경 ID만 전달합니다.
  • 대화 유지, 새 작업 공간: 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)

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

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" \
-H "Api-Revision: 2026-05-20" \
-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
}'

스트리밍은 증분 텍스트, 추론 토큰, 도구 호출 업데이트인 단계 델타의 반복 가능한 항목을 반환합니다. 스트리밍 가이드에서 응답을 스트리밍하는 방법을 자세히 알아보세요.

환경에서 파일 다운로드

에이전트가 샌드박스 내에서 파일을 만들 때 직접 HTTP 요청으로 Files API를 사용하여 다운로드합니다 (아직 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"));

REST

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

tar -xf snapshot.tar -C extracted_snapshot

관리형 에이전트 저장

이전 단계에서는 기본 Antigravity 에이전트를 사용하고 인라인으로 맞춤설정했습니다. 구성 (안내, 기술, 환경)을 반복한 후 관리형 에이전트로 저장할 수 있습니다. 이렇게 하면 구성을 반복하지 않고 ID로 호출할 수 있습니다.

에이전트를 저장할 때 소스에서 또는 기존 환경을 포크하여 base_environment를 정의합니다. 에이전트는 모든 새 상호작용에 이 환경을 사용합니다.

소스에서: 인라인으로 또는 GitHub나 Cloud Storage와 같은 다른 소스에서 소스를 정의합니다.

Python

agent = client.agents.create(
    id="fibonacci-analyst",
    base_agent="antigravity-preview-05-2026",
    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",
    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}`);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/agents" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
    "id": "fibonacci-analyst",
    "base_agent": "antigravity-preview-05-2026",
    "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"
            }
        ]
    }
}'

관리형 에이전트 호출

관리형 에이전트를 저장한 후 ID로 호출할 수 있습니다. 각 호출은 기본 환경을 포크하므로 모든 실행이 깨끗하게 시작됩니다.

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

REST

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

다음 단계