Skip to content
Examples - Antigravity SDKsdkAntigravity SDKAntigravity SDKExamples - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

The official google-antigravity/antigravity-sdk-python examples directory ships 38 self-contained, runnable Python scripts: 28 focused single-feature scripts in examples/getting_started/ and 10 multi-feature applications in examples/deep_dives/.

Create a Python 3.10+ virtual environment, install google-antigravity from PyPI, export your Gemini API key, and clone the repository to run the example scripts:

python3 -m venv .venv
source .venv/bin/activate

# Install the PyPI platform wheel (includes the compiled runtime binary)
pip install google-antigravity
export GEMINI_API_KEY="your_api_key_here"

# Clone the repository and run an example
git clone https://github.com/google-antigravity/antigravity-sdk-python.git
cd antigravity-sdk-python
python3 examples/getting_started/hello_world.py

A few examples use optional packages or credentials:

  • OpenTelemetry tracing (observability_otel.py): pip install "google-antigravity[otel]"
  • Local on-device models (local_models.py): pip install litert-lm and an imported .litertlm checkpoint (or a running Ollama or LM Studio server; no GEMINI_API_KEY required)
  • Gemini Enterprise (vertex.py): Either VERTEX_API_KEY (Express Mode) or GOOGLE_CLOUD_PROJECT plus gcloud auth application-default login (Standard Mode)
  • Filesystem change triggers (triggers.on_file_change): pip install watchfiles when extending triggers.py with OS file watching (triggers.py itself runs with core dependencies only)

Install the SDK skill for AI coding agents

Section titled “Install the SDK skill for AI coding agents”

The repository also includes a reusable google-antigravity-sdk skill containing reference guides and starter patterns so AI coding agents (including Antigravity App, Antigravity CLI, and other SKILL.md-compatible tools) can scaffold and debug SDK code accurately.

Install it with the skills CLI:

# List available skills in the repository
npx skills add Google-Antigravity/antigravity-sdk-python --list

# Install the google-antigravity-sdk skill globally
npx skills add Google-Antigravity/antigravity-sdk-python --skill google-antigravity-sdk --global

Or install it with the Context7 CLI:

npx ctx7 skills install /Google-Antigravity/antigravity-sdk-python google-antigravity-sdk

You can also load a local checkout of skills/google-antigravity-sdk directly into an SDK agent with LocalAgentConfig(skills_paths=[...]), as shown in agent_skills.py.

Getting started examples (examples/getting_started/)

Section titled “Getting started examples (examples/getting_started/)”

Each script isolates a single SDK capability and can be run directly with python3 examples/getting_started/<script>.py.

Core foundations, authentication, and models

Section titled “Core foundations, authentication, and models”
ScriptDemonstratesGuideRequirements
hello_world.pyMinimal Agent and LocalAgentConfig lifecycle, single-turn chat(), and optional model override.QuickstartGEMINI_API_KEY
vertex.pyGemini Enterprise (formerly Vertex AI) authentication in Express Mode (vertex=True, api_key=...) and Standard Mode (project, location, ADC).AuthenticationVERTEX_API_KEY or GOOGLE_CLOUD_PROJECT + ADC
prioritized_inference.pyConfiguring GeminiModelOptions(service_tier=ServiceTier.PRIORITY) on ModelTarget and checking usage_metadata.service_tier for fallback.Models and configurationGEMINI_API_KEY
local_models.pyOffline execution with LiteRTAgentConfig (Gemma 4 26B, auto-lightweight) and LocalOpenAIAgentConfig(...).lightweight() (Ollama, LM Studio), including --dry_run.Local modelslitert-lm + .litertlm model, or local OpenAI-compatible server (no API key)
persona_config.pyCustomizing identity and prompt sections with TemplatedSystemInstructions vs. full prompt replacement with CustomSystemInstructions.Personas and instructionsGEMINI_API_KEY (uses skills/google-antigravity-sdk)
slash_commands.pySending the /plan command programmatically with types.SlashCommand(name=types.BuiltinSlashCommandName.PLAN) in interactive mode to generate a plan artifact.Personas and instructionsGEMINI_API_KEY

