Google Antigravity SDK for Python

repository·main·Indexed 25 days ago

https://github.com/google-antigravity/antigravity-sdk-python

A Python framework for building AI agents powered by Gemini. It provides a scalable, stateful infrastructure layer that abstracts the agentic loop, featuring support for multi-agent chat patterns (round-based and async peer-to-peer), multimodal pipelines, and a flexible middleware system using lifecycle hooks. The SDK includes capabilities for structured output via Pydantic, Model Context Protocol (MCP) integration, autonomous agent policies for workspace scoping, and human-in-the-loop tool approval.

Tokens
33.2K
Snippets
90
Records
132
Agent score
85%

What's inside google-antigravity

  1. Explore Google Antigravity SDK capabilities

    main

    The SDK provides modular capabilities categorized into several functional areas:

    Core Foundations

    • Agent Initialization: Using hello_world.py to learn about context managers and explicit model configuration.
    • Streaming: Using streaming.py for real-time token streaming and inspecting reasoning via response.thoughts.
    • Persona Configuration: Using persona_config.py and TemplatedSystemInstructions to shape agent identity.

    Safety & Governance

    • Policies: Implementing safety policies like "Deny by Default" and ask_user via policies.py.
    • Human-in-the-loop: Using human_in_the_loop.py to pause execution for human confirmation.

    Structured & Multimodal Interactivity

    • Multimodal: Processing images/PDFs and generating visual assets via multimodal.py.
    • Structured Output: Enforcing typed JSON responses using Pydantic schemas with response_schema via structured_output.py.

    Tools, Skills, & Delegation

    • Custom Tools: Defining stateful Python functions using ToolContext via custom_tools.py.
    • Agent Skills: Loading domain-specific skills from SKILL.md files via agent_skills.py.
    • MCP Tools: Connecting to external toolsets via the Model Context Protocol (MCP) via mcp_tools.py.
    • Sub-agents: Delegating tasks to specialized sub-agents via subagents.py.
    • Web Tools: Using built-in web search and URL fetching via web_tools.py.

    Lifecycle, Proactivity, & Observability

    • Hooks: Intercepting pre_turn and post_turn events via hooks.py.
    • Cancellation: Using response.cancel() for programmatic aborts via cancellation.py.
    • Triggers: Running background checks and periodic tasks via triggers.py.
    • Observability: Auditing execution, tracking token costs (including thinking tokens), and logging via observability.py.
    • Error Handling: Recovering from tool failures using the @hooks.on_tool_error decorator via error_handler.py.
    • Persistence: Saving/resuming sessions using conversation_id and save_dir via persistence.py.
    • Data Directory: Overriding the default application data directory for artifacts and media using app_data_dir via app_data_dir_override.py.
  2. Explore Google Antigravity SDK examples

    main

    The repository provides three categories of examples to help you learn the SDK:

    • getting_started/: Single-file, standalone snippets covering core concepts like agents, streaming, tools, policies, hooks, and structured output.
    • deep_dives/: Complex, multi-feature examples that build realistic mini-applications (e.g., interactive CLIs, middleware stacks, multi-agent chat rooms, and autonomous maintenance agents).
    • resources/: Shared assets required by the examples, such as images, MCP servers, and sample files.
  3. Identify core Hook implementation files

    main

    The hook system is distributed across several key modules in the SDK:

    • types.py: Contains the canonical Pydantic V2 boundary types used by all hooks, including ToolCall, Step, ToolResult, HookResult, QuestionResponse, and QuestionHookResult.
    • hooks.py: Defines the base classes for HookContext, HookResult, and specialized interfaces like PreToolCallDecideHook.
    • hook_runner.py: Contains the HookRunner class, which manages hook collections and implements the execution dispatch logic.
    • utils/interactive.py: Provides concrete hooks for interactive CLI usage, such as ToolConfirmationHook and AskQuestionHook.
    • policy.py: Implements a declarative tool call policy system. It can produce a PreToolCallDecideHook from a list of policies using priority-based evaluation.
  4. What is an Agent Skill?

    main
    An Agent Skill is a standardized way to provide AI agents with new capabilities and domain-specific expertise. Following the official Agent Skills specification, a skill typically consists of a directory containing a SKILL.md file (which includes instructions and YAML frontmatter metadata), and may optionally include scripts, references, and assets. This structure allows for capturing repeatable workflows and domain knowledge that can be reused across different agents.
  5. What are Google Antigravity SDK skills?

    main

    Skills are reusable components designed for the Google Antigravity SDK. They provide agents with specialized capabilities, tools, and domain-specific knowledge.

    The google-antigravity-sdk skill specifically provides core documentation and examples for building AI agents, covering topics such as:

    • Agent configuration
    • Error handling
    • Hooks
    • MCP integration
  6. How Agent, Conversation, and Connection work together

    main

    The SDK follows a hierarchical flow to manage AI interactions:

    1. Configuration: You define behavior and capabilities using an AgentConfig.
    2. Orchestration: An Agent is instantiated with the AgentConfig. Upon starting a session, the Agent determines the connection strategy and creates a Conversation.
    3. State & History: The Conversation object acts as the central hub for the active session. It establishes the low-level Connection to the backend and manages message history and the turn-by-turn flow.
    4. Communication: When you trigger an action (such as calling agent.chat()), the Conversation uses the underlying Connection to transmit data to the backend and stream responses back to you.

    This hierarchy allows developers to interact with a high-level Agent interface while state management and transport are handled automatically by the Conversation and Connection layers.

  7. How safety policies and tool access control work

    main

    The Google Antigravity SDK uses a declarative, priority-based policy system to control which tools an agent can execute. Policies are evaluated from highest to lowest priority (9 levels total). Within each priority level, the first match wins (short-circuit evaluation).

    Policy Resolution Order

    1. Specific Deny: policy.deny("tool_name", ...)
    2. Specific Ask: policy.ask_user("tool_name", ...)
    3. Specific Allow: policy.allow("tool_name", ...)
    4. Prefix Wildcard Deny: policy.deny("server/*", ...)
    5. Prefix Wildcard Ask: policy.ask_user("server/*", ...)
    6. Prefix Wildcard Allow: policy.allow("server/*", ...)
    7. Global Wildcard Deny: policy.deny("*", ...)
    8. Global Wildcard Ask: policy.ask_user("*", ...)
    9. Global Wildcard Allow: policy.allow("*", ...)
  8. Build Multimodal pipelines with Image I/O

    main

    You can create pipelines where agents exchange multimodal content. For example, a Generator agent can use the built-in generate_image tool to create an image, and a separate Discriminator agent can receive the raw image bytes as Image content type to describe it.

    Key components:

    • generate_image: Built-in tool for image creation.
    • Image: Content type for image data.
    • Content: The multimodal input wrapper.
    python multimodal_pipeline.py
  9. Use ToolContext to maintain conversation state in tools

    main

    ToolContext is a conversation-aware context that can be injected into tools. It allows tools to access the underlying connection and a per-conversation state store via get_state and set_state.

    Use ToolContext when a tool needs to:

    • Maintain state across multiple invocations in the same conversation (e.g., pagination cursors or scratchpads).
    • Access conversation metadata.
    • Share data with other tools used within the same conversation.

    Important: The state store in ToolContext is isolated from the HookContext. State set by a tool is not visible to hooks, and state set by hooks is not visible to tools.

  10. Core concepts of the Google Antigravity SDK

    main

    The SDK is built on three primary abstractions that manage the lifecycle of an AI interaction:

    1. Agent: The primary entry point for creating and managing AI workflows. It abstracts environment setup, tool loading, and connection management. It is responsible for configuration (models, capabilities, tools, policies), session lifecycle, and orchestrating hooks and triggers.
    2. Conversation: A stateful session object that manages the history and context of an interaction. It tracks turns, accumulates step history, manages context compaction, and provides streaming methods like chat() to ensure context is maintained across multiple turns.
    3. Connection: An abstract interface that handles transport to the agent backend. It decouples high-level APIs from specific transport details (such as local vs. cloud backends) by managing the sending of prompts and receipt of execution steps.
  11. Configure default agent safety behavior

    main

    By default, LocalAgentConfig uses policy.confirm_run_command(). This behavior is conservative:

    • It denies run_command (shell execution is blocked).
    • It allows all other tools (e.g., view, edit, create files).

    If you set workspaces in your config, policy.workspace_only() is automatically prepended, restricting file tools (view_file, create_file, edit_file) to those specific directories.

    When using run_interactive_loop(), the default deny on run_command is automatically upgraded to ask_user, providing a y/n confirmation prompt instead of a hard denial.

    from google.antigravity import LocalAgentConfig
    
    # run_command is denied, all other tools allowed
    config = LocalAgentConfig(
        system_instructions="You are a helpful assistant.",
    )