### Run Hello World Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Set your Gemini API key and run the hello_world example script from the examples directory. ```sh export GEMINI_API_KEY="your_api_key_here" python ./examples/getting_started/hello_world.py ``` -------------------------------- ### Install SDK and Set API Key Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/README.md Install the Google Antigravity SDK using pip and set your Gemini API key as an environment variable. This is a prerequisite for running the examples. ```bash pip install google-antigravity export GEMINI_API_KEY="your_api_key_here" ``` -------------------------------- ### Run Multimodal Pipeline Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the multimodal pipeline example showcasing a generator/discriminator pipeline with multimodal I/O. ```bash python multimodal_pipeline.py ``` -------------------------------- ### Install Google Antigravity SDK Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Install the SDK using pip. This command fetches the necessary runtime binary from PyPI. ```sh pip install google-antigravity ``` -------------------------------- ### Run Host Tool Hooks Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the host tool hooks example to see all supported lifecycle hooks wired and logged. ```bash python host_tool_hooks.py ``` -------------------------------- ### Run Agent Middleware Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the agent middleware example to observe transparent tool interception by stacked hooks. ```bash python agent_middleware.py ``` -------------------------------- ### Install Google Antigravity SDK Skill via Context7 CLI Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/README.md Use the Context7 skills CLI to install skills. You can interactively browse or install a specific skill by providing its path and name. ```bash # Interactively browse and install skills. npx ctx7 skills install /Google-Antigravity/antigravity-sdk-python ``` ```bash # Install a specific skill (e.g., google-antigravity-sdk). npx ctx7 skills install /Google-Antigravity/antigravity-sdk-python google-antigravity-sdk ``` -------------------------------- ### Run Interactive CLI Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the interactive CLI example for a full interactive agent session with custom tools and tool approval. ```bash python interactive_cli.py ``` -------------------------------- ### Session Start Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked when the agent session begins. Ensure the `hooks` object is imported. ```python from google.antigravity.hooks import hooks @hooks.on_session_start async def on_start(): print("Session started") ``` -------------------------------- ### Run Async Chat Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the async chat example for a fully asynchronous peer-to-peer agent chat without rounds. ```bash python async_chat.py ``` -------------------------------- ### Install and Authenticate Antigravity SDK Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/getting_started/README.md Install the SDK using pip and set your API key as an environment variable. Alternatively, pass the key directly in code. ```bash pip install google-antigravity export GEMINI_API_KEY="your_api_key_here" ``` -------------------------------- ### Run Round-Based Chat Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the round-based chat example to demonstrate synchronized parallel agent chat. ```bash python round_based_chat.py ``` -------------------------------- ### Install Google Antigravity SDK Skill via Vercel CLI Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/README.md Use the Vercel skills CLI to interactively browse and install skills. Install a specific skill globally using the --skill and --global flags. ```bash # Interactively browse and install skills. npx skills add Google-Antigravity/antigravity-sdk-python --list ``` ```bash # Install a specific skill (e.g., google-antigravity-sdk). npx skills add Google-Antigravity/antigravity-sdk-python --skill google-antigravity-sdk --global ``` -------------------------------- ### Define an MCP Server with FastMCP Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/mcp_tools.md Example of setting up an MCP server using the FastMCP library to expose an 'add_numbers' tool. ```python from mcp.server import fastmcp mcp = fastmcp.FastMCP("MathServer") @mcp.tool() def add_numbers(a: int, b: int) -> int: """Adds two numbers.""" return a + b mcp.run() ``` -------------------------------- ### Pre-Turn Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked before a turn starts, allowing inspection or rejection of the prompt. It requires importing `types` and `hooks`, and the hook must return a `types.HookResult`. ```python from google.antigravity import types from google.antigravity.hooks import hooks @hooks.pre_turn async def pre_turn(data: str) -> types.HookResult: print(f"Intercepted prompt: {data}") return types.HookResult(allow=True) ``` -------------------------------- ### Implementing Agent Policies with Hooks Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Illustrates how to control agent behavior using a declarative policy system with hooks. This example denies all tools by default, allows file viewing, and prompts the user before running commands. ```python from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig from google.antigravity.hooks.policy import deny, allow, ask_user, enforce from google.antigravity.utils.interactive import run_interactive_loop policies = [ deny("*", ), # Block all tools by default allow("view_file", ), # Allow reading files ask_user("run_command", handler=my_handler), # Ask before running commands ] config = LocalAgentConfig( capabilities=CapabilitiesConfig(), policies=policies, ) async with Agent(config) as agent: await run_interactive_loop(agent) ``` -------------------------------- ### Running Background Tasks with Triggers Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Shows how to set up background tasks that run periodically and can push messages into the agent. This example uses the `every` trigger to check deployment status every 60 seconds. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.triggers import every from google.antigravity.utils.interactive import run_interactive_loop async def check_status(ctx): await ctx.send("Check the deployment status.") config = LocalAgentConfig( triggers=[every(60, check_status)], ) async with Agent(config) as agent: await run_interactive_loop(agent) ``` -------------------------------- ### Configure Stdio Transport for MCP Server Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/mcp_integration.md Use Stdio transport to manage the MCP server lifecycle locally. This example shows how to configure it in LocalAgentConfig. ```python from google.antigravity import Agent, LocalAgentConfig, types mcp_servers = [ types.McpStdioServer( name="my_stdio_server", command="python3", args=["mcp_server.py"], ) ] config = LocalAgentConfig(mcp_servers=mcp_servers) async with Agent(config) as agent: response = await agent.chat("Use the MCP server to perform a task.") print(await response.text()) ``` -------------------------------- ### Define Tool Call Policies Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/hooks/README.md Define a list of policies to enforce tool call behavior. This example blocks all tools by default, allows viewing files, denies specific dangerous commands, and prompts the user for others. ```python from google.antigravity.hooks import policy policies = [ policy.deny("*"), # Block everything by default policy.allow("view_file"), # Except reading files policy.deny("run_command", # Block dangerous commands when=lambda args: "rm" in args.get("CommandLine", "")) policy.ask_user("run_command", # Ask for safe commands handler=my_approval_fn), ] hook = policy.enforce(policies) # Register: HookRunner(pre_tool_call_decide_hooks=[hook]) ``` -------------------------------- ### Post-Tool Call Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked after a tool call has successfully completed. Ensure the `hooks` object is imported. ```python from google.antigravity.hooks import hooks @hooks.post_tool_call async def post_tool(data): print("Tool execution completed") ``` -------------------------------- ### Run Interactive Agent Loop Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Use run_interactive_loop to start an interactive session with the agent. Ensure CapabilitiesConfig is passed to enable all tools, including write operations. ```python from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig from google.antigravity.utils.interactive import run_interactive_loop config = LocalAgentConfig( # api_key="your_api_key_here", capabilities=CapabilitiesConfig(), ) async with Agent(config) as agent: await run_interactive_loop(agent) ``` -------------------------------- ### Post-Turn Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked after a turn finishes, receiving the final response content. Ensure the `hooks` object is imported. ```python from google.antigravity.hooks import hooks @hooks.post_turn async def post_turn(data: str): print(f"Final response: {data}") ``` -------------------------------- ### Compaction Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked when a context compaction event occurs within the agent's lifecycle. Ensure the `hooks` object is imported. ```python from google.antigravity.hooks import hooks @hooks.on_compaction async def on_compact(data): print("Context compaction occurred") ``` -------------------------------- ### Session End Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked when the agent session concludes. Ensure the `hooks` object is imported. ```python from google.antigravity.hooks import hooks @hooks.on_session_end async def on_end(): print("Session ended") ``` -------------------------------- ### Pre-Tool Call (Decide) Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked before a tool call to determine if it should proceed. It requires importing `types` and `hooks`, and must return a `types.HookResult`. ```python from google.antigravity import types from google.antigravity.hooks import hooks @hooks.pre_tool_call_decide async def pre_tool(data: types.ToolCall) -> types.HookResult: print(f"Approving tool call: {data.name}") return types.HookResult(allow=True) ``` -------------------------------- ### Interaction Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked when the agent requires user interaction, such as asking a question. It requires importing `types` and `hooks`, and must return a `types.QuestionHookResult`. ```python from google.antigravity import types from google.antigravity.hooks import hooks @hooks.on_interaction async def on_interact(data: types.AskQuestionInteractionSpec) -> types.QuestionHookResult: print(f"Interaction requested: {data}") return types.QuestionHookResult(responses=[]) ``` -------------------------------- ### Registering Hooks with LocalAgentConfig Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md Hooks are registered by passing a list of hook functions to the `hooks` parameter when creating a `LocalAgentConfig`. This example shows how to include all previously defined hooks. ```python from google.antigravity.connections.local import LocalAgentConfig config = LocalAgentConfig( hooks=[ on_start, on_end, pre_turn, post_turn, pre_tool, post_tool, on_error, on_compact, on_interact, ], ) ``` -------------------------------- ### Add Custom Tools to Agent Configuration Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/agent_configuration.md Integrate custom tools into the agent's capabilities. Refer to the custom tool documentation for a full guide on creation and usage. ```python from google.antigravity import Agent, LocalAgentConfig config = LocalAgentConfig( tools=[my_custom_tool_function], ) ``` -------------------------------- ### File Change Trigger with `on_file_change` Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/periodic_trigger.md Implement file system monitoring using `on_file_change`. This trigger invokes a callback function when specified files or directories are modified. Ensure the `watchfiles` package is installed. ```python async def handle_file_change(ctx: TriggerContext, changes): """Callback for file change events.""" for change in changes: logging.info(f"TRIGGER: File {change.path} was {change.kind}") # await ctx.send("Configuration updated.") # Create a trigger that watches a file or directory # Note: Requires 'watchfiles' package to be installed. file_trigger = on_file_change("/path/to/watch", handle_file_change) ``` -------------------------------- ### Execute First Chat Turn with Antigravity SDK Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/getting_started/README.md Initialize the agent configuration, pick up the API key from the environment, and perform a chat interaction. Prints the response text. ```python import asyncio from google.antigravity import Agent, LocalAgentConfig async def main(): # Initialize the agent configuration. It automatically picks up GEMINI_API_KEY from the environment. config = LocalAgentConfig() async with Agent(config) as agent: response = await agent.chat("Explain quantum computing in one sentence.") print(await response.text()) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### LocalConnection Strategy Usage Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/connections/README.md Demonstrates how to initialize and use the LocalConnectionStrategy to connect to a local agent harness, send a prompt, and receive steps asynchronously. Requires specifying the binary path, Gemini API key, and skill paths. ```python from google.antigravity.connections.local import LocalConnectionStrategy from google.antigravity.types import GeminiConfig strategy = LocalConnectionStrategy( binary_path="/path/to/localharness", gemini_config=GeminiConfig(api_key="..."), skills_paths=["/path/to/skills"], ) async with strategy: connection = strategy.connect() await connection.send("Hello") async for step in connection.receive_steps(): print(step) ``` -------------------------------- ### Create a Simple Agent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Use the Agent class to create a basic AI agent. Configure with system instructions and manage its lifecycle using an async context manager. ```python import asyncio from google.antigravity import Agent, LocalAgentConfig async def main(): config = LocalAgentConfig( system_instructions="You are an expert assistant for codebase navigation.", # api_key="your_api_key_here", ) async with Agent(config) as agent: response = await agent.chat("What files are in the current directory?") print(await response.text()) async def run(): await main() if __name__ == "__main__": asyncio.run(run()) ``` -------------------------------- ### Load Skills from Filesystem Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/agent_skills.md Configure an agent to load skills by specifying a directory containing skill folders in `LocalAgentConfig`. The agent can then be prompted to list and describe its available skills. ```python from google.antigravity import Agent, LocalAgentConfig # Path to the PARENT directory containing skill folders skills_directory = "/path/to/skills" config = LocalAgentConfig( skills_paths=[skills_directory] ) async with Agent(config) as agent: response = await agent.chat("Please list your available skills and tell me what they do.") print(await response.text()) ``` -------------------------------- ### Register and Execute Tools with ToolRunner Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/tools/README.md Demonstrates how to use `ToolRunner` to register a custom tool and execute it directly or process structured tool calls. Ensure `ToolRunner` is initialized with the tools you intend to use. ```python from google.antigravity.tools.tool_runner import ToolRunner def my_custom_tool(param: str) -> str: """A custom tool that does something.""" return f"Processed: {param}" tool_runner = ToolRunner(tools=[my_custom_tool]) # Execute directly result = await tool_runner.execute("my_custom_tool", param="input value") print(result) # Process structured tool calls from google.antigravity import types calls = [types.ToolCall(name="my_custom_tool", args={"param": "another input"})] results = await tool_runner.process_tool_calls(calls) print(results[0].result) ``` -------------------------------- ### Connecting to External MCP Servers Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Demonstrates how to connect the agent to external MCP (Model Context Protocol) servers. This allows the agent to utilize tools exposed by these external servers. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.types import McpStdioServer config = LocalAgentConfig( mcp_servers=[McpStdioServer(name="my_server", command="npx", args=["my-mcp-server"])], ) async with Agent(config) as agent: response = await agent.chat("Use the MCP tools to help me.") ``` -------------------------------- ### Define and Run Triggers with TriggerRunner Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/triggers/README.md Demonstrates how to define a trigger using the @trigger decorator or a helper factory, and how to wire them into the session using TriggerRunner. ```python from google.antigravity.triggers import triggers from google.antigravity.triggers import trigger_runner from google.antigravity.triggers import helpers from google.antigravity import types # 1. Define a trigger using the @trigger decorator. @triggers.trigger async def health_check(ctx: triggers.TriggerContext) -> None: """Pings the agent every 5 minutes.""" while True: await asyncio.sleep(300) await ctx.send("Health check") # 2. Or use a helper factory. async def on_config_change(ctx, changes: list[types.FileChange]): for change in changes: await ctx.send(f"{change.kind.value}: {change.path}") config_watcher = helpers.on_file_change("/etc/app/config.yaml", on_config_change) # 3. Wire them into the session. async with trigger_runner.TriggerRunner( triggers=[health_check, config_watcher], connection=connection, ) as runner: # ... agent session ... pass # stop() called automatically on exit. ``` -------------------------------- ### Enable and Use Image Generation Tool Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/multimodal.md Configure the agent with `GENERATE_IMAGE` capability to allow it to create images based on textual prompts. The system instructions should mention the tool's availability. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.types import CapabilitiesConfig, BuiltinTools config = LocalAgentConfig( system_instructions=f"You have access to the '{BuiltinTools.GENERATE_IMAGE.value}' tool. Use it when asked to generate images.", capabilities=CapabilitiesConfig( enabled_tools=[BuiltinTools.GENERATE_IMAGE] ), ) async with Agent(config) as agent: response = await agent.chat("Generate an image of a futuristic city.") print(await response.text()) ``` -------------------------------- ### Basic Chat with Agent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hello_world.md Demonstrates the most basic chat interaction with an agent. Requires importing Agent and LocalAgentConfig. ```python from google.antigravity import Agent, LocalAgentConfig async with Agent(LocalAgentConfig()) as agent: response = await agent.chat("Hello, World!") print(await response.text()) ``` -------------------------------- ### Append Persona with Simple String Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/persona_config.md A shorthand for appending instructions. Passing a simple string to `system_instructions` adds it as a new section to the default agent instructions. ```python from google.antigravity import Agent, LocalAgentConfig config = LocalAgentConfig( system_instructions="Always respond in pirate slang." ) async with Agent(config) as agent: response = await agent.chat("Hello!") print(await response.text()) ``` -------------------------------- ### Custom Polling Trigger Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/periodic_trigger.md Define a custom trigger by implementing any async function with the `TriggerContext` signature. This example shows a custom polling mechanism that checks an external source periodically. ```python # ============================================================================= # 3. Custom Trigger (any async function matching the signature) # ============================================================================= async def custom_poll_trigger(ctx: TriggerContext): """Custom trigger that polls an external source.""" logging.info("TRIGGER: Custom polling trigger started.") while True: # Simulate checking an external event event_detected = False # Replace with actual check if event_detected: await ctx.send("Custom event detected!") await asyncio.sleep(30) # Poll every 30 seconds ``` -------------------------------- ### Interactive Chat Loop Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hello_world.md Starts a full interactive loop in the terminal for direct user interaction with the agent. This method is intended for testing and direct user engagement, not for automated agents. ```python from google.antigravity import Agent, LocalAgentConfig async with Agent(LocalAgentConfig()) as agent: # Starts a full interactive loop in the terminal await agent.run_interactive_loop() ``` -------------------------------- ### Ask User for Confirmation on All Tools on an MCP Server Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.ask_user() with an MCP server configuration object and a handler to prompt for user confirmation for all tools on that server. ```python from google.antigravity.hooks import policy async def my_approval_handler(tool_call): # Custom logic to ask user or auto-approve # Return True to allow, False to deny return True # Ask for confirmation on all tools on an MCP server policy.ask_user(mcp_server_cfg, handler=my_approval_handler) ``` -------------------------------- ### Allow All Policy Configuration for Development Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Configure an agent to allow all actions. This is suitable only for local development environments where safety is not a concern. ```python from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig from google.antigravity.hooks import policy config = LocalAgentConfig( system_instructions="You are a helpful assistant.", capabilities=CapabilitiesConfig(), policies=[policy.allow_all()], ) ``` -------------------------------- ### Overwrite Instructions with CustomSystemInstructions Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/persona_config.md Use `CustomSystemInstructions` to completely replace all default system instructions. Exercise caution as you become responsible for all necessary safety and operational guidance. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.types import CustomSystemInstructions custom_si = CustomSystemInstructions( text="You are a minimal assistant. You only answer with 'Yes' or 'No'." ) config = LocalAgentConfig( system_instructions=custom_si ) async with Agent(config) as agent: response = await agent.chat("Is the sky blue?") print(await response.text()) ``` -------------------------------- ### On Tool Error Hook Example Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hooks.md This hook is invoked when a tool execution fails, allowing for error handling or modification of the error message. It requires importing `hooks` and can return `None` to let the error propagate. ```python from google.antigravity.hooks import hooks @hooks.on_tool_error async def on_error(data: Exception): print(f"Tool failed: {data}") return None # Let the error propagate ``` -------------------------------- ### Configure Model Context Protocol (MCP) Servers Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/agent_configuration.md Set up Model Context Protocol (MCP) servers for agent communication. Use the types.McpStreamableHttpServer for HTTP-based servers. ```python from google.antigravity import Agent, LocalAgentConfig, types config = LocalAgentConfig( mcp_servers=[ types.McpStreamableHttpServer( name="my_mcp_server", url="http://localhost:8080", ) ], ) ``` -------------------------------- ### Safe Default Policy Configuration Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use the default 'confirm_run_command()' policy which denies 'run_command' while allowing all other tools. This configuration requires no explicit policy list. ```python from google.antigravity import Agent, LocalAgentConfig # run_command is denied, all other tools allowed config = LocalAgentConfig( system_instructions="You are a helpful assistant.", ) ``` -------------------------------- ### Create Filesystem Watcher Trigger with `on_file_change` Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/triggers/README.md The `on_file_change` helper factory creates a trigger that reacts to filesystem changes. It uses `watchfiles` for efficient OS-level watching and passes a list of `FileChange` objects to the callback. ```python async def handle_change(ctx, changes: list[FileChange]): for change in changes: if change.kind == FileChangeKind.MODIFIED: await ctx.send(f"Updated: {change.path}") my_trigger = on_file_change("/path/to/watched/dir", handle_change) ``` -------------------------------- ### Track Token Usage in Agent Session Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/observability.md Use `agent.conversation.total_usage` to get cumulative token counts for the session. Monitor `thoughts_token_count` for models that support extended thinking, as it can significantly increase the total count. Token usage counts may be 0 if agent execution fails. ```python from google.antigravity import Agent, LocalAgentConfig # ... initialize agent ... async with Agent(config) as agent: response = await agent.chat("Hello") usage = agent.conversation.total_usage print(f"Prompt tokens: {usage.prompt_token_count}") print(f"Candidates tokens: {usage.candidates_token_count}") print(f"Thoughts tokens: {usage.thoughts_token_count}") print(f"Total tokens: {usage.total_token_count}") ``` -------------------------------- ### Ask User for Confirmation on Specific Tools on an MCP Server Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.ask_user() with an MCP server configuration object, a list of tool names, and a handler to require user confirmation for a specific subset of tools on that server. ```python from google.antigravity.hooks import policy async def my_approval_handler(tool_call): # Custom logic to ask user or auto-approve # Return True to allow, False to deny return True # Ask for confirmation on a specific subset of tools on an MCP server policy.ask_user(mcp_server_cfg, ["dangerous_tool"], handler=my_approval_handler) ``` -------------------------------- ### Registering Custom Python Functions as Agent Tools Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Shows how to define a Python function and register it as a tool for the agent. The agent can then call this function when needed to fulfill user requests. ```python def get_weather(city: str) -> str: """Returns the current weather for a city.""" return f"It's sunny in {city}." config = LocalAgentConfig( tools=[get_weather], ) async with Agent(config) as agent: response = await agent.chat("What's the weather in Tokyo?") ``` -------------------------------- ### Restore Permissive Behavior with allow_all() Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.allow_all() to permit all tools, including run_command. This is useful for agents that require broad access. ```python from google.antigravity import LocalAgentConfig from google.antigravity.hooks import policy config = LocalAgentConfig( system_instructions="You are a helpful assistant.", policies=[policy.allow_all()], ) ``` -------------------------------- ### Spawning and Using a Subagent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/subagents.md Enable subagents in the LocalAgentConfig and then prompt the agent to use a subagent for a task. The response will contain the aggregated output, including the subagent's work. ```python from google.antigravity import Agent, LocalAgentConfig, types # Enable subagents in the config config = LocalAgentConfig( capabilities=types.CapabilitiesConfig( enable_subagents=True, ) ) async with Agent(config) as agent: # Prompt the agent to use a subagent response = await agent.chat("Use a subagent to write a short poem about nature.") print(await response.text()) ``` -------------------------------- ### Define and Use a Custom Tool Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/custom_tool.md Define a Python function with a docstring to create a custom tool. Configure the agent with this tool and then interact with it. ```python from google.antigravity import Agent, LocalAgentConfig # 1. Define the tool with a descriptive docstring def get_current_temperature(location: str) -> str: """Gets the current temperature for a given location. Args: location: The city and state, e.g. "San Francisco, CA". """ # In a real application, this would call an external weather API. # For this example, we return a hardcoded string. return f"The temperature in {location} is 72°F." # 2. Configure the agent with the custom tool config = LocalAgentConfig( tools=[get_current_temperature], ) # 3. Chat with the agent async with Agent(config) as agent: response = await agent.chat("What's the temperature in Mountain View?") # Stream the response async for chunk in response: print(chunk, end="", flush=True) ``` -------------------------------- ### Deny by Default Policy Configuration Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Configure an agent to deny all actions by default, then selectively allow specific safe tools like 'view_file' and 'code_search'. Use 'ask_user' for commands requiring explicit approval. ```python from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig from google.antigravity.hooks import policy policies = [ policy.deny_all(), policy.allow("view_file"), policy.allow("code_search"), policy.ask_user("run_command", handler=my_approval_handler), ] config = LocalAgentConfig( system_instructions="You are a helpful assistant.", capabilities=CapabilitiesConfig(), # Enables write tools policies=policies, ) ``` -------------------------------- ### Configure System Instructions for Agent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/agent_configuration.md Set system instructions to define the agent's persona or role. For complex personas, refer to persona configuration documentation. ```python config = LocalAgentConfig( system_instructions="You are an expert software architect.", ) ``` -------------------------------- ### Enable Standard Logging for Antigravity SDK Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/observability.md Enable INFO or DEBUG logging for the `google.antigravity` namespace to see harness activity. This outputs information about session start/stop, connection establishment, and tool execution. ```python import logging # Enable INFO logging for the SDK logging.getLogger("google.antigravity").setLevel(logging.INFO) logging.basicConfig(level=logging.INFO) ``` -------------------------------- ### Multimodal Ingestion with Filesystem and In-Memory Data Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/README.md Demonstrates how to send both file attachments (resolved from filesystem paths) and in-memory byte data as multimodal inputs to an agent. Use `from_file` for filesystem paths and direct instantiation of content classes like `Image` for raw bytes. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.types import Image, from_file config = LocalAgentConfig(system_instructions="You are an expert software architect.") async with Agent(config) as agent: # 1. Flat filesystem shortcut (automatically resolves as types.Document) pdf_spec = from_file("spec.pdf") # 2. Direct constructor instantiation (perfect for in-memory raw bytes) chart_image = Image( data=b"raw_png_bytes_here", mime_type="image/png", description="Architecture blueprint" ) # Send a mixed list of text instructions and content classes prompt = [ "Analyze this chart against the specification and list three security vulnerabilities:", chart_image, pdf_spec ] response = await agent.chat(prompt) print(await response.text()) ``` -------------------------------- ### Basic Agent Configuration with Model Selection Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/agent_configuration.md Configure an agent to use a specific model. Ensure the model identifier is valid and explicitly set only when required. ```python from google.antigravity import Agent, LocalAgentConfig config = LocalAgentConfig( model="gemini-3.5-flash", ) async with Agent(config=config) as agent: # Use the agent pass ``` -------------------------------- ### Approve All Tool Calls Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.allow_all() as a convenience preset to approve all tool calls. This is equivalent to policy.allow('*'). ```python from google.antigravity.hooks import policy # Approves all tool calls. Equivalent to allow("*"). policy.allow_all() ``` -------------------------------- ### Ask User for Confirmation on a Standard Tool Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.ask_user() with a tool name and a handler function to require user confirmation before executing a tool. The handler determines whether to allow or deny the execution. ```python from google.antigravity.hooks import policy async def my_approval_handler(tool_call): # Custom logic to ask user or auto-approve # Return True to allow, False to deny return True # Ask for confirmation on a standard tool policy.ask_user("run_command", handler=my_approval_handler) ``` -------------------------------- ### Agent Configuration with Triggers Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/periodic_trigger.md Configure the `Agent` with a list of defined triggers. The agent will manage the execution of these triggers in the background. ```python # ============================================================================= # 3. Custom Trigger (any async function matching the signature) # ============================================================================= async def custom_poll_trigger(ctx: TriggerContext): """Custom trigger that polls an external source.""" logging.info("TRIGGER: Custom polling trigger started.") while True: # Simulate checking an external event event_detected = False # Replace with actual check if event_detected: await ctx.send("Custom event detected!") await asyncio.sleep(30) # Poll every 30 seconds # ============================================================================= # Configuration and Execution # ============================================================================= config = LocalAgentConfig( system_instructions="You are a helpful assistant.", triggers=[timer_trigger, file_trigger, custom_poll_trigger], ) async with Agent(config) as agent: # The agent runs, and all triggers fire in the background. # Perform your agent interactions here. pass ``` -------------------------------- ### Allow All Tools on an MCP Server Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.allow() with an MCP server configuration object to permit all tools accessible through that server. ```python from google.antigravity.hooks import policy # Allow all tools on an MCP server policy.allow(mcp_server_cfg) ``` -------------------------------- ### Allow a Standard Tool Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.allow() to approve specific tool calls without requiring confirmation. This is suitable for tools that are safe to execute directly. ```python from google.antigravity.hooks import policy # Allow a standard built-in tool policy.allow("view_file") ``` -------------------------------- ### Run Autonomous Documentation Agent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the autonomous documentation agent, scoped to .md files, to maintain documentation accuracy. ```bash python doc_maintenance_agent.py [directory] ``` -------------------------------- ### Default Policy: Confirm run_command Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.confirm_run_command() as the default policy, which denies 'run_command' and allows all other tools. Optionally, a handler can be provided to use 'ask_user' instead of a hard deny. ```python from google.antigravity.hooks import policy # Denies run_command, allows everything else. This is the default policy. # Optionally accepts a handler to use ask_user instead of deny. policy.confirm_run_command() ``` -------------------------------- ### Streaming Response Tokens Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/hello_world.md Shows how to stream response tokens as they arrive from the agent. Useful for real-time feedback in chat applications. ```python from google.antigravity import Agent, LocalAgentConfig async with Agent(LocalAgentConfig()) as agent: response = await agent.chat("Tell me a short joke.") async for token in response: print(token, end="", flush=True) ``` -------------------------------- ### Allow All Tools on an MCP Server in Safety Policy Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/mcp_integration.md Configure a safety policy to allow all tools exposed by a specific MCP server. This is useful when using a deny-by-default policy. ```python stdio_server = types.McpStdioServer(name="pirate_math", ...) policies = [ policy.deny_all(), policy.allow(stdio_server), # Allows all tools exposed by pirate_math ] ``` -------------------------------- ### Allow Specific Tools on an MCP Server Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.allow() with an MCP server configuration object and a list of tool names to permit only a subset of tools. ```python from google.antigravity.hooks import policy # Allow a specific subset of tools on an MCP server policy.allow(mcp_server_cfg, ["tool1", "tool2"]) ``` -------------------------------- ### Limit Exposed Tools with Allowlist Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/mcp_integration.md Configure `enabled_tools` on an `McpStdioServer` to expose only a specific list of tools to the agent. ```python stdio_server = types.McpStdioServer( name="my_stdio_server", command="python3", args=["mcp_server.py"], enabled_tools=["pirate_multiply"], # Only this tool will be exposed ) ``` -------------------------------- ### Conversation: Low-level send() and receive_steps() usage Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/conversation/README.md Use `send()` for non-blocking prompt submission and `receive_steps()` to iterate over response steps. This is useful for step-level streaming and handling complex multimodal payloads. Ensure to check `StepSource` and `StepType` for processing. ```python async with Conversation.create(strategy) as conversation: await conversation.send("Tell me a story.") async for step in conversation.receive_steps(): if ( step.source == types.StepSource.MODEL and step.type == types.StepType.TEXT_RESPONSE ): print(step.content, end="") ``` -------------------------------- ### Connect Agent to MCP via Stdio Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/mcp_tools.md Connects an agent to an MCP server using the stdio transport. Ensure the MCP server command and arguments are correctly specified. ```python from google.antigravity import Agent, LocalAgentConfig, types mcp_servers = [ types.McpStdioServer( name="my_stdio_server", command="python3", args=["mcp_server.py"], ) ] config = LocalAgentConfig(mcp_servers=mcp_servers) async with Agent(config) as agent: response = await agent.chat("Add 5 and 3 using the add_numbers tool.") print(await response.text()) ``` -------------------------------- ### Run Autonomous Docstring Agent Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/examples/deep_dives/README.md Execute the autonomous docstring agent, scoped to .py files, to audit and ensure Google-style docstrings. ```bash python docstring_maintenance_agent.py [directory] ``` -------------------------------- ### Deny All Tool Calls Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.deny_all() as a convenience preset to deny all tool calls. This is equivalent to policy.deny('*'). ```python from google.antigravity.hooks import policy # Denies all tool calls. Equivalent to deny("*"). policy.deny_all() ``` -------------------------------- ### User Confirmation for Commands Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/hooks/README.md Implement an asynchronous handler function to confirm user approval for specific tool calls. The handler receives the ToolCall object and returns True to approve or False to deny. ```python async def confirm_with_user(tc: types.ToolCall) -> bool: response = input(f"Allow {tc.name}? (y/n): ") return response.lower() == "y" policy.ask_user("run_command", handler=confirm_with_user) ``` -------------------------------- ### Enable Read-Only Builtin Tools with CapabilitiesConfig Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/tools/README.md Configure the agent to only expose read-only builtin tools by setting `CapabilitiesConfig.enabled_tools`. This prevents the model from seeing or considering write tools. ```python from google.antigravity.types import CapabilitiesConfig, BuiltinTools # Only expose read-only tools — the model can't even see write tools. config = LocalAgentConfig( capabilities=CapabilitiesConfig( enabled_tools=BuiltinTools.read_only(), ), ) ``` -------------------------------- ### Deny a Standard Tool Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/references/safety_policies.md Use policy.deny() to immediately block specific tool calls. This is crucial for preventing potentially harmful operations like arbitrary command execution. ```python from google.antigravity.hooks import policy # Deny a standard built-in tool policy.deny("run_command") ``` -------------------------------- ### Chat with Text and Image Input Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/multimodal.md Pass an image file directly to the chat method alongside text. Ensure the image file exists at the specified path. ```python from google.antigravity import Agent, LocalAgentConfig from google.antigravity.types import Image async with Agent(LocalAgentConfig()) as agent: # Load an image from a file image = Image.from_file("path/to/image.png") # Send both text and image in a list response = await agent.chat(["What is in this image?", image]) print(await response.text()) ``` -------------------------------- ### Apply Safety Policies to MCP Servers Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/skills/google-antigravity-sdk/examples/getting_started/mcp_tools.md Combines MCP servers with declarative policy hooks to enforce fine-grained runtime checks. Policies can allow, deny, or ask the user for specific MCP server actions. ```python from google.antigravity import Agent, LocalAgentConfig, types from google.antigravity.hooks import policy stdio_server = types.McpStdioServer( name="pirate_math", command="python3", args=["mcp_server.py"], ) # Start by blocking all tools by default # Explicitly allow pirate_multiply # Explicitly deny pirate_divide (will cause a runtime denial, visible to the agent) policies = [ policy.deny_all(), policy.allow(stdio_server, ["pirate_multiply"]), policy.deny(stdio_server, ["pirate_divide"]), ] config = LocalAgentConfig(mcp_servers=[stdio_server], policies=policies) async with Agent(config) as agent: # This call is allowed: response = await agent.chat("Multiply 4 and 9.") print(await response.text()) # This call is denied at runtime by policy (the agent will receive a denial message): response = await agent.chat("Divide 12 by 3.") print(await response.text()) ``` -------------------------------- ### Deny Specific Tool Calls at Runtime with Policy Source: https://github.com/google-antigravity/antigravity-sdk-python/blob/main/google/antigravity/tools/README.md Use `policy.deny()` to reject specific tool calls at runtime via the hooks system. This allows the model to see the tool but prevents its use under certain conditions, providing a denial message. ```python from google.antigravity.hooks.policy import deny, allow # The model sees run_command but can't use it for destructive operations. policies = [ deny("run_command", when=lambda args: "rm" in args.get("CommandLine", "")), allow("* "), ] ```