このガイドでは、反重力エージェントを使用して、Gemini API でマネージド エージェントを作成して使用する方法について説明します。最初のエージェント呼び出し、マルチターンの会話の継続、レスポンスのストリーミング、サンドボックスからのファイルのダウンロード、Antigravity マネージド エージェントの操作を行います。
最初のエージェントとのやり取りを実行する
Interactions API への 1 回の呼び出しで、Linux サンドボックスがプロビジョニングされ、エージェント ループが実行され、結果が返されます。次の 3 つのパラメータを定義します。
- 事前定義された汎用マネージド エージェントの現在のバージョンである
"antigravity-preview-05-2026",としてagentを渡します。 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.id と interaction.environment_id を保存します。interaction.output_text を使用して、エージェントの最終回答にアクセスします。interaction.steps には、エージェントが実行した各ステップ(推論、ツール呼び出し、コード実行)が一覧表示されます。
会話を続ける(マルチターン)
この API は、次の 2 つの独立した状態ディメンションを追跡します。
- 会話のコンテキスト: チャットの履歴、推論のトレース、ツールの使用、
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"を設定します。
コンテキストの自動圧縮
長時間にわたるマルチターンの会話では、推論ステップ、ツール呼び出し、大きなファイルの内容の生履歴が急速に増大し、コンテキスト空間を大幅に消費する可能性があります。トークン上限エラーを回避し、エージェントの焦点を維持する(「コンテキストの劣化」を防ぐ)ため、Managed Agents 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
}'
ストリーミングは、ステップのデルタのイテラブルを返します。これは、増分テキスト、推論トークン、ツール呼び出しの更新です。レスポンスをストリーミングする方法については、ストリーミング ガイドをご覧ください。
環境からファイルをダウンロードする
エージェントがサンドボックス内にファイルを作成する場合。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"));
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."
}'
次のステップ
- Antigravity エージェント: 機能、サポートされているツール、マルチモーダル入力、料金、制限事項。
- マネージド エージェントの構築: 独自の指示、スキル、データを使用して Antigravity を拡張します。
- 環境: ソース、ネットワーキング、ライフサイクル、リソースの上限。
- Interactions API: モデルとエージェントの基盤となる API。