教程7:插件


文档摘要

教程 7:插件 您将学到的内容 插件基础:了解什么是插件以及它们的工作原理 全局回调管理:使用插件处理横切关注点 实用插件示例:日志记录、监控和请求修改 核心概念:插件 Google ADK 中的插件是自定义代码模块,可通过回调钩子在代理工作流生命周期的各个阶段执行。与针对单个代理或工具配置的常规回调不同,插件只需在 上注册一次,即可全局应用于该运行器管理的所有代理、工具和 LLM 调用。 插件与回调对比 插件生命周期钩子 为什么要使用插件?

教程 7:插件

您将学到的内容

  • 插件基础:了解什么是插件以及它们的工作原理
  • 全局回调管理:使用插件处理横切关注点
  • 实用插件示例:日志记录、监控和请求修改

核心概念:插件

Google ADK 中的插件是自定义代码模块,可通过回调钩子在代理工作流生命周期的各个阶段执行。与针对单个代理或工具配置的常规回调不同,插件只需在 Runner 上注册一次,即可全局应用于该运行器管理的所有代理、工具和 LLM 调用。

插件与回调对比

┌─────────────────┐ ┌─────────────────┐ │ Regular │ │ Plugin │ │ Callbacks │ │ Callbacks │ ├─────────────────┤ ├─────────────────┤ │ • Per agent │ │ • Global scope │ │ • Per tool │ │ • Runner level │ │ • Specific task │ │ • Cross-cutting │ │ • Local effect │ │ • Reusable │ └─────────────────┘ └─────────────────┘

插件生命周期钩子

┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ User Message │───▶│ Runner Start │───▶│ Agent Execute │ │ Callback │ │ Callback │ │ Callback │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Model Callback │ │ Tool Callback │ │ Event Callback │ │ (before/after)│ │ (before/after)│ │ (modify event)│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Error Handling │ │ Runner End │ │ Cleanup Tasks │ │ Callback │ │ Callback │ │ & Reporting │ └─────────────────┘ └─────────────────┘ └─────────────────┘

为什么要使用插件?

  • 横切关注点:实现适用于整个应用的功能
  • 可重用性:将相关的回调函数打包在一起以供复用
  • 全局监控:跟踪所有代理、工具和模型交互
  • 策略实施:实现安全防护墙和访问控制
  • 日志与指标:集中式日志记录和性能监控
  • 请求/响应修改:动态修改输入和输出

教程概述

本教程通过一个结合多个用例的实战示例,演示如何在 Google ADK 中创建和使用插件:

演示插件功能

  1. 请求日志记录:记录所有用户消息并附带时间戳
  2. 请求修改:为用户消息添加时间戳上下文
  3. 代理追踪:统计并监控代理执行次数
  4. 工具监控:跟踪工具使用情况并处理错误
  5. 最终报告:生成插件活动摘要

项目结构

7_plugins/ ├── README.md # This file - concept explanation ├── agent.py # Agent implementation with plugin ├── app.py # Streamlit interface ├── requirements.txt # Dependencies └── plugin_example.py # Standalone plugin demonstration

学习目标

完成本教程后,您将理解:

  • 插件架构:插件如何扩展 BasePlugin 类
  • 全局作用域:插件如何跨所有代理和工具生效
  • 回调钩子:可用的插件回调方法及其触发时机
  • 实际应用:插件的现实用例
  • 错误处理:如何实现优雅的错误恢复
  • 简单实现:易于理解的插件结构

开始使用

前提条件

  • Python 3.11+
  • Google AI Studio API 密钥
  • 对 Google ADK 的基本了解(教程 1-6)

设置

  1. 获取 API 密钥:访问 Google AI Studio
  2. 创建 .env 文件:在此目录下创建名为 .env 的文件,并填写:
    GOOGLE_API_KEY=your_google_ai_studio_api_key_here
  3. 安装依赖pip install -r requirements.txt

Important:

  • Make sure your .env file is in the same directory as the tutorial files
  • Replace your_google_ai_studio_api_key_here with your actual API key
  • The .env 文件不应提交到版本控制

运行教程

cd 7_plugins streamlit run app.py

关键概念

插件类结构

from google.adk.plugins.base_plugin import BasePlugin class MyPlugin(BasePlugin): def __init__(self): super().__init__(name="my_plugin") # Initialize plugin state async def before_agent_callback(self, *, agent, callback_context): # Called before each agent execution pass async def after_model_callback(self, *, callback_context, llm_response): # Called after each model call pass

插件注册

from google.adk.runners import InMemoryRunner runner = InMemoryRunner( agent=my_agent, app_name="my_app", plugins=[MyPlugin()] # Register plugins here )

可用的回调钩子

  • on_user_message_callback: Modify user input
  • before_run_callback: Setup before execution
  • before_agent_callback / after_agent_callback: Agent lifecycle
  • before_model_callback / after_model_callback: Model interactions
  • before_tool_callback / after_tool_callback: Tool execution
  • on_model_error_callback / on_tool_error_callback: Error handling
  • on_event_callback: Modify events before streaming
  • after_run_callback: Cleanup after execution

Use Cases

Common Plugin Applications

  1. Logging & Tracing: Detailed logs for debugging and analysis
  2. Policy Enforcement: Security guardrails and access controls
  3. Monitoring & Metrics: Performance tracking and analytics
  4. Response Caching: Cache expensive operations
  5. Request/Response Modification: Add context or standardize outputs
  6. Error Recovery: Graceful handling of failures
  7. Usage Analytics: Track patterns and usage statistics

Important Notes

  • Plugin Precedence: Plugin callbacks run before agent-level callbacks
  • Global Scope: Plugins affect all agents, tools, and models in the runner
  • Web Interface: Plugins are not supported by the ADK web interface
  • Error Handling: Plugin error callbacks can suppress exceptions and provide fallbacks

Next Steps

After completing this tutorial, you can:

  • Create custom plugins for your specific use cases
  • Implement monitoring and analytics plugins
  • Build security and policy enforcement plugins
  • Explore advanced plugin patterns and combinations

Troubleshooting

Common Issues

"Missing key inputs argument" Error

  • Ensure you have created a .env file with your Google AI Studio API key
  • Verify the API key is valid and has the necessary permissions
  • Check that the .env file is in the same directory as the tutorial files

Import Errors

  • Make sure you have installed all dependencies: pip install -r requirements.txt
  • 确保您使用的是 Python 3.11 或更高版本

插件无法正常工作

  • 请记住,插件不支持通过 ADK Web 界面使用
  • 确保您通过 Streamlit 应用或 Python 脚本运行代理

其他资源

免责声明
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文(母语)文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。


作者与出处
原作者: Shubhamsaboo
来源:Shubhamsaboo
许可证:Apache-2.0
整理: 灏天文库整理
由灏天文库结构化整理,提供目录导航、全文检索与在线阅读,便于系统化学习
发布者: 作者: Shubhamsaboo 转发
评论区 (0)
U