Skip to content
API reference - Antigravity SDKsdkAntigravity SDKAntigravity SDKAPI reference - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

Module-by-module reference for the public classes, functions, enums, exceptions, and environment variables in the google-antigravity Python SDK (v0.1.24, Python 3.10+, Apache-2.0).

Install from PyPI (platform wheels exist for macOS arm64/x86_64, Linux manylinux_2_17 and musllinux_1_1 aarch64/x86_64, and Windows amd64/arm64):

pip install google-antigravity
pip install "google-antigravity[otel]"  # Optional OpenTelemetry tracing hooks
ModuleContentsGuide
google.antigravityAgent, agent configs, model types, system instructions, media helpers, CapabilitiesConfig, BuiltinTools, CompactionConfig, InlineSkill, ToolContext, UsageMetadata, SandboxStatus, ToolExecutionError, beta.Overview, Quickstart
google.antigravity.modelsDEFAULT_MODEL, DEFAULT_IMAGE_GENERATION_MODEL, endpoints, options, ThinkingLevel, ServiceTier, ModelTarget, ModelType.Authentication, Models and configuration
google.antigravity.typesFull Pydantic V2 boundary type library (all 73 config, response, step, tool, MCP, subagent, budget, interaction, stop, multimodal, and error types).Structured output, Sessions and context
google.antigravity.policyPolicy builders, presets, Policy, AutoPolicy, and Decision (plus enforce, flatten_policies, Predicate, AskUserHandler in google.antigravity.hooks.policy).Policies and sandboxing
google.antigravity.hooksLifecycle hook base classes, 10 hook classes and decorators, HookContext, policy (plus HookRunner in google.antigravity.hooks.hook_runner).Lifecycle hooks and triggers
google.antigravity.triggerstrigger, Trigger, TriggerContext, every, on_file_change, FileChange, FileChangeKind (plus TriggerRunner in google.antigravity.triggers.trigger_runner).Lifecycle hooks and triggers
google.antigravity.toolsToolContext (tools.tool_context), ToolRunner and ToolWithSchema (tools.tool_runner).Tools and skills
google.antigravity.conversation.conversationConversation stateful Layer 2 session API.Sessions and context
google.antigravity.connections.connectionAgentConfig, Connection, ConnectionStrategy, DebugConfig, resolve_active_tools.Models and configuration
google.antigravity.connections.localLocalAgentConfig, LiteRTAgentConfig, LiteRTBackend, LocalOpenAIAgentConfig, LocalConnection, LocalConnectionStrategy, LocalConnectionStep, callable_to_tool_proto, and structured built-in tool result models (ToolOutput).Local models, Tools and skills
google.antigravity.betabeta decorator, BetaNamespace, is_beta, workflows, WorkflowResult, WorkflowProgress.Workflows
google.antigravity.utilsutils.interactive (terminal REPL and approval hooks), utils.otel (OpenTelemetry hooks), utils.state (StateStore).Policies and sandboxing, Observability, evals, and errors

The root package exports 39 symbols directly using from google.antigravity import ...:

  • Entry point and configs: Agent, AgentConfig, LocalAgentConfig, LiteRTAgentConfig, LiteRTBackend, LocalOpenAIAgentConfig
  • Models, endpoints, and retries: ModelTarget, ModelType, ModelEndpoint, GeminiAPIEndpoint, VertexEndpoint, GeminiModelOptions, ThinkingLevel, ServiceTier, RetryConfig, ModelAPIRetryConfig, ModelOutputRetryConfig
  • Capabilities, skills, and context: CapabilitiesConfig, BuiltinTools, AgentBehavior, CompactionConfig, ToolOutputTruncationConfig, InlineSkill, ToolContext
  • System instructions: SystemInstructions, TemplatedSystemInstructions, SystemInstructionSection, CustomSystemInstructions
  • Multimodal content: Content, Image, Document, Audio, Video, from_file, from_bytes
  • Telemetry, status, errors, and beta: UsageMetadata, SandboxStatus, ToolExecutionError, beta

Submodules (types, policy, hooks, triggers, beta, models) can also be imported with from google.antigravity import types, policy, hooks, triggers, beta, models.

google.antigravity.Agent(config: AgentConfig) is the Layer 1 async context manager entry point. It deep-copies declarative configuration (preserving object identity for tools, hooks, triggers, and policies), validates safety policies, starts the connection strategy and triggers, and wires ToolContext.

MemberSignature or typeDescription
__aenter__ / __aexit__async with Agent(config) as agent:Starts and cleanly tears down the session, subprocess, WebSocket transport, and background triggers. Raises ValueError if write tools or MCP servers are active without a policy or PreToolCallDecideHook.
chatasync chat(prompt: Content) -> ChatResponseSends a non-empty text or multimodal prompt and returns a lazy streaming ChatResponse immediately. Raises ValueError for None, empty/whitespace strings, or empty sequences.
beta.run_workflowasync beta.run_workflow(workflow=None, script_path=None, description="", args=None) -> WorkflowResult(Beta) Executes either a @beta.workflows.define function (workflow) or a .py file (script_path) with optional JSON-serializable args: Mapping[str, Any]. Requires enable_subagents=True and BuiltinTools.RUN_WORKFLOW active.
is_startedboolTrue while the agent session has an active Conversation.
conversationConversationActive Layer 2 Conversation. Raises RuntimeError before entering async with Agent(config).
conversation_idstr | NoneRuntime-assigned session ID (populated once the first live step of a turn is received), or None before a turn runs.
sandbox_statusSandboxStatus | NoneOS command sandbox status reported at startup, or None before startup or when unreported.

