이 가이드에서는 Antigravity 에이전트를 사용하여 Gemini API에서 관리형 에이전트를 만들고 사용하는 방법을 안내합니다. 첫 번째 에이전트 호출을 하고, 멀티턴 대화를 계속하고, 응답을 스트리밍하고, 샌드박스에서 파일을 다운로드하고, 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}")
자바스크립트
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}`);
자바
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에는 에이전트가 수행한 각 단계 (추론, 도구 호출, 코드 실행)가 나열됩니다.
대화 이어 나가기 (멀티턴)
API는 두 가지 독립적인 상태 측정기준을 추적합니다.
- 대화 컨텍스트: 채팅 기록, 추론 추적, 도구 사용,
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)
자바스크립트
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);
자바
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."}]
}'
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-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)
자바스크립트
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);
}
}
자바
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 이벤트에 누적된 사용 통계가 포함됩니다. 자세한 내용은 스트리밍 가이드를 참고하세요.
환경에서 파일 다운로드
에이전트가 샌드박스 내에 파일을 생성하는 경우 직접 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"));
자바
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 에이전트를 사용하고 인라인으로 맞춤설정했습니다. 구성 (안내, 스킬, 모델 선택, 환경)을 반복한 후에는 재사용 가능한 관리 에이전트로 저장할 수 있습니다. 이렇게 하면 구성을 반복하지 않고 ID로 호출할 수 있습니다.
에이전트를 저장하면 인라인 상호작용과 아키텍처가 대칭임을 알 수 있습니다. 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}")
자바스크립트
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}`);
자바
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"
}
]
}
}'
관리형 에이전트 호출
관리형 에이전트를 저장한 후 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);
자바
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."
}'
다음 단계
- Antigravity Agent: 기능, 지원되는 도구, 멀티모달 입력, 가격 책정, 제한사항
- 관리형 에이전트 빌드: 자체 안내, 기술, 데이터로 Antigravity를 확장합니다.
- 환경: 소스, 네트워킹, 수명 주기, 리소스 한도
- Interactions API: 모델 및 에이전트의 기본 API입니다.