이 가이드에서는 Antigravity agent를 사용하여 Gemini API에서 관리형 에이전트를 만들고 사용하는 방법을 안내합니다. 첫 번째 에이전트 호출을 하고, 멀티턴 대화를 계속하고, 응답을 스트리밍하고, 샌드박스에서 파일을 다운로드하고, Antigravity 관리 에이전트와 함께 작업합니다.
첫 번째 에이전트 상호작용 실행
Interactions API를 한 번 호출하면 Linux 샌드박스가 프로비저닝되고, 에이전트 루프가 실행되고, 결과가 반환됩니다. 다음 세 가지 매개변수를 정의합니다.
agent을"antigravity-preview-05-2026",으로 전달합니다."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}")
자바스크립트
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.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)
자바스크립트
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)
자바스크립트
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 요청 (아직 SDK 메서드 없음)으로 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")
자바스크립트
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}")
자바스크립트
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)
자바스크립트
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."
}'
다음 단계
- Antigravity Agent: 기능, 지원되는 도구, 멀티모달 입력, 가격 책정, 제한사항
- 관리형 에이전트 빌드: 자체 안내, 기술, 데이터로 Antigravity를 확장합니다.
- 환경: 소스, 네트워킹, 수명 주기, 리소스 한도
- 상호작용 API: 모델 및 에이전트의 기본 API입니다.