Skip to content
Models and configuration - Antigravity SDKsdkAntigravity SDKAntigravity SDKModels and configuration - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

Configure which models power your agent, tune reasoning effort, service tier, output token limits, and retries, and customize runtime behavior through LocalAgentConfig and its fluent presets. All fields on LocalAgentConfig are passed as keyword arguments and validated with Pydantic when constructed.

When you create LocalAgentConfig() with no model arguments, the SDK populates two default targets defined in google.antigravity.models:

ConstantDefault model IDModelTypePurpose
DEFAULT_MODEL"gemini-4-hydrogen"ModelType.TEXT ("text")Primary agent reasoning, conversation, and tool orchestration.
DEFAULT_IMAGE_GENERATION_MODEL"gemini-3.1-flash-lite-image"ModelType.IMAGE ("image")Image generation when BuiltinTools.GENERATE_IMAGE is called.

You can inspect or import both constants directly from google.antigravity.models. When LocalAgentConfig resolves its final target list, it merges sources in strict priority order:

  1. Explicit models (list[ModelTarget]): Added first, exactly as configured.
  2. Shorthand model (str or ModelTarget): Appended after models. If a ModelTarget omits endpoint, it inherits the shorthand endpoint built from vertex, api_key, project, and location.
  3. Defaults per missing ModelType: DEFAULT_MODEL is added only if no earlier entry covers ModelType.TEXT, and DEFAULT_IMAGE_GENERATION_MODEL is added only if no earlier entry covers ModelType.IMAGE. When multiple entries declare the same ModelType, the first matching entry wins.

Pass a model ID string to model to replace the default ModelType.TEXT model while inheriting your top-level authentication settings and keeping DEFAULT_IMAGE_GENERATION_MODEL for ModelType.IMAGE:

from google.antigravity import LocalAgentConfig

config = LocalAgentConfig(
    model="gemini-4-hydrogen",
)

You can also pass a single ModelTarget to model when you want to attach GeminiModelOptions or a custom endpoint without building a full models list:

from google.antigravity import (
    GeminiAPIEndpoint,
    GeminiModelOptions,
    LocalAgentConfig,
    ModelTarget,
    ThinkingLevel,
)

config = LocalAgentConfig(
    model=ModelTarget(
        name="gemini-4-hydrogen",
        endpoint=GeminiAPIEndpoint(
            options=GeminiModelOptions(thinking_level=ThinkingLevel.HIGH),
        ),
    ),
)

Route multiple modalities with ModelTarget

Section titled “Route multiple modalities with ModelTarget”

Use models with ModelTarget(name, types, endpoint) and ModelType to configure separate model IDs for text reasoning (ModelType.TEXT) and image generation (ModelType.IMAGE). ModelTarget.types defaults to [ModelType.TEXT], and every ModelTarget in models must specify a valid endpoint (GeminiAPIEndpoint or VertexEndpoint). On local sessions, the runtime builds its API client from the first ModelType.TEXT target’s endpoint (sharing its backend, credentials, base_url, headers, and options across image generation requests while using the first ModelType.IMAGE target’s name):

from google.antigravity import (
    GeminiAPIEndpoint,
    GeminiModelOptions,
    LocalAgentConfig,
    ModelTarget,
    ModelType,
    ThinkingLevel,
)

config = LocalAgentConfig(
    models=[
        ModelTarget(
            name="gemini-4-hydrogen",
            types=[ModelType.TEXT],
            endpoint=GeminiAPIEndpoint(
                options=GeminiModelOptions(thinking_level=ThinkingLevel.HIGH),
            ),
        ),
        ModelTarget(
            name="gemini-3.1-flash-lite-image",
            types=[ModelType.IMAGE],
            endpoint=GeminiAPIEndpoint(),
        ),
    ],
)

To assign a different model ID to a specific subagent (running on the parent agent’s endpoint), set model on SubagentConfig. See Subagents.


Attach GeminiModelOptions to GeminiAPIEndpoint(options=...) or VertexEndpoint(options=...) to control thinking depth, inference service tier, and per-step output token limits.

FieldTypeDefaultDescription
thinking_levelThinkingLevel or NoneNone (model default)Amount of extended reasoning performed before responding.
service_tierServiceTier or NoneNone (backend default)Compute queue priority and rate-limit fallback tier.
max_output_tokensint or NoneNone (65,535 fallback default)Maximum output tokens per model step (0 < n <= 2,147,483,647).