Streaming, multimodal, structured output, and sessions

Section titled “Streaming, multimodal, structured output, and sessions”
ScriptDemonstratesGuideRequirements
streaming.pyReal-time response token streaming (async for token in response) and reasoning delta streaming (response.thoughts).Streaming and multimodalGEMINI_API_KEY
multimodal.pyPassing Image, Document, and Audio attachments, generating images with BuiltinTools.GENERATE_IMAGE, and returning Image media from custom tools.Streaming and multimodalGEMINI_API_KEY (uses examples/resources/)
structured_output.pyEnforcing Pydantic V2 output schemas with response_schema and reading parsed payloads using await response.structured_output().Structured outputGEMINI_API_KEY
persistence.pySaving a session trajectory with save_dir, reading agent.conversation_id, and resuming context in a new Agent instance.Sessions and contextGEMINI_API_KEY
app_data_dir_override.pyRedirecting generated artifacts, scratch files, and media storage to a custom absolute app_data_dir.Sessions and contextGEMINI_API_KEY
compaction.pyConfiguring sliding-window trajectory compaction thresholds with CompactionConfig(token_threshold=...).Sessions and contextGEMINI_API_KEY
budget_limits.pyCapping max_model_calls, max_tool_calls, max_input_tokens, max_output_tokens, and max_total_tokens, checking StopReason, and resuming with BudgetScope.FORWARD_LOOKING.Sessions and contextGEMINI_API_KEY
cancellation.pyAborting turns with await response.cancel() vs. task.cancel(), and catching types.AntigravityCancelledError before asyncio.CancelledError.Sessions and contextGEMINI_API_KEY

Tools, skills, MCP, subagents, and workflows

Section titled “Tools, skills, MCP, subagents, and workflows”
ScriptDemonstratesGuideRequirements
custom_tools.pyRegistering Python functions as tools and persisting cross-turn session state with injected ToolContext.Tools and skillsGEMINI_API_KEY
web_tools.pyEnabling and calling BuiltinTools.SEARCH_WEB and BuiltinTools.READ_URL_CONTENT.Tools and skillsGEMINI_API_KEY
agent_skills.pyLoading filesystem SKILL.md skills into an agent using LocalAgentConfig(skills_paths=[...]).Tools and skillsGEMINI_API_KEY (uses skills/google-antigravity-sdk)
mcp_tools.pyConnecting local stdio and Streamable HTTP MCP servers (McpStdioServer, McpStreamableHttpServer), filtering tools with disabled_tools, and scoping per-tool MCP safety policies.MCPGEMINI_API_KEY (uses examples/resources/mcp_server.py)
subagents.pyDynamic self-delegation, static SubagentConfig with isolated tools, and three-tier nested delegation using max_subagent_depth and allowed_subagents.SubagentsGEMINI_API_KEY (uses examples/resources/)
workflows.pyDeterministic multi-agent workflows with @beta.workflows.define (phase, call_tool, parallel, args, multi-turn WorkflowAgent, log), .py pipeline scripts, and agent.beta.run_workflow().WorkflowsGEMINI_API_KEY

Safety, lifecycle hooks, triggers, and observability