Common fields (AgentConfig and local configs)

Section titled “Common fields (AgentConfig and local configs)”

LocalAgentConfig, LiteRTAgentConfig, and LocalOpenAIAgentConfig accept keyword-only parameters and share these base options (see Models and configuration):

ParameterTypeLocal config defaultDescription
system_instructionsstr | SystemInstructions | NoneNonePlain str (appended as a templated section), TemplatedSystemInstructions, or CustomSystemInstructions (full replacement).
capabilitiesCapabilitiesConfigCapabilitiesConfig()Built-in tool selection, agent_behavior, subagent depth/allowlist, run_command_config, output truncation, and MCP byte limit. (Base abstract AgentConfig defaults to BuiltinTools.read_only().)
toolslist[Callable[..., Any] | str][]Custom Python callables (sync, async, functools.partial, callable class/dataclass, or ToolWithSchema). Duplicate names with distinct callables across root and subagents raise ValueError.
policiesSequence[Policy | Sequence[Policy]]policy.confirm_run_command()Declarative tool policies. Nested lists are flattened automatically.
hookslist[Hook][]Decorated functions or Hook subclass instances routed by type.
triggerslist[Trigger][]Long-lived background async trigger callables started for the session.
mcp_serverslist[McpServerConfig][]McpStdioServer and McpStreamableHttpServer configurations.
subagentslist[SubagentConfig][]Static subagent definitions available to invoke_subagent and workflows.agent(type_name=...).
workspaceslist[str][os.getcwd()]Workspace directories. Expands ~, normalizes file:// URIs, and resolves relative paths against os.getcwd().
envdict[str, str] | NoneNoneEnvironment variable overrides for the local runtime subprocess and run_command executions.
conversation_idstr | NoneNoneSession ID to create or resume. Must be >= 32 characters and match ^[a-zA-Z0-9-]+$.
session_continuation_modeSessionContinuationMode | NoneNoneRESUME (requires conversation_id), CREATE_OR_RESUME, or CREATE_ONLY.
save_dirstr | NoneNoneDirectory for persisted session trajectories (auto-creates a temporary antigravity_* directory when None).
app_data_dirstr | NoneNoneAbsolute path overriding default ~/.gemini/antigravity storage for artifacts, scratch files, and media. Rejects relative and unexpanded ~ paths.
response_schemadict[str, Any] | type[BaseModel] | str | NoneNonePydantic BaseModel subclass, JSON Schema dict, or JSON str enforcing structured output through finish.
skills_pathslist[str][]Directories containing SKILL.md files or skill subfolders. Mutually exclusive with inline_skills on local configs.
inline_skillslist[InlineSkill][]In-memory skill definitions. Mutually exclusive with skills_paths on local configs.
retry_configRetryConfig | NoneNoneAPI exponential backoff and model output retry settings.
budget_configBudgetConfig | NoneNoneCall and token budget caps (LIFETIME or FORWARD_LOOKING).
compaction_configCompactionConfig | NoneNoneContext compaction token ceiling (token_threshold).
debug_configDebugConfig | bool | dict | NoneNoneEnables "google.antigravity" logger level and backend tracing (True constructs DebugConfig()).

Cloud Gemini API and Gemini Enterprise (formerly Vertex AI) configuration (google.antigravity.LocalAgentConfig). Adds these keyword parameters:

ParameterTypeDefaultDescription
modelstr | ModelTarget | NoneNoneShorthand text model name or ModelTarget. Falls back to DEFAULT_MODEL ("gemini-4-hydrogen").
modelslist[ModelTarget] | NoneNoneExplicit model target list. Merge precedence: models > model > defaults (DEFAULT_MODEL for TEXT, DEFAULT_IMAGE_GENERATION_MODEL for IMAGE).
api_keystr | NoneNoneAPI key for Gemini Developer API (default) or Gemini Enterprise Express Mode (when vertex=True).
vertexbool | NoneNoneRoutes to Gemini Enterprise (VertexEndpoint). Auto-set to True when GOOGLE_GENAI_USE_VERTEXAI or GOOGLE_GENAI_USE_ENTERPRISE is "true" or "1".
projectstr | NoneNoneGoogle Cloud project ID for Gemini Enterprise Standard Mode (ADC). Falls back to GOOGLE_CLOUD_PROJECT.
locationstr | NoneNoneGoogle Cloud region for Gemini Enterprise Standard Mode (for example, "us-central1"). Falls back to GOOGLE_CLOUD_LOCATION.

Managed on-device inference configuration (google.antigravity.LiteRTAgentConfig; requires litert-lm, >= 0.19.1 for image vision; see Local models). Automatically applies .lightweight() presets with a derived CompactionConfig(token_threshold=40960).