ThinkingLevel adjusts how much reasoning a thinking-capable Gemini model performs before emitting text or tool calls (see the Gemini thinking levels guide):

Enum memberWire valueTypical use
ThinkingLevel.MINIMAL"minimal"Lowest latency for straightforward lookups and routing.
ThinkingLevel.LOW"low"Light reasoning for fast interactive turns.
ThinkingLevel.MEDIUM"medium"Balanced latency and depth for everyday coding tasks.
ThinkingLevel.HIGH"high"Deep multi-step planning, debugging, and .eval() benchmarks.
ThinkingLevel.EXTRA_HIGH"xhigh"Maximum reasoning budget for the hardest tasks on supported models.

ServiceTier selects the inference processing queue for a model endpoint:

  • ServiceTier.STANDARD ("standard"): Standard on-demand processing.
  • ServiceTier.PRIORITY ("priority"): High-priority compute queue for low, predictable latency (billed at Priority tier rates; see Gemini Priority Inference).
  • ServiceTier.FLEX ("flex"): Flexible processing tier for latency-tolerant batch or background workloads.

When traffic on ServiceTier.PRIORITY exceeds dynamic rate limits, the backend can automatically serve overflow requests on ServiceTier.STANDARD (billed at standard rates) rather than failing with HTTP 429 or 503. Inspect response.usage_metadata.service_tier after a turn completes to check which tier served the request (see prioritized_inference.py):

import asyncio
from google.antigravity import (
    Agent,
    GeminiAPIEndpoint,
    GeminiModelOptions,
    LocalAgentConfig,
    ModelTarget,
    ServiceTier,
    ThinkingLevel,
)


async def main() -> None:
    config = LocalAgentConfig(
        model=ModelTarget(
            name="gemini-4-hydrogen",
            endpoint=GeminiAPIEndpoint(
                options=GeminiModelOptions(
                    thinking_level=ThinkingLevel.MEDIUM,
                    service_tier=ServiceTier.PRIORITY,
                    max_output_tokens=100_000,
                ),
            ),
        ),
    )

    async with Agent(config) as agent:
        response = await agent.chat("Audit the error handling in this package.")
        text = await response.text()
        print(text)

        usage = response.usage_metadata
        if usage and usage.service_tier == ServiceTier.STANDARD:
            print("Note: request fell back from PRIORITY to STANDARD tier.")


asyncio.run(main())

When max_output_tokens is None, the local runtime uses the model’s registered output limit when known and otherwise defaults to 65,535 output tokens per step (including for gemini-4-hydrogen). Set max_output_tokens to any positive 32-bit signed integer (1 through 2,147,483,647) to lower per-step output ceilings or to allow decodes above 64k tokens on models that support larger output limits.


The runtime automatically retries transient model API failures and malformed model outputs when retry_config is omitted:

  • API retries (ModelAPIRetryConfig): Defaults to 8 retries (9 total attempts) with a 4,000 ms initial sleep, 2.0 exponential multiplier, and 0.4 jitter range (capped at 4 minutes) for transient errors such as HTTP 429 rate limits, 5xx responses, and dropped connections. Supports max_retries (0 to 4,294,967,295; pass 0 to fail fast), initial_sleep_duration_ms (use > 0 to override the 4,000 ms default), exponential_multiplier (use > 0.0 to override the 2.0 default, such as 1.0 for constant backoff), and jitter_range (>= 0.0).
  • Model output retries (ModelOutputRetryConfig): Defaults to 4 retries when the model emits a malformed tool call or violates a configured response_schema. Supports max_retries (0 to 4,294,967,295).
  • Benchmark preset (RetryConfig.benchmark()): Configures ModelAPIRetryConfig(max_retries=4_294_967_295, initial_sleep_duration_ms=1000) (max uint32, 2^32 - 1) so transient 429 and 503 throttling does not abort long evaluation or load-test runs, while leaving model_output_retry at its standard runtime default.
from google.antigravity import (
    LocalAgentConfig,
    ModelAPIRetryConfig,
    ModelOutputRetryConfig,
    RetryConfig,
)

