API reference
Section titled “API reference”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).
Package overview and top-level exports
Section titled “Package overview and top-level exports”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
Public modules
Section titled “Public modules”| Module | Contents | Guide |
|---|---|---|
google. | Agent, agent configs, model types, system instructions, media helpers, CapabilitiesConfig, BuiltinTools, CompactionConfig, InlineSkill, ToolContext, UsageMetadata, SandboxStatus, ToolExecutionError, beta. | Overview, Quickstart |
google. | DEFAULT_MODEL, DEFAULT_IMAGE_GENERATION_MODEL, endpoints, options, ThinkingLevel, ServiceTier, ModelTarget, ModelType. | Authentication, Models and configuration |
google. | Full 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. | Policy builders, presets, Policy, AutoPolicy, and Decision (plus enforce, flatten_policies, Predicate, AskUserHandler in google.antigravity.hooks.policy). | Policies and sandboxing |
google. | Lifecycle hook base classes, 10 hook classes and decorators, HookContext, policy (plus HookRunner in google.antigravity.hooks.hook_runner). | Lifecycle hooks and triggers |
google. | trigger, Trigger, TriggerContext, every, on_file_change, FileChange, FileChangeKind (plus TriggerRunner in google.antigravity.triggers.trigger_runner). | Lifecycle hooks and triggers |
google. | ToolContext (tools.tool_context), ToolRunner and ToolWithSchema (tools.tool_runner). | Tools and skills |
google. | Conversation stateful Layer 2 session API. | Sessions and context |
google. | AgentConfig, Connection, ConnectionStrategy, DebugConfig, resolve_active_tools. | Models and configuration |
google. | LocalAgentConfig, LiteRTAgentConfig, LiteRTBackend, LocalOpenAIAgentConfig, LocalConnection, LocalConnectionStrategy, LocalConnectionStep, callable_to_tool_proto, and structured built-in tool result models (ToolOutput). | Local models, Tools and skills |
google. | beta decorator, BetaNamespace, is_beta, workflows, WorkflowResult, WorkflowProgress. | Workflows |
google. | utils.interactive (terminal REPL and approval hooks), utils.otel (OpenTelemetry hooks), utils.state (StateStore). | Policies and sandboxing, Observability, evals, and errors |
Top-level google.antigravity.__all__
Section titled “Top-level google.antigravity.__all__”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.
| Member | Signature or type | Description |
|---|---|---|
__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. |
chat | async chat(prompt: Content) -> ChatResponse | Sends 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. | async 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_started | bool | True while the agent session has an active Conversation. |
conversation | Conversation | Active Layer 2 Conversation. Raises RuntimeError before entering async with Agent(config). |
conversation_id | str | None | Runtime-assigned session ID (populated once the first live step of a turn is received), or None before a turn runs. |
sandbox_status | SandboxStatus | None | OS command sandbox status reported at startup, or None before startup or when unreported. |
Agent configuration classes
Section titled “Agent configuration classes”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):
| Parameter | Type | Local config default | Description |
|---|---|---|---|
system_ | str | SystemInstructions | None | None | Plain str (appended as a templated section), TemplatedSystemInstructions, or CustomSystemInstructions (full replacement). |
capabilities | CapabilitiesConfig | CapabilitiesConfig() | 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().) |
tools | list[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. |
policies | Sequence[Policy | Sequence[Policy]] | policy.confirm_run_command() | Declarative tool policies. Nested lists are flattened automatically. |
hooks | list[Hook] | [] | Decorated functions or Hook subclass instances routed by type. |
triggers | list[Trigger] | [] | Long-lived background async trigger callables started for the session. |
mcp_servers | list[McpServerConfig] | [] | McpStdioServer and McpStreamableHttpServer configurations. |
subagents | list[SubagentConfig] | [] | Static subagent definitions available to invoke_subagent and workflows.agent(type_name=...). |
workspaces | list[str] | [os.getcwd()] | Workspace directories. Expands ~, normalizes file:// URIs, and resolves relative paths against os.getcwd(). |
env | dict[str, str] | None | None | Environment variable overrides for the local runtime subprocess and run_command executions. |
conversation_id | str | None | None | Session ID to create or resume. Must be >= 32 characters and match ^[a-zA-Z0-9-]+$. |
session_ | SessionContinuationMode | None | None | RESUME (requires conversation_id), CREATE_OR_RESUME, or CREATE_ONLY. |
save_dir | str | None | None | Directory for persisted session trajectories (auto-creates a temporary antigravity_* directory when None). |
app_data_dir | str | None | None | Absolute path overriding default ~/.gemini/antigravity storage for artifacts, scratch files, and media. Rejects relative and unexpanded ~ paths. |
response_schema | dict[str, Any] | type[BaseModel] | str | None | None | Pydantic BaseModel subclass, JSON Schema dict, or JSON str enforcing structured output through finish. |
skills_paths | list[str] | [] | Directories containing SKILL.md files or skill subfolders. Mutually exclusive with inline_skills on local configs. |
inline_skills | list[InlineSkill] | [] | In-memory skill definitions. Mutually exclusive with skills_paths on local configs. |
retry_config | RetryConfig | None | None | API exponential backoff and model output retry settings. |
budget_config | BudgetConfig | None | None | Call and token budget caps (LIFETIME or FORWARD_LOOKING). |
compaction_ | CompactionConfig | None | None | Context compaction token ceiling (token_threshold). |
debug_config | DebugConfig | bool | dict | None | None | Enables "google.antigravity" logger level and backend tracing (True constructs DebugConfig()). |
LocalAgentConfig parameters
Section titled “LocalAgentConfig parameters”Cloud Gemini API and Gemini Enterprise (formerly Vertex AI) configuration (google.antigravity.LocalAgentConfig). Adds these keyword parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
model | str | ModelTarget | None | None | Shorthand text model name or ModelTarget. Falls back to DEFAULT_MODEL ("gemini-4-hydrogen"). |
models | list[ModelTarget] | None | None | Explicit model target list. Merge precedence: models > model > defaults (DEFAULT_MODEL for TEXT, DEFAULT_IMAGE_GENERATION_MODEL for IMAGE). |
api_key | str | None | None | API key for Gemini Developer API (default) or Gemini Enterprise Express Mode (when vertex=True). |
vertex | bool | None | None | Routes to Gemini Enterprise (VertexEndpoint). Auto-set to True when GOOGLE_GENAI_USE_VERTEXAI or GOOGLE_GENAI_USE_ENTERPRISE is "true" or "1". |
project | str | None | None | Google Cloud project ID for Gemini Enterprise Standard Mode (ADC). Falls back to GOOGLE_CLOUD_PROJECT. |
location | str | None | None | Google Cloud region for Gemini Enterprise Standard Mode (for example, "us-central1"). Falls back to GOOGLE_CLOUD_LOCATION. |
LiteRTAgentConfig and LiteRTBackend
Section titled “LiteRTAgentConfig and LiteRTBackend”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).
| Parameter | Type | Default | Description |
|---|---|---|---|
model_path | str | (required) | Absolute path to a .litertlm checkpoint (use os.path.expanduser() for ~). |
backend | LiteRTBackend | str | LiteRTBackend.GPU | Hardware backend: LiteRTBackend.CPU ("cpu"), LiteRTBackend.GPU ("gpu"), or LiteRTBackend.NPU ("npu"). |
enable_ | bool | False | Enables multi-token prediction speculative decoding. |
cache_dir | str | None | None | Writable directory for engine compilation cache. |
audio_backend | LiteRTBackend | str | None | None | Hardware backend override for audio processing. |
vision_backend | LiteRTBackend | str | None | None | Hardware backend override for image/vision processing (auto-detected from litert_lm.ModelInfo when None). |
port | int | 0 | Local loopback server port (0 selects an ephemeral port). |
download_ | bool | False | Reserved flag for automatic weight downloads (currently not enforced in v0.1.24; model_path must exist on disk or startup raises AntigravityValidationError). |
LocalOpenAIAgentConfig parameters
Section titled “LocalOpenAIAgentConfig parameters”Configuration for external OpenAI-compatible servers such as Ollama, LM Studio, or vLLM (google.antigravity.LocalOpenAIAgentConfig; call .lightweight() explicitly for small-context models):
| Parameter | Type | Default | Description |
|---|---|---|---|
model | str | ModelTarget | None | None | Model identifier served by the external endpoint (for example, "gemma-4-26B-A4B-it"). |
base_url | str | None | None | Non-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”| Symbol | Signature / Fields | Description |
|---|---|---|
config. | lightweight() -> Self | Returns 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(thinking_level: ThinkingLevel | None = ThinkingLevel.HIGH) -> Self | Returns 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(*, tool_runner, hook_runner) -> ConnectionStrategy | Instantiates the Layer 3 ConnectionStrategy for the config. |
DebugConfig | enable_server_side_tracing: bool = True, logging_level: int | str | None = logging.DEBUG, apply_logging() -> None | Imported 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). |
Models, endpoints, and retries
Section titled “Models, endpoints, and retries”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.
| Symbol | Definition / Fields | Description |
|---|---|---|
DEFAULT_MODEL | "gemini-4-hydrogen" | Default text generation model on LocalAgentConfig. |
DEFAULT_ | "gemini-3.1-flash-lite-image" | Default image generation model on LocalAgentConfig. |
ModelTarget | name: str | None = None, types: list[ModelType] = [ModelType.TEXT], endpoint: ModelEndpoint | None = None | Associates a model name and modalities with an authentication endpoint. |
ModelType | TEXT = "text", IMAGE = "image" | Model purpose discriminator enum. |
ModelEndpoint | base_url: str | None = None, http_headers: dict[str, str] | None = None, validate_endpoint() -> None | Abstract base class for model endpoints. |
Gemini | api_key: str | None = None, options: GeminiModelOptions | None = None, base_url=None, http_headers=None | Gemini Developer API endpoint (requires api_key or GEMINI_API_KEY unless base_url is set). |
VertexEndpoint | project: str | None = None, location: str | None = None, api_key: str | None = None, options: GeminiModelOptions | None = None, base_url=None, http_headers=None | Gemini 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). |
Gemini | thinking_level: ThinkingLevel | None = None, service_tier: ServiceTier | None = None, max_output_tokens: int | None = None | Gemini generation options (max_output_tokens in (0, 2^31 - 1]; uses the model’s registered output limit or falls back to 65535). |
ThinkingLevel | MINIMAL = "minimal", LOW = "low", MEDIUM = "medium", HIGH = "high", EXTRA_HIGH = "xhigh" | Reasoning depth enum for thinking-capable Gemini models. |
ServiceTier | STANDARD = "standard", PRIORITY = "priority", FLEX = "flex" | Inference compute tier enum. |
RetryConfig | api_retry: ModelAPIRetryConfig | None = None, model_output_retry: ModelOutputRetryConfig | None = None, RetryConfig.benchmark() -> RetryConfig | Combined 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. |
Model | max_retries: int | None = None, initial_sleep_duration_ms: int | None = None, exponential_multiplier: float | None = None, jitter_range: float | None = None | Exponential backoff settings for transient API errors (non-negative). |
Model | max_retries: int | None = None | Retry ceiling (>= 0) for malformed tool calls or response_schema validation failures. |
Responses, streaming, and conversations
Section titled “Responses, streaming, and conversations”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):
| Member | Signature or type | Description |
|---|---|---|
__aiter__ | async for token in response: ... (AsyncIterator[str]) | Streams conversational Text.text deltas. |
thoughts | AsyncIterator[str] | Streams internal model reasoning Thought.text deltas. |
tool_calls | AsyncIterator[ToolCall] | Streams deduplicated ToolCall dispatches in real time. |
chunks | AsyncIterator[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() -> str | Drains the stream and returns concatenated response text. |
resolve() | async resolve() -> list[StreamChunk | ToolCall | ToolResult] | Drains the stream and returns all buffered items. |
structured_ | async structured_output() -> Any | None | Drains the stream (re-raising any stream error) and returns the parsed root-turn response_schema payload, or None. |
cancel() | async cancel() -> None | Aborts the active turn on the backend (no-op if already finished), raising AntigravityCancelledError to consumers. |
usage_metadata | UsageMetadata | None | Per-turn accumulated token usage (snapshotted on completion). |
stop_reason | StopReason | Per-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*, andsum().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)):
| Member | Signature or type | Description |
|---|---|---|
create | async with Conversation.create(strategy) as conv: | Context manager that enters a ConnectionStrategy and yields a Conversation seeded with any restored history. |
chat | async chat(prompt: Content | None = None, **kwargs) -> ChatResponse | Sends prompt (draining any unconsumed prior turn first) and returns a ChatResponse. |
send | async send(prompt: Content | None, **kwargs) -> None | Low-level non-blocking prompt send. |
receive_steps | receive_steps() -> AsyncIterator[Step] | Yields and records Step updates until the turn becomes idle. |
receive_chunks | receive_chunks() -> AsyncIterator[StreamChunk | ToolCall] | Yields semantic Thought, Text, and deduplicated ToolCall chunks for the active turn. |
get_ | get_last_structured_output() -> Any | None | Returns the parsed structured output from the most recent root FINISH step, or None. |
clear_history | clear_history() -> None | Clears in-memory step history, turn indices, and compaction indices without closing the session. |
history | list[Step] | Copy of recorded steps across all turns (up to max_history_size; 0 disables trimming). |
last_response | str | Content of the most recent step with is_complete_response=True, or "". |
turn_count | int | Number of send() calls recorded in history. |
compaction_ | list[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_ / last_ / trajectory_ | UsageMetadata / UsageMetadata | None / dict[str, UsageMetadata] | Cumulative session usage, last-turn delta, and per-trajectory cumulative usage map. |
conversation_id / sandbox_status / is_idle / connection | str / SandboxStatus | None / bool / Connection | Session ID, OS sandbox status, idle state, and underlying Layer 3 Connection. |
cancel / wait_for_idle / wait_for_wakeup / disconnect | async 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)”Stepfields:id: str = "",step_index: int = 0,trajectory_id: str = "",parent_trajectory_id: str = ""(non-empty for subagent steps),depth: int = 0(remains0for subagent steps on local agent configs; filter subagent steps usingparent_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). (LocalConnectionStepinconnections.localextendsStepwithhttp_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.
Boundary types (google.antigravity.types)
Section titled “Boundary types (google.antigravity.types)”Capabilities and BuiltinTools
Section titled “Capabilities and BuiltinTools”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, default1),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 default10240),compaction_threshold: int | None = None(deprecated; useCompactionConfig).RunCommandConfig(enable_daemons: bool = False, timeout_seconds: float | None = None, enable_sandbox: bool = False)(default timeout600s).ToolOutputTruncationConfig(max_tokens: int)(0 <= max_tokens <= 2^31 - 1; preserves prefix, truncates tail;0disables).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-enablesmanage_taskwheneverRUN_COMMANDorSCHEDULEis active. - Opt-in only (include in
enabled_tools):ASK_QUESTION("ask_question"), and legacyBuiltinTools.deprecated()membersLIST_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 exceptRUN_COMMAND),minimal()(RUN_COMMAND,VIEW_FILE,CREATE_FILE,EDIT_FILE),file_tools()(VIEW_FILE,CREATE_FILE,EDIT_FILE),deprecated(),all_tools(),none().
- Default-enabled (
Instructions, behavior, and slash commands
Section titled “Instructions, behavior, and slash commands”TemplatedSystemInstructions(identity: str | None = None, sections: list[SystemInstructionSection] = [])andSystemInstructionSection(content: str, title: str = "user_system_instructions")(see Personas and instructions).CustomSystemInstructions(text: str, title: str | None = None): replaces all default system instructions; optionaltitlerenders<title>instead of<System>.SystemInstructions = CustomSystemInstructions | TemplatedSystemInstructions.AgentBehavior:AUTONOMOUS = "autonomous",INTERACTIVE = "interactive",MINIMAL = "minimal".SlashCommand(name: BuiltinSlashCommandName)(frozen) andBuiltinSlashCommandName:PLAN = "plan".
Multimodal content
Section titled “Multimodal content”ContentPrimitive = str | Image | Document | Audio | Video | SlashCommandandContent = ContentPrimitive | Sequence[ContentPrimitive].Image,Document,Audio,Video: frozen models withdata: bytes,mime_type: str(trimmed, case-insensitive validation),description: str | None = None, and classmethodfrom_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) andfrom_bytes(data: bytes, mime_type: str, description: str | None = None) -> Image | Document | Audio | Video.
Skills, MCP servers, and subagents
Section titled “Skills, MCP servers, and subagents”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 bothMcpStdioServerandMcpStreamableHttpServer; defaults to300s for connection/discovery and180s 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 honortimeout_secondsand ignoretimeout,sse_read_timeout, andterminate_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). WhencapabilitiesisNone, defaults to read-only tools.modeloverrides 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_configoverrides per-subagenttimeout_secondswhileenable_sandboxandenable_daemonsinherit 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; onLocalAgentConfig,LiteRTAgentConfig, andLocalOpenAIAgentConfig, onlyskills_pathsis supported and non-emptyinline_skillsraisesValueError).
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_tokensandmax_total_tokensmeasure 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-emptyreasonrequired whenCONTINUE),StopDecision(ALLOW_STOP,CONTINUE).
- Exceptions:
AntigravityConnectionError,AntigravityExecutionError,AntigravityCancelledError(subclassesasyncio.CancelledError),AntigravityValidationError(message, errors=None),ToolExecutionError(message, tool_name, server_name=None, call_id=None, step_id=None)(subclassesRuntimeError). See Observability, evals, and errors.
Policies (google.antigravity.policy)
Section titled “Policies (google.antigravity.policy)”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.
Hooks (google.antigravity.hooks)
Section titled “Hooks (google.antigravity.hooks)”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.
| Decorator | Class | Category | Input data | Return |
|---|---|---|---|---|
@on_ | On | InspectHook | None (None on .run()) | None |
@on_session_end | On | InspectHook | None (None on .run()) | None |
@pre_turn | PreTurnHook | DecideHook | Content | HookResult |
@post_turn | Post | InspectHook | str | None |
@pre_ | Pre | DecideHook | ToolCall | HookResult (optional modified_) |
@post_tool_call | Post | InspectHook | ToolResult | None |
@on_tool_error | On | Transform | Exception (Tool) | str | None |
@on_interaction | On | Transform | Ask | Question |
@on_compaction | On | InspectHook | Step | None |
@stop | StopHook | Transform | StopArgs | Stop |
Triggers (google.antigravity.triggers)
Section titled “Triggers (google.antigravity.triggers)”See Lifecycle hooks and triggers.
| Symbol | Signature / Fields | Description |
|---|---|---|
@trigger | trigger(func: Callable[[TriggerContext], Awaitable[None]]) | Validates a single-argument async def trigger and marks __is_trigger__ = True. |
Trigger | Callable[[TriggerContext], Awaitable[None]] | Trigger callable type alias. |
TriggerContext | async send(content: str) -> None | Per-trigger handle that pushes notifications into the active agent connection. |
every | every(interval_seconds: float, callback) -> Trigger | Invokes await callback(ctx) repeatedly after each interval_seconds (> 0). |
on_file_change | on_file_change(path: str | Path, callback) -> Trigger | Watches path and invokes await callback(ctx, changes: Sequence[FileChange]). Lazily imports watchfiles (install separately). |
FileChange / FileChangeKind | FileChange(kind: FileChangeKind, path: str); ADDED = "added", MODIFIED = "modified", DELETED = "deleted" | Frozen change record emitted by on_file_change. |
TriggerRunner | TriggerRunner(triggers, connection) (start(), stop(), is_running, async with) | Imported from google.antigravity.triggers.trigger_runner for Layer 2 sessions. |
Tools and structured tool outputs
Section titled “Tools and structured tool outputs”See Tools and skills.
ToolContext(google.antigravity.ToolContext/google.antigravity.tools.tool_context): auto-injected into any custom tool parameter typed asToolContext(includingOptional,Union,Annotated, and deferred string annotations) and stripped from the model-facing schema. Exposesconversation_id: strand inherits thread-safeStateStoremethods (independent fromHookContext).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 andToolContextinjection.ToolRunner(tools=None)(google.antigravity.tools.tool_runner): Layer 2 registry withregister(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, andtools.- 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 unionToolOutput.
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(subclassesChatResponse; addsscript_path: str,script: str,description: str,output: str,response_text: str) andbeta.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-levelreturn, anyyield, andprint()),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) -> strworkflows.log(*values: Any) -> Noneworkflows.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 callawait handle(prompt: str, schema: Any = None)for multi-turn)await workflows.call_tool(name: str, **tool_args: Any) -> strawait 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 fromagent.beta.run_workflow(..., args={...}))
- Authoring and validation:
Utilities (google.antigravity.utils)
Section titled “Utilities (google.antigravity.utils)”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(requiresgoogle-antigravity[otel]):get_otel_hooks(agent_name: str = "Antigravity") -> list[Hook], plus individual hook classesOTelSessionStartHook,OTelSessionEndHook,OTelPreTurnHook(agent_name="Antigravity"),OTelPostTurnHook,OTelPreStepHook,OTelPostStepHook,OTelPreToolCallHook,OTelPostToolCallHook,OTelOnToolErrorHook.google.antigravity.utils.state:StateStore(parent: StateStore | None = None)withthreading.RLock-protectedget_state(key, default=None),set_state(key, value),update_state(key, updater_fn, default=None),lock() -> RLock, andwith store:context manager protocol.
Environment variables
Section titled “Environment variables”Explicit keyword arguments on LocalAgentConfig, GeminiAPIEndpoint, and VertexEndpoint always take precedence over environment variables:
| Variable | Used by | Description |
|---|---|---|
GEMINI_API_KEY | GeminiAPIEndpoint, LocalAgentConfig | API 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_ | LocalConnectionStrategy | Fallback base URL for GeminiAPIEndpoint when endpoint.base_url is unset (also read from config.env; still requires api_key or GEMINI_API_KEY). |
GOOGLE_ | LocalAgentConfig | Set to "True" or "1" (case-insensitive) to enable Gemini Enterprise (vertex=True) by default. |
GOOGLE_ | LocalAgentConfig | Alias for GOOGLE_GENAI_USE_VERTEXAI ("True" or "1" enables vertex=True). |
GOOGLE_ | VertexEndpoint | Default Google Cloud project ID for Standard Mode (ignored when api_key or base_url is set). |
GOOGLE_ | VertexEndpoint | Default Google Cloud region for Standard Mode (ignored when api_key or base_url is set). |
ANTIGRAVITY_ | LocalConnectionStrategy | Absolute path override for the localharness runtime binary (also honored through LocalAgentConfig(env=...)). |
ANTIGRAVITY_ | LiteRTConnectionStrategy | Set to "1" to suppress the startup warning when running LiteRTAgentConfig on a host without verified Metal or CUDA acceleration. |