ParameterTypeDefaultDescription
model_pathstr(required)Absolute path to a .litertlm checkpoint (use os.path.expanduser() for ~).
backendLiteRTBackend | strLiteRTBackend.GPUHardware backend: LiteRTBackend.CPU ("cpu"), LiteRTBackend.GPU ("gpu"), or LiteRTBackend.NPU ("npu").
enable_speculative_decodingboolFalseEnables multi-token prediction speculative decoding.
cache_dirstr | NoneNoneWritable directory for engine compilation cache.
audio_backendLiteRTBackend | str | NoneNoneHardware backend override for audio processing.
vision_backendLiteRTBackend | str | NoneNoneHardware backend override for image/vision processing (auto-detected from litert_lm.ModelInfo when None).
portint0Local loopback server port (0 selects an ephemeral port).
download_if_missingboolFalseReserved flag for automatic weight downloads (currently not enforced in v0.1.24; model_path must exist on disk or startup raises AntigravityValidationError).

Configuration for external OpenAI-compatible servers such as Ollama, LM Studio, or vLLM (google.antigravity.LocalOpenAIAgentConfig; call .lightweight() explicitly for small-context models):

ParameterTypeDefaultDescription
modelstr | ModelTarget | NoneNoneModel identifier served by the external endpoint (for example, "gemma-4-26B-A4B-it").
base_urlstr | NoneNoneNon-empty base URL (for example, "http://localhost:11434/v1"). Raises AntigravityValidationError at startup if empty and not set on model.endpoint.base_url.

AgentConfig preset methods and DebugConfig

Section titled “AgentConfig preset methods and DebugConfig”
SymbolSignature / FieldsDescription
config.lightweight()lightweight() -> SelfReturns a copy with enabled_tools=BuiltinTools.minimal(), agent_behavior=AgentBehavior.MINIMAL, enable_subagents=False, and compaction_config=CompactionConfig(token_threshold=65536) (40960 on LiteRTAgentConfig), preserving caller overrides.
config.eval(...)eval(thinking_level: ThinkingLevel | None = ThinkingLevel.HIGH) -> SelfReturns a benchmark preset copy with disabled_tools=[BuiltinTools.GENERATE_IMAGE], enable_subagents=False, RunCommandConfig(enable_daemons=True), policies=[policy.allow_all()], retry_config=RetryConfig.benchmark(), and thinking_level on text Gemini/Vertex models, preserving explicit caller fields (including LiteRTAgentConfig’s auto-applied lightweight defaults). Pass thinking_level=None on local or pre-configured targets.
config.create_strategy(...)create_strategy(*, tool_runner, hook_runner) -> ConnectionStrategyInstantiates the Layer 3 ConnectionStrategy for the config.
DebugConfigenable_server_side_tracing: bool = True, logging_level: int | str | None = logging.DEBUG, apply_logging() -> NoneImported from google.antigravity.connections.connection. Sets the google.antigravity Python logger level (attach a standard logging handler to display output; enable_server_side_tracing has no effect on local agent configs).

Defined in google.antigravity.models and re-exported from google.antigravity and google.antigravity.types (constants DEFAULT_MODEL and DEFAULT_IMAGE_GENERATION_MODEL live in google.antigravity.models). See Authentication and Models and configuration.

SymbolDefinition / FieldsDescription
DEFAULT_MODEL"gemini-4-hydrogen"Default text generation model on LocalAgentConfig.
DEFAULT_IMAGE_GENERATION_MODEL"gemini-3.1-flash-lite-image"Default image generation model on LocalAgentConfig.
ModelTargetname: str | None = None, types: list[ModelType] = [ModelType.TEXT], endpoint: ModelEndpoint | None = NoneAssociates a model name and modalities with an authentication endpoint.
ModelTypeTEXT = "text", IMAGE = "image"Model purpose discriminator enum.
ModelEndpointbase_url: str | None = None, http_headers: dict[str, str] | None = None, validate_endpoint() -> NoneAbstract base class for model endpoints.
GeminiAPIEndpointapi_key: str | None = None, options: GeminiModelOptions | None = None, base_url=None, http_headers=NoneGemini Developer API endpoint (requires api_key or GEMINI_API_KEY unless base_url is set).
VertexEndpointproject: str | None = None, location: str | None = None, api_key: str | None = None, options: GeminiModelOptions | None = None, base_url=None, http_headers=NoneGemini Enterprise (Vertex AI) endpoint. Supports Express Mode (api_key), Standard Mode (project + location with ADC), or custom base_url proxy (api_key and project/location are mutually exclusive when base_url is unset).
GeminiModelOptionsthinking_level: ThinkingLevel | None = None, service_tier: ServiceTier | None = None, max_output_tokens: int | None = NoneGemini generation options (max_output_tokens in (0, 2^31 - 1]; uses the model’s registered output limit or falls back to 65535).
ThinkingLevelMINIMAL = "minimal", LOW = "low", MEDIUM = "medium", HIGH = "high", EXTRA_HIGH = "xhigh"Reasoning depth enum for thinking-capable Gemini models.
ServiceTierSTANDARD = "standard", PRIORITY = "priority", FLEX = "flex"Inference compute tier enum.
RetryConfigapi_retry: ModelAPIRetryConfig | None = None, model_output_retry: ModelOutputRetryConfig | None = None, RetryConfig.benchmark() -> RetryConfigCombined retry configuration. benchmark() sets max_retries=4294967295 and initial_sleep_duration_ms=1000. Runtime defaults: 8 API retries (4000 ms initial sleep, 2.0 multiplier, 0.4 jitter) and 4 output retries.
ModelAPIRetryConfigmax_retries: int | None = None, initial_sleep_duration_ms: int | None = None, exponential_multiplier: float | None = None, jitter_range: float | None = NoneExponential backoff settings for transient API errors (non-negative).
ModelOutputRetryConfigmax_retries: int | None = NoneRetry ceiling (>= 0) for malformed tool calls or response_schema validation failures.

