Observability, evals, and errors
Section titled “Observability, evals, and errors”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.
Token usage tracking
Section titled “Token usage tracking”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 eachChatResponse(andWorkflowResult) when its stream completes so later turns do not overwrite retained response objects.agent.conversation.last_turn_usagereturns the most recent turn’s delta (orNoneif 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.
UsageMetadata fields
Section titled “UsageMetadata fields”Fields are None when not reported and 0 when the model explicitly recorded zero tokens for that category:
| Field | Type | Description |
|---|---|---|
prompt_ | int | None | Input tokens in the prompt (including any cached tokens). |
cached_ | int | None | Subset of prompt_token_count served from context cache. |
candidates_ | int | None | Generated output tokens, excluding thinking tokens. |
thoughts_ | int | None | Tokens consumed by internal model reasoning/thinking. |
total_ | int | None | Sum of prompt, candidate, and thought tokens. |
service_tier | ServiceTier | None | Effective 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).
OpenTelemetry tracing
Section titled “OpenTelemetry tracing”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())
Span hierarchy and attributes
Section titled “Span hierarchy and attributes”All spans are emitted under the tracer name "google-antigravity-sdk" and nest in the following hierarchy:
| Span name | Parent | Attributes and status |
|---|---|---|
antigravity. | Root | Covers the full async with Agent(config) session lifecycle. |
invoke_ | antigravity.session | One per turn. Sets gen_ai.operation.name="invoke_agent" and gen_ai.agent.name. |
invoke_ | 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. | Turn or subagent span | Sets antigravity.step.index, antigravity.step.trajectory_id, antigravity.step.type, and antigravity.step.status; sets StatusCode.ERROR on StepStatus.ERROR. |
execute_ | Active step span | Sets gen_ai.operation.name="execute_tool" and gen_ai.tool.name. Records exceptions and sets StatusCode.ERROR on tool failures. |
Logging and debug diagnostics
Section titled “Logging and debug diagnostics”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).
Evaluations and benchmarks
Section titled “Evaluations and benchmarks”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: ...
What .eval() configures
Section titled “What .eval() configures”Calling .eval() returns a modified copy of the configuration and preserves any fields you explicitly set on the base config:
| Setting | .eval() default | Override behavior |
|---|---|---|
capabilities. | [BuiltinTools.GENERATE_IMAGE] | Omitted if you explicitly set capabilities.enabled_tools, or replaced by your disabled_tools. |
capabilities. | False | Preserved if explicitly set on capabilities. |
capabilities. | RunCommandConfig(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_config | RetryConfig.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_level | ThinkingLevel.HIGH | Applied 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.
Error handling
Section titled “Error handling”Exception hierarchy
Section titled “Exception hierarchy”| Exception | Import | Base class | Extra attributes | When raised |
|---|---|---|---|---|
Antigravity | google. | Exception | None | Unexpected WebSocket transport closure/reader failure, or non-retryable HTTP 400, 401, or 403 system error steps (including on Local). |
Antigravity | google. | Exception | None | Terminal agent loop error (including Stop, other terminal HTTP errors such as 404 or exhausted 429/5xx retries, or @hooks. denial) or non-zero local runtime exit code. |
Antigravity | google. | asyncio. | None | Active turn aborted programmatically using await response. or await agent.. |
Antigravity | google. | Exception | message: str, errors: list[dict[str, Any]] | Session-startup validation failures (such as missing GEMINI_ or Vertex credentials, a ModelTarget in models without endpoint, a missing base_url on Local, or a nonexistent Lite). |
Tool | google. (and types) | Runtime | tool_, server_, call_, step_ | Delivered to @hooks. on tool failures, and raised by await agent. when run_ is not invoked or ends with Step. |
RuntimeError | built-in | Exception | Standard | Missing localharness binary or litert-lm dependency, local subprocess/WebSocket startup or handshake failure (such as missing Local), or accessing agent. before session start. |
WorkflowError | google. | Exception | None | Workflow syntax/AST validation failures (arguments on @workflows., top-level return, any yield, or print()). |
ToolError | google. | Workflow | tool: str, message: str | Raised inside a running workflow script when await workflows. fails or targets an unsupported or disabled tool. |
pydantic. / Value | pydantic / built-in | ValueError | Standard | Invalid config arguments, empty chat() prompt, missing safety policy, or mutually exclusive fields. |
Catching SDK exceptions and cancellation
Section titled “Catching SDK exceptions and cancellation”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.
Troubleshooting
Section titled “Troubleshooting”- Missing runtime binary after cloning from GitHub: Cloning
antigravity-sdk-pythondoes not include the compiledlocalharnessbinary. Install a platform wheel from PyPI withpip install google-antigravityin your virtual environment. For custom deployments that stage the binary separately, setANTIGRAVITY_HARNESS_PATH(in the environment or inLocalAgentConfig(env={"ANTIGRAVITY_HARNESS_PATH": "/abs/path/to/localharness"})). - Missing credentials (
AntigravityValidationError: A Gemini API key is required): ExportGEMINI_API_KEYinos.environ, passLocalAgentConfig(api_key="..."), enable Gemini Enterprise withvertex=True(see Authentication), or switch toLiteRTAgentConfig/LocalOpenAIAgentConfig. - Relative or
~path rejected forapp_data_dir:app_data_dirrequires an already-expanded absolute path (os.path.abspath(os.path.expanduser("~/my-agent-data"))). Relative paths and raw"~/..."strings raise a validation error. - Unexpanded
~inLiteRTAgentConfig.model_path:model_pathis not tilde-expanded automatically. Wrap paths withos.path.expanduser("~/.litert-lm/models/gemma4-26b/model.litertlm"). (By contrast,workspacesandfrom_file()do expand~.) - Missing GPU warning or slow inference on
LiteRTAgentConfig: The SDK checks for Metal (Apple Silicon) or CUDA (Linux/Windows) whenbackend="gpu". If no supported GPU is detected and you intentionally want CPU fallback, setbackend=LiteRTBackend.CPU(orbackend="cpu") or exportANTIGRAVITY_ALLOW_CPU=1to silence the hardware warning. See Local models. - Invalid
conversation_id: Customconversation_idvalues 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: Avoidpolicies=[]unless you restrictcapabilities=CapabilitiesConfig(enabled_tools=BuiltinTools.read_only())or attach aPreToolCallDecideHook. Use the defaultconfirm_run_command()or an explicit policy list (see Policies and sandboxing).
Next steps
Section titled “Next steps”- Sessions and context: Configure
BudgetConfig,CompactionConfig, session resumption, and programmatic cancellation. - Lifecycle hooks and triggers: Intercept tool errors with
@hooks.on_tool_errorand build custom audit hooks. - API reference: Look up every public class, method, enum, and environment variable.
- Examples: Run
observability.py,observability_otel.py, anderror_handler.py.