Workflows
Section titled “Workflows”Orchestrate multi-agent fan-out, staged pipelines, programmatic tool calls, and multi-turn specialist conversations in Python using google.antigravity.beta.workflows and await agent.beta.run_workflow(...). Unlike open-ended subagent delegation, workflows express control flow directly in Python code while delegating individual reasoning steps to schema-constrained agents.
Prerequisites and imports
Section titled “Prerequisites and imports”Import workflows from google.antigravity.beta (or access beta.workflows from the top-level beta export):
from google.antigravity import Agent, LocalAgentConfig, beta
from google.antigravity.beta import workflows
assert beta.is_beta(workflows)
assert beta.is_beta(beta.WorkflowResult)
Executing a workflow requires two capabilities on CapabilitiesConfig, both enabled by default on LocalAgentConfig:
enable_subagents=TrueBuiltinTools.RUN_WORKFLOWincluded in the active built-in tools (callingagent.beta.run_workflow()when either is disabled raisesValueError, and any customenabled_toolsallowlist must includeBuiltinTools.RUN_WORKFLOW)
Your active safety policies must also allow run_workflow plus any tools invoked by spawned workflow agents (direct workflows.call_tool() calls run a fixed built-in subset enabled by the parent agent’s CapabilitiesConfig and do not run declarative policies or tool hooks). The default policy.confirm_run_command() policy allows run_workflow and file tools while blocking run_command.
Authoring modes
Section titled “Authoring modes”You can author workflows either as typed Python functions decorated with @workflows.define or as standalone .py script files on disk.
Decorated Python functions (@workflows.define)
Section titled “Decorated Python functions (@workflows.define)”Decorate a zero-argument async def (or def) function with @workflows.define (or @beta.workflows.define). At decoration time, the SDK extracts the function body’s AST, strips its leading docstring, rewrites workflows.<primitive> (and beta.workflows.<primitive>) references into standalone workflow script primitives, validates the syntax rules, and returns a frozen workflows.WorkflowDefinition dataclass (name, description, source, fn). This gives you full IDE autocomplete, static type checking, and fail-fast validation at import time.
import asyncio
import os
from google.antigravity import Agent, LocalAgentConfig, types
from google.antigravity.beta import workflows
@workflows.define
async def security_audit() -> None:
"""Reads target files, audits them in parallel, and synthesizes findings."""
workflows.phase("Read and audit files")
async def audit_file(path: str):
content = await workflows.call_tool("read_file", Path=path)
return await workflows.agent(
f"Identify the primary security issue in `{path}` in one sentence:\n{content}",
schema={"type": "string"},
role=f"Audit {path.rsplit('/', 1)[-1]}",
type_name="file_auditor",
)
findings = await workflows.parallel(workflows.args["paths"], audit_file)
workflows.phase("Synthesize report")
combined = "\n".join(str(item).strip() for item in findings)
lead = workflows.agent(
"You are the lead security reviewer.",
role="Lead Reviewer",
type_name="lead_synthesizer",
)
summary = await lead(
f"Summarize these findings:\n{combined}",
schema={
"type": "object",
"properties": {
"total_issues": {"type": "integer"},
"highest_severity": {"type": "string"},
"summary": {"type": "string"},
},
"required": ["total_issues", "highest_severity", "summary"],
},
)
remediation = await lead(
"Propose a one-sentence fix for the highest-severity issue.",
schema={"type": "string"},
)
workflows.log(
f"{summary['total_issues']} issues "
f"(highest={summary['highest_severity']}): {summary['summary']}"
)
workflows.log(f"Fix: {remediation}")
async def main() -> None:
file_auditor = types.SubagentConfig(
name="file_auditor",
description="Audits a single code snippet for vulnerabilities.",
system_instructions="Report the key vulnerability in one concise sentence.",
capabilities=types.SubagentCapabilities(enabled_tools=[]),
)
lead_synthesizer = types.SubagentConfig(
name="lead_synthesizer",
description="Combines security findings across multiple turns.",
system_instructions="Synthesize findings and match each turn's JSON schema.",
capabilities=types.SubagentCapabilities(enabled_tools=[]),
)
config = LocalAgentConfig(
workspaces=["./project"],
subagents=[file_auditor, lead_synthesizer],
)
async with Agent(config) as agent:
result = await agent.beta.run_workflow(
security_audit,
args={
"paths": [
os.path.abspath("./project/auth.py"),
os.path.abspath("./project/db.py"),
]
},
)
print(result.output)
if __name__ == "__main__":
asyncio.run(main())
External .py workflow scripts (script_path)
Section titled “External .py workflow scripts (script_path)”Store reusable workflows as standalone .py files and execute them with script_path= (accepting str or os.PathLike[str]). In standalone script files, the runtime injects phase, log, agent, call_tool, parallel, pipeline, args, and ToolError directly as top-level globals (no workflows. import is needed), and top-level await is enabled:
# workflows/release_checklist.py
phase("Sequential verification")
checks = args.get("checks", ["unit_tests", "type_check", "lint"])
results = await pipeline(
checks,
lambda item: agent(
f"Verify the '{item}' release gate and report status in one sentence.",
schema={"type": "string"},
role=f"Verify {item}",
),
)
for name, outcome in zip(checks, results):
log(f"{name}: {str(outcome).strip()}")
Run the standalone script from your host application by passing script_path:
from google.antigravity import Agent, LocalAgentConfig
async with Agent(LocalAgentConfig(workspaces=["./project"])) as agent:
result = await agent.beta.run_workflow(
script_path="workflows/release_checklist.py",
description="Run the sequential release verification checklist",
args={"checks": ["unit_tests", "docs_links"]},
)
print(result.output)
Relative script_path values are checked against each directory in config.workspaces first, then resolved against the current working directory. The SDK reads and validates the file with workflows.validate_workflow_source() before starting the turn, raising FileNotFoundError if missing or workflows.WorkflowError if invalid.
Workflow primitives reference
Section titled “Workflow primitives reference”All primitives below are accessed as workflows.<name> inside @workflows.define functions and as bare <name> globals inside standalone .py scripts (google/antigravity/workflows.py).
| Primitive | Signature or type | Description |
|---|---|---|
phase | phase(name: str) -> str | Starts a named workflow stage to structure progress reporting and output logs. |
log | log(*values: Any) -> None | Appends a progress or result line (requires at least 1 value) to the current phase and result.output. Replaces print(). |
agent | agent(prompt: str | None = None, schema: Any = None, role: str | None = None, type_name: str = "self", workspace: WorkspaceMode = "inherit") -> WorkflowAgent | Spawns a single-turn agent when awaited directly (non-empty schema required), or returns a reusable multi-turn WorkflowAgent handle when assigned and called with await handle(prompt, schema=...) (schema required on each turn). |
call_tool | call_tool(name: str, **tool_args: Any) -> Coroutine[Any, Any, str] | Invokes a supported built-in tool (read_file, write_file, edit_file, search_web, invoke_subagent, send_message, or manage_task) directly from Python without a model turn and returns its output string. Raises ToolError on failure or if the tool is unsupported or disabled. |
parallel | parallel(items: Iterable[Any], fn: Callable[[Any], Awaitable[Any]]) -> Coroutine[Any, Any, list[Any]] | Executes await fn(item) concurrently for every element in items and returns results in input order. |
pipeline | pipeline(items: Iterable[Any], fn: Callable[[Any], Awaitable[Any]]) -> Coroutine[Any, Any, list[Any]] | Executes await fn(item) sequentially one item at a time and returns the collected list of results. |
args | dict[str, Any] | Dictionary of JSON-serializable runtime arguments passed through agent.beta.run_workflow(..., args={...}). |
ToolError | ToolError(tool: str, message: str) | Exception (subclass of WorkflowError) raised inside a workflow when call_tool() fails or is denied. Exposes .tool and .message. |
Single-turn and multi-turn WorkflowAgent handles
Section titled “Single-turn and multi-turn WorkflowAgent handles”workflows.agent(...) supports two execution patterns, paired with required structured output schemas and optional specialist agent types and workspace isolation:
- Single-turn execution:
await workflows.agent(prompt, schema={...}, role="...")runs one task and returns the parsed JSON value matchingschema(for example, alist[str],dict, orstr). A non-empty JSON Schemadict(or JSON string), such as{"type": "string"}, is required wheneverworkflows.agent(...)is awaited directly; omittingschemaraisesValueError("agent: schema is required"). - Multi-turn conversation: Bind
reviewer = workflows.agent("Standing instructions", role="Reviewer")without awaiting it, then callawait reviewer(prompt, schema=...)across multiple turns. The agent retains its conversation history across calls; pass a non-emptyschemaon each individualawait reviewer(...)turn (omitting it when no defaultschemawas set raisesValueError("agent: schema is required")). - Targeting a declared subagent (
type_name): Defaults to"self"(cloning the parent agent). Settype_nameto thenameof atypes.SubagentConfiginLocalAgentConfig(subagents=[...])to pin a custommodel,system_instructions,capabilities,tools, orskills_config(see Subagents). Userolefor a human-readable per-invocation label in progress logs when multiple parallel calls share onetype_name. - Workspace isolation (
workspace: WorkspaceMode): Controls how the spawned agent accesses your workspace (WorkspaceMode = Literal["inherit", "branch", "share"]):"inherit"(default): Runs directly in the parent agent’s existing workspace directory. Best for read-only analysis or sequential edits."branch": Forks an isolated workspace copy (a git worktree for Git repositories, or a directory copy for non-Git directories). Forked worktrees are not deleted automatically when the workflow finishes."share": Creates a separate working tree sharing the parent’s underlying Git repository storage (requires a Git/VCS repository; useful when parallel agents edit or test simultaneously). Created worktrees remain on disk after the workflow completes so you can inspect, integrate, or prune them.
from google.antigravity.beta import workflows
@workflows.define
async def patch_and_verify() -> None:
workflows.phase("Explore variants in parallel")
approaches = ["iterative", "memoized"]
proposals = await workflows.parallel(
approaches,
lambda approach: workflows.agent(
f"Prototype a {approach} fix and report benchmark output.",
schema={
"type": "object",
"properties": {
"approach": {"type": "string"},
"passed": {"type": "boolean"},
"summary": {"type": "string"},
},
"required": ["approach", "passed", "summary"],
},
role=f"Try {approach}",
workspace="branch",
),
)
workflows.phase("Compare results")
judge = workflows.agent("Compare candidate patches objectively.", role="Judge")
winner = await judge(
f"Pick the strongest passing proposal: {proposals}",
schema={"type": "string"},
)
rationale = await judge(
"List any follow-up edge cases to test before merging.",
schema={"type": "array", "items": {"type": "string"}},
)
workflows.log(f"Selected: {winner}")
for item in rationale:
workflows.log(f"- {item}")
Direct tool calls and ToolError handling
Section titled “Direct tool calls and ToolError handling”Use await workflows.call_tool(name, **tool_args) to run supported built-in operations directly from Python without spending a model call, and catch workflows.ToolError to handle missing inputs or unavailable tools gracefully:
from google.antigravity.beta import workflows
@workflows.define
async def read_configs() -> None:
workflows.phase("Load configuration files")
for path in workflows.args.get("files", []):
try:
text = await workflows.call_tool("read_file", Path=path)
workflows.log(f"Loaded {path} ({len(text)} chars)")
except workflows.ToolError as err:
workflows.log(f"Skipped {path} ({err.tool} failed: {err.message})")
AST validation rules and source helpers
Section titled “AST validation rules and source helpers”Both @workflows.define and agent.beta.run_workflow() validate workflow source against the run_workflow AST rules before execution and raise workflows.WorkflowError when a rule is violated:
| Construct | Allowed? | Notes |
|---|---|---|
Top-level await, for / while loops, if / try | Yes | Compiled with ast.PyCF_ALLOW_TOP_LEVEL_AWAIT. |
Nested def / async def helpers and lambda | Yes | return statements are allowed inside nested helper functions passed to parallel() or pipeline(). |
Parameters on @workflows. functions | No | Raises WorkflowError. Pass runtime inputs through args={...} and read workflows.args. |
| Empty function body (or docstring-only body) | No | Raises WorkflowError. |
Top-level return statement | No | Raises WorkflowError. Emit final outputs with workflows.log(...). |
yield or yield from (top-level or nested) | No | Raises WorkflowError. |
print(... (including builtins.) | No | Raises WorkflowError everywhere in the script (including nested helpers). Use workflows.log(...). |
You can also run validation and source extraction directly in tests or CI pipelines:
workflows.validate_workflow_source(source: str) -> None: Parses and validates raw standalone workflow script text, raisingworkflows.WorkflowErroron syntax errors or disallowed AST nodes.workflows.extract_workflow_source(fn_or_def: Callable[[], Any] | WorkflowDefinition) -> str: Extracts, strips qualifiers from, validates, and returns the standalone Python source for a zero-argument function orWorkflowDefinition(also stored onmy_workflow.source).
from google.antigravity.beta import workflows
# Validate an external workflow script in unit tests without starting an Agent
with open("workflows/release_checklist.py", encoding="utf-8") as f:
workflows.validate_workflow_source(f.read())
Execute workflows and inspect results
Section titled “Execute workflows and inspect results”agent.beta.run_workflow()
Section titled “agent.beta.run_workflow()”Call await agent.beta.run_workflow() to execute either a decorated workflow or a standalone script file:
result: beta.WorkflowResult = await agent.beta.run_workflow(
workflow=None, # WorkflowDefinition or zero-arg callable (mutually exclusive with script_path)
script_path=None, # str | os.PathLike[str] to a .py script (mutually exclusive with workflow)
description="", # Optional run label; defaults to workflow docstring or function/file name
args=None, # Optional JSON-serializable Mapping[str, Any] exposed as workflows.args
)
Key validation and error behaviors:
- Provide strictly one of
workfloworscript_path; supplying both or neither raisesValueError. argsmust be a JSON-serializableMapping(non-mappings raiseTypeError; non-serializable values orNaN/Infinityfloats raiseValueError).- For decorated functions, the SDK writes the extracted source to a temporary
.pyfile inside the first writable workspace (falling back to the system temp directory on read-only mounts) and deletes it automatically when the call completes. - If the
run_workflowstep ends in error (or is not invoked),run_workflow()raisesToolExecutionError(tool_name="run_workflow").
beta.WorkflowResult and step.workflow_progress
Section titled “beta.WorkflowResult and step.workflow_progress”agent.beta.run_workflow() returns a beta.WorkflowResult instance. WorkflowResult subclasses types.ChatResponse, giving you both workflow-specific attributes and all standard turn response accessors:
| Attribute or method | Type | Description |
|---|---|---|
result.output | str | Formatted phase, log, and execution output produced by the workflow script. |
result. | str | Final assistant response text summarizing the completed workflow turn. |
result. | str | Resolved path to the .py workflow script that executed. |
result.script | str | Inline workflow script source (populated when the model invokes run_workflow with inline source). |
result. | str | Effective description used for the workflow run. |
result. | UsageMetadata | None | Accumulated token usage snapshot for the workflow turn (inherited from ChatResponse). |
result. | StopReason | Turn stop reason, such as budget or quota termination (inherited from ChatResponse). |
result.chunks / .thoughts / .tool_calls | AsyncIterator[...] | Buffered streaming cursors plus await result.text(), await result.resolve(), and await result.structured_output() (inherited from ChatResponse). |
You can also inspect workflow execution metadata directly on trajectory steps in agent.conversation.history (including turns where the model calls run_workflow on its own during agent.chat()). Each run_workflow step populates step.workflow_progress with a beta.WorkflowProgress Pydantic model containing script_path, script, description, and output:
import os
from google.antigravity import Agent, beta
# Reuse `config` (declaring `file_auditor` and `lead_synthesizer`) and `security_audit` from above
async with Agent(config) as agent:
result: beta.WorkflowResult = await agent.beta.run_workflow(
security_audit,
args={
"paths": [
os.path.abspath("./project/auth.py"),
os.path.abspath("./project/db.py"),
]
},
)
print("Description:", result.description)
print("Workflow log:\n", result.output)
print("Assistant summary:", result.response_text)
if result.usage_metadata:
print("Total tokens:", result.usage_metadata.total_token_count)
# Inspect step-level WorkflowProgress entries in conversation history
for step in agent.conversation.history:
if step.workflow_progress is not None:
prog: beta.WorkflowProgress = step.workflow_progress
print(
f"Step {step.step_index} ({step.status.value}): "
f"desc={prog.description!r} path={prog.script_path!r}"
)
For full ChatResponse cursor and Conversation history APIs, see Streaming and multimodal and Sessions and context.
Related examples and next steps
Section titled “Related examples and next steps”examples/getting_started/workflows.py: Complete runnable example covering@workflows.define,call_tool,parallel, multi-turnWorkflowAgentsynthesis withSubagentConfig, and standalonescript_pathexecution withpipeline.- Subagents: Configure
types.SubagentConfigspecialists (models, tools, capabilities, and skills) referenced bytype_name. - Tools and skills: Control
BuiltinTools.RUN_WORKFLOW, built-in capabilities used byworkflows.call_tool(), and custom tools available to spawned workflow agents. - Policies and sandboxing: Enforce runtime policies across workflow-spawned agents and tool calls.