See Streaming and multimodal, Structured output, and Sessions and context.

ChatResponse and stream chunks (google.antigravity.types)

Section titled “ChatResponse and stream chunks (google.antigravity.types)”

Every streaming iterator on ChatResponse returns an independent cursor over a shared buffer (safe to consume sequentially or concurrently with asyncio.gather):

MemberSignature or typeDescription
__aiter__async for token in response: ... (AsyncIterator[str])Streams conversational Text.text deltas.
thoughtsAsyncIterator[str]Streams internal model reasoning Thought.text deltas.
tool_callsAsyncIterator[ToolCall]Streams deduplicated ToolCall dispatches in real time.
chunksAsyncIterator[StreamChunk | ToolCall | ToolResult]Unfiltered stream of items (Agent.chat() and Conversation.chat() emit Text, Thought, and ToolCall items; inspect ToolResult using @hooks.post_tool_call).
text()async text() -> strDrains the stream and returns concatenated response text.
resolve()async resolve() -> list[StreamChunk | ToolCall | ToolResult]Drains the stream and returns all buffered items.
structured_output()async structured_output() -> Any | NoneDrains the stream (re-raising any stream error) and returns the parsed root-turn response_schema payload, or None.
cancel()async cancel() -> NoneAborts the active turn on the backend (no-op if already finished), raising AntigravityCancelledError to consumers.
usage_metadataUsageMetadata | NonePer-turn accumulated token usage (snapshotted on completion).
stop_reasonStopReasonPer-turn stop reason (snapshotted on completion).

Chunk and telemetry models:

  • StreamChunk(step_index: int) (frozen base), Text(step_index: int, text: str), Thought(step_index: int, text: str, signature: bytes | None = None).
  • ToolCall(name: BuiltinTools | str, args: dict[str, Any] = {}, id: str | None = None, step_id: str | None = None, canonical_path: str | None = None, server_name: str | None = None).
  • ToolResult(name: BuiltinTools | str, id: str | None = None, step_id: str | None = None, result: Any = None, error: str | None = None, exception: Exception | None = None, server_name: str | None = None).
  • UsageMetadata(prompt_token_count=None, cached_content_token_count=None, candidates_token_count=None, thoughts_token_count=None, total_token_count=None, service_tier=None): supports +, -, scalar *, and sum().
  • SandboxStatus(available: bool, unavailable_reason: str | None = None).

Conversation (google.antigravity.conversation.conversation)

Section titled “Conversation (google.antigravity.conversation.conversation)”

Accessible through agent.conversation or standalone with async with Conversation.create(strategy) as conversation: (constructor Conversation(conn, *, max_history_size=10_000, history=None)):

MemberSignature or typeDescription
createasync with Conversation.create(strategy) as conv:Context manager that enters a ConnectionStrategy and yields a Conversation seeded with any restored history.
chatasync chat(prompt: Content | None = None, **kwargs) -> ChatResponseSends prompt (draining any unconsumed prior turn first) and returns a ChatResponse.
sendasync send(prompt: Content | None, **kwargs) -> NoneLow-level non-blocking prompt send.
receive_stepsreceive_steps() -> AsyncIterator[Step]Yields and records Step updates until the turn becomes idle.
receive_chunksreceive_chunks() -> AsyncIterator[StreamChunk | ToolCall]Yields semantic Thought, Text, and deduplicated ToolCall chunks for the active turn.
get_last_structured_outputget_last_structured_output() -> Any | NoneReturns the parsed structured output from the most recent root FINISH step, or None.
clear_historyclear_history() -> NoneClears in-memory step history, turn indices, and compaction indices without closing the session.
historylist[Step]Copy of recorded steps across all turns (up to max_history_size; 0 disables trimming).
last_responsestrContent of the most recent step with is_complete_response=True, or "".
turn_countintNumber of send() calls recorded in history.
compaction_indiceslist[int]Indices in history of completed (StepStatus.DONE) StepType.COMPACTION steps with depth == 0 (on local configs, also check not step.parent_trajectory_id to exclude subagent compactions).
total_usage / last_turn_usage / trajectory_usagesUsageMetadata / UsageMetadata | None / dict[str, UsageMetadata]Cumulative session usage, last-turn delta, and per-trajectory cumulative usage map.
conversation_id / sandbox_status / is_idle / connectionstr / SandboxStatus | None / bool / ConnectionSession ID, OS sandbox status, idle state, and underlying Layer 3 Connection.
cancel / wait_for_idle / wait_for_wakeup / disconnectasync cancel(), async wait_for_idle(), async wait_for_wakeup(timeout=300.0) -> bool, async disconnect()Turn cancellation, idle/wakeup synchronization, and transport shutdown.

