Examples
Section titled “Examples”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/.
Prerequisites and setup
Section titled “Prerequisites and setup”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-lmand an imported.litertlmcheckpoint (or a running Ollama or LM Studio server; noGEMINI_API_KEYrequired) - Gemini Enterprise (
vertex.py): EitherVERTEX_API_KEY(Express Mode) orGOOGLE_CLOUD_PROJECTplusgcloud auth application-default login(Standard Mode) - Filesystem change triggers (
triggers.on_file_change):pip install watchfileswhen extendingtriggers.pywith OS file watching (triggers.pyitself 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”| Script | Demonstrates | Guide | Requirements |
|---|---|---|---|
hello_world.py | Minimal Agent and LocalAgentConfig lifecycle, single-turn chat(), and optional model override. | Quickstart | GEMINI_API_KEY |
vertex.py | Gemini Enterprise (formerly Vertex AI) authentication in Express Mode (vertex=True, api_key=...) and Standard Mode (project, location, ADC). | Authentication | VERTEX_API_KEY or GOOGLE_CLOUD_PROJECT + ADC |
prioritized_ | Configuring GeminiModelOptions(service_tier=ServiceTier.PRIORITY) on ModelTarget and checking usage_metadata.service_tier for fallback. | Models and configuration | GEMINI_API_KEY |
local_models.py | Offline execution with LiteRTAgentConfig (Gemma 4 26B, auto-lightweight) and LocalOpenAIAgentConfig(...).lightweight() (Ollama, LM Studio), including --dry_run. | Local models | litert-lm + .litertlm model, or local OpenAI-compatible server (no API key) |
persona_ | Customizing identity and prompt sections with TemplatedSystemInstructions vs. full prompt replacement with CustomSystemInstructions. | Personas and instructions | GEMINI_API_KEY (uses skills/google-antigravity-sdk) |
slash_ | Sending the /plan command programmatically with types.SlashCommand(name=types.BuiltinSlashCommandName.PLAN) in interactive mode to generate a plan artifact. | Personas and instructions | GEMINI_API_KEY |
Streaming, multimodal, structured output, and sessions
Section titled “Streaming, multimodal, structured output, and sessions”| Script | Demonstrates | Guide | Requirements |
|---|---|---|---|
streaming.py | Real-time response token streaming (async for token in response) and reasoning delta streaming (response.thoughts). | Streaming and multimodal | GEMINI_API_KEY |
multimodal.py | Passing Image, Document, and Audio attachments, generating images with BuiltinTools.GENERATE_IMAGE, and returning Image media from custom tools. | Streaming and multimodal | GEMINI_API_KEY (uses examples/resources/) |
structured_ | Enforcing Pydantic V2 output schemas with response_schema and reading parsed payloads using await response.structured_output(). | Structured output | GEMINI_API_KEY |
persistence.py | Saving a session trajectory with save_dir, reading agent.conversation_id, and resuming context in a new Agent instance. | Sessions and context | GEMINI_API_KEY |
app_ | Redirecting generated artifacts, scratch files, and media storage to a custom absolute app_data_dir. | Sessions and context | GEMINI_API_KEY |
compaction.py | Configuring sliding-window trajectory compaction thresholds with CompactionConfig(token_threshold=...). | Sessions and context | GEMINI_API_KEY |
budget_ | Capping 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 context | GEMINI_API_KEY |
cancellation.py | Aborting turns with await response.cancel() vs. task.cancel(), and catching types.AntigravityCancelledError before asyncio.CancelledError. | Sessions and context | GEMINI_API_KEY |
Tools, skills, MCP, subagents, and workflows
Section titled “Tools, skills, MCP, subagents, and workflows”| Script | Demonstrates | Guide | Requirements |
|---|---|---|---|
custom_tools.py | Registering Python functions as tools and persisting cross-turn session state with injected ToolContext. | Tools and skills | GEMINI_API_KEY |
web_tools.py | Enabling and calling BuiltinTools.SEARCH_WEB and BuiltinTools.READ_URL_CONTENT. | Tools and skills | GEMINI_API_KEY |
agent_skills.py | Loading filesystem SKILL.md skills into an agent using LocalAgentConfig(skills_paths=[...]). | Tools and skills | GEMINI_API_KEY (uses skills/google-antigravity-sdk) |
mcp_tools.py | Connecting local stdio and Streamable HTTP MCP servers (McpStdioServer, McpStreamableHttpServer), filtering tools with disabled_tools, and scoping per-tool MCP safety policies. | MCP | GEMINI_API_KEY (uses examples/resources/mcp_server.py) |
subagents.py | Dynamic self-delegation, static SubagentConfig with isolated tools, and three-tier nested delegation using max_subagent_depth and allowed_subagents. | Subagents | GEMINI_API_KEY (uses examples/resources/) |
workflows.py | Deterministic multi-agent workflows with @beta.workflows.define (phase, call_tool, parallel, args, multi-turn WorkflowAgent, log), .py pipeline scripts, and agent.beta.run_workflow(). | Workflows | GEMINI_API_KEY |
Safety, lifecycle hooks, triggers, and observability
Section titled “Safety, lifecycle hooks, triggers, and observability”| Script | Demonstrates | Guide | Requirements |
|---|---|---|---|
policies.py | Deny-by-default rules, allow, deny, ask_user, typed Pydantic when predicates, and blocking custom tools. | Policies and sandboxing | GEMINI_API_KEY |
autonomous_ | Opting into unattended run_command execution with policies=[policy.allow_all()]. | Policies and sandboxing | GEMINI_API_KEY |
sandboxing.py | Confining run_command inside the OS-level command sandbox with RunCommandConfig(enable_sandbox=True) and verifying blocked out-of-workspace writes. | Policies and sandboxing | GEMINI_API_KEY (OS sandbox support on host to block probe) |
human_ | Handling interactive agent questions in the terminal with interactive.AskQuestionHook and AgentBehavior.INTERACTIVE (pair with BuiltinTools.ASK_QUESTION in enabled_tools). | Lifecycle hooks and triggers | GEMINI_API_KEY, interactive terminal |
hooks.py | Wiring 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 triggers | GEMINI_API_KEY |
triggers.py | Running periodic every() triggers and custom @triggers.trigger tasks that push background alerts with ctx.send(). | Lifecycle hooks and triggers | GEMINI_API_KEY (watchfiles only if adding on_file_change) |
observability. | Enabling "google.antigravity" debug logs, auditing tool results with @hooks.post_tool_call, and inspecting UsageMetadata (including thinking tokens). | Observability, evals, and errors | GEMINI_API_KEY |
error_ | Shaping tool failure messages with @hooks.on_tool_error (ToolExecutionError) and catching AntigravityValidationError and AntigravityConnectionError. | Observability, evals, and errors | GEMINI_API_KEY |
Deep-dive examples (examples/deep_dives/)
Section titled “Deep-dive examples (examples/deep_dives/)”These multi-feature examples combine hooks, policies, custom tools, MCP servers, multimodal pipelines, and concurrent agents into complete workflows:
| Script | Demonstrates | Primary guides | Requirements |
|---|---|---|---|
interactive_ | End-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, MCP | GEMINI_API_KEY, interactive terminal (uses examples/resources/mcp_server.py) |
auto_ | Interactive and scripted CLI powered by policy.auto(handler=..., model=...) that displays safety assessment reasoning before confirming flagged calls. | Policies and sandboxing | GEMINI_API_KEY (supports --prompt and --auto_confirm flags) |
agent_ | Composing PreToolCallDecideHook, PostToolCallHook, and OnToolErrorHook as transparent middleware for rate limiting, audit logging, and error recovery. | Lifecycle hooks and triggers | GEMINI_API_KEY |
host_ | Decorator-based registration for session, turn, built-in/custom/subagent tool, compaction, and interaction hooks with detailed step and event payload logging. | Lifecycle hooks and triggers | GEMINI_API_KEY |
observability_ | Configuring an OpenTelemetry TracerProvider and ConsoleSpanExporter with otel.get_otel_hooks() across custom tool calls and delegated subagents. | Observability, evals, and errors | GEMINI_API_KEY, pip install "google-antigravity[otel]" |
round_ | Synchronized multi-agent discussion room running parallel turns with asyncio.gather, periodic every() triggers, and a custom pass_turn() opt-out tool. | Subagents, Tools and skills | GEMINI_API_KEY |
async_chat.py | Asynchronous peer-to-peer multi-agent chat using independent agent loops, asyncio.Condition wakeups, and custom tools without fixed rounds. | Subagents, Sessions and context | GEMINI_API_KEY |
multimodal_ | Two-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 multimodal | GEMINI_API_KEY |
doc_ | Autonomous 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 skills | GEMINI_API_KEY |
docstring_ | Autonomous Python docstring auditor that disables create_file and run_command through CapabilitiesConfig and restricts edit_file to .py files. | Policies and sandboxing, Tools and skills | GEMINI_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.