Section titled “Safety, lifecycle hooks, triggers, and observability”
ScriptDemonstratesGuideRequirements
policies.pyDeny-by-default rules, allow, deny, ask_user, typed Pydantic when predicates, and blocking custom tools.Policies and sandboxingGEMINI_API_KEY
autonomous_shell.pyOpting into unattended run_command execution with policies=[policy.allow_all()].Policies and sandboxingGEMINI_API_KEY
sandboxing.pyConfining run_command inside the OS-level command sandbox with RunCommandConfig(enable_sandbox=True) and verifying blocked out-of-workspace writes.Policies and sandboxingGEMINI_API_KEY (OS sandbox support on host to block probe)
human_in_the_loop.pyHandling interactive agent questions in the terminal with interactive.AskQuestionHook and AgentBehavior.INTERACTIVE (pair with BuiltinTools.ASK_QUESTION in enabled_tools).Lifecycle hooks and triggersGEMINI_API_KEY, interactive terminal
hooks.pyWiring all 10 lifecycle hook decorators (on_session_start, on_session_end, pre_turn, post_turn, pre_tool_call_decide, post_tool_call, on_tool_error, on_interaction, on_compaction, and stop continuation).Lifecycle hooks and triggersGEMINI_API_KEY
triggers.pyRunning periodic every() triggers and custom @triggers.trigger tasks that push background alerts with ctx.send().Lifecycle hooks and triggersGEMINI_API_KEY (watchfiles only if adding on_file_change)
observability.pyEnabling "google.antigravity" debug logs, auditing tool results with @hooks.post_tool_call, and inspecting UsageMetadata (including thinking tokens).Observability, evals, and errorsGEMINI_API_KEY
error_handler.pyShaping tool failure messages with @hooks.on_tool_error (ToolExecutionError) and catching AntigravityValidationError and AntigravityConnectionError.Observability, evals, and errorsGEMINI_API_KEY

These multi-feature examples combine hooks, policies, custom tools, MCP servers, multimodal pipelines, and concurrent agents into complete workflows:

ScriptDemonstratesPrimary guidesRequirements
interactive_cli.pyEnd-to-end interactive terminal agent with custom tools, a local stdio MCP server, policy.ask_user, AskQuestionHook, streaming output, and token usage reporting.Policies and sandboxing, MCPGEMINI_API_KEY, interactive terminal (uses examples/resources/mcp_server.py)
auto_policy_cli.pyInteractive and scripted CLI powered by policy.auto(handler=..., model=...) that displays safety assessment reasoning before confirming flagged calls.Policies and sandboxingGEMINI_API_KEY (supports --prompt and --auto_confirm flags)
agent_middleware.pyComposing PreToolCallDecideHook, PostToolCallHook, and OnToolErrorHook as transparent middleware for rate limiting, audit logging, and error recovery.Lifecycle hooks and triggersGEMINI_API_KEY
host_tool_hooks.pyDecorator-based registration for session, turn, built-in/custom/subagent tool, compaction, and interaction hooks with detailed step and event payload logging.Lifecycle hooks and triggersGEMINI_API_KEY
observability_otel.pyConfiguring an OpenTelemetry TracerProvider and ConsoleSpanExporter with otel.get_otel_hooks() across custom tool calls and delegated subagents.Observability, evals, and errorsGEMINI_API_KEY, pip install "google-antigravity[otel]"
round_based_chat.pySynchronized multi-agent discussion room running parallel turns with asyncio.gather, periodic every() triggers, and a custom pass_turn() opt-out tool.Subagents, Tools and skillsGEMINI_API_KEY
async_chat.pyAsynchronous peer-to-peer multi-agent chat using independent agent loops, asyncio.Condition wakeups, and custom tools without fixed rounds.Subagents, Sessions and contextGEMINI_API_KEY
multimodal_pipeline.pyTwo-agent generator and discriminator pipeline that produces an image using generate_image and passes raw Image bytes to a second agent for blind visual inspection.Streaming and multimodalGEMINI_API_KEY
doc_maintenance_agent.pyAutonomous documentation maintenance agent that reads source files and restricts writes to .md files in a target directory with conditional when policies.Policies and sandboxing, Tools and skillsGEMINI_API_KEY
docstring_maintenance_agent.pyAutonomous Python docstring auditor that disables create_file and run_command through CapabilitiesConfig and restricts edit_file to .py files.Policies and sandboxing, Tools and skillsGEMINI_API_KEY

Shared sample assets (examples/resources/)

Section titled “Shared sample assets (examples/resources/)”

Several examples load fixtures from examples/resources/, including mcp_server.py (a local sample MCP server used by mcp_tools.py, subagents.py, and interactive_cli.py) and sample inputs (example_image.png and sample_audio.wav used by multimodal.py, plus sample_doc.txt used by multimodal.py and subagents.py). Keep this folder alongside the example scripts when running them locally.