Step and step enums (google.antigravity.types)

Section titled “Step and step enums (google.antigravity.types)”
  • Step fields: id: str = "", step_index: int = 0, trajectory_id: str = "", parent_trajectory_id: str = "" (non-empty for subagent steps), depth: int = 0 (remains 0 for subagent steps on local agent configs; filter subagent steps using parent_trajectory_id), type: StepType = UNKNOWN, source: StepSource = UNKNOWN, target: StepTarget = UNKNOWN, status: StepStatus = UNKNOWN, content: str = "", content_delta: str = "", thinking: str = "", thinking_delta: str = "", tool_calls: list[ToolCall] = [], error: str = "", is_complete_response: bool | None = None, structured_output: Any | None = None, workflow_progress: WorkflowProgress | None = None, usage_metadata: UsageMetadata | None = None (deprecated). (LocalConnectionStep in connections.local extends Step with http_code: int = 0.)
  • StepType: TEXT_RESPONSE, TOOL_CALL, SYSTEM_MESSAGE, COMPACTION, FINISH, THINKING, UNKNOWN.
  • StepSource: SYSTEM, USER, MODEL, UNKNOWN.
  • StepTarget: USER ("TARGET_USER"), ENVIRONMENT ("TARGET_ENVIRONMENT"), UNSPECIFIED ("TARGET_UNSPECIFIED"), UNKNOWN ("UNKNOWN").
  • StepStatus: ACTIVE, DONE, WAITING_FOR_USER, ERROR, CANCELED, UNKNOWN.
  • CapabilitiesConfig: enable_subagents: bool = True, agent_behavior: AgentBehavior = AgentBehavior.AUTONOMOUS, enabled_tools: list[BuiltinTools] | None = None, disabled_tools: list[BuiltinTools] | None = None (mutually exclusive), finish_tool_schema_json: str | None = None, max_subagent_depth: int | None = None (>= 1, default 1), allowed_subagents: list[str] | None = None, run_command_config: RunCommandConfig | None = None, tool_output_truncation_config: ToolOutputTruncationConfig | int | None = None, mcp_max_output_bytes: int | None = None ((0, 2^31 - 1], runtime default 10240), compaction_threshold: int | None = None (deprecated; use CompactionConfig).
  • RunCommandConfig(enable_daemons: bool = False, timeout_seconds: float | None = None, enable_sandbox: bool = False) (default timeout 600s).
  • ToolOutputTruncationConfig(max_tokens: int) (0 <= max_tokens <= 2^31 - 1; preserves prefix, truncates tail; 0 disables).
  • BuiltinTools (str, Enum):
    • Default-enabled (BuiltinTools.default(), 11 members): VIEW_FILE ("view_file"), CREATE_FILE ("create_file"), EDIT_FILE ("edit_file"), RUN_COMMAND ("run_command"), INVOKE_SUBAGENT ("invoke_subagent"; START_SUBAGENT / "start_subagent" is a deprecated alias), RUN_WORKFLOW ("run_workflow"), GENERATE_IMAGE ("generate_image"), SEARCH_WEB ("search_web"), READ_URL_CONTENT ("read_url_content"), SCHEDULE ("schedule"), FINISH ("finish"). The runtime also auto-enables manage_task whenever RUN_COMMAND or SCHEDULE is active.
    • Opt-in only (include in enabled_tools): ASK_QUESTION ("ask_question"), and legacy BuiltinTools.deprecated() members LIST_DIR ("list_directory"), SEARCH_DIR ("search_directory"), FIND_FILE ("find_file").
    • Classmethod sets: default(), read_only() (VIEW_FILE, READ_URL_CONTENT, SCHEDULE, FINISH), nondestructive() (all non-deprecated except RUN_COMMAND), minimal() (RUN_COMMAND, VIEW_FILE, CREATE_FILE, EDIT_FILE), file_tools() (VIEW_FILE, CREATE_FILE, EDIT_FILE), deprecated(), all_tools(), none().

Instructions, behavior, and slash commands

