Sessions and context
Section titled “Sessions and context”Manage multi-turn state across an agent’s lifecycle using the Layer 2
Conversation API, disk-backed session persistence (save_dir and
conversation_id), isolated application data directories (app_data_dir),
automatic context compaction (CompactionConfig), and execution budgets
(types.BudgetConfig).
Work with the Conversation API
Section titled “Work with the Conversation API”Every started Agent owns a Layer 2 Conversation accessible at
agent.conversation (accessing it before entering async with Agent(config)
raises RuntimeError). Most applications send turns with agent.chat(), then
use agent.conversation to inspect step history, per-trajectory token usage,
compaction events, or low-level step streams.
from google.antigravity import Agent, LocalAgentConfig, types
async with Agent(LocalAgentConfig()) as agent:
# Low-level send + step-by-step trajectory streaming
await agent.conversation.send("List the main modules in this project.")
async for step in agent.conversation.receive_steps():
if (
step.source == types.StepSource.MODEL
and step.type == types.StepType.TEXT_RESPONSE
and step.is_complete_response
):
print(step.content)
print(f"Turns: {agent.conversation.turn_count}")
print(f"Recorded steps: {len(agent.conversation.history)}")
print(f"Total tokens: {agent.conversation.total_usage.total_token_count}")
Standalone Conversation.create(strategy)
Section titled “Standalone Conversation.create(strategy)”When you need direct Layer 2 session control without the Layer 1 Agent
wrapper, open a Conversation directly with the Conversation.create(strategy)
async context manager and a ConnectionStrategy such as
LocalConnectionStrategy:
from google.antigravity import GeminiAPIEndpoint, ModelTarget, ModelType, policy
from google.antigravity.connections.local import LocalConnectionStrategy
from google.antigravity.conversation.conversation import Conversation
from google.antigravity.models import DEFAULT_MODEL
strategy = LocalConnectionStrategy(
workspaces=["."],
models=[
ModelTarget(
name=DEFAULT_MODEL,
types=[ModelType.TEXT],
endpoint=GeminiAPIEndpoint(),
),
],
policies=policy.confirm_run_command(),
)
async with Conversation.create(strategy) as conversation:
response = await conversation.chat("Summarize README.md.")
print(await response.text())
print(f"Session ID: {conversation.conversation_id}")
Conversation methods and properties
Section titled “Conversation methods and properties”Conversation(conn, *, max_history_size=10_000, history=None) caps its
in-memory history buffer at 10,000 Step entries by default, trimming the
oldest entries (and shifting turn and compaction indices) as newer steps arrive.
| Member | Signature / type | Description |
|---|---|---|
Conversation. | async with Conversation.create(strategy) as conv | Classmethod async context manager that enters strategy, connects, and yields a Conversation seeded with any restored history. |
chat(prompt=None, **kwargs) | async -> types.ChatResponse | Calls send(prompt, **kwargs) and returns a lazy streaming ChatResponse (see Streaming and multimodal). |
send(prompt, **kwargs) | async -> None | Sends a Content prompt. If a previous turn is still active, drains remaining steps into history (or awaits wait_for_idle()) first. |
receive_steps() | AsyncIterator[types.Step] | Yields Step objects as they arrive, appends each to history, and exits once the turn is idle (concurrent calls raise RuntimeError). |
receive_ | AsyncIterator[StreamChunk | ToolCall] | Wraps receive_steps() and yields real-time types.Thought, types.Text, and deduplicated types.ToolCall events. |
get_ | -> Any | None | Returns the parsed structured output from the most recent root FINISH step, or None (see Structured output). |
history | list[types.Step] | Shallow copy of accumulated steps in arrival order (up to max_history_size, default 10_000). |
clear_history() | -> None | Clears recorded steps, turn indices, compaction indices, and cached turn output to reclaim memory without closing the session. |
compaction_ | list[int] | Positions in history of completed COMPACTION steps with depth == 0 (when subagents are active on local sessions, also check not step.parent_trajectory_id to restrict to root compactions). |
turn_count | int | Number of send() calls recorded in the current history window. |
last_response | str | content of the most recent step with is_complete_response=True, or "". |
last_turn_usage | UsageMetadata | None | Token usage delta for the most recent turn, or None if zero or unavailable. |
total_usage | UsageMetadata | Cumulative token usage across all turns in the session. |
trajectory_ | dict[str, UsageMetadata] | Cumulative token usage keyed by trajectory_id (root conversation plus each subagent trajectory). |
conversation_id | str | Active conversation identifier reported by the connection ("" on local sessions, and None on agent.conversation_id, until the first live step of a turn is received). |
sandbox_status | SandboxStatus | None | OS command sandbox availability reported at handshake (see Policies and sandboxing). |
connection | Connection | Underlying Layer 3 transport for advanced integrations. |
is_idle | bool | True when no turn is executing and the session is ready for input. |
wait_for_idle() | async -> None | Blocks until the active turn completes and the session becomes idle. |
wait_ | async -> bool | Delegates to Connection.wait_for_wakeup(timeout). Blocks up to timeout seconds on custom Connection implementations that support background wakeups (True on wakeup, False on timeout); returns False immediately without blocking on local connections (LocalAgentConfig, LiteRTAgentConfig, and LocalOpenAIAgentConfig). |
cancel() | async -> None | Cancels the turn currently in progress. |
disconnect() | async -> None | Closes the underlying connection transport and releases background resources. |
Step structure and enums
Section titled “Step structure and enums”Each entry in conversation.history (or yielded by receive_steps()) is a
types.Step model capturing a single trajectory event across the root agent or
a nested subagent:
| Field | Type | Description |
|---|---|---|
id | str | Step identifier ("" when unset). |
step_index | int | Zero-based index of the step within its trajectory. |
trajectory_id | str | Identifier of the trajectory that emitted the step (matches conversation_id or "main" for the root agent; unique per subagent). |
parent_ | str | Parent trajectory identifier for subagent steps ("" for root steps). |
depth | int | Nesting depth (defaults to 0; local harness steps do not populate depth for subagents, so check bool(step.parent_trajectory_id) to identify subagent steps). |
type | types.StepType | TEXT_RESPONSE, TOOL_CALL, SYSTEM_MESSAGE, COMPACTION, FINISH, THINKING, or UNKNOWN. |
source | types.StepSource | SYSTEM, USER, MODEL, or UNKNOWN. |
target | types.StepTarget | USER ("TARGET_USER"), ENVIRONMENT ("TARGET_ENVIRONMENT"), UNSPECIFIED ("TARGET_UNSPECIFIED"), or UNKNOWN. |
status | types.StepStatus | ACTIVE, DONE, WAITING_FOR_USER, ERROR, CANCELED, or UNKNOWN. |
content / content_delta | str | Full text content or incremental text delta for the step. |
thinking / thinking_delta | str | Full reasoning text or incremental reasoning delta for the step. |
tool_calls | list[types.ToolCall] | Tool invocations associated with the step. |
error | str | Error message when status is StepStatus.ERROR. |
is_ | bool | None | True when the step carries a finalized response message. |
structured_ | Any | None | Parsed JSON payload extracted on StepType.FINISH steps when response_schema is configured. |
workflow_ | beta.WorkflowProgress | None | Progress metadata for run_workflow steps (see Workflows). |
Persist and resume sessions
Section titled “Persist and resume sessions”By default, when save_dir is None, the SDK creates a new per-session
temporary directory (antigravity_*) in the OS temp directory (not
automatically deleted when the session exits). To preserve conversation
trajectories across process restarts, set save_dir to a persistent directory
and pass the same conversation_id when reconnecting:
from google.antigravity import Agent, LocalAgentConfig, types
save_dir = "./agent_sessions"
# Session 1: Create a persisted conversation and record its ID
async with Agent(LocalAgentConfig(save_dir=save_dir)) as agent:
response = await agent.chat(
"We are migrating the billing service from REST to gRPC."
)
print(await response.text())
saved_id = agent.conversation_id
print(f"Saved conversation ID: {saved_id}")
# Session 2: Resume the saved trajectory in a later process
resume_config = LocalAgentConfig(
save_dir=save_dir,
conversation_id=saved_id,
session_continuation_mode=types.SessionContinuationMode.RESUME,
)
async with Agent(resume_config) as agent:
response = await agent.chat("Which service and protocol are we migrating?")
print(await response.text())
Custom conversation IDs
Section titled “Custom conversation IDs”You can either capture the runtime-assigned agent.conversation_id from an
initial session or supply your own deterministic conversation_id on
LocalAgentConfig. Custom IDs are validated at config construction time and
must:
- Be at least 32 characters long (
len(conversation_id) >= 32). - Contain only ASCII letters, digits, and hyphens (
^[a-zA-Z0-9-]+$). Underscores and spaces raiseValueError.
config = LocalAgentConfig(
save_dir="./agent_sessions",
conversation_id="customer-42-session-2026-11-18-0001",
session_continuation_mode=types.SessionContinuationMode.CREATE_OR_RESUME,
)
Control reconnection with SessionContinuationMode
Section titled “Control reconnection with SessionContinuationMode”Set session_continuation_mode (types.SessionContinuationMode | None, default
None) to enforce strict create or resume semantics:
| Mode | Value | Behavior |
|---|---|---|
Session | "resume" | Resumes an existing session in save_dir and fails if no matching session exists (including when save_dir is None, which starts from a fresh temporary directory and raises RuntimeError). Requires conversation_id (omitting it raises ValueError). |
Session | "create_or_resume" | Resumes the session if conversation_id already exists in save_dir, or creates a new session if it does not. |
Session | "create_only" | Creates a brand-new session and fails if a session with the same conversation_id already exists. |
When session_continuation_mode is omitted (None), supplying save_dir and
an existing conversation_id restores the saved session if present and creates
it otherwise.
Isolate application data with app_data_dir
Section titled “Isolate application data with app_data_dir”While save_dir stores serialized session trajectories, app_data_dir controls
where the local runtime writes per-conversation brain/<conversation_id>/
artifacts (such as /plan documents and reports), scratch files, and generated
or uploaded media.
- Default:
~/.gemini/antigravity(resolved automatically whenapp_data_dirisNone). - Validation:
app_data_dirmust be an absolute path (os.path.isabs(app_data_dir)). Relative paths and unexpanded~strings (such as"~/my-agent-data") raiseValueError; expand user or relative paths withpathlib.Path(...).expanduser().resolve()first.
Override app_data_dir to isolate artifacts per tenant, test run, or sandboxed
job (set AgentBehavior.INTERACTIVE so the agent receives the built-in
brain/<conversation_id>/ artifact directory instructions):
import pathlib
import tempfile
from google.antigravity import (
Agent,
AgentBehavior,
CapabilitiesConfig,
LocalAgentConfig,
)
app_data = pathlib.Path(tempfile.mkdtemp(prefix="agent_appdata_")).resolve()
config = LocalAgentConfig(
app_data_dir=str(app_data),
capabilities=CapabilitiesConfig(
agent_behavior=AgentBehavior.INTERACTIVE,
),
)
async with Agent(config) as agent:
response = await agent.chat(
"Create an artifact named 'audit_summary.md' outlining key checks."
)
print(await response.text())
artifact = app_data / "brain" / str(agent.conversation_id) / "audit_summary.md"
if artifact.exists():
print(f"Artifact stored at: {artifact}")
Configure context compaction
Section titled “Configure context compaction”Long multi-turn and tool-heavy sessions accumulate large trajectories. Configure
CompactionConfig(token_threshold: int | None = None) on compaction_config to
automatically summarize older conversation turns once active context exceeds
token_threshold (must be > 0), keeping recent turns verbatim while staying
within your context and latency target.
- When
compaction_configisNone(ortoken_thresholdisNone), the runtime applies its built-in default threshold. - Calling
.lightweight()on a configuration instance (for example,LocalAgentConfig().lightweight()) returns a copy that setsCompactionConfig(token_threshold=65536)unless you supply an explicitcompaction_config. LiteRTAgentConfigautomatically derivesCompactionConfig(token_threshold=40960)from its default 65,536-token KV cache capacity (reserving 16,384 output tokens and an 8,192-token safety buffer) unless you overridecompaction_config. See Local models.
You can observe compaction events both in real time with @hooks.on_compaction
(which receives the types.Step for the compaction) and after a turn through
agent.conversation.compaction_indices. Compacted steps remain in
agent.conversation.history for auditing and transcripts even after they leave
the model’s active prompt window:
from google.antigravity import (
Agent,
CompactionConfig,
LocalAgentConfig,
hooks,
types,
)
@hooks.on_compaction
async def on_compacted(step: types.Step) -> None:
print(f"Context compacted at trajectory step {step.step_index}")
config = LocalAgentConfig(
compaction_config=CompactionConfig(token_threshold=50_000),
hooks=[on_compacted],
)
async with Agent(config) as agent:
response = await agent.chat(
"Inspect each package directory and compile an architecture overview."
)
print(await response.text())
# History indices of completed compaction steps (filter out subagent steps if any)
for idx in agent.conversation.compaction_indices:
compaction_step = agent.conversation.history[idx]
if not compaction_step.parent_trajectory_id:
print(
f"History[{idx}]: {compaction_step.type.value} ({compaction_step.status.value})"
)
See Lifecycle hooks and triggers for registering
class-based OnCompactionHook handlers and combining compaction with other
session hooks.
Enforce execution budgets and handle stop reasons
Section titled “Enforce execution budgets and handle stop reasons”Pass budget_config=types.BudgetConfig(...) on LocalAgentConfig to cap model
calls, tool executions, and token spend across the root conversation and any
spawned subagents combined. All numeric limits default to None (unlimited) and
must be >= 1 when specified; you can set any combination of limits together.
| Field | Type | Default | What it measures |
|---|---|---|---|
max_model_calls | int | None | None | Maximum model invocations (reasoning or generation calls) within scope. |
max_tool_calls | int | None | None | Maximum tool invocations across built-in, custom, and MCP tools within scope. |
max_ | int | None | None | Maximum net uncached input tokens (prompt_token_count - cached_content_token_count) accumulated across model calls within scope. |
max_ | int | None | None | Maximum cumulative output tokens (candidates_token_count + thoughts_token_count) within scope. |
max_ | int | None | None | Maximum cumulative total net tokens (net uncached input tokens plus output tokens) within scope. |
scope | types.BudgetScope | BudgetScope.LIFETIME | Whether limits apply to cumulative spend from step 0 (LIFETIME) or only new spend after configuring or resuming (FORWARD_LOOKING). |
All five numeric budget limits are evaluated after each invocation; once
cumulative usage reaches any configured limit, pending tool calls are denied and
further model invocations halt with the corresponding StopReason.
Choose a BudgetScope for resumed sessions
Section titled “Choose a BudgetScope for resumed sessions”types.BudgetScope controls how counters are evaluated when you resume a
persisted conversation:
BudgetScope.LIFETIME("LIFETIME", default): Counts all calls and tokens from the beginning of the conversation (step 0), including prior sessions restored fromsave_dir.BudgetScope.FORWARD_LOOKING("FORWARD_LOOKING"): Measures only the delta consumed after the current session starts or resumes, allowing you to grant a fresh per-run allowance on top of an existing trajectory.
from google.antigravity import Agent, LocalAgentConfig, types
save_dir = "./agent_sessions"
# Initial session with a tight lifetime budget
initial_config = LocalAgentConfig(
save_dir=save_dir,
budget_config=types.BudgetConfig(
max_model_calls=5,
max_tool_calls=10,
max_total_tokens=25_000,
),
)
async with Agent(initial_config) as agent:
res = await agent.chat("Analyze failing unit tests in tests/.")
print(await res.text())
print(f"Stop reason: {res.stop_reason.value}")
conv_id = agent.conversation_id
# Resume later with a fresh forward-looking budget for follow-up work
resumed_config = LocalAgentConfig(
save_dir=save_dir,
conversation_id=conv_id,
session_continuation_mode=types.SessionContinuationMode.RESUME,
budget_config=types.BudgetConfig(
max_model_calls=3,
max_output_tokens=4_000,
scope=types.BudgetScope.FORWARD_LOOKING,
),
)
async with Agent(resumed_config) as agent:
follow_up = await agent.chat("Propose the smallest fix for the top failure.")
try:
text = await follow_up.text()
if follow_up.stop_reason != types.StopReason.UNSPECIFIED:
print(f"Budget stop: {follow_up.stop_reason.value}")
else:
print(text)
except types.AntigravityExecutionError as err:
print(f"Stopped ({follow_up.stop_reason.value}): {err}")
StopReason reference
Section titled “StopReason reference”Budget exhaustion (MAX_*_EXCEEDED) halts the turn cleanly instead of raising
an exception. Drain the ChatResponse (for example with await response.text()
or await response.resolve()) and check response.stop_reason. By contrast,
StopReason.QUOTA_EXHAUSTED accompanies a terminal backend quota failure that
raises types.AntigravityExecutionError when draining the response, with
response.stop_reason still populated for inspection in the handler:
types. member | Value | Meaning |
|---|---|---|
Stop | "UNSPECIFIED" | Default value indicating normal turn completion without a budget or quota halt. |
Stop | "MAX_MODEL_CALLS_EXCEEDED" | Session reached or exceeded BudgetConfig.max_model_calls. |
Stop | "MAX_TOOL_CALLS_EXCEEDED" | Session reached or exceeded BudgetConfig.max_tool_calls. |
Stop | "MAX_INPUT_TOKENS_EXCEEDED" | Net uncached input tokens reached or exceeded BudgetConfig.max_input_tokens. |
Stop | "MAX_OUTPUT_TOKENS_EXCEEDED" | Cumulative output tokens (candidates plus thoughts) reached or exceeded BudgetConfig.max_output_tokens. |
Stop | "MAX_TOTAL_TOKENS_EXCEEDED" | Cumulative net tokens (uncached input plus output) reached or exceeded BudgetConfig.max_total_tokens. |
Stop | "QUOTA_EXHAUSTED" | Backend model API quota was exhausted during the turn (raises AntigravityExecutionError on drain). |
Sample code
Section titled “Sample code”Explore runnable scripts in the SDK repository on GitHub:
persistence.py: Savingagent.conversation_idwithsave_dirand resuming context in a newAgentinstance.app_data_dir_override.py: Directingbrain/artifacts and session media into a custom absoluteapp_data_dir.compaction.py: Configuring sliding-window trajectory compaction withCompactionConfig.budget_limits.py: All fiveBudgetConfiglimits,StopReasonhandling, andBudgetScope.FORWARD_LOOKINGon resumed sessions.
Next steps
Section titled “Next steps”- Lifecycle hooks and triggers: Hook session start/end, compaction, turns, and background triggers.
- Observability, evals, and errors: Audit token usage across trajectories, export OpenTelemetry spans, and handle SDK exceptions.
- Streaming and multimodal: Stream turn chunks and cancel
active turns with
AntigravityCancelledError. - API reference: Complete class, method, and enum
reference for
google.antigravity.