# Custom retry policy for production services
service_config = LocalAgentConfig(
    retry_config=RetryConfig(
        api_retry=ModelAPIRetryConfig(
            max_retries=5,
            initial_sleep_duration_ms=1000,
            exponential_multiplier=2.0,
            jitter_range=0.1,
        ),
        model_output_retry=ModelOutputRetryConfig(max_retries=2),
    ),
)

# High-resilience preset for evaluation suites
benchmark_config = LocalAgentConfig(
    retry_config=RetryConfig.benchmark(),
)

Every AgentConfig subclass exposes .lightweight() and .eval(). Both methods return a modified copy of the configuration and preserve any fields you explicitly passed on the original instance.

Setting.lightweight().eval(thinking_level=ThinkingLevel.HIGH)
Built-in toolsenabled_tools=BuiltinTools.minimal() (run_command, view_file, create_file, edit_file)disabled_tools=[BuiltinTools.GENERATE_IMAGE] (skipped if you set enabled_tools)
Agent behaviorAgentBehavior.MINIMAL (trimmed prompt scaffolding)Unchanged (AgentBehavior.AUTONOMOUS by default)
Subagentsenable_subagents=Falseenable_subagents=False
Command executionUnchangedrun_command_config=RunCommandConfig(enable_daemons=True) (merged with your run_command_config)
PoliciesUnchanged (policy.confirm_run_command() by default)policies=[policy.allow_all()]
RetriesUnchangedretry_config=RetryConfig.benchmark()
CompactionCompactionConfig(token_threshold=65536) (40960 on LiteRTAgentConfig)Unchanged
Thinking levelUnchangedThinkingLevel.HIGH on ModelType.TEXT Gemini and Vertex targets
from google.antigravity import (
    CompactionConfig,
    LocalAgentConfig,
    LocalOpenAIAgentConfig,
    ThinkingLevel,
)

# Small-context preset with a custom compaction override preserved
local_config = LocalOpenAIAgentConfig(
    model="gemma4:26b",
    base_url="http://localhost:11434/v1",
    compaction_config=CompactionConfig(token_threshold=32768),
).lightweight()

# Standardized evaluation preset (autonomous tools, benchmark retries, HIGH thinking)
eval_config = LocalAgentConfig(
    workspaces=["/tmp/eval-task"],
).eval()

# Override the eval thinking level, or pass None to keep existing ModelTarget options
medium_eval_config = LocalAgentConfig().eval(
    thinking_level=ThinkingLevel.MEDIUM
)

All parameters on LocalAgentConfig are keyword-only:

FieldTypeDefaultDescription
modelstr, ModelTarget, or NoneNoneShorthand model override. Merged after models and before DEFAULT_MODEL ("gemini-4-hydrogen").
modelslist[ModelTarget] or NoneDefault text + image targetsExplicit ModelTarget list with highest merge priority across ModelType.TEXT and ModelType.IMAGE.
api_keystr or NoneNoneAPI key for the Gemini Developer API (falls back to GEMINI_API_KEY) or Gemini Enterprise Express Mode (vertex=True). See Authentication.
vertexbool or NoneNoneRoutes shorthand models to VertexEndpoint when True. Auto-set to True if GOOGLE_GENAI_USE_VERTEXAI or GOOGLE_GENAI_USE_ENTERPRISE is "true" or "1". See Authentication.
projectstr or NoneNoneGoogle Cloud project ID for Gemini Enterprise Standard Mode (falls back to GOOGLE_CLOUD_PROJECT; mutually exclusive with api_key). See Authentication.
locationstr or NoneNoneGoogle Cloud region for Gemini Enterprise Standard Mode (falls back to GOOGLE_CLOUD_LOCATION; mutually exclusive with api_key). See Authentication.
system_instructionsstr, SystemInstructions, or NoneNonePlain string (wrapped as TemplatedSystemInstructions), TemplatedSystemInstructions, or full-replacement CustomSystemInstructions. See Personas and instructions.
workspaceslist[str] or None[os.getcwd()]Workspace directories accessible to the agent. Expands ~ and resolves relative paths to absolute paths; file tools are confined to these directories by default.
envdict[str, str] or NoneNoneEnvironment variable overrides merged onto os.environ for the localharness subprocess and run_command executions (also consulted for ANTIGRAVITY_HARNESS_PATH and GOOGLE_GEMINI_BASE_URL).
app_data_dirstr or NoneNone (~/.gemini/antigravity)Root directory for runtime data, brain/ artifacts, scratch files, and generated media. Must be an absolute path; unexpanded ~ or relative paths raise ValueError (use os.path.expanduser() or pathlib.Path.resolve()). See Sessions and context.
capabilitiesCapabilitiesConfig or NoneCapabilitiesConfig()Controls visible built-in tools (enabled_tools or disabled_tools), agent_behavior, enable_subagents, max_subagent_depth, allowed_subagents, run_command_config, tool_output_truncation_config, and mcp_max_output_bytes. See Tools and skills.
policiesSequence[Policy], nested Sequence, or Nonepolicy.confirm_run_command()Declarative tool execution policies (nested lists are flattened automatically). Allows standard tools and denies run_command by default. Passing policies=[] while write tools or MCP servers are active without a PreToolCallDecideHook raises ValueError at startup. See Policies and sandboxing.
hookslist[Hook] or None[]Lifecycle hooks (InspectHook, DecideHook, TransformHook) for session, turn, tool, error, interaction, compaction, and stop interception. See Lifecycle hooks and triggers.
triggerslist[Trigger] or None[]Background async triggers (such as triggers.every() and triggers.on_file_change()) that send proactive prompts during the session. See Lifecycle hooks and triggers.
toolslist[Callable[..., Any]] or None[]Custom sync or async Python functions, callables, or ToolWithSchema wrappers exposed as tools (with optional auto-injected ToolContext). See Tools and skills.
mcp_serverslist[McpServerConfig] or None[]External McpStdioServer and McpStreamableHttpServer definitions. See MCP.
subagentslist[SubagentConfig] or None[]Static subagent definitions with dedicated instructions, capabilities, tools, model overrides, and skill configurations. See Subagents.
skills_pathslist[str] or None[]Filesystem paths containing SKILL.md directories. Mutually exclusive with inline_skills (combining both raises ValueError). See Tools and skills.
inline_skillslist[InlineSkill] or None[]In-memory InlineSkill definitions passed without filesystem directories. Mutually exclusive with skills_paths. See Tools and skills.
response_schemadict[str, Any], type[BaseModel], str, or NoneNonePydantic BaseModel subclass, JSON Schema dict, or JSON string constraining the agent’s final output (read with await response.structured_output()). See Structured output.
save_dirstr or NoneNone (temporary dir)Directory used to persist conversation trajectories across runs. When None, the SDK creates a temporary antigravity_* directory. See Sessions and context.
conversation_idstr or NoneNoneSession identifier for creating or resuming a saved conversation. When set, must be at least 32 characters matching ^[a-zA-Z0-9-]+$. Required when session_continuation_mode is RESUME. See Sessions and context.
session_continuation_modeSessionContinuationMode or NoneNoneSession resume policy (RESUME, CREATE_OR_RESUME, or CREATE_ONLY from google.antigravity.types). See Sessions and context.
compaction_configCompactionConfig or NoneNone (backend default)Sets CompactionConfig(token_threshold=...) for automatic history compaction (replaces deprecated CapabilitiesConfig.compaction_threshold). See Sessions and context.
budget_configBudgetConfig or NoneNoneEnforces ceilings on model calls, tool calls, and input, output, or total tokens (BudgetScope.LIFETIME or FORWARD_LOOKING). See Sessions and context.
retry_configRetryConfig or NoneNone (8 API / 4 output retries)Overrides API backoff retries (ModelAPIRetryConfig) and output validation retries (ModelOutputRetryConfig).
debug_configDebugConfig, bool, dict, or NoneNoneConfigures client-side SDK logging (google.antigravity logger level, defaulting to logging.DEBUG when debug_config=True; attach a standard Python logging handler such as logging.basicConfig() to emit output, while enable_server_side_tracing is unused on local configs). Pass debug_config=True or a DebugConfig from google.antigravity.connections.connection. See Observability, evals, and errors.

LiteRTAgentConfig and LocalOpenAIAgentConfig inherit the same core runtime fields from BaseLocalAgentConfig and replace the Gemini/Vertex model and auth shorthands with local backend parameters. See Local models and API reference.