Section titled “Instructions, behavior, and slash commands”
  • TemplatedSystemInstructions(identity: str | None = None, sections: list[SystemInstructionSection] = []) and SystemInstructionSection(content: str, title: str = "user_system_instructions") (see Personas and instructions).
  • CustomSystemInstructions(text: str, title: str | None = None): replaces all default system instructions; optional title renders <title> instead of <System>.
  • SystemInstructions = CustomSystemInstructions | TemplatedSystemInstructions.
  • AgentBehavior: AUTONOMOUS = "autonomous", INTERACTIVE = "interactive", MINIMAL = "minimal".
  • SlashCommand(name: BuiltinSlashCommandName) (frozen) and BuiltinSlashCommandName: PLAN = "plan".
  • ContentPrimitive = str | Image | Document | Audio | Video | SlashCommand and Content = ContentPrimitive | Sequence[ContentPrimitive].
  • Image, Document, Audio, Video: frozen models with data: bytes, mime_type: str (trimmed, case-insensitive validation), description: str | None = None, and classmethod from_file(path: str | Path, description: str | None = None).
    • Image: image/bmp, image/jpeg, image/png, image/webp.
    • Document: application/pdf, application/json, text/css, text/csv, text/html, text/javascript, text/plain, text/rtf, text/xml.
    • Audio: audio/wav, audio/x-wav, audio/wave, audio/vnd.wave, audio/mp3, audio/mp4, audio/webm, audio/aac, audio/ogg, audio/flac, audio/opus, audio/mpeg, audio/m4a, audio/l16.
    • Video: video/3gpp, video/avi, video/mp4, video/mpeg, video/mpg, video/quicktime, video/webm, video/wmv, video/x-flv.
  • from_file(path: str | Path, description: str | None = None) -> Image | Document | Audio | Video (expands ~ and infers MIME type) and from_bytes(data: bytes, mime_type: str, description: str | None = None) -> Image | Document | Audio | Video.
  • InlineSkill(name: str, description: str, content: str, allowed_tools: list[str] = [], dependent_tools: list[str] = [], dependent_skills: list[str] = [], metadata: dict[str, str] = {}) (see Tools and skills).
  • BaseMcpServerConfig: name: str (pattern ^[a-zA-Z0-9_-]+$), timeout_seconds: int | None = None (applies to both McpStdioServer and McpStreamableHttpServer; defaults to 300s for connection/discovery and 180s per tool call), enabled_tools: list[str] | None = None, disabled_tools: list[str] | None = None (mutually exclusive), force_all_tools_eager: bool = False (see MCP).
    • McpStdioServer(name, command: str, args: list[str] = [], env: dict[str, str] | None = None, type: Literal["stdio"] = "stdio", ...)
    • McpStreamableHttpServer(name, url: str, headers: dict[str, str] | None = None, timeout: float = 30.0, sse_read_timeout: float = 300.0, terminate_on_close: bool = True, type: Literal["http"] = "http", ...) (local agent configs honor timeout_seconds and ignore timeout, sse_read_timeout, and terminate_on_close)
    • McpServerConfig = McpStdioServer | McpStreamableHttpServer
  • SubagentConfig(name: str, description: str, system_instructions: str | SystemInstructions | None = None, capabilities: SubagentCapabilities | None = None, tools: list[Callable[..., Any] | str] | None = [], model: str | None = None, skills_config: SubagentSkillsConfig | SubagentInheritSkillsConfig | SubagentNoneSkillsConfig | SubagentOverrideSkillsConfig | None = None) (see Subagents). When capabilities is None, defaults to read-only tools. model overrides the model name on the parent agent’s endpoint.
  • SubagentCapabilities(agent_behavior: AgentBehavior = AUTONOMOUS, allowed_subagents: list[str] | None = None, enabled_tools: list[BuiltinTools] | None = None, disabled_tools: list[BuiltinTools] | None = None, run_command_config: RunCommandConfig | None = None) (on local configs, run_command_config overrides per-subagent timeout_seconds while enable_sandbox and enable_daemons inherit from the root config).
  • Subagent skills: SubagentSkillsConfig(inherit_config=None, none_config=None, override_config=None) (at most one set), SubagentInheritSkillsConfig(skill_names: list[str] = [], extra_skills_paths: list[str] = []), SubagentNoneSkillsConfig(), SubagentOverrideSkillsConfig(skills_paths: list[str] = [], inline_skills: list[InlineSkill] = []) (at least one non-empty; on LocalAgentConfig, LiteRTAgentConfig, and LocalOpenAIAgentConfig, only skills_paths is supported and non-empty inline_skills raises ValueError).

Sessions, compaction, budgets, hook payloads, and errors

Section titled “Sessions, compaction, budgets, hook payloads, and errors”
  • SessionContinuationMode: RESUME = "resume", CREATE_OR_RESUME = "create_or_resume", CREATE_ONLY = "create_only".
  • CompactionConfig(token_threshold: int | None = None) (> 0).
  • BudgetConfig(max_model_calls: int | None = None, max_tool_calls: int | None = None, max_input_tokens: int | None = None, max_output_tokens: int | None = None, max_total_tokens: int | None = None, scope: BudgetScope = BudgetScope.LIFETIME) (all limits >= 1; max_input_tokens and max_total_tokens measure net uncached input tokens).
  • BudgetScope: LIFETIME = "LIFETIME", FORWARD_LOOKING = "FORWARD_LOOKING".
  • StopReason: UNSPECIFIED, MAX_MODEL_CALLS_EXCEEDED, MAX_TOOL_CALLS_EXCEEDED, MAX_INPUT_TOKENS_EXCEEDED, MAX_OUTPUT_TOKENS_EXCEEDED, MAX_TOTAL_TOKENS_EXCEEDED, QUOTA_EXHAUSTED.
  • Hook payloads:
    • HookResult(allow: bool = True, message: str = "", modified_args: dict[str, Any] | None = None)
    • AskQuestionInteractionSpec(questions: list[AskQuestionEntry]), AskQuestionEntry(question: str, options: list[AskQuestionOption], is_multi_select: bool = False), AskQuestionOption(id: str, text: str)
    • QuestionHookResult(responses: list[QuestionResponse], cancelled: bool = False), QuestionResponse(selected_option_ids: list[str] | None = None, freeform_response: str = "", skipped: bool = False)
    • StopArgs(response_text: str = "", trajectory_id: str = "", continuation_count: int = 0, stop_reason: StopReason = UNSPECIFIED, error_message: str = ""), StopHookResult(decision: StopDecision = ALLOW_STOP, reason: str = "") (non-empty reason required when CONTINUE), StopDecision (ALLOW_STOP, CONTINUE).
  • Exceptions: AntigravityConnectionError, AntigravityExecutionError, AntigravityCancelledError (subclasses asyncio.CancelledError), AntigravityValidationError(message, errors=None), ToolExecutionError(message, tool_name, server_name=None, call_id=None, step_id=None) (subclasses RuntimeError). See Observability, evals, and errors.

