Skip to content
Observability evals and errors - Antigravity SDKsdkAntigravity SDKAntigravity SDKObservability, evals, and errors - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

Measure per-turn and per-subagent token consumption, export distributed OpenTelemetry traces, configure standardized evaluation presets with .eval(), and handle SDK exceptions cleanly in production applications.

The SDK reports token consumption through UsageMetadata (exported from both google.antigravity and google.antigravity.types) at three granularities:

  • Per turn (response.usage_metadata): Accumulated usage across all model calls in that turn. Snapshotted onto each ChatResponse (and WorkflowResult) when its stream completes so later turns do not overwrite retained response objects. agent.conversation.last_turn_usage returns the most recent turn’s delta (or None if zero tokens were recorded).
  • Cumulative session (agent.conversation.total_usage): Running total across every turn and subagent in the active session.
  • Per trajectory (agent.conversation.trajectory_usages): dict[str, UsageMetadata] mapping the root conversation trajectory ID and each spawned subagent trajectory ID to its own cumulative usage.

Fields are None when not reported and 0 when the model explicitly recorded zero tokens for that category:

FieldTypeDescription
prompt_token_countint | NoneInput tokens in the prompt (including any cached tokens).
cached_content_token_countint | NoneSubset of prompt_token_count served from context cache.
candidates_token_countint | NoneGenerated output tokens, excluding thinking tokens.
thoughts_token_countint | NoneTokens consumed by internal model reasoning/thinking.
total_token_countint | NoneSum of prompt, candidate, and thought tokens.
service_tierServiceTier | NoneEffective inference tier (STANDARD, PRIORITY, or FLEX), useful for detecting priority-tier fallback to STANDARD (see Models and configuration).
import asyncio
from google.antigravity import Agent, LocalAgentConfig, UsageMetadata


async def main() -> None:
    turn_usages: list[UsageMetadata] = []

    async with Agent(LocalAgentConfig()) as agent:
        for prompt in [
            "List the Python modules in this directory.",
            "Delegate a quick summary of the largest module to a subagent.",
        ]:
            response = await agent.chat(prompt)
            await response.text()
            if response.usage_metadata is not None:
                turn_usages.append(response.usage_metadata)
                print(
                    f"Turn total={response.usage_metadata.total_token_count} "
                    f"(thoughts={response.usage_metadata.thoughts_token_count}, "
                    f"cached={response.usage_metadata.cached_content_token_count})"
                )

        # Session and per-trajectory breakdown (root + each subagent)
        print("Session total:", agent.conversation.total_usage.total_token_count)
        for traj_id, usage in agent.conversation.trajectory_usages.items():
            print(f"  trajectory {traj_id}: {usage.total_token_count} tokens")

    # UsageMetadata arithmetic: +, -, scalar *, and built-in sum()
    combined = sum(turn_usages, start=UsageMetadata())
    delta = turn_usages[1] - turn_usages[0] if len(turn_usages) == 2 else UsageMetadata()
    buffered_estimate = combined * 1.2
    print("Combined:", combined.total_token_count)
    print("Turn 2 - Turn 1:", delta.total_token_count)
    print("1.2x buffer:", buffered_estimate.total_token_count)


if __name__ == "__main__":
    asyncio.run(main())

UsageMetadata supports addition (u1 + u2), subtraction (u2 - u1 and 0 - u1), non-negative finite scalar multiplication (u * 1.5 and 1.5 * u, rounding counts), and sum(items, start=UsageMetadata()) (or sum(items) when non-empty, since 0 + u returns a copy of u). When adding two records with different non-None service_tier values, the merged tier defaults to ServiceTier.STANDARD.

To enforce proactive limits on model calls, tool calls, or tokens, configure types.BudgetConfig (see Sessions and context).

Install the optional otel extra to instrument agent sessions with OpenTelemetry spans:

pip install "google-antigravity[otel]"

This installs opentelemetry-api and opentelemetry-sdk. Register the tracing hook suite with otel.get_otel_hooks(agent_name="Antigravity") from google.antigravity.utils.otel (create a fresh list per Agent instance):

import asyncio
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    ConsoleSpanExporter,
    SimpleSpanProcessor,
)
from google.antigravity import Agent, LocalAgentConfig
from google.antigravity.utils import otel


def lookup_release(service: str) -> str:
    """Returns the currently deployed version of a service."""
    return f"{service}@2.4.1"


