如何使用 Google Antigravity 构建持久可靠的智能体系统:从指令到循环
原题How to Build Durable Agentic Systems with Google Antigravity: From Instructions to Loops
读前速览
本文介绍了构建持久可靠的智能体系统的系统化方法:将工程工作划分为五个层级,并建立持久状态、验证关卡、评估、停止条件和标准化技能等核心护栏。
智能体工作的五层框架
工作可从简单问题(无需智能体)一路划分到完整系统(需要 AGENTS.md、技能、辅助组件和验证关卡)。层级越高,所需的智能体方案和护栏也越复杂。
验证循环的数学依据
顺序智能体链的成功率会呈指数级下降(p^N)。但通过单次重试验证循环,以准确率为 95% 的模型为例,可在每个步骤发现并纠正错误,使 20 步链路的端到端成功率维持在 95%。
持久可靠系统的五项关键护栏
持久状态(Git 检查点)、验证关卡(确定性测试)、评估(用于语义判断)、停止条件(轮次/Token 上限)以及标准化技能和指令,共同构成可靠智能体自动化的基础,使系统能够在需要时进行调试和干预。
平台内置基础功能与自定义循环
对于大多数使用场景,Google Antigravity 提供了内置的 /goal 和 /grill-me 命令;而在复杂的多智能体环境中,自定义循环更灵活。文章通过无状态的 bash 实现和一个包含预算控制监督验证的 Python SDK 示例,展示了这两种做法。
完整摘要
本文探讨了软件工程中智能体循环的演进,说明开发方式如何从简单的提示词工程转向复杂的系统设计。文章提出一个五层框架,用于划分工作:问题、任务、功能/用户故事、项目/史诗和系统。文章聚焦的核心挑战是,智能体链中的成功率会随着步骤增加而呈指数级下降;作者通过验证循环和单次重试纠偏来应对这一问题。数学分析表明,对于 20 步链路,准确率为 95% 的模型配合有效率为 95% 的验证关卡,成功率可达到 95%;若不进行此类干预,成功率则只有 36%。随后,文章详细介绍了持久可靠系统的五项关键护栏:持久状态(由 Git 支持的检查点)、验证关卡(自动化测试套件)、评估(用于非确定性检查)、停止条件(轮次和成本上限),以及标准化的技能和指令。文章还对比了 Google Antigravity 的 /goal 和 /grill-me 等平台内置基础功能与自定义循环架构,并提供了无状态的 bash 示例,以及使用 Google Antigravity SDK 的详细 Python 实现,展示如何根据任务类型路由模型,并通过预算控制的监督验证机制进行检查。
目录 · 11 节
过去几个月里,我看到关于智能体循环的讨论愈发热烈。但对我来说,现实更简单:提示工程已从单项任务转向系统设计,而在软件工程中,我当前的主要瓶颈是模型周边的运行框架(而非模型本身)。本文将向你展示如何构建并验证这些运行框架,让你在 Google Antigravity 中从单轮指令迈向持久可靠的智能体循环。I watched the discussion on agentic loops grow louder over the past few months. But for me, the reality is simpler: prompt engineering has shifted from individual tasks to systems design, and the harness around the model (not the model itself) is now my primary constraint in software engineering. In this article, I'll show you how to build and verify those harnesses so you can move from single-turn instructions to durable agentic loops in Google Antigravity.
并非所有任务都同等重要。Not all tasks are equal
我们可以将交给代理的工作分为五个不同层级,从快速提问到敏捷任务、用户故事、史诗级任务,直至持续运行的系统:You can categorize the work that we give to our agents into five distinct tiers, scaling from a quick question up through Agile tasks, stories, and epics to a continuous system:
- 一个简单的问题:这不需要智能体,助手就能回答。
A simple question: This does not require an agent; an assistant can answer it.
- 一项任务/想法:这是一个可以通过单条提示词零样本完成的任务。使用 Google AI Studio,快速将想法转化为功能原型。
A task / idea: This is one where a single prompt can zero-shot it. Use Google AI Studio to quickly transform ideas to functional prototypes.
- 一个应用 / 更大型的功能 / 一项需求:在 AI 出现之前,这类工作需要每周规划,并拆分成多个子任务。执行时使用循环,并采用功能完备的智能体,例如 Google Antigravity。在这一层级,你的引导也会前移:在任何循环运行之前,就先敲定规格说明、计划和可执行测试。
An app / larger feature / story: The kind of work that required weekly planning and splitting into subtasks before AI. Use loops for execution and full-featured agents, like Google Antigravity. This tier is also where your steering moves upstream: You lock in the spec, the plan, and the executable tests before any loop runs.
- 项目/史诗:几个功能连接起来后,构成一个连贯的故事。循环在这里也可能有助于规划。这也是需要超越简单回合制提示的地方。
A project / epic: A few features that make a cohesive story when connected. Loops here might help with planning too. This is also where one needs to go beyond simple turn-based prompting.
- A system:所有项目和任务的总览。在这里,你可以编写 AGENTS.md 项目指令、创建技能、设置 sidecar、接入验证关卡,并配置仪表盘,以便随时掌握所有事项。这个层级的循环带来的影响最大,风险也相应更高。
A system: An overview of all of the projects and tasks. This is where you write
AGENTS.mdproject instructions, create skills, set up sidecars, wire up verification gates, and configure an instrument cluster to keep themselves on top of everything. Loops at this level make the biggest difference and come with similarly higher risks.
图 1:工程工作的五个层级,从单次提示到经过验证的智能体循环。Figure 1: Five tiers of engineering work, from single prompts to verified agentic loops.
为什么要循环?Why the loop?
软件开发的基准正在发生转变。这种转变体现了人性的一条基本规律:我们追求尽可能高的杠杆效应,从手动劳动转向委派,最终走向编排。由于注意力成了新的瓶颈,任何能让工作以更少中断持续推进的事物,都可能推动我们朝正确的方向迈进一步。到 2026 年初,针对开源项目的实证研究估计,在 GitHub 上超过 128,000 个活跃代码仓库中,已有 22% 至 29% 采用了编码智能体。如今熟练运用智能体工作流的人,能够借助更高的杠杆效应,提升整个团队的生产力。然而,这也加重了所有承担系统层面责任的人的认知负担。The baseline of software development is shifting. This shift represents a basic law of human nature: we seek the highest leverage possible, moving from manual labor to delegation, and finally to orchestration. Because attention is the new bottleneck, anything that lets the work continue with less interruption could make a move in the right direction. By early 2026, empirical research of open-source projects estimated that coding agent adoption had reached between 22% and 29% of more than 128,000 active repositories on GitHub. Those who become proficient in agentic workflows now operate with a level of leverage that elevates their entire team's productivity. However, it also increases the cognitive load on everyone who is taking responsibility at the systemic level.
为了理解这一转变,我们来追溯循环的技术演进脉络,并设定一些总体预期。To understand this shift, let's trace the technical lineage of loops and set some high level expectations.
学术基础Academic foundations
学术界的起点是 Yao 等人于 2022 年 10 月发表的 ReAct 论文,该论文将推理轨迹与工具调用交织在一起。ReAct 通过先推理再行动,在 ALFWorld 上的表现比强化学习基线高出 34%,在 WebShop 上高出 10%,这也体现了人类的本性:把计划说出来时,我们表现得更好。随后,2023 年初出现了 AutoGPT,并筹集了数百万美元的风险投资。ReAct 的早期版本常常陷入无限循环,但它证明开发者渴望无需人工干预的自动化,也凸显了对结构性防护措施的需求。The academic seed was Yao et al.'s ReAct paper in October 2022, which interleaved reasoning traces with tool calls. ReAct beat reinforcement learning baselines by 34% on ALFWorld and 10% on WebShop by reasoning before acting, mirroring human nature: we perform better when verbalizing plans. Then came AutoGPT in early 2023, raising millions in venture funding. While early iterations of ReAct frequently spun in infinite loops, it proved developers wanted hands-off automation, highlighting the need for structural guardrails.
无状态实验Stateless experimentation
2025 年年中,开发者运行无状态的 Bash 循环,将提示传入命令行代理,并在每次循环时重置上下文文件。重置上下文可以避免认知膨胀,也承认人类的记忆限制同样适用于模型。无状态 Bash 循环之所以奏效,只是因为持久状态保存在模型之外:Git 历史记录、进度文件和测试套件中。经过数月的自动运行,它成功构建出了自举编译器。到 2026 年春季,主流工具环境吸收了这一模式,推出了像 /goal 这样的原生命令,让代理能够在无人值守的循环中运行。In mid-2025, developers ran stateless bash loops that piped prompts into command-line agents and reset context files on every tick. Resetting context prevents cognitive bloat and acknowledges that human memory limits also apply to models. Stateless bash loops worked only because the durable state lived outside the model: in Git history, in progress files, and in the test suite. It successfully built self-hosting compilers over months of automated runs. By spring 2026, major tool environments absorbed this pattern, shipping native commands like /goal to let agents run unattended loops.
自主性的数学原理The mathematics of autonomy
考虑一个理论示例:Consider a theoretical example:
如果你让智能体以扁平的顺序链连续完成多项任务,它的成功率会呈指数级下降。当每个独立步骤都是一个相互独立的概率事件时,包含 N 个步骤的序列,其累计成功率为 p^N。比如,如果你用准确率为 p = 0.95 的模型执行一项需要连续修改 20 个文件的任务,那么成功率只有 36%。如果没有你的结构性干预,它们几乎必然会失败。If you put your agent in a flat sequential chain to complete multiple tasks in a row, the agent's success rate degrades exponentially. When each of its individual steps operates as an independent probability event, a sequence of N steps has a cumulative success rate of pN. For instance, if you run a task requiring 20 consecutive file modifications with a model that has p = 0.95 accuracy, then you face a success rate of only 36%. Without your structural interventions, they will fail almost certainly.
0.95 是真实数字吗?把它视为每一步可靠性的示例,而不是基准测试结果。即便是前沿模型,也只有在经过验证的执行框架中运行,才能可靠地完成多步任务。如果你自己的每步可靠性更接近 75%,那么到第 10 步时,未经验证的链式流程成功率已经低于 6%。围绕模型的验证机制决定了可靠性的上限,这就是闭环如此重要的原因。Is 0.95 a real number? Treat it as an illustrative per-step reliability, not as a benchmark result. Even a frontier model reaches reliable multi-step outcomes only when it runs inside a verified harness. If your own per-step reliability sits closer to 75%, then the raw chain is already under 6% by step 10. The verification around the model sets the ceiling, which is why the loop matters.
这就是你需要评估循环的原因。验证关卡不应强迫智能体无限重试(这会导致无休止的循环失控)。相反,它应该准确指出错误发生的位置,并允许模型仅针对该错误重试一次以将其修复。如果智能体的基础准确率为 95%,而评估循环有 95% 的概率能在这唯一一次重试中发现并修复错误,那么单步成功概率就会提升至 0.95 + (0.05 × 0.95) = 99.75%。This is why you need evaluation loops. A verification gate should not force your agent to retry indefinitely (which causes infinite spinning runaways). Instead, it should pinpoint where the error occurred and allow the model exactly one targeted retry to fix it. If your agent has a 95% base accuracy, and your evaluation loop has a 95% chance of spotting and fixing the error on that single retry, the effective step success probability rises to 0.95 + (0.05 x 0.95) = 99.75%.
这种计算假设检查独立于工作模型,因此把关检查必须来自外部。编译器、测试套件和代码检查工具可以免费提供这种保障;行为评估则能让你在几秒内对具体的工具调用和中间操作进行断言,而不必等待完整的端到端基准测试。对于确定性测试无法做出的语义判断,我会搭配不同系列的模型,让审查模型不至于也有工作模型的盲点。That arithmetic assumes the check is independent of the worker, so the gate has to be an outside check. Compilers, test suites, and linters give you that for free, and behavioral evaluations let you assert on discrete tool calls and intermediate actions in seconds instead of waiting on a full end-to-end benchmark. For semantic judgments that a deterministic test cannot make, I pair models from different families so the reviewer does not share the worker's blind spot.
即使修复失败,只要能以 95% 的准确率发现错误,你就可以介入并手动重新校准系统,同时保持子代理 99.75% 的准确率,且只需承担人工介入的成本。Even if fixing fails, just spotting the error with a 95% accuracy, lets you jump in and manually realign the system while keeping the same 99.75% subagent accuracy and only paying the cost of human-in-the-loop intervention.
下表展示了不同链长度下的完成概率,并比较了原始模型与这种单次重试纠正拓扑:The table below shows the probability of completion across different chain lengths, comparing raw models to this single-retry course-correction topology:
|
Chain Length |
95% Accuracy |
95% x 95% Loop |
|
3 Steps |
86% |
99% |
|
5 Steps |
77% |
99% |
|
10 Steps |
60% |
98% |
|
15 Steps |
46% |
96% |
|
20 Steps |
36% |
95% |
|
30 Steps |
21% |
93% |
|
50 Steps |
8% |
88% |
那上下文膨胀的问题呢?What about context bloat?
如果链条中的每一步都增加约 1% 的上下文 token,那么在需要压缩之前,链条长度不会超过 50 步。对于这类独立运行的代理,如果基础准确率达到 95%,并且我们关心的每个维度都能以 95% 的准确率进行评估(并据此调整),就能保持较高的成功率。如果你能建立一种可扩展的问题分而治之方法,就可以运用类似的原则来驱动子代理。正如我们所见,在 20 步的情况下,95% 的准确率配合一次重试的纠错循环,可以实现 95% 的端到端成功率(前提是纠错过程本身不超过 20 步的软性上限),同时将上下文规模控制在合理范围内。请注意,纠错过程并未明确要求由 AI 或人来执行,而是需要能够产出准确且可验证的结果。If each step in a chain adds approximately 1% of context in tokens, you end up with a chain that is not much longer than 50 steps before we require compression. A 95% base accuracy that can be evaluated (and course corrected with 95% accuracy for each dimension that we care about) should keep you at good success rates for such individual running agents. If you establish a scalable way to divide and conquer problems, you can apply similar principles to drive your subagents. As we can see, at 20 steps, a 95% accuracy paired with a single-retry corrective loop yields a 95% end-to-end success rate (assuming the correction itself stays under our 20 steps soft limit) while keeping context size reasonable. Note that there is no explicit requirement for the correction to be AI or human driven, but rather it needs to produce accurate and verifiable results.
在这里,你需要将问题拆分为若干任务,每项任务只需少量步骤即可完成。如果问题较为复杂,仍然可以处理,但必须将其拆分为更小的子问题,依此类推。以我们的示例为例,这意味着为每个层级代理、任务和轨迹分配最多 20 个步骤,并为下一级监督代理再分配 20 个步骤,以整合各方贡献。为防止偏离,应在所有子代理和监督层级分别进行评估,并制定最终验收标准。This is where you divide problems into tasks that require a small number of steps each. If a problem is more complex, it remains approachable, but it must be divided into smaller subproblems, and so on. For our example, this means allocating up to 20 steps for each level agent, task, and trajectory and another 20 steps for the next level supervisory agent to consolidate contributions. To prevent drift, establish separate evaluations at all subagent and supervisory levels with a final acceptance criteria.
最后,在更高层级运行自动化之前,你必须对每个层级至少评估一次这些指标,以确认它们衡量的是正确的目标。这些只是粗略估算,但能帮助你快速判断是否应该拆分问题、重复某个步骤,还是提交结果并继续下一步。Lastly, you must evaluate these metrics at least once for each level to verify that they measure the right target before running automation at a higher level. These are general estimations, but help you quickly decide whether you should split a problem, repeat a step, or commit results and move on.
在实际应用中,你的数值会有所不同,但缩放规律会类似。In practice, your numbers will look different, but the scaling laws will be similar.
如何构建一个持久耐用的系统How to build a durable system
最初让我感到棘手的问题,如今已成为我最主要的探索动力之一:当我们对这门技艺本身仍有许多需要学习时,该如何构建自动化?我有几个想法。What started as a source of friction has now become one of my primary driving curiosities: how do we build automation when we still have a lot to learn about the craft itself? I have a few ideas.
要构建一个不会脱缰失控的循环,你必须设立核心护栏,以确保准确性,并让我们能在必要时进行调试和干预。具体来说,以下是我确定的几个支柱:To build a loop that does not run off a cliff, you must establish core guardrails that will keep accuracy high and will allow us to debug and intervene whenever necessary. Specifically, these are the pillars I identified:
- 持久化状态:基于 Git 的检查点可确保代理在崩溃后继续工作。
Durable state: Git-backed checkpoints ensure that your agent can resume work after a crash.
- 验证关卡:自动化测试套件和编译器会以确定的方式检查变更是否正确。在开始实现之前,提前编写验收标准和测试,并在项目说明中明确规定一条规则:代理不能通过删除或削弱测试来通过关卡。如果实施得当,关卡的准确率可以超过 95%。不过,你仍应留意可能遗漏的边界情况。尤其是当某项功能的验证、评估或人工校验成功率彼此不一致时。
Verification gates: Automated test suites and compilers deterministically check that the changes are correct. Write the acceptance criteria and the tests upstream, before implementation starts, and make one rule explicit in your project instructions: an agent cannot pass a gate by deleting or weakening a test. When done properly, gates can have >95% accuracy. However, you should be on the lookout for edge cases you might have forgotten about. Especially if verification, evaluation, or manual validation success rates diverge for any of your features.
- 评测:对于任何无法以确定性方式验证但又很重要的事项,都应设置评估或基准测试,以便日后检查其准确性。尽量将其设计成只需回答简单的“是”或“否”,并确保准确率较高,理想情况下超过 95%。如果结果表明存在困惑或意外失败,你可能需要将评判标准拆分得更简单一些。
Evals: Anything that cannot be deterministically verified but is important should have an evaluation or benchmark which you can later inspect for accuracy. Try to write them in a way that will keep answers to a simple yes or no and accuracy high, ideally over 95%. If you're getting results that point to confusion or unexpected failures, you probably need to split the criteria into simpler ones.
- 停止条件:轮次限制(如上所见,20 似乎是最佳值)以及 token 或美元成本上限,能在 API 预算失控前停止运行。
Halt conditions: Turn limits (as we saw above, 20 seems to be the sweet spot) and token or dollar cost ceilings stop runs before API budgets get out of control.
- 标准化技能和指令:可复用的实用工具,采用 SKILL.md 格式编写文档,最好与代码和权威来源参考资料打包在一起。将它们与 AGENTS.md 配合使用,后者用于存放每次运行时都要加载的项目不变量。技能会一直保留在磁盘上,直到其描述与任务匹配,因此不会占用 20 步上下文窗口。
Standardized skills and instructions: Reusable utilities, documented in the
SKILL.mdformat, preferably bundled with code and source of truth references. Pair them with anAGENTS.mdthat holds the project invariants every run load. Skills stay on disk until their description matches the task, so they do not eat into the 20-step context window.
这些支柱指的不是某个模型版本,而是一个模型家族。单个模型的领先地位只能持续几周。每次发布后得以留存的资产,是运行框架及其流程:每次运行都会加载的 AGENTS.md 指令、仅在相关时才加载的 SKILL.md 模块、全天候运行这一循环的隔离式 Cloud Run 沙箱、确定性检查,以及跨模型评审。运行失败或你不得不介入时,除了修改代码,也要改进运行框架:新增一项测试、在 AGENTS.md 中添加一行,或在技能说明中记下一条。即使下一次运行从零开始构建上下文,它也能继承这次经验。These pillars don't name a model version, but rather a model family. Individual model leads last only weeks. The asset that survives each release is the harness and its processes: the AGENTS.md instructions every run loads, the SKILL.md modules loaded only when relevant, the isolated Cloud Run sandbox where the loop runs around the clock, the deterministic checks, and the cross-model review. When a run fails or you have to intervene, patch your harness along with the code: a new test, a line in AGENTS.md, a note in the skill. The next run inherits the lesson even though its context starts from zero.
平台内置系统Platform built-in systems
Google Antigravity 等平台已将这些模式(/grill-me 和 /goal)固化为内置原语,对于大多数简单用例而言,工作重心由自定义脚本转向了平台功能。无论你使用 Google Antigravity 2.0、agy CLI,还是 VS Code、JetBrains 或 Cursor 中的 Antigravity,这些 harness 文件都会随代码仓库一同迁移。我建议你试试看。不过请记得留意轨迹长度,并观察模型是否出现困惑。Platforms like Google Antigravity have codified these patterns (/grill-me and /goal) into built-in primitives, shifting the work from custom scripts to platform capabilities for most straightforward use cases. The same harness files travel with the repository whether you run Google Antigravity 2.0, the agy CLI, or Antigravity inside VS Code, JetBrains, or Cursor. I would encourage you to give these a try. Do remember, however, to keep an eye on trajectory lengths and look for model confusion.
在协调需要在完成前进行大量验证和测量的多轮任务时,我自己经常依赖 Google Antigravity 2.0 中的 /goal 原语。为了让这一执行过程有据可依,请先使用 /grill-me 命令进行交互式访谈,敲定设计约束、不变量以及判定成功的测试,然后再运行 /goal 循环。I myself frequently rely on the /goal primitives in Google Antigravity 2.0 when coordinating multi-turn tasks that require extensive validation and measurements before completion. To anchor this execution, use the /grill-me command for an interactive interview to lock in design constraints, invariants, and the tests that decide success before running /goal loops.
为这篇技术文章构建指标并进行编辑,只是我运用这些执行循环的一个例子。Constructing the metrics for this technical article and then editing it is just one example of how I use these execution loops.
将 /goal 与 /grill-me 配合使用,可以建立高效的结对编程模式:先就意图达成一致,再自主执行。By pairing /goal with /grill-me, you can establish an effective pair-programming dynamic: alignment on intent, followed by autonomy in execution.
自定义 DIY 循环Custom DIY loops
要理解循环的演进,请比较两种不同的 DIY 智能体循环架构:To understand the evolution of loops, compare two distinct architectures for DIY agentic loops:
无状态五行代码Stateless five-liner
Geoffrey Huntley 的“Ralph”循环是无状态架构的典型案例。下面是一个最简单的可运行 Antigravity CLI 循环:Geoffrey Huntley's "Ralph" loop is a prime example of stateless architecture. Here's the simplest working version of an Antigravity CLI loop:
limit=20
for ((i=1; i<=limit; i++)); do
agy -p "$(cat prompt.md)" --sandbox || break
./commit-and-test && break
done
虽然简单,但对于多文件协作而言,无状态循环并不可靠,因为重置上下文会丢弃思考日志。While simple, the stateless loop is fragile for multi-file coordination because resetting context discards thinking logs.
一个优秀的智能体技能可以通过指导模型将相关进展报告输出为类似 Wiki 的 Markdown 文件,并通过查看 Git 日志来跟踪变更,从而解决这一限制的大部分问题。A good agent skill could fix much of this limitation by instructing the model to output relevant progress reports in wiki-like markdown files and track changes by looking at git logs.
不过,这种复杂性也给规模更大的多智能体环境带来了开发挑战,而自定义循环似乎有望解决这些问题。Still, this complexity has led to developer challenges in larger multi-agent environments, for which custom loops seem to hold the promise.
那么,如果你想深入探索呢?So what if you want to go to the deep end?
如果你想从头编写一个自定义循环,下面是一个使用 Google Antigravity SDK 的实用 Python 实现。具体来说,这个循环会执行以下操作:If you want to write a custom loop from scratch, here is a practical Python implementation using the Google Antigravity SDK. Specifically, this loop does the following actions:
- 初始化一个监管者会话。
Initializes a supervisor session.
- 执行一项任务。
Executes a task.
- 使用真实测试套件验证输出。
Verifies the output with the real test suite.
- 将实际失败输出反馈回来,进行一次精准重试。
Feeds the actual failure output back for exactly one targeted retry.
- 严格执行调用次数和令牌预算限制。
Enforces strict call and token budgets.
其中的任务并非都同等重要,所用模型也不必相同。主管和实施者使用 Gemini 4 Carbon,因为编排、架构设计和复杂修复需要前沿推理能力;代码库搜索交给 Gemini 4 Hydrogen;验证则由确定性脚本完成,完全不消耗 token。《AI Tokenomics 指南》介绍了这种拆分方式的预算考量。这远非可直接用于生产环境的解决方案,而是一个实验性的起点,你可以根据自己的需求进行调整:Not every task inside it is equal, so neither is the model. The supervisor and the implementer run on Gemini 4 Carbon because orchestration, architecture, and the complex fixes need frontier reasoning, codebase search goes to Gemini 4 Hydrogen, and verification goes to a deterministic script that costs no tokens at all. The Guide to AI Tokenomics covers the budgeting side of this split. Far from being a production-ready solution, this is an experimental starting point that you can adapt to suit your individual needs:
图 2:Google Antigravity SDK 中的预算约束型监督验证循环。Figure 2: Budgeted supervisory verification loop in the Google Antigravity SDK.
import asyncio
import subprocess
from google.antigravity import Agent, LocalAgentConfig, types
from google.antigravity.hooks import policy
def verify_output(workspace_path: str) -> tuple[bool, str]:
"""Verification gate: run the test suite and keep the real failure output."""
result = subprocess.run(
["go", "test", "./..."], cwd=workspace_path, capture_output=True, text=True
)
output = (result.stdout + "\n" + result.stderr).strip()
return result.returncode == 0, output
# 1. Define subagents with scoped tools and a model that fits each job
researcher = types.SubagentConfig(
name="researcher",
description="Searches the codebase and summarizes implementation paths.",
system_instructions=(
"You are a research subagent. Analyze the codebase, find implementation "
"paths, and report back without modifying any files."
),
model="gemini-4-hydrogen",
capabilities=types.SubagentCapabilities(
enabled_tools=[
types.BuiltinTools.VIEW_FILE,
types.BuiltinTools.SEARCH_DIR,
types.BuiltinTools.FIND_FILE,
],
),
)
feature_implementer = types.SubagentConfig(
name="feature_implementer",
description="Implements a scoped code change and keeps the tests passing.",
system_instructions=(
"You are a feature implementation subagent. Follow AGENTS.md, write "
"clean code, run the tests, and fix compiler errors. Never delete or "
"weaken a test to make it pass."
),
model="gemini-4-carbon",
capabilities=types.SubagentCapabilities(
enabled_tools=[
types.BuiltinTools.VIEW_FILE,
types.BuiltinTools.EDIT_FILE,
types.BuiltinTools.CREATE_FILE,
types.BuiltinTools.RUN_COMMAND,
],
),
)
# 2. Expose both subagents to the supervisor, with a 20-call and token budget
supervisor_config = LocalAgentConfig(
model="gemini-4-carbon",
workspaces=["./workspace"],
subagents=[researcher, feature_implementer],
policies=[policy.allow_all()],
budget_config=types.BudgetConfig(
max_model_calls=20,
max_total_tokens=200_000,
),
system_instructions=(
"You are a supervisor agent. Delegate codebase exploration to "
"@researcher and code changes to @feature_implementer. Summarize each "
"completed step before moving on."
),
)
async def run_agentic_loop(prompt: str, max_retries: int = 1) -> bool:
"""Supervisory loop. We only instantiate and run the supervisor explicitly."""
async with Agent(supervisor_config) as supervisor:
for attempt in range(1, max_retries + 2):
print(f"[Supervisor Loop] Attempt {attempt}/{max_retries + 1}...")
# Send prompt to the supervisor; it spawns subagents autonomously as needed
response = await supervisor.chat(prompt)
await response.text() # Drain the stream before reading the stop reason
# Halt condition: the SDK stops the turn when a budget is exceeded
if response.stop_reason in (
types.StopReason.MAX_MODEL_CALLS_EXCEEDED,
types.StopReason.MAX_TOTAL_TOKENS_EXCEEDED,
):
print(f"Loop halted: budget exceeded ({response.stop_reason}).")
return False
usage = supervisor.conversation.total_usage
print(f"Tokens used so far: {usage.total_token_count or 0:,} / 200,000")
# Verification gate: deterministic, and independent of the worker
success, error_msg = verify_output("./workspace")
if success:
print("Goal completed: verification gate passed.")
return True
# Exactly one targeted retry, with the real failure output
prompt = (
"The previous attempt failed verification with the following output:\n"
f"{error_msg}\n"
"Delegate a targeted fix to @feature_implementer and run the tests again."
)
print("Verification still failing after the retry. Handing over to a human.")
return False
if __name__ == "__main__":
asyncio.run(run_agentic_loop("Refactor types.go to use explicit interfaces."))
前述实现定义了以下预算:The preceding implementation defines the following budgets:
- max_model_calls=20,软限制,按监督器整个会话累计计数
max_model_calls=20, a soft limit, counted across the supervisor's whole session - max_total_tokens=200_000 作为成本上限
max_total_tokens=200_000as the cost ceiling
任一条件触发时,SDK 都会停止本轮并报告 stop_reason。max_retries=1 会限制每个部分的尝试次数:首次尝试加一次修正。如果验证仍未通过,循环就会返回 False,由人工接手,而不是让模型一直重试直到预算耗尽。The SDK stops the turn and reports a stop_reason when either one trips. max_retries=1 limits each section: the first attempt plus one fix. If the verification still fails after that, the loop returns False and a human takes the seat instead of the model spinning until the budget runs out.
如果你不想从头构建并托管自己的自定义 SDK 循环,可以使用 Antigravity Agent——一种自主的异步编码代理。Antigravity Agent 在安全、隔离的 Google Cloud 沙箱中运行。这样,你就可以使用托管代理,在 Google 托管的基础设施上编排执行计划,从而创建类似的智能体循环。或者,你也可以在一个长时间运行的 Cloud Run 沙箱中运行上述循环,这样即使合上笔记本电脑,循环也会继续运行。If you prefer not to build and host your own custom SDK loops from scratch, use Antigravity Agent, an autonomous, asynchronous coding agent. Antigravity Agent operates in a secure, isolated Google Cloud sandbox. This way you can create similar agentic loops by using managed agents to orchestrate execution plans under Google managed infrastructure. Alternatively, you can run the preceding loop inside a long-lived Cloud Run sandbox so that the loop keeps working after you close your laptop.
没有一种方案适合所有情况No one size fits all
你必须为每个验证系统划定明确的边界,以确保自己始终掌握控制权。无论你的循环机制多么完善,如果作为责任人的你无法批准智能体的输出,那么它产出的任何工件都价值有限。好消息是,制定质量评估评分卡或循环算法,与制作其他类型的软件工件所采用的流程相似。因此,大部分执行工作都可以自动化。You must establish a clear boundary for each of your validation systems that lets you stay in control. No matter how perfect your loop, if you, as the responsible human, cannot sign off on your agent's output, there is minimal value in any of the artifacts it is producing. The good news is that building a quality evaluation scorecard or a loop algorithm uses a similar process to producing any other type of software artifact. So, much of the execution will be automated.
最后,要做出明智的判断,你应该从内部观察每一轮循环。随着你看到事情逐渐顺利推进,并建立起信心,就可以上升一个层级。这是了解智能体在哪些方面遇到困难,以及如何改进流程本身的唯一方法。Finally, to make a sound judgment, you should observe each loop from the inside. As you see things working out, with this acquired confidence you step one level up. This is the only way to learn where the agent struggles and how to improve the process itself.