See Policies and sandboxing for evaluation precedence and examples.

  • Types: Decision (APPROVE, DENY, ASK_USER), Policy(tool, decision, when=None, ask_user=None, name="", reason=""), AutoPolicy(ask_user=None, name="auto", model=None).
  • Builders: allow(tool, mcp_tools=None, *, when=None, name=""), deny(tool, mcp_tools=None, *, when=None, name="", reason=""), ask_user(tool, mcp_tools=None, *, handler=None, when=None, name="", reason="").
  • Presets: confirm_run_command(handler=None), safe_defaults(handler), workspace_only(workspaces), allow_all(), deny_all(), auto(*, name="auto", handler=None, model=None).
  • Additional exports in google.antigravity.hooks.policy: enforce(policies, *, mcp_servers=None) -> PreToolCallDecideHook, flatten_policies(policies) -> list[Policy], Predicate, AskUserHandler.

See Lifecycle hooks and triggers. Decorators accept sync or async callables and inject HookContext when a parameter is named context or typed as HookContext. Base classes: InspectHook[T], DecideHook[T], TransformHook[T, R]. Context hierarchy (inherits StateStore): HookContext (SessionContext -> TurnContext -> OperationContext in google.antigravity.hooks.hooks). Runner: HookRunner(hooks=None, ...) in google.antigravity.hooks.hook_runner.

DecoratorClassCategoryInput dataReturn
@on_session_startOnSessionStartHookInspectHookNone (None on .run())None
@on_session_endOnSessionEndHookInspectHookNone (None on .run())None
@pre_turnPreTurnHookDecideHookContentHookResult
@post_turnPostTurnHookInspectHookstrNone
@pre_tool_call_decidePreToolCallDecideHookDecideHookToolCallHookResult (optional modified_args)
@post_tool_callPostToolCallHookInspectHookToolResultNone
@on_tool_errorOnToolErrorHookTransformHookException (ToolExecutionError)str | None
@on_interactionOnInteractionHookTransformHookAskQuestionInteractionSpecQuestionHookResult
@on_compactionOnCompactionHookInspectHookStepNone
@stopStopHookTransformHookStopArgsStopHookResult

See Lifecycle hooks and triggers.

SymbolSignature / FieldsDescription
@triggertrigger(func: Callable[[TriggerContext], Awaitable[None]])Validates a single-argument async def trigger and marks __is_trigger__ = True.
TriggerCallable[[TriggerContext], Awaitable[None]]Trigger callable type alias.
TriggerContextasync send(content: str) -> NonePer-trigger handle that pushes notifications into the active agent connection.
everyevery(interval_seconds: float, callback) -> TriggerInvokes await callback(ctx) repeatedly after each interval_seconds (> 0).
on_file_changeon_file_change(path: str | Path, callback) -> TriggerWatches path and invokes await callback(ctx, changes: Sequence[FileChange]). Lazily imports watchfiles (install separately).
FileChange / FileChangeKindFileChange(kind: FileChangeKind, path: str); ADDED = "added", MODIFIED = "modified", DELETED = "deleted"Frozen change record emitted by on_file_change.
TriggerRunnerTriggerRunner(triggers, connection) (start(), stop(), is_running, async with)Imported from google.antigravity.triggers.trigger_runner for Layer 2 sessions.

See Tools and skills.

  • ToolContext (google.antigravity.ToolContext / google.antigravity.tools.tool_context): auto-injected into any custom tool parameter typed as ToolContext (including Optional, Union, Annotated, and deferred string annotations) and stripped from the model-facing schema. Exposes conversation_id: str and inherits thread-safe StateStore methods (independent from HookContext).
  • ToolWithSchema(fn: Callable[..., Any], input_schema: dict[str, Any]) (google.antigravity.tools.tool_runner): wraps a callable with an explicit JSON Schema while preserving metadata and ToolContext injection.
  • ToolRunner(tools=None) (google.antigravity.tools.tool_runner): Layer 2 registry with register(tool, name=None), unregister(name), set_context(ctx), get_public_callable(tool_name), async execute(tool_name, **kwargs), async process_tool_calls(tool_calls) -> list[ToolResult], tool_names, and tools.
  • Structured built-in tool outputs (google.antigravity.connections.local): RunCommandResult(output=""), ListDirectoryEntry(name="", is_directory=False, file_size=0), ListDirectoryResult(entries=[]), SearchDirectoryResult(num_results=0), FindFileResult(output=""), EditFileResult(summary=""), GenerateImageResult(image_name="", aspect_ratio="", output_path=""), SearchWebResult(summary=""), ReadUrlContentResult(title="", summary="", content_path=""), TextResult(text=""), and their union ToolOutput.