async def main() -> None:
    provider = TracerProvider()
    provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
    trace.set_tracer_provider(provider)

    config = LocalAgentConfig(
        tools=[lookup_release],
        hooks=otel.get_otel_hooks(agent_name="ReleaseBot"),
    )

    async with Agent(config) as agent:
        response = await agent.chat("What version of billing-api is deployed?")
        print(await response.text())

    provider.shutdown()


if __name__ == "__main__":
    asyncio.run(main())

All spans are emitted under the tracer name "google-antigravity-sdk" and nest in the following hierarchy:

Span nameParentAttributes and status
antigravity.sessionRootCovers the full async with Agent(config) session lifecycle.
invoke_agent <agent_name>antigravity.sessionOne per turn. Sets gen_ai.operation.name="invoke_agent" and gen_ai.agent.name.
invoke_agent <subagent_name>invoke_agent <agent_name>Created when invoke_subagent starts (resolving the name from TypeName, Role, or "subagent") so child subagent steps parent under it. Sets gen_ai.operation.name="invoke_agent", gen_ai.agent.name, and antigravity.subagent.trajectory_id.
antigravity.step.<step_index>Turn or subagent spanSets antigravity.step.index, antigravity.step.trajectory_id, antigravity.step.type, and antigravity.step.status; sets StatusCode.ERROR on StepStatus.ERROR.
execute_tool <tool_name>Active step spanSets gen_ai.operation.name="execute_tool" and gen_ai.tool.name. Records exceptions and sets StatusCode.ERROR on tool failures.

The SDK logs under the standard Python "google.antigravity" logger hierarchy. Configure it directly or pass debug_config on any AgentConfig subclass:

import logging
from google.antigravity import LocalAgentConfig
from google.antigravity.connections.connection import DebugConfig

# Option 1: Standard Python logging (for example, INFO in staging/production)
logging.basicConfig(level=logging.INFO)
logging.getLogger("google.antigravity").setLevel(logging.INFO)

# Option 2: Shorthand boolean enables DebugConfig() (sets logger level to DEBUG)
quick_debug = LocalAgentConfig(debug_config=True)

# Option 3: Explicit DebugConfig for fine-grained control
custom_debug = LocalAgentConfig(
    debug_config=DebugConfig(
        enable_server_side_tracing=True,
        logging_level=logging.INFO,
    ),
)

DebugConfig sets the "google.antigravity" logger level immediately when the configuration is instantiated (logging_level accepts int, level name str, or None to leave logger levels unchanged; configure a standard Python logging handler such as logging.basicConfig() so DEBUG and INFO records are emitted). enable_server_side_tracing (default True) is ignored on local agent configs (LocalAgentConfig, LiteRTAgentConfig, and LocalOpenAIAgentConfig). Combine logging with @hooks.post_tool_call, @hooks.on_tool_error, or @hooks.on_compaction for structured application audit trails (see Lifecycle hooks and triggers).

Use the fluent .eval() preset on AgentConfig (LocalAgentConfig, LiteRTAgentConfig, or LocalOpenAIAgentConfig) to benchmark coding and agentic tasks under a standardized, autonomous configuration:

def eval(
    self,
    thinking_level: ThinkingLevel | None = ThinkingLevel.HIGH,
) -> Self: ...

Calling .eval() returns a modified copy of the configuration and preserves any fields you explicitly set on the base config:

Setting.eval() defaultOverride behavior
capabilities.disabled_tools[BuiltinTools.GENERATE_IMAGE]Omitted if you explicitly set capabilities.enabled_tools, or replaced by your disabled_tools.
capabilities.enable_subagentsFalsePreserved if explicitly set on capabilities.
capabilities.run_command_configRunCommandConfig(enable_daemons=True)Merged with any explicit RunCommandConfig fields (such as enable_sandbox=True or timeout_seconds).
policies[policy.allow_all()]Preserved if you explicitly passed policies=[...].
retry_configRetryConfig.benchmark()Preserved if you explicitly passed retry_config=.... Uses up to 4,294,967,295 API retries (initial_sleep_duration_ms=1000) for transient 429/503 errors while keeping default model output validation retries.
Text model thinking_levelThinkingLevel.HIGHApplied to every ModelType.TEXT target using GeminiAPIEndpoint or VertexEndpoint. Pass thinking_level=ThinkingLevel.EXTRA_HIGH (or another level) to customize.

Run an evaluation and inspect the trajectory

Section titled “Run an evaluation and inspect the trajectory”

Pair .eval() with agent.conversation.history, response.stop_reason, and response.usage_metadata to grade both final outputs and intermediate actions:

import asyncio
from google.antigravity import (
    Agent,
    CapabilitiesConfig,
    LocalAgentConfig,
    ThinkingLevel,
    types,
)


