Skip to content
Sessions and context - Antigravity SDKsdkAntigravity SDKAntigravity SDKSessions and context - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

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).

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}")

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(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.

MemberSignature / typeDescription
Conversation.createasync with Conversation.create(strategy) as convClassmethod async context manager that enters strategy, connects, and yields a Conversation seeded with any restored history.
chat(prompt=None, **kwargs)async -> types.ChatResponseCalls send(prompt, **kwargs) and returns a lazy streaming ChatResponse (see Streaming and multimodal).
send(prompt, **kwargs)async -> NoneSends 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_chunks()AsyncIterator[StreamChunk | ToolCall]Wraps receive_steps() and yields real-time types.Thought, types.Text, and deduplicated types.ToolCall events.
get_last_structured_output()-> Any | NoneReturns the parsed structured output from the most recent root FINISH step, or None (see Structured output).
historylist[types.Step]Shallow copy of accumulated steps in arrival order (up to max_history_size, default 10_000).
clear_history()-> NoneClears recorded steps, turn indices, compaction indices, and cached turn output to reclaim memory without closing the session.
compaction_indiceslist[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_countintNumber of send() calls recorded in the current history window.
last_responsestrcontent of the most recent step with is_complete_response=True, or "".
last_turn_usageUsageMetadata | NoneToken usage delta for the most recent turn, or None if zero or unavailable.
total_usageUsageMetadataCumulative token usage across all turns in the session.
trajectory_usagesdict[str, UsageMetadata]Cumulative token usage keyed by trajectory_id (root conversation plus each subagent trajectory).
conversation_idstrActive 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_statusSandboxStatus | NoneOS command sandbox availability reported at handshake (see Policies and sandboxing).
connectionConnectionUnderlying Layer 3 transport for advanced integrations.
is_idleboolTrue when no turn is executing and the session is ready for input.
wait_for_idle()async -> NoneBlocks until the active turn completes and the session becomes idle.
wait_for_wakeup(timeout=300.0)async -> boolDelegates 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 -> NoneCancels the turn currently in progress.
disconnect()async -> NoneCloses the underlying connection transport and releases background resources.

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:

FieldTypeDescription
idstrStep identifier ("" when unset).
step_indexintZero-based index of the step within its trajectory.
trajectory_idstrIdentifier of the trajectory that emitted the step (matches conversation_id or "main" for the root agent; unique per subagent).
parent_trajectory_idstrParent trajectory identifier for subagent steps ("" for root steps).
depthintNesting depth (defaults to 0; local harness steps do not populate depth for subagents, so check bool(step.parent_trajectory_id) to identify subagent steps).
typetypes.StepTypeTEXT_RESPONSE, TOOL_CALL, SYSTEM_MESSAGE, COMPACTION, FINISH, THINKING, or UNKNOWN.
sourcetypes.StepSourceSYSTEM, USER, MODEL, or UNKNOWN.
targettypes.StepTargetUSER ("TARGET_USER"), ENVIRONMENT ("TARGET_ENVIRONMENT"), UNSPECIFIED ("TARGET_UNSPECIFIED"), or UNKNOWN.
statustypes.StepStatusACTIVE, DONE, WAITING_FOR_USER, ERROR, CANCELED, or UNKNOWN.
content / content_deltastrFull text content or incremental text delta for the step.
thinking / thinking_deltastrFull reasoning text or incremental reasoning delta for the step.
tool_callslist[types.ToolCall]Tool invocations associated with the step.
errorstrError message when status is StepStatus.ERROR.
is_complete_responsebool | NoneTrue when the step carries a finalized response message.
structured_outputAny | NoneParsed JSON payload extracted on StepType.FINISH steps when response_schema is configured.
workflow_progressbeta.WorkflowProgress | NoneProgress metadata for run_workflow steps (see Workflows).

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())

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 raise ValueError.
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:

ModeValueBehavior
SessionContinuationMode.RESUME"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).
SessionContinuationMode.CREATE_OR_RESUME"create_or_resume"Resumes the session if conversation_id already exists in save_dir, or creates a new session if it does not.
SessionContinuationMode.CREATE_ONLY"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 when app_data_dir is None).
  • Validation: app_data_dir must be an absolute path (os.path.isabs(app_data_dir)). Relative paths and unexpanded ~ strings (such as "~/my-agent-data") raise ValueError; expand user or relative paths with pathlib.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}")

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_config is None (or token_threshold is None), the runtime applies its built-in default threshold.
  • Calling .lightweight() on a configuration instance (for example, LocalAgentConfig().lightweight()) returns a copy that sets CompactionConfig(token_threshold=65536) unless you supply an explicit compaction_config.
  • LiteRTAgentConfig automatically derives CompactionConfig(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 override compaction_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.

FieldTypeDefaultWhat it measures
max_model_callsint | NoneNoneMaximum model invocations (reasoning or generation calls) within scope.
max_tool_callsint | NoneNoneMaximum tool invocations across built-in, custom, and MCP tools within scope.
max_input_tokensint | NoneNoneMaximum net uncached input tokens (prompt_token_count - cached_content_token_count) accumulated across model calls within scope.
max_output_tokensint | NoneNoneMaximum cumulative output tokens (candidates_token_count + thoughts_token_count) within scope.
max_total_tokensint | NoneNoneMaximum cumulative total net tokens (net uncached input tokens plus output tokens) within scope.
scopetypes.BudgetScopeBudgetScope.LIFETIMEWhether 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.

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 from save_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}")

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.StopReason memberValueMeaning
StopReason.UNSPECIFIED"UNSPECIFIED"Default value indicating normal turn completion without a budget or quota halt.
StopReason.MAX_MODEL_CALLS_EXCEEDED"MAX_MODEL_CALLS_EXCEEDED"Session reached or exceeded BudgetConfig.max_model_calls.
StopReason.MAX_TOOL_CALLS_EXCEEDED"MAX_TOOL_CALLS_EXCEEDED"Session reached or exceeded BudgetConfig.max_tool_calls.
StopReason.MAX_INPUT_TOKENS_EXCEEDED"MAX_INPUT_TOKENS_EXCEEDED"Net uncached input tokens reached or exceeded BudgetConfig.max_input_tokens.
StopReason.MAX_OUTPUT_TOKENS_EXCEEDED"MAX_OUTPUT_TOKENS_EXCEEDED"Cumulative output tokens (candidates plus thoughts) reached or exceeded BudgetConfig.max_output_tokens.
StopReason.MAX_TOTAL_TOKENS_EXCEEDED"MAX_TOTAL_TOKENS_EXCEEDED"Cumulative net tokens (uncached input plus output) reached or exceeded BudgetConfig.max_total_tokens.
StopReason.QUOTA_EXHAUSTED"QUOTA_EXHAUSTED"Backend model API quota was exhausted during the turn (raises AntigravityExecutionError on drain).

Explore runnable scripts in the SDK repository on GitHub:

  • persistence.py: Saving agent.conversation_id with save_dir and resuming context in a new Agent instance.
  • app_data_dir_override.py: Directing brain/ artifacts and session media into a custom absolute app_data_dir.
  • compaction.py: Configuring sliding-window trajectory compaction with CompactionConfig.
  • budget_limits.py: All five BudgetConfig limits, StopReason handling, and BudgetScope.FORWARD_LOOKING on resumed sessions.