Beta namespace and workflows (google.antigravity.beta)

Section titled “Beta namespace and workflows (google.antigravity.beta)”

Experimental APIs live under google.antigravity.beta and .beta class/instance accessors and may change between minor releases. See Workflows.

  • Namespace helpers: @beta (or @beta("CustomName")), BetaNamespace, is_beta(obj) -> bool.
  • Workflow results: beta.WorkflowResult (subclasses ChatResponse; adds script_path: str, script: str, description: str, output: str, response_text: str) and beta.WorkflowProgress(script_path="", script="", description="", output="").
  • google.antigravity.beta.workflows:
    • Authoring and validation: @workflows.define(fn) -> WorkflowDefinition(name, description, source, fn) (zero-argument function; bans top-level return, any yield, and print()), extract_workflow_source(fn_or_def) -> str, validate_workflow_source(source: str) -> None, WorkspaceMode = Literal["inherit", "branch", "share"], WorkflowError, ToolError(tool: str, message: str).
    • Workflow script primitives (compile-time typed stubs; calling directly outside a workflow run raises RuntimeError):
      • workflows.phase(name: str) -> str
      • workflows.log(*values: Any) -> None
      • workflows.agent(prompt: str | None = None, schema: Any = None, role: str | None = None, type_name: str = "self", workspace: WorkspaceMode = "inherit") -> WorkflowAgent (await directly for single-turn, or bind and call await handle(prompt: str, schema: Any = None) for multi-turn)
      • await workflows.call_tool(name: str, **tool_args: Any) -> str
      • await workflows.parallel(items: Iterable[Any], fn: Callable[[Any], Awaitable[Any]]) -> list[Any]
      • await workflows.pipeline(items: Iterable[Any], fn: Callable[[Any], Awaitable[Any]]) -> list[Any]
      • workflows.args: dict[str, Any] (populated from agent.beta.run_workflow(..., args={...}))
  • google.antigravity.utils.interactive (development CLI helpers): async run_interactive_loop(config: AgentConfig, agent_class: type[Agent] = Agent) -> None, AskQuestionHook (OnInteractionHook), ToolConfirmationHook (PreToolCallDecideHook), async ask_user_handler(tc: ToolCall, reason: str = "") -> bool, async async_input(prompt: str = "") -> str, Spinner(message: str = "Thinking...").
  • google.antigravity.utils.otel (requires google-antigravity[otel]): get_otel_hooks(agent_name: str = "Antigravity") -> list[Hook], plus individual hook classes OTelSessionStartHook, OTelSessionEndHook, OTelPreTurnHook(agent_name="Antigravity"), OTelPostTurnHook, OTelPreStepHook, OTelPostStepHook, OTelPreToolCallHook, OTelPostToolCallHook, OTelOnToolErrorHook.
  • google.antigravity.utils.state: StateStore(parent: StateStore | None = None) with threading.RLock-protected get_state(key, default=None), set_state(key, value), update_state(key, updater_fn, default=None), lock() -> RLock, and with store: context manager protocol.

Explicit keyword arguments on LocalAgentConfig, GeminiAPIEndpoint, and VertexEndpoint always take precedence over environment variables:

VariableUsed byDescription
GEMINI_API_KEYGeminiAPIEndpoint, LocalAgentConfigAPI key for the default Gemini Developer API backend (validated from os.environ, not config.env; also required by localharness at runtime when GeminiAPIEndpoint(base_url=...) is set without api_key).
GOOGLE_GEMINI_BASE_URLLocalConnectionStrategyFallback base URL for GeminiAPIEndpoint when endpoint.base_url is unset (also read from config.env; still requires api_key or GEMINI_API_KEY).
GOOGLE_GENAI_USE_VERTEXAILocalAgentConfigSet to "True" or "1" (case-insensitive) to enable Gemini Enterprise (vertex=True) by default.
GOOGLE_GENAI_USE_ENTERPRISELocalAgentConfigAlias for GOOGLE_GENAI_USE_VERTEXAI ("True" or "1" enables vertex=True).
GOOGLE_CLOUD_PROJECTVertexEndpointDefault Google Cloud project ID for Standard Mode (ignored when api_key or base_url is set).
GOOGLE_CLOUD_LOCATIONVertexEndpointDefault Google Cloud region for Standard Mode (ignored when api_key or base_url is set).
ANTIGRAVITY_HARNESS_PATHLocalConnectionStrategyAbsolute path override for the localharness runtime binary (also honored through LocalAgentConfig(env=...)).
ANTIGRAVITY_ALLOW_CPULiteRTConnectionStrategySet to "1" to suppress the startup warning when running LiteRTAgentConfig on a host without verified Metal or CUDA acceleration.