async def evaluate_task(workspace: str, task_prompt: str) -> dict[str, object]:
    config = LocalAgentConfig(
        workspaces=[workspace],
        capabilities=CapabilitiesConfig(
            run_command_config=types.RunCommandConfig(
                enable_sandbox=True,
                timeout_seconds=300,
            ),
        ),
        budget_config=types.BudgetConfig(max_model_calls=40),
    ).eval(thinking_level=ThinkingLevel.HIGH)

    async with Agent(config) as agent:
        response = await agent.chat(task_prompt)
        final_text = await response.text()

        tool_calls = [call.name async for call in response.tool_calls]
        steps = agent.conversation.history
        failed_steps = [
            (step.step_index, step.error)
            for step in steps
            if step.status == types.StepStatus.ERROR
        ]
        usage = agent.conversation.total_usage

        return {
            "conversation_id": agent.conversation_id,
            "stop_reason": response.stop_reason.value,
            "final_text": final_text,
            "step_count": len(steps),
            "compactions": len(agent.conversation.compaction_indices),
            "tool_calls": tool_calls,
            "failed_steps": failed_steps,
            "total_tokens": usage.total_token_count,
            "thought_tokens": usage.thoughts_token_count,
            "trajectory_tokens": {
                tid: u.total_token_count
                for tid, u in agent.conversation.trajectory_usages.items()
            },
        }


if __name__ == "__main__":
    result = asyncio.run(
        evaluate_task(
            "/abs/path/to/fixture_repo",
            "Run the test suite, fix any failing tests, and re-run to verify.",
        )
    )
    print(result)

Each types.Step in agent.conversation.history exposes id, step_index, trajectory_id, parent_trajectory_id (non-empty for subagent steps), depth (0 for the root conversation; remains 0 for subagent steps on local agent configs, so filter subagent trajectories with step.parent_trajectory_id), type (StepType), source (StepSource), target (StepTarget), status (StepStatus), content, thinking, tool_calls, error, is_complete_response, structured_output, and workflow_progress.

ExceptionImportBase classExtra attributesWhen raised
AntigravityConnectionErrorgoogle.antigravity.typesExceptionNoneUnexpected WebSocket transport closure/reader failure, or non-retryable HTTP 400, 401, or 403 system error steps (including on LocalOpenAIAgentConfig).
AntigravityExecutionErrorgoogle.antigravity.typesExceptionNoneTerminal agent loop error (including StopReason.QUOTA_EXHAUSTED, other terminal HTTP errors such as 404 or exhausted 429/5xx retries, or @hooks.pre_turn denial) or non-zero local runtime exit code.
AntigravityCancelledErrorgoogle.antigravity.typesasyncio.CancelledErrorNoneActive turn aborted programmatically using await response.cancel() or await agent.conversation.cancel().
AntigravityValidationErrorgoogle.antigravity.typesExceptionmessage: str, errors: list[dict[str, Any]]Session-startup validation failures (such as missing GEMINI_API_KEY or Vertex credentials, a ModelTarget in models without endpoint, a missing base_url on LocalOpenAIAgentConfig, or a nonexistent LiteRTAgentConfig.model_path).
ToolExecutionErrorgoogle.antigravity (and types)RuntimeErrortool_name: str, server_name: str | None, call_id: str | None, step_id: str | NoneDelivered to @hooks.on_tool_error on tool failures, and raised by await agent.beta.run_workflow(...) when run_workflow is not invoked or ends with StepStatus.ERROR.
RuntimeErrorbuilt-inExceptionStandardMissing localharness binary or litert-lm dependency, local subprocess/WebSocket startup or handshake failure (such as missing LocalOpenAIAgentConfig.model), or accessing agent.conversation before session start.
WorkflowErrorgoogle.antigravity.beta.workflowsExceptionNoneWorkflow syntax/AST validation failures (arguments on @workflows.define, top-level return, any yield, or print()).
ToolErrorgoogle.antigravity.beta.workflowsWorkflowErrortool: str, message: strRaised inside a running workflow script when await workflows.call_tool(...) fails or targets an unsupported or disabled tool.
pydantic.ValidationError / ValueErrorpydantic / built-inValueErrorStandardInvalid config arguments, empty chat() prompt, missing safety policy, or mutually exclusive fields.

Because AntigravityCancelledError inherits from asyncio.CancelledError, always catch types.AntigravityCancelledError before asyncio.CancelledError so programmatic response.cancel() calls are handled separately from task timeouts or cancellation:

import asyncio
import pydantic
from google.antigravity import (
    Agent,
    LocalAgentConfig,
    ToolExecutionError,
    hooks,
    types,
)


@hooks.on_tool_error
def recover_tool_error(err: Exception) -> str | None:
    if isinstance(err, ToolExecutionError):
        print(
            f"Tool failed: name={err.tool_name} server={err.server_name} "
            f"call_id={err.call_id} step_id={err.step_id}: {err}"
        )
        # Return a non-empty string to replace the raw error sent to the model
        return f"Tool '{err.tool_name}' failed ({err}). Try an alternative approach."
    return None


async def run_safely(prompt: str) -> str | None:
    response: types.ChatResponse | None = None
    try:
        config = LocalAgentConfig(hooks=[recover_tool_error])
        async with asyncio.timeout(120), Agent(config) as agent:
            response = await agent.chat(prompt)
            return await response.text()
    except types.AntigravityCancelledError as err:
        print(f"Turn cancelled by caller: {err}")
    except (TimeoutError, asyncio.CancelledError):
        print("Session timed out or parent task was cancelled; runtime cleaned up.")
    except (types.AntigravityValidationError, pydantic.ValidationError, ValueError) as err:
        print(f"Invalid configuration or input: {err}")
    except types.AntigravityConnectionError as err:
        print(f"Backend connection error: {err}")
    except types.AntigravityExecutionError as err:
        if (
            response is not None
            and response.stop_reason == types.StopReason.QUOTA_EXHAUSTED
        ):
            print("Halted: model API quota exhausted.")
        else:
            print(f"Agent execution failed: {err}")
    except ToolExecutionError as err:
        print(f"Workflow or tool failure ({err.tool_name}): {err}")
    except RuntimeError as err:
        print(f"Runtime startup or handshake failure: {err}")
    return None

Note that normal tool failures inside agent.chat() do not abort the turn: the runtime captures them, invokes any @hooks.on_tool_error hooks as a ToolExecutionError (original Python exception subclasses like ValueError are not preserved across the runtime boundary), and feeds the error message back to the model so it can self-correct. See Lifecycle hooks and triggers for hook patterns and Models and configuration for customizing RetryConfig.

When a session exits due to asyncio.timeout(), asyncio.CancelledError, or a startup exception, Agent.__aexit__ terminates and reaps the local runtime subprocess and closes stdio pipes and WebSocket transports deterministically.

  • Missing runtime binary after cloning from GitHub: Cloning antigravity-sdk-python does not include the compiled localharness binary. Install a platform wheel from PyPI with pip install google-antigravity in your virtual environment. For custom deployments that stage the binary separately, set ANTIGRAVITY_HARNESS_PATH (in the environment or in LocalAgentConfig(env={"ANTIGRAVITY_HARNESS_PATH": "/abs/path/to/localharness"})).
  • Missing credentials (AntigravityValidationError: A Gemini API key is required): Export GEMINI_API_KEY in os.environ, pass LocalAgentConfig(api_key="..."), enable Gemini Enterprise with vertex=True (see Authentication), or switch to LiteRTAgentConfig / LocalOpenAIAgentConfig.
  • Relative or ~ path rejected for app_data_dir: app_data_dir requires an already-expanded absolute path (os.path.abspath(os.path.expanduser("~/my-agent-data"))). Relative paths and raw "~/..." strings raise a validation error.
  • Unexpanded ~ in LiteRTAgentConfig.model_path: model_path is not tilde-expanded automatically. Wrap paths with os.path.expanduser("~/.litert-lm/models/gemma4-26b/model.litertlm"). (By contrast, workspaces and from_file() do expand ~.)
  • Missing GPU warning or slow inference on LiteRTAgentConfig: The SDK checks for Metal (Apple Silicon) or CUDA (Linux/Windows) when backend="gpu". If no supported GPU is detected and you intentionally want CPU fallback, set backend=LiteRTBackend.CPU (or backend="cpu") or export ANTIGRAVITY_ALLOW_CPU=1 to silence the hardware warning. See Local models.
  • Invalid conversation_id: Custom conversation_id values must be at least 32 characters long and match ^[a-zA-Z0-9-]+$ (letters, digits, and hyphens only; underscores raise a validation error).
  • Write tools or MCP servers are enabled without a safety policy: Avoid policies=[] unless you restrict capabilities=CapabilitiesConfig(enabled_tools=BuiltinTools.read_only()) or attach a PreToolCallDecideHook. Use the default confirm_run_command() or an explicit policy list (see Policies and sandboxing).