生命周期与钩子

本页目录

SDK 提供后台事件调度、会话状态持久化、生命周期钩子和令牌成本审计的机制。

生命周期钩子与成本审计

您可以使用生命周期钩子装饰器拦截 Agent 轮次、处理工具错误并审核令牌使用情况。

例如,您可以配置在执行前记录用户提示、拦截或修改消息或优雅地处理异常而不会导致 Agent 崩溃的钩子:

from google.antigravity import Agent, LocalAgentConfig, hooks, types

@hooks.pre_turn
async def log_turn(prompt: str) -> types.HookResult:
    print(f"User prompt: {prompt}")
    return types.HookResult(allow=True)

@hooks.on_tool_error
async def handle_error(err: Exception) -> None:
    print(f"Tool execution failed: {err}")

config = LocalAgentConfig(hooks=[log_turn, handle_error])

async with Agent(config) as agent:
    response = await agent.chat("Analyze repository status.")
    print(await response.text())

    # Token usage auditing
    if response.usage_metadata:
        print(f"Turn tokens: {response.usage_metadata.total_token_count}")

触发器

触发器支持您根据特定的计划或事件自动运行任务。

例如,您可以配置一个触发器来每 60 秒监控一次服务状态:

import asyncio
from google.antigravity import Agent, LocalAgentConfig
from google.antigravity.triggers import every

async def check_status(ctx):
    print("Checking background service status...")

config = LocalAgentConfig(triggers=[every(60, check_status)])

async def main():
    async with Agent(config) as agent:
        print("Agent running. Monitoring status every 60 seconds...")
        await asyncio.sleep(120)

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

会话持久化

会话持久性支持您在应用程序重新启动时保留和恢复有状态会话。请注意,conversation_id 的长度必须至少为 32 个字符,并且仅包含字母数字字符和连字符(不允许使用下划线)。

配置存储目录和会话标识符以保存或加载会话:

from google.antigravity import LocalAgentConfig

# conversation_id persists or restores an existing session
conversation_id = "session-12345678901234567890123456789012"

config = LocalAgentConfig(
    save_dir="./sessions",
    conversation_id=conversation_id,
    app_data_dir="/path/to/custom/storage",
)

示例代码

有关完整的工作代码示例,请查看 GitHub 存储库: