AgentKit 2.0 が出たときの最初の感覚は「これ、マジで簡単になったな」でした。
1.x の時代、複数のエージェントを組み合わせるというのは、自分で OpenAI の API を直に叩いて、エージェント間のメッセージフローを自分で管理して、それこそ「本当にこれで動くのか?」というレベルの心理的負荷がありました。Antigravity 上で 3 つのマルチエージェント パターンを実装してみて、初めて「あ、AgentKit 2.0 はこの複雑さをかなり吸収してくれるんだ」と実感しました。
ここで扱うのはAgentKit 2.0 の設計思想から、実装パターン 3 選、本番運用で何が起きるのか、までを体系的にお伝えします。これを読み終わったら、今日のうちに自分の最初のマルチエージェントシステムを立ち上げられるはずです。
AgentKit 2.0 の設計思想と 1.x からの変化
まず、AgentKit 2.0 が何をフォーカスしたのかを理解することが大事です。
1.x は「エージェント基盤」でした。「Gemini を使って自律的に動くエージェントを作ってね」という宣言型の API で、ユーザーは LLM の挙動を信じるしかありませんでした。2.0 は違います。明示的な制御フロー を提供することに舵を切ったのです。
AgentKit 2.0 では、3 つの層を明確に分けます:
Agent — 1 つの目的を持つ独立した実行単位。「商品情報を検索する」「ユーザーの承認を取る」など、単一責任型
Workflow — Agent を組み合わせるレシピ。「まず調査、その結果を承認層に渡す」という流れを定義
Coordinator — Workflow 全体を監督します。複数の Workflow が並行走行していても安全に統合できる存在
この 3 層を理解した瞬間に、複雑なマルチエージェントシステムが「詳細なテスト仕様書」と同じくらい予測可能になります。
1.x との最大の違いは、ユーザーが明示的に制御をハンドル するのに対して、2.0 では システムが多くの制御を引き受ける ということです。
3 つの核となる抽象化の理解
AgentKit 2.0 の設計をマスターするには、このセクションが一番重要です。
Agent — 単一責任の実行単位
Agent は「1 つのことだけを非常に上手にやる」モジュールです。
import { Agent } from '@google-cloud/agentkit' ;
const researchAgent = new Agent ({
name: 'researcher' ,
systemPrompt: 'You are a product researcher. Find detailed information about the given product from web sources.' ,
tools: [ 'search' , 'summarize' ],
maxIterations: 5 ,
timeoutMs: 30000 ,
});
// 使い方
const result = await researchAgent. execute ({
input: '「Antigravity の 2026 年 4 月アップデート」について調査してください' ,
});
ここで大事なポイントが 3 つあります。
1. tools の明示的な指定
Agent が何ができるかを事前に宣言することで、LLM の「できもしないことを勝手にやろうとする」エラーが減ります。1.x では暗黙的に全 API を使えましたが、2.0 では「このエージェントは search と summarize だけ」と限定することで、コスト削減と予測可能性が両立します。
2. timeoutMs の設定
ブラウザ操作や外部 API 呼び出しを含む Agent は、30 秒程度が現実的です。長すぎるタイムアウトを設定すると、詰まったエージェントがいつまでも待機状態になり、全体の Workflow を巻き込みます。本番運用では、このタイムアウト値が最初のボトルネックになります。
3. maxIterations の設定
これは「LLM が自分の思考を何サイクル繰り返していいか」という制限です。無限ループ防止ですね。デフォルトは 10 ですが、複雑な思考が必要なエージェント(承認判定など)は 3〜5 に落とすのが安全です。
Workflow — 複数 Agent の協調レシピ
Workflow は Agent を「配列」で繋ぐのではなく、「有向グラフ」で繋ぎます。
import { Workflow, Edge } from '@google-cloud/agentkit' ;
const multiAgentWorkflow = new Workflow ({
name: 'product_review_workflow' ,
agents: {
research: researchAgent,
fact_check: factCheckAgent,
summarize: summarizeAgent,
},
edges: [
new Edge ( 'research' , 'fact_check' , ( output ) => output. length > 1000 ),
new Edge ( 'fact_check' , 'summarize' , () => true ),
],
});
const result = await multiAgentWorkflow. execute ({
input: { product: 'Antigravity IDE' },
});
ポイント:
条件分岐エッジ
new Edge の第 3 引数の関数で、前の Agent の出力に基づいて「次の Agent に進むか」を判定できます。例:research の結果が十分でなかったら fact_check をスキップ、という流れが可能です。
並列実行の非サポート
AgentKit 2.0 の Workflow は「現在のところ」線形です。複数 Agent が並列で走る場合は、後述の Coordinator を使います。直列設計のおかげで、デバッグがずっと容易です。
Coordinator — システム全体の監督
複数の Workflow を同時に走らせたり、Workflow の結果に基づいて新しい Workflow を起動したり、という「メタレベルの制御」を Coordinator が担当します。
import { Coordinator } from '@google-cloud/agentkit' ;
const coordinator = new Coordinator ({
workflows: {
review: multiAgentWorkflow,
approval: approvalWorkflow,
},
maxConcurrent: 3 ,
onConflict: 'halt' , // または 'delegate'
});
const results = await coordinator. executeAll ({
inputs: [
{ product: 'Antigravity' },
{ product: 'Cursor' },
{ product: 'VS Code' },
],
});
maxConcurrent
同時に走らせる Workflow 数。デフォルト 2 は、API rate limit や LLM の課金を考えると現実的です。本番では環境変数で管理します。
onConflict: 'halt' vs 'delegate'
複数の Workflow が同じリソース(例えば DB レコード)にアクセスしようとしたときの動作。halt は衝突を検出して停止(安全)、delegate は Coordinator が自動的に順序を決める(高速ですが複雑)。初期段階では halt を推奨します。
パターン 1: 並列調査エージェント
最初のパターンは、複数の「調査役」が同時に異なる情報源から情報を集め、最後に 1 つのエージェントが統合する形です。
import { Agent, Workflow, Coordinator } from '@google-cloud/agentkit' ;
// 3 つの調査エージェント
const webSearchAgent = new Agent ({
name: 'web_search_agent' ,
systemPrompt: 'Search for information using web sources only.' ,
tools: [ 'google_search' , 'summarize' ],
maxIterations: 4 ,
timeoutMs: 40000 ,
});
const githubAgent = new Agent ({
name: 'github_agent' ,
systemPrompt: 'Find information from GitHub repositories, issues, and discussions.' ,
tools: [ 'github_api' , 'code_analysis' ],
maxIterations: 3 ,
timeoutMs: 30000 ,
});
const docsAgent = new Agent ({
name: 'docs_agent' ,
systemPrompt: 'Extract relevant information from official documentation.' ,
tools: [ 'docs_fetch' , 'parse_markdown' ],
maxIterations: 3 ,
timeoutMs: 25000 ,
});
// 結果統合エージェント
const synthesisAgent = new Agent ({
name: 'synthesis_agent' ,
systemPrompt: `You are a senior analyst. You receive research from 3 sources:
- web_search_agent: findings from the web
- github_agent: findings from GitHub
- docs_agent: findings from official docs
Your job is to synthesize these into a single coherent report that clearly attributes each claim to its source.` ,
tools: [ 'format' , 'validate' ],
maxIterations: 5 ,
timeoutMs: 30000 ,
});
// Workflow で「調査 3 つ→統合」の流れを定義
const researchWorkflow = new Workflow ({
name: 'parallel_research_workflow' ,
agents: {
web: webSearchAgent,
github: githubAgent,
docs: docsAgent,
synthesis: synthesisAgent,
},
edges: [
// 調査エージェント 3 つは同時起動(が、現在の実装では順序保証なしで起動される)
// その後、synthesis エージェントが全結果を受け取る
new Edge ( 'web' , 'synthesis' , () => true ),
new Edge ( 'github' , 'synthesis' , () => true ),
new Edge ( 'docs' , 'synthesis' , () => true ),
],
});
const result = await researchWorkflow. execute ({
input: {
topic: 'Antigravity IDE の 2026 年ロードマップ' ,
context: 'リサーチはできるだけ最新の情報を集めてください' ,
},
});
console. log (result);
// 出力:
// {
// status: 'success',
// synthesis_result: {
// report: "Antigravity の...",
// sources: { web: [...], github: [...], docs: [...] }
// }
// }
このパターンの強み
情報源が明確に分離されているため、バグ追跡が容易
1 つの調査エージェントが詰まっても、他は進行し続ける(のが理想だが、現実には synthesis が全て完了を待つ)
結果の再現性が高い(同じプロンプト→同じ結果の傾向)
落とし穴
synthesis_agent が 3 つの調査結果を同時に受け取るには、事前に全結果を変数に格納しておく必要があります。AgentKit 2.0 にはパイプライン機構 がないため、手動で構築します。実装は後述の「デバッグとトレーシング」セクションで触れます。
パターン 2: 直列承認チェーン
次は「提案→確認→実行」という 3 段階の直列フロー。組織内での意思決定プロセスをモデル化します。
// 提案エージェント
const proposalAgent = new Agent ({
name: 'proposal_agent' ,
systemPrompt: `You are a proposal architect. Given a requirement, generate a concrete implementation plan.
Output must be valid JSON with fields: title, steps, estimated_hours, risk_level, alternatives.` ,
tools: [ 'plan' , 'estimate' ],
maxIterations: 5 ,
timeoutMs: 45000 ,
});
// 確認エージェント(人間が前に立つ)
const reviewerAgent = new Agent ({
name: 'reviewer_agent' ,
systemPrompt: `You are a technical reviewer. Evaluate the proposal from proposal_agent.
Check for:
1. Feasibility (can this be done?)
2. Timeline (is the estimate realistic?)
3. Risks (what could go wrong?)
Output: APPROVED or REJECTED with explanation.` ,
tools: [ 'assess_feasibility' , 'historical_data' ],
maxIterations: 3 ,
timeoutMs: 30000 ,
});
// 実行エージェント
const executorAgent = new Agent ({
name: 'executor_agent' ,
systemPrompt: `You are a project executor. You receive an APPROVED proposal.
Break it into actionable tasks, assign resources, set up monitoring.` ,
tools: [ 'task_create' , 'resource_allocate' , 'monitoring_setup' ],
maxIterations: 6 ,
timeoutMs: 60000 ,
});
// 承認チェーン Workflow
const approvalWorkflow = new Workflow ({
name: 'approval_chain' ,
agents: {
propose: proposalAgent,
review: reviewerAgent,
execute: executorAgent,
},
edges: [
// 条件分岐:review が APPROVED なら execute へ、そうでなければ終了
new Edge ( 'propose' , 'review' , () => true ),
new Edge ( 'review' , 'execute' , ( reviewOutput ) => {
return reviewOutput.decision === 'APPROVED' ;
}),
],
});
const approval = await approvalWorkflow. execute ({
input: {
requirement: 'Antigravity IDE に「コード品質分析」機能を追加する' ,
budget_hours: 80 ,
},
});
console. log (approval);
// 出力:
// {
// status: 'success',
// proposal: { title: '...', steps: [...], estimated_hours: 72 },
// review_decision: 'APPROVED',
// execution_plan: { tasks: [...], resources: [...] }
// }
このパターンの強み
承認判断が明示的に記録される
rejected の場合、自動的にフロー終了(無駄なリソース消費なし)
人間の judgment point を明確に設計できる
注意点
条件分岐の判定ロジック(reviewOutput.decision === 'APPROVED')は、review Agent の出力形式に依存します。JSON 出力が安定していない場合、パースエラーで全体が止まります。この対策は「品質チェック」セクションで述べます。
パターン 3: 階層型監督エージェント
最後のパターンは、1 つの「上位エージェント」が複数の「下位エージェント」を統括する形。特に複雑な問題を「サブ問題に分割→各サブ問題を下位エージェントに委譲→結果を統合」というアプローチです。
// 下位エージェント(専門家)
const architectAgent = new Agent ({
name: 'architect' ,
systemPrompt: 'You are a software architect. Design the system architecture for the given requirement.' ,
tools: [ 'design_pattern' , 'architecture_decision' ],
maxIterations: 4 ,
timeoutMs: 30000 ,
});
const securityAgent = new Agent ({
name: 'security_expert' ,
systemPrompt: 'You are a security expert. Identify potential security risks and recommend mitigations.' ,
tools: [ 'threat_analysis' , 'security_best_practices' ],
maxIterations: 4 ,
timeoutMs: 30000 ,
});
const performanceAgent = new Agent ({
name: 'performance_expert' ,
systemPrompt: 'You are a performance engineer. Analyze the architecture and identify optimization opportunities.' ,
tools: [ 'profiling' , 'benchmarking' ],
maxIterations: 4 ,
timeoutMs: 30000 ,
});
// 上位エージェント(監督者)
const supervisorAgent = new Agent ({
name: 'supervisor' ,
systemPrompt: `You are a technical director supervising 3 specialists:
- architect: handles system design
- security_expert: handles security
- performance_expert: handles performance
Given a requirement, delegate tasks to each specialist, collect their feedback, and produce a final integrated decision.` ,
tools: [ 'delegate_task' , 'integrate_feedback' , 'decision_make' ],
maxIterations: 8 ,
timeoutMs: 60000 ,
});
// 階層型 Workflow
const hierarchicalWorkflow = new Workflow ({
name: 'hierarchical_review' ,
agents: {
supervisor: supervisorAgent,
architect: architectAgent,
security: securityAgent,
performance: performanceAgent,
},
edges: [
// supervisor が最初に起動、その結果を 3 つの下位エージェントに委譲
new Edge ( 'supervisor' , 'architect' , () => true ),
new Edge ( 'supervisor' , 'security' , () => true ),
new Edge ( 'supervisor' , 'performance' , () => true ),
],
});
const result = await hierarchicalWorkflow. execute ({
input: {
requirement: 'Antigravity 用のローカル LLM統合プラグインを開発する' ,
constraints: { budget_days: 10 , team_size: 2 },
},
});
console. log (result);
このパターンが活躍する場面
大規模フィーチャー決定(建築判断が必要)
セキュリティ監査が必須なシステム
パフォーマンスが重要度の高いコンポーネント
実装の落とし穴
supervisor が 3 つの specialist に委譲した後、結果を集約するロジックが AgentKit 2.0 の範囲だけでは完全に自動化できません。手作業で「各 specialist の出力を supervisor の次のステップに渡す」という処理が必要になります。これが複雑さの主な原因です。
本番運用で起きる障害と対策
ここからが、公式ドキュメントには書かれていない「実戦知」です。
障害 1: タイムアウトの多段階化
実装当初は Agent ごとに固定のタイムアウトを設定します。でも本番では、複数の Agent が走っているため、「全体の Workflow はまだ完了していないのに、特定の Agent だけタイムアウト」という局面が頻出します。
// ❌ 悪い例:固定タイムアウト
const agent = new Agent ({
timeoutMs: 30000 , // すべての実行で 30秒
});
// ✅ 良い例:適応的なタイムアウト
class AdaptiveAgent {
private baseTimeoutMs = 30000 ;
private currentWorkflowStartTime = 0 ;
async execute ( input : any , workflowDeadlineMs : number ) {
const elapsedMs = Date. now () - this .currentWorkflowStartTime;
const remainingMs = workflowDeadlineMs - elapsedMs;
const timeoutMs = Math. min ( this .baseTimeoutMs, Math. max (remainingMs - 5000 , 5000 ));
return agent. execute (input, { timeoutMs });
}
}
実践的には、Workflow 全体に 120 秒のハードデッドライン、各 Agent は平均 30 秒だが最後の Agent は余った時間を使える、という設計がおすすめです。
障害 2: 無限ループ検出の自動化
Agent が「これで十分か?」と自問し続けて、maxIterations に到達するケースがあります。特に複雑な判定(例:「この結果は信頼できるか?」)を求めると起きやすい。
// ❌ 危険:判定が曖昧で、いつ終わるか不明
const judgmentAgent = new Agent ({
systemPrompt: 'Determine if the information is reliable.' ,
maxIterations: 10 , // デフォルトだと 10 回まで思考
});
// ✅ 安全:判定が明確で、終了条件がある
const judgmentAgent = new Agent ({
systemPrompt: `Determine if the information is reliable.
Output ONLY valid JSON:
{
"is_reliable": true | false,
"confidence": 0.0 to 1.0,
"reasoning": "..."
}
You MUST output JSON in exactly this format. Do not think further once JSON is output.` ,
maxIterations: 3 , // 複雑な判定は 3 回あれば十分
});
ポイントは 出力形式を JSON に限定 することで、Agent が「思考を終わらせるべきタイミング」を明確にすることです。
障害 3: API キーと rate limit の枯渇
複数 Agent が同時に動くと、API 呼び出しが爆発的に増えます。特に Google Search API や Gemini API の quota を超える。
import { Agent, RateLimiter } from '@google-cloud/agentkit' ;
// グローバル rate limiter
const rateLimiter = new RateLimiter ({
maxRequests: 100 ,
windowMs: 60000 , // 1 分間に 100 リクエストまで
});
const agent = new Agent ({
name: 'search_agent' ,
rateLimiter, // 全 API 呼び出しをこの limiter で統制
tools: [ 'google_search' ],
});
本番では、API キーを環境変数化 し、quota ごとに複数キーを持つ構成が必須です。
障害 4: Agent の出力が JSON として parse できない
LLM は「JSON を出力する」と指示されても、時々失敗します。
// ✅ Fallback 付きパース
function safeJsonParse ( output : string ) {
try {
return JSON . parse (output);
} catch (e) {
// JSON 風のテキストを抽出
const match = output. match ( / \{ [\s\S] * \} / );
if (match) {
try {
return JSON . parse (match[ 0 ]);
} catch (e2) {
// 最終手段:出力をそのまま返す(後続で適切にハンドル)
return { raw_output: output, parse_error: true };
}
}
throw new Error ( 'Failed to parse agent output' );
}
}
コスト管理の実装テクニック
マルチエージェントシステムは、シングルエージェントより 5〜10 倍 の API 呼び出しが発生します。コスト爆発は本番での最大の脅威です。
// コスト追跡
interface CostTracker {
completionTokens : number ;
promptTokens : number ;
costUsd : number ;
estimatedCostUsd : number ; // 現在のレート×累計
}
const tracker : CostTracker = { completionTokens: 0 , promptTokens: 0 , costUsd: 0 , estimatedCostUsd: 0 };
const coordinator = new Coordinator ({
workflows: { /* ... */ },
onAgentComplete : ( result ) => {
const { tokens } = result.usage;
tracker.completionTokens += tokens.completion;
tracker.promptTokens += tokens.prompt;
// Gemini 1.5 Pro: $7.50/M prompts, $30/M completions
const costUsd = (tokens.prompt * 7.50 + tokens.completion * 30 ) / 1_000_000 ;
tracker.costUsd += costUsd;
tracker.estimatedCostUsd = tracker.costUsd * 1.2 ; // 20% buffer
// コスト上限に達したら停止
if (tracker.estimatedCostUsd > 100 ) {
console. warn ( 'Cost limit approaching, halting...' );
return { action: 'halt' };
}
},
});
本番では、1 リクエスト当たりの予算上限 を設定し、超過したら自動ロールバックする仕組みが必須です。
デバッグとトレーシング
マルチエージェントシステムのデバッグは、従来の単一プロセスのそれとは全く異なります。
// 完全なイベントログ
const debuggingWorkflow = new Workflow ({
/* ... */
onEdgeTransition : ( from , to , data ) => {
console. log ( `[TRACE] ${ from } -> ${ to }` );
console. log ( `[OUTPUT] ${ JSON . stringify ( data , null , 2 ) }` );
},
onAgentStart : ( agentName , input ) => {
console. log ( `[AGENT START] ${ agentName } at ${ new Date (). toISOString () }` );
console. log ( `[INPUT] ${ JSON . stringify ( input ) }` );
},
onAgentError : ( agentName , error ) => {
console. error ( `[AGENT ERROR] ${ agentName }` );
console. error (error.stack);
},
});
const result = await debuggingWorkflow. execute (input);
さらに重要な対策:
タイムシリーズデータの記録
各 Agent の開始時刻・終了時刻・消費トークン数を記録し、時間の経過に伴うボトルネック分析を可能にします。
const traces : Array <{
agent : string ;
startTime : number ;
endTime : number ;
durationMs : number ;
tokensUsed : number ;
}> = [];
coordinator. onAgentComplete = ( result ) => {
traces. push ({
agent: result.agent,
startTime: result.startTime,
endTime: result.endTime,
durationMs: result.endTime - result.startTime,
tokensUsed: result.usage.tokens.total,
});
};
// 実行後の分析
function analyzeBottleneck () {
const totalMs = Math. max ( ... traces. map ( t => t.endTime)) - Math. min ( ... traces. map ( t => t.startTime));
const parallelizableMs = traces. reduce (( acc , t ) => acc + t.durationMs, 0 ) - totalMs;
console. log ( `Total: ${ totalMs }ms, Parallelizable: ${ parallelizableMs }ms` );
}
Antigravity 環境ならではの工夫
Antigravity 上でマルチエージェントを実装する際の、特有の最適化が 2 つあります。
1. Manager Surface での並列ビュー活用
複数の Workflow を同時に Manager Surface で表示し、各 Agent の進行状況をリアルタイム監視できます。これは Cursor や VS Code では得られない視認性です。
// Antigravity 統合ログ
coordinator. onAgentStart = ( agent ) => {
// Manager Surface に「〇〇 Agent が起動」と表示
console. log ( `[🚀 AGENT START] ${ agent } running on Antigravity Manager...` );
};
2. Browser Agents との相互利用
Antigravity の Browser Agents(API ドキュメント検索、GitHub Actions の実行確認等)と AgentKit 2.0 の Workflow を組み合わせると、完全自動化が実現します。
const mixedWorkflow = new Workflow ({
agents: {
research: researchAgent, // AgentKit Agent
browser_check: new BrowserAgent ({ // Antigravity 統組込みの Browser Agent
task: 'Check GitHub Actions deployment status' ,
}),
summary: summaryAgent,
},
edges: [
new Edge ( 'research' , 'browser_check' ),
new Edge ( 'browser_check' , 'summary' ),
],
});
個人開発者の視点から(実体験メモ)
次のステップ
AgentKit 2.0 をマスターしたら、次に検討する価値がある領域が 2 つあります。
1. Memory & Persistence の統合
複数の Workflow が共通のナレッジベース(例:会社の設計ドキュメント DB)にアクセスする必要がある場合、エージェント間で「学習」を共有する仕組みが要ります。これは 2.1 では正式実装されると予想します。
2. Human-in-the-Loop の拡張
現在は「提案→承認」の 2 段階ですが、「進行中に人間が介入」「特定の判断を人間に委譲」という柔軟なフローがあると、信頼度が劇的に上がります。
マルチエージェントシステムは、ここから先、個人開発者の生産性を大きく左右するテクノロジーになります。今のうちに基本を固めておくことで、2026 年後半に「本当に便利なシステム」を自分のプロダクトに組み込めるはずです。
ぜひ、この 3 つのパターンで試してみて、自分の現場に合わせた応用を考えてみてください。