Models and configuration
Section titled “Models and configuration”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.
Default models and merge precedence
Section titled “Default models and merge precedence”When you create LocalAgentConfig() with no model arguments, the SDK populates
two default targets defined in google.antigravity.models:
| Constant | Default model ID | ModelType | Purpose |
|---|---|---|---|
DEFAULT_MODEL | "gemini-4-hydrogen" | ModelType.TEXT ("text") | Primary agent reasoning, conversation, and tool orchestration. |
DEFAULT_ | "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:
- Explicit
models(list[ModelTarget]): Added first, exactly as configured. - Shorthand
model(strorModelTarget): Appended aftermodels. If aModelTargetomitsendpoint, it inherits the shorthand endpoint built fromvertex,api_key,project, andlocation. - Defaults per missing
ModelType:DEFAULT_MODELis added only if no earlier entry coversModelType.TEXT, andDEFAULT_IMAGE_GENERATION_MODELis added only if no earlier entry coversModelType.IMAGE. When multiple entries declare the sameModelType, the first matching entry wins.
Select and route models
Section titled “Select and route models”Override the text model with model
Section titled “Override the text model with model”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.
Gemini model options
Section titled “Gemini model options”Attach GeminiModelOptions to GeminiAPIEndpoint(options=...) or
VertexEndpoint(options=...) to control thinking depth, inference service tier,
and per-step output token limits.
| Field | Type | Default | Description |
|---|---|---|---|
thinking_level | ThinkingLevel or None | None (model default) | Amount of extended reasoning performed before responding. |
service_tier | ServiceTier or None | None (backend default) | Compute queue priority and rate-limit fallback tier. |
max_ | int or None | None (65,535 fallback default) | Maximum output tokens per model step (0 < n <= 2,147,483,647). |
Thinking levels
Section titled “Thinking levels”ThinkingLevel adjusts how much reasoning a thinking-capable Gemini model
performs before emitting text or tool calls (see the
Gemini thinking levels guide):
| Enum member | Wire value | Typical use |
|---|---|---|
Thinking | "minimal" | Lowest latency for straightforward lookups and routing. |
Thinking | "low" | Light reasoning for fast interactive turns. |
Thinking | "medium" | Balanced latency and depth for everyday coding tasks. |
Thinking | "high" | Deep multi-step planning, debugging, and .eval() benchmarks. |
Thinking | "xhigh" | Maximum reasoning budget for the hardest tasks on supported models. |
Service tiers and dynamic fallback
Section titled “Service tiers and dynamic fallback”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())
Maximum output tokens
Section titled “Maximum output tokens”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.
Retry and backoff configuration
Section titled “Retry and backoff configuration”The runtime automatically retries transient model API failures and malformed
model outputs when retry_config is omitted:
- API retries (
ModelAPIRetryConfig): Defaults to8retries (9total attempts) with a4,000ms initial sleep,2.0exponential multiplier, and0.4jitter range (capped at 4 minutes) for transient errors such as HTTP429rate limits,5xxresponses, and dropped connections. Supportsmax_retries(0to4,294,967,295; pass0to fail fast),initial_sleep_duration_ms(use> 0to override the4,000ms default),exponential_multiplier(use> 0.0to override the2.0default, such as1.0for constant backoff), andjitter_range(>= 0.0). - Model output retries (
ModelOutputRetryConfig): Defaults to4retries when the model emits a malformed tool call or violates a configuredresponse_schema. Supportsmax_retries(0to4,294,967,295). - Benchmark preset (
RetryConfig.benchmark()): ConfiguresModelAPIRetryConfig(max_retries=4_294_967_295, initial_sleep_duration_ms=1000)(maxuint32,2^32 - 1) so transient429and503throttling does not abort long evaluation or load-test runs, while leavingmodel_output_retryat 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(),
)
Fluent configuration presets
Section titled “Fluent configuration presets”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 tools | enabled_tools=BuiltinTools.minimal() (run_command, view_file, create_file, edit_file) | disabled_tools=[BuiltinTools.GENERATE_IMAGE] (skipped if you set enabled_tools) |
| Agent behavior | AgentBehavior.MINIMAL (trimmed prompt scaffolding) | Unchanged (AgentBehavior.AUTONOMOUS by default) |
| Subagents | enable_subagents=False | enable_subagents=False |
| Command execution | Unchanged | run_command_config=RunCommandConfig(enable_daemons=True) (merged with your run_command_config) |
| Policies | Unchanged (policy.confirm_run_command() by default) | policies=[policy.allow_all()] |
| Retries | Unchanged | retry_config=RetryConfig.benchmark() |
| Compaction | CompactionConfig(token_threshold=65536) (40960 on LiteRTAgentConfig) | Unchanged |
| Thinking level | Unchanged | ThinkingLevel.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
)
LocalAgentConfig fields reference
Section titled “LocalAgentConfig fields reference”All parameters on LocalAgentConfig are keyword-only:
| Field | Type | Default | Description |
|---|---|---|---|
model | str, ModelTarget, or None | None | Shorthand model override. Merged after models and before DEFAULT_MODEL ("gemini-4-hydrogen"). |
models | list[ModelTarget] or None | Default text + image targets | Explicit ModelTarget list with highest merge priority across ModelType.TEXT and ModelType.IMAGE. |
api_key | str or None | None | API key for the Gemini Developer API (falls back to GEMINI_API_KEY) or Gemini Enterprise Express Mode (vertex=True). See Authentication. |
vertex | bool or None | None | Routes 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. |
project | str or None | None | Google Cloud project ID for Gemini Enterprise Standard Mode (falls back to GOOGLE_CLOUD_PROJECT; mutually exclusive with api_key). See Authentication. |
location | str or None | None | Google Cloud region for Gemini Enterprise Standard Mode (falls back to GOOGLE_CLOUD_LOCATION; mutually exclusive with api_key). See Authentication. |
system_ | str, SystemInstructions, or None | None | Plain string (wrapped as TemplatedSystemInstructions), TemplatedSystemInstructions, or full-replacement CustomSystemInstructions. See Personas and instructions. |
workspaces | list[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. |
env | dict[str, str] or None | None | Environment 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_dir | str or None | None (~/.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. |
capabilities | CapabilitiesConfig or None | CapabilitiesConfig() | 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. |
policies | Sequence[Policy], nested Sequence, or None | policy.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. |
hooks | list[Hook] or None | [] | Lifecycle hooks (InspectHook, DecideHook, TransformHook) for session, turn, tool, error, interaction, compaction, and stop interception. See Lifecycle hooks and triggers. |
triggers | list[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. |
tools | list[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_servers | list[McpServerConfig] or None | [] | External McpStdioServer and McpStreamableHttpServer definitions. See MCP. |
subagents | list[SubagentConfig] or None | [] | Static subagent definitions with dedicated instructions, capabilities, tools, model overrides, and skill configurations. See Subagents. |
skills_paths | list[str] or None | [] | Filesystem paths containing SKILL.md directories. Mutually exclusive with inline_skills (combining both raises ValueError). See Tools and skills. |
inline_skills | list[InlineSkill] or None | [] | In-memory InlineSkill definitions passed without filesystem directories. Mutually exclusive with skills_paths. See Tools and skills. |
response_schema | dict[str, Any], type[BaseModel], str, or None | None | Pydantic BaseModel subclass, JSON Schema dict, or JSON string constraining the agent’s final output (read with await response.structured_output()). See Structured output. |
save_dir | str or None | None (temporary dir) | Directory used to persist conversation trajectories across runs. When None, the SDK creates a temporary antigravity_* directory. See Sessions and context. |
conversation_id | str or None | None | Session 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_ | SessionContinuationMode or None | None | Session resume policy (RESUME, CREATE_OR_RESUME, or CREATE_ONLY from google.antigravity.types). See Sessions and context. |
compaction_ | CompactionConfig or None | None (backend default) | Sets CompactionConfig(token_threshold=...) for automatic history compaction (replaces deprecated CapabilitiesConfig.compaction_threshold). See Sessions and context. |
budget_config | BudgetConfig or None | None | Enforces ceilings on model calls, tool calls, and input, output, or total tokens (BudgetScope.LIFETIME or FORWARD_LOOKING). See Sessions and context. |
retry_config | RetryConfig or None | None (8 API / 4 output retries) | Overrides API backoff retries (ModelAPIRetryConfig) and output validation retries (ModelOutputRetryConfig). |
debug_config | DebugConfig, bool, dict, or None | None | Configures 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.