跳转到内容

组建你的第一个智能代理团队:使用 ADK 开发一个功能强大的天气信息机器人

Google Colaboratory 的标志 在 Colab 中打开(该文件/应用程序等)。

本教程是在前一个教程的基础上继续扩展的。 多工具代理(Multi-tool agent) 项目。现在,你已经准备好更深入地研究这个问题,并构建一个更加复杂、功能更完善的系统了。 多智能体系统(Multi-Agent System).

我们将开始着手构建这个……(具体内容需要根据上下文来确定)。 Weather Bot 代理团队我们逐步在简单的基础上添加各种高级功能。最初,我们只有一个能够查询天气信息的代理程序;随后,我们会逐步为其添加更多功能,例如:

  • 利用不同的 AI 模型(Gemini、GPT、Claude)。
  • 为不同的任务(例如问候语和告别语)设计专门的子代理程序。
  • 实现代理之间的智能任务分配(即让代理能够自动、智能地完成彼此之间的工作)。
  • 通过使用持久化的会话状态(persistent session state)来为代理(agents)提供存储空间(即内存)。
  • 通过回调函数来实现关键的安全防护机制。

为什么需要一个天气机器人团队?

这个用例虽然看起来很简单,但实际上提供了一个实用且易于理解的框架,用于探索构建复杂、实际应用所需的核心 ADK(Android Development Kit)概念。你将学习如何设计应用程序中的交互逻辑、管理应用程序的状态、确保系统的安全性,以及协调多个 AI 系统协同工作。

ADK到底是什么?

作为提醒:ADK 是一个基于 Python 的框架,旨在简化由大型语言模型(LLMs)驱动的应用程序的开发过程。该框架提供了强大的开发工具,用于创建能够进行推理、制定计划、使用各种工具、与用户动态交互以及在团队中有效协作的智能代理(agents)。

在这个高级教程中,你将掌握以下内容:

  • ✅ 工具定义与使用: 编写 Python 函数tools这些规则为代理程序提供了特定的功能(例如获取数据),并指导它们如何有效地使用这些功能。
  • ✅ 多大型语言模型(Multi-LLM)的灵活性: 通过 LiteLLM 的集成,可以配置代理程序以使用各种领先的 large language models(LLMs),例如 Gemini、GPT-4o 和 Claude Sonnet,从而让您能够为每个任务选择最适合的模型。
  • ✅ 代理委托与协作(Agent Delegation & Collaboration): 设计专门的子代理,并实现自动路由功能。)auto flow)将用户请求分配给团队中最合适的代理(即负责处理该请求的成员)。
  • ✅ 用于内存的会话状态(Session State for Memory): 利用(某种资源、技术或方法) Session State 和 ToolContext 为了让代理能够在对话的不同环节中记住相关信息,从而实现更加符合上下文的互动(即更加自然、合理的对话)。
  • ✅ 带有回调功能的安全防护机制: 实施;执行 before_model_callback 和 before_tool_callback 根据预定义的规则来检查、修改或阻止请求/工具的使用,从而提高应用程序的安全性和可控性。

最终状态预期(End State Expectation):

通过完成本教程,您将构建一个功能齐全的多智能体天气机器人系统。该系统不仅可以提供天气信息,还能处理对话中的各种细节(如礼貌用语等),记住用户上次查询的城市,并在预设的安全范围内运行;所有这些功能都是通过 ADK(Active Development Kit)来实现的。

先决条件:

  • ✅ 需要对 Python 编程有扎实的理解。
  • ✅ 需要熟悉大型语言模型(LLMs)、应用程序编程接口(APIs)以及“代理”(agents)的概念。
  • ❗ 至关重要的是:必须完成 ADK 快速入门教程(ADK Quickstart tutorials),或者具备相应的 ADK 基础知识(包括 Agent、Runner、SessionService 的概念以及基本工具的使用方法)。 本教程正是建立在这些概念之上的。
  • ✅ API 密钥 对于您打算使用的大型语言模型(LLMs),请参考相应的工具或平台(例如:用于 Gemini 的 Google AI Studio、OpenAI Platform、Anthropic Console)。

关于执行环境的说明:

本教程是为交互式笔记本环境(如 Google Colab、Colab Enterprise 或 Jupyter Notebook)设计的。请注意以下事项:

  • 运行异步代码: Notebook 环境对异步代码的处理方式有所不同。您会看到一些使用这些异步代码的示例。 await (当事件循环已经在运行时适用,这种情况在笔记本环境中很常见) asyncio.run() (在以独立程序运行时,通常需要这个功能。) .py (可以在脚本中实现,也可以在特定的笔记本设置中实现)。这些代码块为这两种情况都提供了相应的指导。
  • 手动运行器/会话设置: 这些步骤包括明确地创建(某些内容)。 Runner 和 SessionService 这种方法之所以被推荐,是因为它能够让你对代理程序的执行生命周期、会话管理以及状态持久化(即数据在程序关闭后的保留方式)进行精细的控制。

替代方案:使用 ADK 的内置工具(Web UI、CLI 或 API 服务器)

如果您更喜欢使用 ADK 的标准工具来自动处理运行器(runner)和会话(session)管理的设置,那么您可以找到相应的解决方案。 等效代码 为此目的,该版本被设计为可以直接通过类似命令来运行。 adk web (用于 Web 用户界面) adk run (用于 CLI(命令行界面)交互),或 adk api_server (用于公开某个 API)。请按照以下步骤操作: README.md 请参考该替代资源中提供的说明。


准备好组建你的代理团队了吗?让我们开始吧!

注意: 本教程适用于 adk 版本 1.0.0 及更高版本。

# @title Step 0: Setup and Installation
# Install ADK and LiteLLM for multi-model support

!pip install google-adk -q
!pip install "litellm>=1.84" -q

print("Installation complete.")
# @title Import necessary libraries
import os
import asyncio
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm # For multi-model support
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai import types # For creating message Content/Parts

import warnings
# Ignore all warnings
warnings.filterwarnings("ignore")

import logging
logging.basicConfig(level=logging.ERROR)

print("Libraries imported.")
# @title Configure API Keys (Replace with your actual keys!)

# --- IMPORTANT: Replace placeholders with your real API keys ---

# Gemini API Key (Get from Google AI Studio: https://aistudio.google.com/app/apikey)
os.environ["GOOGLE_API_KEY"] = "YOUR_GOOGLE_API_KEY" # <--- REPLACE

# [Optional]
# OpenAI API Key (Get from OpenAI Platform: https://platform.openai.com/api-keys)
os.environ['OPENAI_API_KEY'] = 'YOUR_OPENAI_API_KEY' # <--- REPLACE

# [Optional]
# Anthropic API Key (Get from Anthropic Console: https://console.anthropic.com/settings/keys)
os.environ['ANTHROPIC_API_KEY'] = 'YOUR_ANTHROPIC_API_KEY' # <--- REPLACE

# --- Verify Keys (Optional Check) ---
print("API Keys Set:")
print(f"Google API Key set: {'Yes' if os.environ.get('GOOGLE_API_KEY') and os.environ['GOOGLE_API_KEY'] != 'YOUR_GOOGLE_API_KEY' else 'No (REPLACE PLACEHOLDER!)'}")
print(f"OpenAI API Key set: {'Yes' if os.environ.get('OPENAI_API_KEY') and os.environ['OPENAI_API_KEY'] != 'YOUR_OPENAI_API_KEY' else 'No (REPLACE PLACEHOLDER!)'}")
print(f"Anthropic API Key set: {'Yes' if os.environ.get('ANTHROPIC_API_KEY') and os.environ['ANTHROPIC_API_KEY'] != 'YOUR_ANTHROPIC_API_KEY' else 'No (REPLACE PLACEHOLDER!)'}")

# Configure ADK to use API keys directly (not Agent Platform for this multi-model setup)
os.environ["GOOGLE_GENAI_USE_ENTERPRISE"] = "False"


# @markdown **Security Note:** It's best practice to manage API keys securely (e.g., using Colab Secrets or environment variables) rather than hardcoding them directly in the notebook. Replace the placeholder strings above.
# --- Define Model Constants for easier use ---

# More supported models can be referenced here: https://ai.google.dev/gemini-api/docs/models#model-variations
MODEL_GEMINI_FLASH = "gemini-flash-latest"

# More supported models can be referenced here: https://docs.litellm.ai/docs/providers/openai#openai-chat-completion-models
MODEL_GPT_4O = "openai/gpt-4.1" # You can also try: gpt-4.1-mini, gpt-4o etc.

# More supported models can be referenced here: https://docs.litellm.ai/docs/providers/anthropic
MODEL_CLAUDE_SONNET = "claude-sonnet-4-6" # You can also try: claude-opus-4-6, etc

print("\nEnvironment configured.")

步骤 1:您的第一个代理程序——基本天气查询功能

让我们首先构建我们的天气机器人(Weather Bot)的基本组件:一个能够执行特定任务(查询天气信息)的代理(agent)。这需要创建两个核心部分:

  1. 一个工具: 这是一个 Python 函数,用于为代理(agent)提供所需的功能/资源。 能力;才能 用于获取天气数据。
  2. 一名特工: 这个 AI “大脑” 能理解用户的需求,知道系统中有一个用于查询天气的工具,并决定何时以及如何使用该工具。

1. 定义该工具(Tool)……get_weather)

在 ADK 中, 工具 这些是构成基础模块(building blocks)的核心元素,它们赋予代理(agents)超出单纯文本生成能力的实际功能。这些基础模块通常都是普通的 Python 函数,用于执行特定的操作,例如调用 API、查询数据库或进行计算。

我们的第一个工具将提供…… mock 天气报告功能。这使我们能够在不需要外部 API 密钥的情况下,专注于代理(agent)的结构设计。之后,你可以轻松地将这个模拟函数替换为能够调用真实天气服务功能的函数。

关键概念:文档字符串(docstrings)非常重要! 该代理的 Large Language Model(LLM)在很大程度上依赖于该函数的输出/结果。 `docstring` 为了理解:

  • 什么 这个工具确实可以完成相应的任务。
  • 当……的时候 要使用它。
  • 需要传递哪些参数(arguments)? 这需要……)city: str).
  • 需要哪些信息? 它会返回结果。

最佳实践: 为你的工具编写清晰、描述性强且准确的文档字符串(docstrings)。这对于大型语言模型(LLM)正确使用这些工具至关重要。

# @title Define the get_weather Tool
def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city (e.g., "New York", "London", "Tokyo").

    Returns:
        dict: A dictionary containing the weather information.
              Includes a 'status' key ('success' or 'error').
              If 'success', includes a 'report' key with weather details.
              If 'error', includes an 'error_message' key.
    """
    print(f"--- Tool: get_weather called for city: {city} ---") # Log tool execution
    city_normalized = city.lower().replace(" ", "") # Basic normalization

    # Mock weather data
    mock_weather_db = {
        "newyork": {"status": "success", "report": "The weather in New York is sunny with a temperature of 25°C."},
        "london": {"status": "success", "report": "It's cloudy in London with a temperature of 15°C."},
        "tokyo": {"status": "success", "report": "Tokyo is experiencing light rain and a temperature of 18°C."},
    }

    if city_normalized in mock_weather_db:
        return mock_weather_db[city_normalized]
    else:
        return {"status": "error", "error_message": f"Sorry, I don't have weather information for '{city}'."}

# Example tool usage (optional test)
print(get_weather("New York"))
print(get_weather("Paris"))

2. 定义代理(Agent);weather_agent)

现在,让我们来创建…… 代理(Agent) itself. An Agent 在 ADK 中,系统负责协调用户、大型语言模型(LLM)以及各种可用工具之间的交互。

我们使用几个关键参数来配置它:

  • name:该代理的唯一标识符(例如:“weather_agent_v1”)。
  • model:指定要使用哪个大型语言模型(LLM)(例如: MODEL_GEMINI_FLASH我们将从某个具体的 Gemini 模型开始讨论。
  • description:对代理(agent)整体功能的简要概述。这一点在后续非常重要,因为其他代理需要决定是否将任务委托给该代理时,这个概述将起到关键作用。 `this` agent.
  • instruction:为大型语言模型(LLM)提供了详细的指导,包括其行为方式、应展现的“人格特征”(即用户印象)、其目标,以及具体实施细节。 如何以及何时 “to utilize its assigned” 的意思是“利用其被分配到的资源或权限”。 tools.
  • tools:一个列表,其中包含了代理程序被允许使用的实际 Python 工具函数(例如: [get_weather]).

最佳实践: 提供清晰且具体的信息。 instruction 提示(Prompts):指令越详细,大型语言模型(LLM)就越能理解自己的职责,以及如何有效地使用相关工具。如果需要的话,应明确说明错误处理的方法。

最佳实践: 请选择具有描述性的名称(或内容)。 name 和 description 这些值(values)由 ADK 在内部使用,对于诸如自动委托(automatic delegation,稍后会有详细说明)等功能来说至关重要。

# @title Define the Weather Agent
# Use one of the model constants defined earlier
AGENT_MODEL = MODEL_GEMINI_FLASH # Starting with Gemini

weather_agent = Agent(
    name="weather_agent_v1",
    model=AGENT_MODEL, # Can be a string for Gemini or a LiteLlm object
    description="Provides weather information for specific cities.",
    instruction="You are a helpful weather assistant. "
                "When the user asks for the weather in a specific city, "
                "use the 'get_weather' tool to find the information. "
                "If the tool returns an error, inform the user politely. "
                "If the tool is successful, present the weather report clearly.",
    tools=[get_weather], # Pass the function directly
)

print(f"Agent '{weather_agent.name}' created using model '{AGENT_MODEL}'.")

3. 设置 Runner 和 Session Service

为了管理对话并执行相关操作,我们还需要另外两个组件:

  • SessionService:负责管理不同用户和会话之间的对话历史记录及会话状态。 InMemorySessionService 这是一个简单的实现方案,所有数据都存储在内存中,非常适合用于测试和简单的应用程序。该方案能够记录双方交换的消息内容。关于状态持久化(即数据在程序关闭后仍能被保留)的问题,我们将在第 4 步中进一步探讨。
  • Runner:这个引擎负责协调用户与系统之间的交互流程。它接收用户的输入,将其转发给相应的处理节点(agent),根据处理节点的逻辑来管理对大型语言模型(LLM)及各种工具的调用,并通过相应的机制处理会话状态的更新。 SessionService该过程会生成一些事件,这些事件反映了用户与系统交互的进展情况。
# @title Setup Session Service and Runner

# --- Session Management ---
# Key Concept: SessionService stores conversation history & state.
# InMemorySessionService is simple, non-persistent storage for this tutorial.
session_service = InMemorySessionService()

# Define constants for identifying the interaction context
APP_NAME = "weather_tutorial_app"
USER_ID = "user_1"
SESSION_ID = "session_001" # Using a fixed ID for simplicity

# Create the specific session where the conversation will happen
session = await session_service.create_session(
    app_name=APP_NAME,
    user_id=USER_ID,
    session_id=SESSION_ID
)
print(f"Session created: App='{APP_NAME}', User='{USER_ID}', Session='{SESSION_ID}'")

# --- OR ---

# Uncomment the following lines if running as a standard Python script (.py file):

# from google.adk.sessions import Session
#
# async def init_session(app_name:str,user_id:str,session_id:str) -> Session:
#     session = await session_service.create_session(
#         app_name=app_name,
#         user_id=user_id,
#         session_id=session_id
#     )
#     print(f"Session created: App='{app_name}', User='{user_id}', Session='{session_id}'")
#     return session
#
# session = asyncio.run(init_session(APP_NAME,USER_ID,SESSION_ID))

# --- Runner ---
# Key Concept: Runner orchestrates the agent execution loop.
runner = Runner(
    agent=weather_agent, # The agent we want to run
    app_name=APP_NAME,   # Associates runs with our app
    session_service=session_service # Uses our session manager
)
print(f"Runner created for agent '{runner.agent.name}'.")

4. 与代理(Agent)进行交互

我们需要一种方法来向我们的代理发送消息并接收其回复。由于大型语言模型(LLM)的调用以及相关工具的执行可能需要一些时间,因此…… Runner 异步运行。

我们将定义一个…… async 辅助函数(helper function)call_agent_async) that:

  1. 接收用户的查询字符串。
  2. 将其打包到 ADK 中。 Content `format.`
  3. 调用(函数或方法) runner.run_async同时,系统还会提供用户/会话的相关信息以及新发送的消息内容。
  4. 遍历…… 事件 这些事件由运行器(runner)生成。它们代表了代理(agent)执行过程中的各个步骤(例如:请求了某个工具(tool)的调用、收到了该工具的返回结果、中间阶段的 LLM(Large Language Model,大型语言模型)生成的思考内容、以及最终的响应)。
  5. 用于识别并打印…… 最终响应(Final Response) 正在使用的事件(event in use) event.is_final_response().

为什么 async? 与大型语言模型(LLMs)以及可能的工具(如外部 API)的交互属于 I/O 操作(即输入/输出操作)。 asyncio 这使得程序能够高效地处理这些操作,而不会阻塞程序的执行。

# @title Define Agent Interaction Function

from google.genai import types # For creating message Content/Parts

async def call_agent_async(query: str, runner, user_id, session_id):
  """Sends a query to the agent and prints the final response."""
  print(f"\n>>> User Query: {query}")

  # Prepare the user's message in ADK format
  content = types.Content(role='user', parts=[types.Part(text=query)])

  final_response_text = "Agent did not produce a final response." # Default

  # Key Concept: run_async executes the agent logic and yields Events.
  # We iterate through events to find the final answer.
  async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content):
      # You can uncomment the line below to see *all* events during execution
      # print(f"  [Event] Author: {event.author}, Type: {type(event).__name__}, Final: {event.is_final_response()}, Content: {event.content}")

      # Key Concept: is_final_response() marks the concluding message for the turn.
      if event.is_final_response():
          if event.content and event.content.parts:
             # Assuming text response in the first part
             final_response_text = event.content.parts[0].text
          elif event.actions and event.actions.escalate: # Handle potential errors/escalations
             final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}"
          # Add more checks here if needed (e.g., specific error codes)
          break # Stop processing events once the final response is found

  print(f"<<< Agent Response: {final_response_text}")

5. 运行对话(即执行与用户之间的交互过程)。

最后,让我们通过向代理发送一些查询来测试我们的设置。我们将这些查询封装在一个函数或模块中…… async 在主函数中调用(某个函数或方法)。 async 使用该函数并运行它。 await.

请查看输出结果:

  • 查看用户查询内容。
  • 请注意: --- Tool: get_weather called... --- 当代理程序使用该工具时,系统会记录相应的日志信息。
  • 请观察代理程序的最终响应结果,特别是它如何处理“天气数据无法获取”(例如巴黎地区的天气数据)的情况。
# @title Run the Initial Conversation

# We need an async function to await our interaction helper
async def run_conversation():
    await call_agent_async("What is the weather like in London?",
                                       runner=runner,
                                       user_id=USER_ID,
                                       session_id=SESSION_ID)

    await call_agent_async("How about Paris?",
                                       runner=runner,
                                       user_id=USER_ID,
                                       session_id=SESSION_ID) # Expecting the tool's error message

    await call_agent_async("Tell me the weather in New York",
                                       runner=runner,
                                       user_id=USER_ID,
                                       session_id=SESSION_ID)

# Execute the conversation using await in an async context (like Colab/Jupyter)
await run_conversation()

# --- OR ---

# Uncomment the following lines if running as a standard Python script (.py file):
# import asyncio
# if __name__ == "__main__":
#     try:
#         asyncio.run(run_conversation())
#     except Exception as e:
#         print(f"An error occurred: {e}")

恭喜您!您已经成功创建了第一个 ADK 代理,并成功与其进行了交互。该代理能够理解用户的请求,使用相应的工具来获取信息,并根据工具的返回结果给出适当的响应。

在下一步中,我们将探讨如何轻松地更换为该智能体提供支持的底层语言模型(Language Model)。

步骤 2:使用 LiteLLM 实现多模型训练 [可选]

在第一步中,我们构建了一个功能性的“天气代理”(Weather Agent),该代理由特定的 Gemini 模型提供支持。虽然这种方案非常有效,但在实际应用中,灵活性往往更为重要——因为用户通常希望能够根据需要灵活地使用不同的模型或算法。 不同的;有区别的 大型语言模型(Large Language Models,简称 LLMs)。为什么呢?

  • 性能: 某些模型在特定任务上表现出色(例如编程、推理、创意写作)。
  • 成本: 不同型号的价格各不相同。
  • 功能(Capabilities): 这些模型提供了多种功能、不同的上下文窗口大小以及微调选项。
  • 可用性/冗余性: 拥有备用方案可以确保即使在某个服务提供商出现问题时,你的应用程序仍然能够正常运行。

ADK 通过与相关系统的集成,实现了模型之间的无缝切换。 LiteLLM `library.LiteLLM` 作为一个统一的接口,可以用于调用超过 100 种不同的大型语言模型(Large Language Models, LLMs)。

在这一步中,我们将:

  1. 了解如何配置 ADK(Adobe Digital Kit)。 Agent 可以使用来自 OpenAI(GPT)和 Anthropic(Claude)等提供商的模型。 LiteLlm wrapper.
  2. 定义并配置我们的 Weather Agent 实例(这些实例各自拥有独立的会话(session)和运行机制(runner)),并立即对这些实例进行测试;每个 Weather Agent 实例都使用不同的大型语言模型(LLM)进行支持。
  3. 与这些不同的代理进行交互,以观察它们在响应方式上的潜在差异(即使它们使用的是相同的底层工具)。

1. 导入 LiteLlm

我们在初始设置阶段(步骤 0)就已经导入了这个组件,但它却是实现多模型支持的关键要素。

# @title 1. Import LiteLlm
from google.adk.models.lite_llm import LiteLlm

2. 定义并测试多模型智能体(Multi-Model Agents)

我们不再只传递一个模型名称字符串(该字符串默认指向 Google 的 Gemini 模型),而是将所需的模型标识符字符串放在一个特定的结构或容器中。 LiteLlm class.

  • 关键概念: LiteLlm Wrapper: The LiteLlm(model="provider/model_name") 该语法告诉 ADK:对于该代理的请求,应通过 LiteLLM 库将其路由到指定的模型提供者。

请确保您已在步骤 0 中配置了 OpenAI 和 Anthropic 所需的 API 密钥。我们将会使用这些密钥来与这些服务进行交互。 call_agent_async 这个函数(之前已经定义过)现在可以接受……(具体参数或输入内容需要根据上下文补充)。 runner, user_id,以及 session_id)以便在每个代理程序设置完成后立即与其进行交互。

下面的每个模块都将:

  • 使用特定的 LiteLLM 模型来定义该代理(agent)。MODEL_GPT_4O 或者 MODEL_CLAUDE_SONNET).
  • 创建一个…… 新的、独立的 InMemorySessionService 以及专门为该代理的测试运行而创建的会话(session)。这样可以将本次演示过程中的对话记录与其他对话记录分开,确保它们的独立性。
  • 创建一个…… Runner 该配置是专为特定的代理及其会话服务量身定制的。
  • 立即调用 call_agent_async 用于发送查询并测试该代理程序(agent)。

最佳实践: 使用常量来表示模型名称(例如: MODEL_GPT_4O, MODEL_CLAUDE_SONNET (在步骤 0 中已经定义了这些内容)这样可以避免输入错误,并使代码更易于管理。

错误处理: 我们将代理定义(agent definitions)包裹在……中。 try...except 这样做可以防止整个代码单元因缺少或使用无效的特定提供商的 API 密钥而失败,从而确保教程能够继续使用那些模型进行教学。 是(are 是 be 的复数形式) 已配置。

首先,让我们使用 OpenAI 的 GPT-4o 来创建并测试这个代理(agent)。

# @title Define and Test GPT Agent

# Make sure 'get_weather' function from Step 1 is defined in your environment.
# Make sure 'call_agent_async' is defined from earlier.

# --- Agent using GPT-4o ---
weather_agent_gpt = None # Initialize to None
runner_gpt = None      # Initialize runner to None

try:
    weather_agent_gpt = Agent(
        name="weather_agent_gpt",
        # Key change: Wrap the LiteLLM model identifier
        model=LiteLlm(model=MODEL_GPT_4O),
        description="Provides weather information (using GPT-4o).",
        instruction="You are a helpful weather assistant powered by GPT-4o. "
                    "Use the 'get_weather' tool for city weather requests. "
                    "Clearly present successful reports or polite error messages based on the tool's output status.",
        tools=[get_weather], # Re-use the same tool
    )
    print(f"Agent '{weather_agent_gpt.name}' created using model '{MODEL_GPT_4O}'.")

    # InMemorySessionService is simple, non-persistent storage for this tutorial.
    session_service_gpt = InMemorySessionService() # Create a dedicated service

    # Define constants for identifying the interaction context
    APP_NAME_GPT = "weather_tutorial_app_gpt" # Unique app name for this test
    USER_ID_GPT = "user_1_gpt"
    SESSION_ID_GPT = "session_001_gpt" # Using a fixed ID for simplicity

    # Create the specific session where the conversation will happen
    session_gpt = await session_service_gpt.create_session(
        app_name=APP_NAME_GPT,
        user_id=USER_ID_GPT,
        session_id=SESSION_ID_GPT
    )
    print(f"Session created: App='{APP_NAME_GPT}', User='{USER_ID_GPT}', Session='{SESSION_ID_GPT}'")

    # Create a runner specific to this agent and its session service
    runner_gpt = Runner(
        agent=weather_agent_gpt,
        app_name=APP_NAME_GPT,       # Use the specific app name
        session_service=session_service_gpt # Use the specific session service
        )
    print(f"Runner created for agent '{runner_gpt.agent.name}'.")

    # --- Test the GPT Agent ---
    print("\n--- Testing GPT Agent ---")
    # Ensure call_agent_async uses the correct runner, user_id, session_id
    await call_agent_async(query = "What's the weather in Tokyo?",
                           runner=runner_gpt,
                           user_id=USER_ID_GPT,
                           session_id=SESSION_ID_GPT)
    # --- OR ---

    # Uncomment the following lines if running as a standard Python script (.py file):
    # import asyncio
    # if __name__ == "__main__":
    #     try:
    #         asyncio.run(call_agent_async(query = "What's the weather in Tokyo?",
    #                      runner=runner_gpt,
    #                       user_id=USER_ID_GPT,
    #                       session_id=SESSION_ID_GPT)
    #     except Exception as e:
    #         print(f"An error occurred: {e}")

except Exception as e:
    print(f"❌ Could not create or run GPT agent '{MODEL_GPT_4O}'. Check API Key and model name. Error: {e}")

接下来,我们也会对 Anthropic 的 Claude Sonnet 做同样的处理。

# @title Define and Test Claude Agent

# Make sure 'get_weather' function from Step 1 is defined in your environment.
# Make sure 'call_agent_async' is defined from earlier.

# --- Agent using Claude Sonnet ---
weather_agent_claude = None # Initialize to None
runner_claude = None      # Initialize runner to None

try:
    weather_agent_claude = Agent(
        name="weather_agent_claude",
        # Key change: Wrap the LiteLLM model identifier
        model=LiteLlm(model=MODEL_CLAUDE_SONNET),
        description="Provides weather information (using Claude Sonnet).",
        instruction="You are a helpful weather assistant powered by Claude Sonnet. "
                    "Use the 'get_weather' tool for city weather requests. "
                    "Analyze the tool's dictionary output ('status', 'report'/'error_message'). "
                    "Clearly present successful reports or polite error messages.",
        tools=[get_weather], # Re-use the same tool
    )
    print(f"Agent '{weather_agent_claude.name}' created using model '{MODEL_CLAUDE_SONNET}'.")

    # InMemorySessionService is simple, non-persistent storage for this tutorial.
    session_service_claude = InMemorySessionService() # Create a dedicated service

    # Define constants for identifying the interaction context
    APP_NAME_CLAUDE = "weather_tutorial_app_claude" # Unique app name
    USER_ID_CLAUDE = "user_1_claude"
    SESSION_ID_CLAUDE = "session_001_claude" # Using a fixed ID for simplicity

    # Create the specific session where the conversation will happen
    session_claude = await session_service_claude.create_session(
        app_name=APP_NAME_CLAUDE,
        user_id=USER_ID_CLAUDE,
        session_id=SESSION_ID_CLAUDE
    )
    print(f"Session created: App='{APP_NAME_CLAUDE}', User='{USER_ID_CLAUDE}', Session='{SESSION_ID_CLAUDE}'")

    # Create a runner specific to this agent and its session service
    runner_claude = Runner(
        agent=weather_agent_claude,
        app_name=APP_NAME_CLAUDE,       # Use the specific app name
        session_service=session_service_claude # Use the specific session service
        )
    print(f"Runner created for agent '{runner_claude.agent.name}'.")

    # --- Test the Claude Agent ---
    print("\n--- Testing Claude Agent ---")
    # Ensure call_agent_async uses the correct runner, user_id, session_id
    await call_agent_async(query = "Weather in London please.",
                           runner=runner_claude,
                           user_id=USER_ID_CLAUDE,
                           session_id=SESSION_ID_CLAUDE)

    # --- OR ---

    # Uncomment the following lines if running as a standard Python script (.py file):
    # import asyncio
    # if __name__ == "__main__":
    #     try:
    #         asyncio.run(call_agent_async(query = "Weather in London please.",
    #                      runner=runner_claude,
    #                       user_id=USER_ID_CLAUDE,
    #                       session_id=SESSION_ID_CLAUDE)
    #     except Exception as e:
    #         print(f"An error occurred: {e}")


except Exception as e:
    print(f"❌ Could not create or run Claude agent '{MODEL_CLAUDE_SONNET}'. Check API Key and model name. Error: {e}")

请仔细观察两个代码块的输出结果。你应该会看到:

  1. 每个代理(agent)……weather_agent_gpt, weather_agent_claude如果 API 密钥有效,那么该资源将会被成功创建。
  2. 每个任务都会专门分配一个会话(session)和一个执行器(runner)来进行处理。
  3. 每个代理都正确地识别出了需要使用该工具(或服务)的必要性。 get_weather 在处理该查询时(您会看到……) --- Tool: get_weather called... --- (log)。
  4. The 底层工具逻辑(underlying tool logic) 该功能保持不变,始终会返回我们预先准备好的模拟数据(mock data)。
  5. 然而, 最终的文本响应 每个代理生成的文本在表达方式、语气或格式上可能会略有不同。这是因为指令提示是由不同的大型语言模型(GPT-4o 和 Claude Sonnet)来解释和执行的。

这一步展示了 ADK + LiteLLM 所提供的强大功能与灵活性:您可以轻松地使用各种大型语言模型(LLMs)来测试和部署代理程序(agents),同时确保您的核心应用程序逻辑(工具、代理程序的基本结构)保持一致。

在下一步中,我们将不再局限于使用单个代理(即单个处理任务的程序),而是组建一个小型团队,让团队中的成员能够互相委托任务。


步骤 3:组建代理团队——负责问候与告别环节的工作分配

在步骤 1 和步骤 2 中,我们构建并测试了一个专门用于查询天气信息的代理系统。虽然该系统在其特定任务上表现良好,但现实世界中的应用程序通常需要处理更多种类的用户交互。 (用于表示可能性或可能性较小)可能;也许 我们不断为这个单一的天气信息处理系统添加更多的工具和复杂的操作指令,但这很快就会导致系统变得难以管理且效率降低。

一种更为可靠的方法是构建一个……(此处应填写具体的解决方案或系统名称)。 代理团队(Agent Team)这包括以下内容:

  1. 创建多个…… 专业代理人每个组件都是为特定的功能而设计的(例如,一个用于获取天气信息,另一个用于生成问候语,还有一个用于执行计算)。
  2. “Designating a” 的意思是“指定某个事物”或“为某事物分配一个名称/角色”。例如: - “The committee decided to designate this project as a priority.”(委员会决定将这个项目列为优先事项。) - “We need to designate a representative to attend the meeting.”(我们需要指定一名代表参加会议。) 根代理(Root Agent) (或称为“协调器”)负责接收用户的初始请求。
  3. 启用根代理(root agent)以…… **delegate** 根据用户的意图,系统会向最合适的专门子代理发送请求。

为什么要组建一个代理团队(Agent Team)?

  • 模块化: 更易于开发、测试和维护各个代理程序(即那些执行特定任务的软件组件)。
  • 专业领域: 每个代理都可以根据其具体任务进行微调(例如调整指令或选择合适的模型)。
  • 可扩展性: 通过添加新的代理(agents),可以更轻松地实现新功能。
  • 效率: 允许使用可能更简单、成本更低的模型来处理简单的任务(例如发送问候信息)。

在这一步中,我们将:

  1. 开发用于处理问候语的简单工具。)say_hello)以及告别()say_goodbye).
  2. 创建两个新的专业子代理(sub-agents)。 greeting_agent 和 farewell_agent.
  3. 更新我们的主要天气数据提供者。)weather_agent_v2)来充当…… 根代理(Root Agent).
  4. 配置根代理(root agent)及其子代理(sub-agents),并启用相关功能。 自动委托(即任务或责任的自动转移).
  5. 通过向根代理(root agent)发送不同类型的请求来测试代理流程(delegation flow)的功能。

1. 为下属代理人(Sub-Agents)定义所需的工具(Tools)。

首先,让我们创建一些简单的 Python 函数,这些函数将作为我们新专业代理人员的工具。请记住,清晰的文档字符串(docstrings)对于使用这些函数的代理人员来说非常重要。

# @title Define Tools for Greeting and Farewell Agents
from typing import Optional # Make sure to import Optional

# Ensure 'get_weather' from Step 1 is available if running this step independently.
# def get_weather(city: str) -> dict: ... (from Step 1)

def say_hello(name: Optional[str] = None) -> str:
    """Provides a simple greeting. If a name is provided, it will be used.

    Args:
        name (str, optional): The name of the person to greet. Defaults to a generic greeting if not provided.

    Returns:
        str: A friendly greeting message.
    """
    if name:
        greeting = f"Hello, {name}!"
        print(f"--- Tool: say_hello called with name: {name} ---")
    else:
        greeting = "Hello there!" # Default greeting if name is None or not explicitly passed
        print(f"--- Tool: say_hello called without a specific name (name_arg_value: {name}) ---")
    return greeting

def say_goodbye() -> str:
    """Provides a simple farewell message to conclude the conversation."""
    print(f"--- Tool: say_goodbye called ---")
    return "Goodbye! Have a great day."

print("Greeting and Farewell tools defined.")

# Optional self-test
print(say_hello("Alice"))
print(say_hello()) # Test with no argument (should use default "Hello there!")
print(say_hello(name=None)) # Test with name explicitly as None (should use default "Hello there!")

2. 定义副代理人(负责问候和告别工作)

现在,创建…… Agent 这些实例是为我们的专家准备的;请注意他们的工作非常专注(即他们的任务非常明确、目标非常具体)。 instruction 而且,至关重要的是,他们的态度非常明确(即他们的立场或观点非常清晰)。 description. The description 这是主要信息吗? 根代理(Root Agent) 用于做出决策(或判断) 当……的时候 需要将这些任务委托给这些次级代理(sub-agents)来处理。

最佳实践: 子代理(Sub-agent) description 这些字段应该能够准确且简洁地描述它们的具体功能。这对于实现高效的自动化任务分配(即自动将任务分配给相应的处理者)至关重要。

最佳实践: 子代理(Sub-agent) instruction 这些字段应该根据其有限的功能范围进行定制,明确地告诉它们该执行什么操作。 (用于列举各种事物)各种各样的东西 待办事项(例如:“您的……”) 只有;仅仅 “任务是……”

# @title Define Greeting and Farewell Sub-Agents

# If you want to use models other than Gemini, Ensure LiteLlm is imported and API keys are set (from Step 0/2)
# from google.adk.models.lite_llm import LiteLlm
# MODEL_GPT_4O, MODEL_CLAUDE_SONNET etc. should be defined
# Or else, continue to use: model = MODEL_GEMINI_FLASH

# --- Greeting Agent ---
greeting_agent = None
try:
    greeting_agent = Agent(
        # Using a potentially different/cheaper model for a simple task
        model = MODEL_GEMINI_FLASH,
        # model=LiteLlm(model=MODEL_GPT_4O), # If you would like to experiment with other models
        name="greeting_agent",
        instruction="You are the Greeting Agent. Your ONLY task is to provide a friendly greeting to the user. "
                    "Use the 'say_hello' tool to generate the greeting. "
                    "If the user provides their name, make sure to pass it to the tool. "
                    "Do not engage in any other conversation or tasks.",
        description="Handles simple greetings and hellos using the 'say_hello' tool.", # Crucial for delegation
        tools=[say_hello],
    )
    print(f"✅ Agent '{greeting_agent.name}' created using model '{greeting_agent.model}'.")
except Exception as e:
    print(f"❌ Could not create Greeting agent. Check API Key ({greeting_agent.model}). Error: {e}")

# --- Farewell Agent ---
farewell_agent = None
try:
    farewell_agent = Agent(
        # Can use the same or a different model
        model = MODEL_GEMINI_FLASH,
        # model=LiteLlm(model=MODEL_GPT_4O), # If you would like to experiment with other models
        name="farewell_agent",
        instruction="You are the Farewell Agent. Your ONLY task is to provide a polite goodbye message. "
                    "Use the 'say_goodbye' tool when the user indicates they are leaving or ending the conversation "
                    "(e.g., using words like 'bye', 'goodbye', 'thanks bye', 'see you'). "
                    "Do not perform any other actions.",
        description="Handles simple farewells and goodbyes using the 'say_goodbye' tool.", # Crucial for delegation
        tools=[say_goodbye],
    )
    print(f"✅ Agent '{farewell_agent.name}' created using model '{farewell_agent.model}'.")
except Exception as e:
    print(f"❌ Could not create Farewell agent. Check API Key ({farewell_agent.model}). Error: {e}")

3. 定义根代理(Weather Agent v2)及其子代理。

现在,我们升级我们的……(请根据实际情况填写具体的产品名称或服务名称)。 weather_agent主要的变化包括:

  • 添加…… sub_agents 参数:我们传递一个包含相关数据的列表。 greeting_agent 和 farewell_agent 我们刚刚创建的实例。
  • 更新…… instruction我们明确地告诉了根代理(root agent)应该执行的具体操作。 关于 其下属代理机构以及…… 当……的时候 它应该把任务委托给他们。

关键概念:自动委托(Auto Flow) 通过提供…… sub_agents `list` 和 `ADK` 支持自动任务委托功能。当根代理(root agent)收到用户的查询时,其大型语言模型(LLM)不仅会参考自身的指令和工具,还会考虑其他相关信息。 description 每个子代理的能力。如果大型语言模型(LLM)判断某个查询更符合某个子代理所描述的能力(例如“能够处理简单的问候语”),它将自动生成一个特殊的内部指令,以便该子代理能够执行相应的任务。 “Transfer control” 的意思是“转移控制权”或“控制权的转移”。在计算机科学或系统架构中,这通常指的是将系统的控制权从当前的操作者或程序转移到另一个操作者或程序。例如,在多线程环境中,一个线程可能会将控制权传递给另一个线程;在操作系统层面,这可能表现为进程之间的切换。 将查询结果发送给该轮次中的子代理(sub-agent)。子代理随后会使用自己的模型、指令和工具来处理该查询。

最佳实践: 请确保根代理(root agent)的指令能够清晰地指导其授权(delegation)决策过程。需要按名称提及各个子代理(sub-agents),并明确说明在何种条件下应进行授权。

# @title Define the Root Agent with Sub-Agents

# Ensure sub-agents were created successfully before defining the root agent.
# Also ensure the original 'get_weather' tool is defined.
root_agent = None
runner_root = None # Initialize runner

if greeting_agent and farewell_agent and 'get_weather' in globals():
    # Let's use a capable Gemini model for the root agent to handle orchestration
    root_agent_model = MODEL_GEMINI_FLASH

    weather_agent_team = Agent(
        name="weather_agent_v2", # Give it a new version name
        model=root_agent_model,
        description="The main coordinator agent. Handles weather requests and delegates greetings/farewells to specialists.",
        instruction="You are the main Weather Agent coordinating a team. Your primary responsibility is to provide weather information. "
                    "Use the 'get_weather' tool ONLY for specific weather requests (e.g., 'weather in London'). "
                    "You have specialized sub-agents: "
                    "1. 'greeting_agent': Handles simple greetings like 'Hi', 'Hello'. Delegate to it for these. "
                    "2. 'farewell_agent': Handles simple farewells like 'Bye', 'See you'. Delegate to it for these. "
                    "Analyze the user's query. If it's a greeting, delegate to 'greeting_agent'. If it's a farewell, delegate to 'farewell_agent'. "
                    "If it's a weather request, handle it yourself using 'get_weather'. "
                    "For anything else, respond appropriately or state you cannot handle it.",
        tools=[get_weather], # Root agent still needs the weather tool for its core task
        # Key change: Link the sub-agents here!
        sub_agents=[greeting_agent, farewell_agent]
    )
    print(f"✅ Root Agent '{weather_agent_team.name}' created using model '{root_agent_model}' with sub-agents: {[sa.name for sa in weather_agent_team.sub_agents]}")

else:
    print("❌ Cannot create root agent because one or more sub-agents failed to initialize or 'get_weather' tool is missing.")
    if not greeting_agent: print(" - Greeting Agent is missing.")
    if not farewell_agent: print(" - Farewell Agent is missing.")
    if 'get_weather' not in globals(): print(" - get_weather function is missing.")

4. 与代理团队进行互动

既然我们已经定义了我们的根代理(root agent)……weather_agent_team - 注意:请确保此变量名称与上一个代码块中定义的名称一致。 # @title Define the Root Agent with Sub-Agents(这个产品/服务可能被赋予了某个名称……) root_agent)通过其专业的子代理机构,我们来测试一下这种委托机制(即如何将任务分配给子代理机构来执行)。

以下代码块将会:

  1. 定义一个…… async function run_team_conversation.
  2. 在这个函数内部,创建一个……(具体内容需要根据上下文来确定)。 新的、专用的(资源或设备) InMemorySessionService 以及一个特定的会话(session)session_001_agent_team)这只是为了这次测试运行而设置的。这样做可以将对话记录单独提取出来,以便测试团队成员之间的互动方式(即团队协作情况)。
  3. 创建一个…… Runner (runner_agent_team)已配置为使用我们的…… weather_agent_team (根代理)以及专用的会话服务。
  4. 请使用我们更新后的版本。 call_agent_async 这是一个用于发送不同类型查询(问候、天气信息请求、告别信息)的函数。 runner_agent_team我们明确地为这次特定的测试传递了运行器(runner)、用户 ID(user ID)和会话 ID(session ID)。
  5. 立即执行该命令。 run_team_conversation function.

我们预期流程如下:

  1. “Hello there!” 这个查询会被发送到…… runner_agent_team.
  2. 根代理(Root Agent)weather_agent_team)接收该信息,并根据其中的指示进行处理。 greeting_agent“根据描述,将任务委托给他人处理。”
  3. greeting_agent 处理查询,并调用相关函数(或方法)。 say_hello 该工具接收请求并生成相应的响应。
  4. “纽约的天气怎么样?”这个查询是…… 不;并非 这些任务被委托给根代理(root agent)处理,由根代理直接使用其相应的功能来完成这些操作。 get_weather tool.
  5. “谢谢,再见!”这个查询被委托给了…… farewell_agent该系统使用了其自身的功能/资源/方法等(具体内容需根据上下文确定)。 say_goodbye tool.
# @title Interact with the Agent Team
import asyncio # Ensure asyncio is imported

# Ensure the root agent (e.g., 'weather_agent_team' or 'root_agent' from the previous cell) is defined.
# Ensure the call_agent_async function is defined.

# Check if the root agent variable exists before defining the conversation function
root_agent_var_name = 'root_agent' # Default name from Step 3 guide
if 'weather_agent_team' in globals(): # Check if user used this name instead
    root_agent_var_name = 'weather_agent_team'
elif 'root_agent' not in globals():
    print("⚠️ Root agent ('root_agent' or 'weather_agent_team') not found. Cannot define run_team_conversation.")
    # Assign a dummy value to prevent NameError later if the code block runs anyway
    root_agent = None # Or set a flag to prevent execution

# Only define and run if the root agent exists
if root_agent_var_name in globals() and globals()[root_agent_var_name]:
    # Define the main async function for the conversation logic.
    # The 'await' keywords INSIDE this function are necessary for async operations.
    async def run_team_conversation():
        print("\n--- Testing Agent Team Delegation ---")
        session_service = InMemorySessionService()
        APP_NAME = "weather_tutorial_agent_team"
        USER_ID = "user_1_agent_team"
        SESSION_ID = "session_001_agent_team"
        session = await session_service.create_session(
            app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
        )
        print(f"Session created: App='{APP_NAME}', User='{USER_ID}', Session='{SESSION_ID}'")

        actual_root_agent = globals()[root_agent_var_name]
        runner_agent_team = Runner( # Or use InMemoryRunner
            agent=actual_root_agent,
            app_name=APP_NAME,
            session_service=session_service
        )
        print(f"Runner created for agent '{actual_root_agent.name}'.")

        # --- Interactions using await (correct within async def) ---
        await call_agent_async(query = "Hello there!",
                               runner=runner_agent_team,
                               user_id=USER_ID,
                               session_id=SESSION_ID)
        await call_agent_async(query = "What is the weather in New York?",
                               runner=runner_agent_team,
                               user_id=USER_ID,
                               session_id=SESSION_ID)
        await call_agent_async(query = "Thanks, bye!",
                               runner=runner_agent_team,
                               user_id=USER_ID,
                               session_id=SESSION_ID)

    # --- Execute the `run_team_conversation` async function ---
    # Choose ONE of the methods below based on your environment.
    # Note: This may require API keys for the models used!

    # METHOD 1: Direct await (Default for Notebooks/Async REPLs)
    # If your environment supports top-level await (like Colab/Jupyter notebooks),
    # it means an event loop is already running, so you can directly await the function.
    print("Attempting execution using 'await' (default for notebooks)...")
    await run_team_conversation()

    # METHOD 2: asyncio.run (For Standard Python Scripts [.py])
    # If running this code as a standard Python script from your terminal,
    # the script context is synchronous. `asyncio.run()` is needed to
    # create and manage an event loop to execute your async function.
    # To use this method:
    # 1. Comment out the `await run_team_conversation()` line above.
    # 2. Uncomment the following block:
    """
    import asyncio
    if __name__ == "__main__": # Ensures this runs only when script is executed directly
        print("Executing using 'asyncio.run()' (for standard Python scripts)...")
        try:
            # This creates an event loop, runs your async function, and closes the loop.
            asyncio.run(run_team_conversation())
        except Exception as e:
            print(f"An error occurred: {e}")
    """

else:
    # This message prints if the root agent variable wasn't found earlier
    print("\n⚠️ Skipping agent team conversation execution as the root agent was not successfully defined in a previous step.")

仔细查看输出日志,尤其是…… --- Tool: ... called --- `messages`。您应该注意以下几点:

  • 对于 “Hello there!”, say_hello 该工具被命名为……(表明了其名称或名称的来源)。 greeting_agent (我已经处理好了这个问题。)
  • 对于“纽约的天气怎么样?”这个问题, get_weather 该工具被称为 [具体名称](表示是由根代理(root agent)处理的)。
  • 对于 “Thanks, bye!”, say_goodbye 该工具被命名为……(表明了其名称或名称的来源)。 farewell_agent (我已经处理好了这个问题。)

这证实了操作已经成功完成。 自动委托(即任务或责任的自动转移)根代理(root agent)根据其接收到的指令进行操作…… description“s of its” 是一个英语短语,通常用于描述某物的一部分或特征。在这个短语中,“s” 可以代表“some”或“several”,而 “of its” 则表示“属于该事物的”。例如:“The book contains several interesting chapters (这本书包含几个有趣的章节)。” 这个短语强调的是某个整体中的某个部分或特征。 sub_agents系统能够正确地将用户请求路由到团队中相应的专业代理人员手中。

您现在已经使用多个协同工作的“代理”(agent)来构建您的应用程序了。这种模块化的设计是构建更复杂、功能更强大的代理系统的基础。在下一步中,我们将让这些代理能够通过“会话状态”(session state)在不同的执行轮次之间记住信息。

步骤 4:通过会话状态(Session State)添加内存功能及个性化设置

到目前为止,我们的客服团队可以通过任务分配来处理各种任务,但每次交互都是从零开始的(即客服人员不会记得之前的对话内容或用户的偏好)。为了提供更加复杂、且能够理解用户上下文的体验,客服人员确实需要具备这样的能力。 内存ADK 通过以下方式提供了这一功能: 会话状态(Session State).

什么是会话状态(Session State)?

  • 这是一个 Python 字典。session.state)与特定的用户会话相关联(该用户会话通过某种方式被识别出来)。 APP_NAME, USER_ID, SESSION_ID).
  • 它能够持续存储信息。 在多次对话过程中 在该会话期间(within that session)。
  • 代理(Agents)和工具(Tools)可以读取和写入该状态数据,从而能够记住相关细节、调整自身的行为方式,并提供个性化的响应。

代理如何与状态进行交互:

  1. ToolContext (主要方法): 这些工具可以接受某种输入或数据。 ToolContext 对象(ADK 会自动为任何带有注释的参数生成该对象) ToolContext无论该对象位于系统的哪个位置,它都可以直接访问会话状态(session state)。 tool_context.state这使得工具能够读取用户的偏好设置或保存处理结果。 在……期间;当……的时候 execution.
  2. output_key (自动保存代理响应): An Agent 可以对其进行配置(即:可以通过设置某些参数来调整其功能或行为)。 output_key="your_key"然后,ADK 会自动将代理在该轮次中的最终文本响应保存下来。 session.state["your_key"].

在这一步中,我们将通过以下方式来加强我们的“天气机器人”团队:

  1. 使用…… new InMemorySessionService 为了单独展示某个状态(即该状态在系统中的表现或行为)。
  2. 使用用户的偏好设置来初始化会话状态…… temperature_unit.
  3. 创建一个具有“状态感知”功能的天气工具版本……)get_weather_stateful)该程序会通过以下方式读取用户的偏好设置: ToolContext 并根据需要调整输出格式(摄氏度/华氏度)。
  4. 将根代理(root agent)更新为使用这个具有状态管理的工具(stateful tool),并对其进行相应的配置。 output_key 该系统会自动将其最终的天气报告保存到会话状态(session state)中。
  5. 通过进行对话来观察:初始状态如何影响该工具的功能;手动状态的变化又如何改变工具后续的行为;以及…… output_key 该系统会持续保留代理(agent)的响应内容。

1. 初始化新的会话服务(Session Service)及其相关状态(State)。

为了清楚地展示状态管理的过程(而不会受到之前步骤的干扰),我们将创建一个新的实例(instance)。 InMemorySessionService我们还将创建一个会话(session),该会话包含一个初始状态,用于定义用户偏好的温度单位。

# @title 1. Initialize New Session Service and State

# Import necessary session components
from google.adk.sessions import InMemorySessionService

# Create a NEW session service instance for this state demonstration
session_service_stateful = InMemorySessionService()
print("✅ New InMemorySessionService created for state demonstration.")

# Define a NEW session ID for this part of the tutorial
SESSION_ID_STATEFUL = "session_state_demo_001"
USER_ID_STATEFUL = "user_state_demo"

# Define initial state data - user prefers Celsius initially
initial_state = {
    "user_preference_temperature_unit": "Celsius"
}

# Create the session, providing the initial state
session_stateful = await session_service_stateful.create_session(
    app_name=APP_NAME, # Use the consistent app name
    user_id=USER_ID_STATEFUL,
    session_id=SESSION_ID_STATEFUL,
    state=initial_state # <<< Initialize state during creation
)
print(f"✅ Session '{SESSION_ID_STATEFUL}' created for user '{USER_ID_STATEFUL}'.")

# Verify the initial state was set correctly
retrieved_session = await session_service_stateful.get_session(app_name=APP_NAME,
                                                         user_id=USER_ID_STATEFUL,
                                                         session_id = SESSION_ID_STATEFUL)
print("\n--- Initial Session State ---")
if retrieved_session:
    print(retrieved_session.state)
else:
    print("Error: Could not retrieve session.")

2. 开发一个具有状态感知功能的天气预报工具get_weather_stateful)

现在,我们创建了一个新版本的天气工具。该工具的核心功能是能够接收用户输入的数据。 tool_context: ToolContext 这使其能够进行访问。 tool_context.state它将会读取该文件的内容。 user_preference_temperature_unit 并根据需要格式化温度值。

  • 关键概念: ToolContext 这个对象充当桥梁,使您的工具逻辑能够与会话的上下文进行交互(包括读取和写入状态变量)。ADK 会根据参数的名称来查找相应的参数。 ToolContext 该工具会自动为参数添加注释,并将其插入到函数签名中的任意位置;被添加了注释的参数也会被隐藏起来,不会被大型语言模型(LLM)所使用的数据库模式(schema)所识别。

  • 最佳实践: 在从状态中读取数据时,请使用(该方法/工具等)。 dictionary.get('key', default_value) 为了处理那些“键”可能还不存在的情况,从而确保你的工具不会崩溃。

from google.adk.tools.tool_context import ToolContext

def get_weather_stateful(city: str, tool_context: ToolContext) -> dict:
    """Retrieves weather, converts temp unit based on session state."""
    print(f"--- Tool: get_weather_stateful called for {city} ---")

    # --- Read preference from state ---
    preferred_unit = tool_context.state.get("user_preference_temperature_unit", "Celsius") # Default to Celsius
    print(f"--- Tool: Reading state 'user_preference_temperature_unit': {preferred_unit} ---")

    city_normalized = city.lower().replace(" ", "")

    # Mock weather data (always stored in Celsius internally)
    mock_weather_db = {
        "newyork": {"temp_c": 25, "condition": "sunny"},
        "london": {"temp_c": 15, "condition": "cloudy"},
        "tokyo": {"temp_c": 18, "condition": "light rain"},
    }

    if city_normalized in mock_weather_db:
        data = mock_weather_db[city_normalized]
        temp_c = data["temp_c"]
        condition = data["condition"]

        # Format temperature based on state preference
        if preferred_unit == "Fahrenheit":
            temp_value = (temp_c * 9/5) + 32 # Calculate Fahrenheit
            temp_unit = "°F"
        else: # Default to Celsius
            temp_value = temp_c
            temp_unit = "°C"

        report = f"The weather in {city.capitalize()} is {condition} with a temperature of {temp_value:.0f}{temp_unit}."
        result = {"status": "success", "report": report}
        print(f"--- Tool: Generated report in {preferred_unit}. Result: {result} ---")

        # Example of writing back to state (optional for this tool)
        tool_context.state["last_city_checked_stateful"] = city
        print(f"--- Tool: Updated state 'last_city_checked_stateful': {city} ---")

        return result
    else:
        # Handle city not found
        error_msg = f"Sorry, I don't have weather information for '{city}'."
        print(f"--- Tool: City '{city}' not found. ---")
        return {"status": "error", "error_message": error_msg}

print("✅ State-aware 'get_weather_stateful' tool defined.")

3. 重新定义子代理(Sub-Agents)并更新根代理(Root Agent)

为了确保这一步骤是独立完整的,并且能够正确地完成(即不会受到其他步骤的影响),我们首先需要重新定义相关的内容。 greeting_agent 和 farewell_agent 完全按照第 3 步中的设置来操作。接下来,我们定义新的根代理(root agent)。weather_agent_v4_stateful):

  • 它使用了新的功能/技术。 get_weather_stateful tool.
  • 其中包含了用于代表团成员之间的问候语和告别语的相关内容。
  • 至关重要的是……它设置了(某些内容)。 output_key="last_weather_report" 该系统会自动将其最终的天气信息保存到会话状态(session state)中。
# @title 3. Redefine Sub-Agents and Update Root Agent with output_key

# Ensure necessary imports: Agent, LiteLlm, Runner
from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm
from google.adk.runners import Runner
# Ensure tools 'say_hello', 'say_goodbye' are defined (from Step 3)
# Ensure model constants MODEL_GPT_4O, MODEL_GEMINI_FLASH etc. are defined

# --- Redefine Greeting Agent (from Step 3) ---
greeting_agent = None
try:
    greeting_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="greeting_agent",
        instruction="You are the Greeting Agent. Your ONLY task is to provide a friendly greeting using the 'say_hello' tool. Do nothing else.",
        description="Handles simple greetings and hellos using the 'say_hello' tool.",
        tools=[say_hello],
    )
    print(f"✅ Agent '{greeting_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Greeting agent. Error: {e}")

# --- Redefine Farewell Agent (from Step 3) ---
farewell_agent = None
try:
    farewell_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="farewell_agent",
        instruction="You are the Farewell Agent. Your ONLY task is to provide a polite goodbye message using the 'say_goodbye' tool. Do not perform any other actions.",
        description="Handles simple farewells and goodbyes using the 'say_goodbye' tool.",
        tools=[say_goodbye],
    )
    print(f"✅ Agent '{farewell_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Farewell agent. Error: {e}")

# --- Define the Updated Root Agent ---
root_agent_stateful = None
runner_root_stateful = None # Initialize runner

# Check prerequisites before creating the root agent
if greeting_agent and farewell_agent and 'get_weather_stateful' in globals():

    root_agent_model = MODEL_GEMINI_FLASH # Choose orchestration model

    root_agent_stateful = Agent(
        name="weather_agent_v4_stateful", # New version name
        model=root_agent_model,
        description="Main agent: Provides weather (state-aware unit), delegates greetings/farewells, saves report to state.",
        instruction="You are the main Weather Agent. Your job is to provide weather using 'get_weather_stateful'. "
                    "The tool will format the temperature based on user preference stored in state. "
                    "Delegate simple greetings to 'greeting_agent' and farewells to 'farewell_agent'. "
                    "Handle only weather requests, greetings, and farewells.",
        tools=[get_weather_stateful], # Use the state-aware tool
        sub_agents=[greeting_agent, farewell_agent], # Include sub-agents
        output_key="last_weather_report" # <<< Auto-save agent's final weather response
    )
    print(f"✅ Root Agent '{root_agent_stateful.name}' created using stateful tool and output_key.")

    # --- Create Runner for this Root Agent & NEW Session Service ---
    runner_root_stateful = Runner(
        agent=root_agent_stateful,
        app_name=APP_NAME,
        session_service=session_service_stateful # Use the NEW stateful session service
    )
    print(f"✅ Runner created for stateful root agent '{runner_root_stateful.agent.name}' using stateful session service.")

else:
    print("❌ Cannot create stateful root agent. Prerequisites missing.")
    if not greeting_agent: print(" - greeting_agent definition missing.")
    if not farewell_agent: print(" - farewell_agent definition missing.")
    if 'get_weather_stateful' not in globals(): print(" - get_weather_stateful tool missing.")

4. 交互并测试状态流程(Interact and Test State Flow)

现在,让我们执行一段对话,该对话旨在测试使用相关功能(或系统)进行状态交互(state interactions)的情况。 runner_root_stateful (与我们具有状态存储功能的代理相关联的……) session_service_stateful我们将使用…… call_agent_async 这个函数是在之前定义的,它的作用是确保我们传递正确的运行器(runner)和用户 ID(user ID)。USER_ID_STATEFUL),以及会话 ID(session ID)。SESSION_ID_STATEFUL).

对话流程如下:

  1. 查询伦敦的天气信息: The get_weather_stateful 该工具应从第1节中初始化的会话状态中读取用户最初选择的温度单位(“摄氏度”)。根代理的最终响应(即以摄氏度表示的天气报告)应被保存到相应的存储位置。 state['last_weather_report'] 通过……的方式 output_key configuration.
  2. 手动更新状态: 我们将…… 直接修改 存储在该对象(或结构)内部的状态信息。 InMemorySessionService `instance`(实例)session_service_stateful).
    • 为什么非要直接修改呢? The session_service.get_session() 该方法返回一个值(或结果)。 复制 该副本属于会话(session)的一部分。修改该副本不会影响后续代理(agent)运行时所使用的数据状态。在这种测试场景中…… InMemorySessionService通过这些方法,我们可以访问系统的内部功能/数据。 sessions 用于进行更改的字典 实际的;真实的 存储的状态值(用于……) user_preference_temperature_unit 将温度单位转换为“华氏度”。 注意:在实际应用中,状态的变更通常是由工具或代理逻辑的返回所触发的。 EventActions(state_delta=...)这些更新不是通过直接的手动操作来完成的。
  3. 再次查询纽约的天气情况: The get_weather_stateful 该工具现在应该从系统中读取更新后的“华氏温度”偏好设置,并据此转换相应的温度值。 new `response`(以华氏度表示的天气信息)将会覆盖之前的值。 state['last_weather_report'] 由于…… output_key.
  4. 向客服代表问好: 请确认以下事项: 1. **授权与委托**:确保相关权限已正确授予相关人员或团队; 2. **责任划分**:明确各方在项目中的职责与权限; 3. **沟通机制**:建立有效的沟通渠道,确保信息及时、准确地传递; 4. **监督与控制**:实施必要的监督机制,确保各项工作的顺利进行; 5. **风险管理**:识别潜在的风险因素,并制定相应的应对措施。 请注意,具体需要验证的内容可能因项目类型和具体情况而有所不同。请根据实际情况填写相应的信息。 greeting_agent 该功能仍然能够与那些需要维护状态(即“有状态”)的操作正确地一起使用(即同时运行而不会出现问题)。
  5. 检查最终状态: 对话结束后,我们最后一次检索该会话(获取其副本),并将其状态打印出来以确认相关信息。 user_preference_temperature_unit 确实使用的是“华氏度”(Fahrenheit);请注意最后保存下来的数值。 output_key (这将是本次运行中的上一个天气报告),然后查看…… last_city_checked_stateful 该值由工具生成(即:value written by the tool)。
# @title 4. Interact to Test State Flow and output_key
import asyncio # Ensure asyncio is imported

# Ensure the stateful runner (runner_root_stateful) is available from the previous cell
# Ensure call_agent_async, USER_ID_STATEFUL, SESSION_ID_STATEFUL, APP_NAME are defined

if 'runner_root_stateful' in globals() and runner_root_stateful:
    # Define the main async function for the stateful conversation logic.
    # The 'await' keywords INSIDE this function are necessary for async operations.
    async def run_stateful_conversation():
        print("\n--- Testing State: Temp Unit Conversion & output_key ---")

        # 1. Check weather (Uses initial state: Celsius)
        print("--- Turn 1: Requesting weather in London (expect Celsius) ---")
        await call_agent_async(query= "What's the weather in London?",
                               runner=runner_root_stateful,
                               user_id=USER_ID_STATEFUL,
                               session_id=SESSION_ID_STATEFUL
                              )

        # 2. Manually update state preference to Fahrenheit - DIRECTLY MODIFY STORAGE
        print("\n--- Manually Updating State: Setting unit to Fahrenheit ---")
        try:
            # Access the internal storage directly - THIS IS SPECIFIC TO InMemorySessionService for testing
            # NOTE: In production with persistent services (Database, VertexAI), you would
            # typically update state via agent actions or specific service APIs if available,
            # not by direct manipulation of internal storage.
            stored_session = session_service_stateful.sessions[APP_NAME][USER_ID_STATEFUL][SESSION_ID_STATEFUL]
            stored_session.state["user_preference_temperature_unit"] = "Fahrenheit"
            # Optional: You might want to update the timestamp as well if any logic depends on it
            # import time
            # stored_session.last_update_time = time.time()
            print(f"--- Stored session state updated. Current 'user_preference_temperature_unit': {stored_session.state.get('user_preference_temperature_unit', 'Not Set')} ---") # Added .get for safety
        except KeyError:
            print(f"--- Error: Could not retrieve session '{SESSION_ID_STATEFUL}' from internal storage for user '{USER_ID_STATEFUL}' in app '{APP_NAME}' to update state. Check IDs and if session was created. ---")
        except Exception as e:
             print(f"--- Error updating internal session state: {e} ---")

        # 3. Check weather again (Tool should now use Fahrenheit)
        # This will also update 'last_weather_report' via output_key
        print("\n--- Turn 2: Requesting weather in New York (expect Fahrenheit) ---")
        await call_agent_async(query= "Tell me the weather in New York.",
                               runner=runner_root_stateful,
                               user_id=USER_ID_STATEFUL,
                               session_id=SESSION_ID_STATEFUL
                              )

        # 4. Test basic delegation (should still work)
        # The greeting is authored by the delegated sub-agent, not the root agent,
        # so output_key does NOT fire: 'last_weather_report' keeps the NY report.
        print("\n--- Turn 3: Sending a greeting ---")
        await call_agent_async(query= "Hi!",
                               runner=runner_root_stateful,
                               user_id=USER_ID_STATEFUL,
                               session_id=SESSION_ID_STATEFUL
                              )

    # --- Execute the `run_stateful_conversation` async function ---
    # Choose ONE of the methods below based on your environment.

    # METHOD 1: Direct await (Default for Notebooks/Async REPLs)
    # If your environment supports top-level await (like Colab/Jupyter notebooks),
    # it means an event loop is already running, so you can directly await the function.
    print("Attempting execution using 'await' (default for notebooks)...")
    await run_stateful_conversation()

    # METHOD 2: asyncio.run (For Standard Python Scripts [.py])
    # If running this code as a standard Python script from your terminal,
    # the script context is synchronous. `asyncio.run()` is needed to
    # create and manage an event loop to execute your async function.
    # To use this method:
    # 1. Comment out the `await run_stateful_conversation()` line above.
    # 2. Uncomment the following block:
    """
    import asyncio
    if __name__ == "__main__": # Ensures this runs only when script is executed directly
        print("Executing using 'asyncio.run()' (for standard Python scripts)...")
        try:
            # This creates an event loop, runs your async function, and closes the loop.
            asyncio.run(run_stateful_conversation())
        except Exception as e:
            print(f"An error occurred: {e}")
    """

    # --- Inspect final session state after the conversation ---
    # This block runs after either execution method completes.
    print("\n--- Inspecting Final Session State ---")
    final_session = await session_service_stateful.get_session(app_name=APP_NAME,
                                                         user_id= USER_ID_STATEFUL,
                                                         session_id=SESSION_ID_STATEFUL)
    if final_session:
        # Use .get() for safer access to potentially missing keys
        print(f"Final Preference: {final_session.state.get('user_preference_temperature_unit', 'Not Set')}")
        print(f"Final Last Weather Report (from output_key): {final_session.state.get('last_weather_report', 'Not Set')}")
        print(f"Final Last City Checked (by tool): {final_session.state.get('last_city_checked_stateful', 'Not Set')}")
        # Print full state for detailed view
        # print(f"Full State Dict: {final_session.state}") # For detailed view
    else:
        print("\n❌ Error: Could not retrieve final session state.")

else:
    print("\n⚠️ Skipping state test conversation. Stateful root agent runner ('runner_root_stateful') is not available.")

通过查看对话流程以及最终会话状态的输出结果,您可以确认:

  • 状态读取(State Read): 这个天气工具……)get_weather_stateful)能够被正确地读取。 user_preference_temperature_unit 从该状态开始,伦敦的温度最初被设置为“摄氏度”(Celsius)。
  • 状态更新: 直接修改成功地将存储的偏好设置更改为“华氏度”(Fahrenheit)。
  • 状态读取(已更新): 当用户询问纽约的天气时,该工具会显示“华氏度”(Fahrenheit),并自动完成温度单位的转换。
  • 工具状态写入(Tool State Write): 该工具成功完成了写入操作。 last_city_checked_stateful 在第二次天气检查之后,将 “New York” 通过相应的途径添加到该州的列表中。 tool_context.state.
  • **Delegation:** (注:根据语境,“Delegation”可以译为“授权”或“委托”。如果是指“代表团”的意思,也可以保留原词。) 前往……的代表团 greeting_agent 即使在状态发生变化之后,`for "Hi!"` 仍然能够正常执行(即:该代码仍然能够按照预期运行)。
  • output_key: The output_key="last_weather_report" 已成功保存根代理的配置信息。 final (用于表示“……的响应”) 每轮(游戏中) 在这个过程中,最终发出响应的是根代理(root agent)。然而,最后的问候语(“Hello, there!”)实际上是由被委托的子代理(delegated sub-agent)生成的,而不是根代理。 output_key 在最后一轮中,该事件并未被触发,因此之前的天气报告仍然保留在会话状态中(即未被修改)。
  • 最终状态(Final State): 最终确认显示,用户选择的温度单位仍然是“华氏度”(Fahrenheit)。

您现在已经成功地将会话状态(session state)集成到了系统中,从而能够根据用户的需求来个性化代理(agent)的行为。 ToolContext为测试目的而手动设置的状态 InMemorySessionService……并观察了其变化过程。 output_key 提供了一种简单的机制,用于保存代理程序对系统状态的最新响应。这种关于状态管理的基本理解非常重要,因为在我们接下来的步骤中,将使用回调函数来实现安全防护机制(即防止错误或不当行为的措施)。


步骤 5:增加安全性——安装输入防护栏 before_model_callback

我们的代理团队正变得越来越有能力:他们能够记住用户的偏好,并能有效地使用各种工具。然而,在现实世界的场景中,我们通常还需要一些安全机制来控制代理的行为。 在……之前 那些可能存在问题的请求甚至会直接传递到大型语言模型(LLM)的核心处理部分。

ADK 提供了…… 回调函数(Callbacks) – 这些函数允许你连接到代理执行生命周期中的特定阶段。 before_model_callback 对于确保输入数据的安全性来说,这种方法尤其有用。

“What is” 是一个常见的英语疑问句,用于询问某事物的名称、性质或功能。例如:“What is this book?”(这本书叫什么?) before_model_callback?

  • 这是一个由你定义的 Python 函数,ADK 会执行该函数。 就在……之前 代理将其编译后的请求(包括对话记录、指令以及用户的最新消息)发送给底层的大型语言模型(LLM)。
  • 用途: 根据预定义的规则,检查请求内容;如有必要,对其进行修改;或者直接将其屏蔽(即完全阻止该请求的继续处理)。

常见使用场景:

  • 输入验证/过滤: 检查用户输入是否满足相关要求,或是否包含被禁止的内容(例如个人身份信息(PII)或敏感关键词)。
  • “护栏”(Guardrails): 防止有害的、与主题无关的或违反政策的请求被大型语言模型(LLM)处理。
  • 动态提示语修改功能: 在发送请求之前,及时将相关信息(例如来自会话状态的信息)添加到大型语言模型(LLM)的请求上下文中。

工作原理:

  1. 定义一个函数,该函数接受一个参数…… callback_context: CallbackContext 和 llm_request: LlmRequest.

    • callback_context:提供对代理信息(agent info)和会话状态(session state)的访问权限。callback_context.state),等等。
    • llm_request:包含发送给大型语言模型(LLM)的所有数据内容。contents, config).
  2. 在函数内部:

    • 检查(Inspect): 检查;审查 llm_request.contents (尤其是最后一条用户留言。)
    • **修改功能(请谨慎使用):** 你 可以;能够 更改……的某些部分 llm_request.
    • “Block (Guardrail)”: 返回一个…… LlmResponse `object.AdK` 会立即将此响应发送回来。 skipping 轮到大型语言模型(LLM)进行操作/响应了。
    • 允许: 返回 NoneADK随后会使用这个(可能已被修改的)请求来调用大型语言模型(LLM)。

在这一步中,我们将:

  1. 定义一个…… before_model_callback function (block_keyword_guardrail该功能会检查用户输入的内容中是否包含某个特定的关键词(“BLOCK”)。
  2. 更新我们的状态管理型根代理(stateful root agent)。weather_agent_v4_stateful 从第 4 步开始,您需要使用这个回调函数(callback)。
  3. 创建一个新的运行器(runner),该运行器与这个已更新的代理(agent)关联,但使用的是……(具体使用的资源或配置信息未在原文本中提供)。 相同的状态保持型会话服务(same stateful session service) 为了保持状态的连续性(即确保系统在各种操作或故障后仍能正确地继续运行)。
  4. 通过发送普通请求以及包含关键词的请求来测试该防护机制(即“护栏”系统)的功能。

1. 定义护栏回调函数(Guardrail Callback Function)

该函数将检查系统中的最后一条用户消息。 llm_request `content`。如果其中包含字符串 “BLOCK”(不区分大小写),则会生成相应的内容并返回该内容。 LlmResponse 用于阻止数据流的传输;否则,程序会继续执行并返回结果。 None.

# @title 1. Define the before_model_callback Guardrail

# Ensure necessary imports are available
from google.adk.agents.callback_context import CallbackContext
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types # For creating response content
from typing import Optional

def block_keyword_guardrail(
    callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
    """
    Inspects the latest user message for 'BLOCK'. If found, blocks the LLM call
    and returns a predefined LlmResponse. Otherwise, returns None to proceed.
    """
    agent_name = callback_context.agent_name # Get the name of the agent whose model call is being intercepted
    print(f"--- Callback: block_keyword_guardrail running for agent: {agent_name} ---")

    # Extract the text from the latest user message in the request history
    last_user_message_text = ""
    if llm_request.contents:
        # Find the most recent message with role 'user'
        for content in reversed(llm_request.contents):
            if content.role == 'user' and content.parts:
                # Assuming text is in the first part for simplicity
                if content.parts[0].text:
                    last_user_message_text = content.parts[0].text
                    break # Found the last user message text

    print(f"--- Callback: Inspecting last user message: '{last_user_message_text[:100]}...' ---") # Log first 100 chars

    # --- Guardrail Logic ---
    keyword_to_block = "BLOCK"
    if keyword_to_block in last_user_message_text.upper(): # Case-insensitive check
        print(f"--- Callback: Found '{keyword_to_block}'. Blocking LLM call! ---")
        # Optionally, set a flag in state to record the block event
        callback_context.state["guardrail_block_keyword_triggered"] = True
        print(f"--- Callback: Set state 'guardrail_block_keyword_triggered': True ---")

        # Construct and return an LlmResponse to stop the flow and send this back instead
        return LlmResponse(
            content=types.Content(
                role="model", # Mimic a response from the agent's perspective
                parts=[types.Part(text=f"I cannot process this request because it contains the blocked keyword '{keyword_to_block}'.")],
            )
            # Note: You could also set an error_message field here if needed
        )
    else:
        # Keyword not found, allow the request to proceed to the LLM
        print(f"--- Callback: Keyword not found. Allowing LLM call for {agent_name}. ---")
        return None # Returning None signals ADK to continue normally

print("✅ block_keyword_guardrail function defined.")

2. 更新根代理(Root Agent),使其能够使用回调功能(Callback)。

我们重新定义了“root agent”(即系统的核心代理组件),并为其添加了新的功能/属性。 before_model_callback 我们将这个参数传递给我们的新函数(即“guardrail function”),并为其指定一个新的版本名称,以便更清晰地表示其功能。

重要提示: 我们需要重新定义这些次级代理(sub-agents)。greeting_agent, farewell_agent)以及那些需要维护状态(即“有状态”)的工具(stateful tools)。get_weather_stateful如果这些组件在之前的步骤中尚未被获取到,那么需要在本步骤中再次获取它们,以确保根代理(root agent)的定义能够访问其所有组件。

# @title 2. Update Root Agent with before_model_callback


# --- Redefine Sub-Agents (Ensures they exist in this context) ---
greeting_agent = None
try:
    # Use a defined model constant
    greeting_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="greeting_agent", # Keep original name for consistency
        instruction="You are the Greeting Agent. Your ONLY task is to provide a friendly greeting using the 'say_hello' tool. Do nothing else.",
        description="Handles simple greetings and hellos using the 'say_hello' tool.",
        tools=[say_hello],
    )
    print(f"✅ Sub-Agent '{greeting_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Greeting agent. Check Model/API Key ({greeting_agent.model}). Error: {e}")

farewell_agent = None
try:
    # Use a defined model constant
    farewell_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="farewell_agent", # Keep original name
        instruction="You are the Farewell Agent. Your ONLY task is to provide a polite goodbye message using the 'say_goodbye' tool. Do not perform any other actions.",
        description="Handles simple farewells and goodbyes using the 'say_goodbye' tool.",
        tools=[say_goodbye],
    )
    print(f"✅ Sub-Agent '{farewell_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Farewell agent. Check Model/API Key ({farewell_agent.model}). Error: {e}")


# --- Define the Root Agent with the Callback ---
root_agent_model_guardrail = None
runner_root_model_guardrail = None

# Check all components before proceeding
if greeting_agent and farewell_agent and 'get_weather_stateful' in globals() and 'block_keyword_guardrail' in globals():

    # Use a defined model constant
    root_agent_model = MODEL_GEMINI_FLASH

    root_agent_model_guardrail = Agent(
        name="weather_agent_v5_model_guardrail", # New version name for clarity
        model=root_agent_model,
        description="Main agent: Handles weather, delegates greetings/farewells, includes input keyword guardrail.",
        instruction="You are the main Weather Agent. Provide weather using 'get_weather_stateful'. "
                    "Delegate simple greetings to 'greeting_agent' and farewells to 'farewell_agent'. "
                    "Handle only weather requests, greetings, and farewells.",
        tools=[get_weather_stateful],
        sub_agents=[greeting_agent, farewell_agent], # Reference the redefined sub-agents
        output_key="last_weather_report", # Keep output_key from Step 4
        before_model_callback=block_keyword_guardrail # <<< Assign the guardrail callback
    )
    print(f"✅ Root Agent '{root_agent_model_guardrail.name}' created with before_model_callback.")

    # --- Create Runner for this Agent, Using SAME Stateful Session Service ---
    # Ensure session_service_stateful exists from Step 4
    if 'session_service_stateful' in globals():
        runner_root_model_guardrail = Runner(
            agent=root_agent_model_guardrail,
            app_name=APP_NAME, # Use consistent APP_NAME
            session_service=session_service_stateful # <<< Use the service from Step 4
        )
        print(f"✅ Runner created for guardrail agent '{runner_root_model_guardrail.agent.name}', using stateful session service.")
    else:
        print("❌ Cannot create runner. 'session_service_stateful' from Step 4 is missing.")

else:
    print("❌ Cannot create root agent with model guardrail. One or more prerequisites are missing or failed initialization:")
    if not greeting_agent: print("   - Greeting Agent")
    if not farewell_agent: print("   - Farewell Agent")
    if 'get_weather_stateful' not in globals(): print("   - 'get_weather_stateful' tool")
    if 'block_keyword_guardrail' not in globals(): print("   - 'block_keyword_guardrail' callback")

3. 通过互动来测试该“护栏”(即该系统或机制)的功能。

让我们来测试护栏的功能表现吧。我们将使用……(此处应填写具体的测试方法或工具)。 同一会话(same session) (SESSION_ID_STATEFUL)如步骤 4 所示,以证明该状态在这些变化之后仍然保持不变。

  1. 发送一个普通的天气查询请求(该请求应该能够通过系统的审核并成功执行)。
  2. 发送一个包含 “BLOCK” 字样的请求(该请求应被回调函数拦截)。
  3. 发送一条问候信息(该信息需要通过根代理(root agent)的审核机制,随后被转发给相应的处理节点,并最终正常执行)。
# @title 3. Interact to Test the Model Input Guardrail
import asyncio # Ensure asyncio is imported

# Ensure the runner for the guardrail agent is available
if 'runner_root_model_guardrail' in globals() and runner_root_model_guardrail:
    # Define the main async function for the guardrail test conversation.
    # The 'await' keywords INSIDE this function are necessary for async operations.
    async def run_guardrail_test_conversation():
        print("\n--- Testing Model Input Guardrail ---")

        # Use the runner for the agent with the callback and the existing stateful session ID
        # Define a helper lambda for cleaner interaction calls
        interaction_func = lambda query: call_agent_async(query,
                                                         runner_root_model_guardrail,
                                                         USER_ID_STATEFUL, # Use existing user ID
                                                         SESSION_ID_STATEFUL # Use existing session ID
                                                        )
        # 1. Normal request (Callback allows, should use Fahrenheit from previous state change)
        print("--- Turn 1: Requesting weather in London (expect allowed, Fahrenheit) ---")
        await interaction_func("What is the weather in London?")

        # 2. Request containing the blocked keyword (Callback intercepts)
        print("\n--- Turn 2: Requesting with blocked keyword (expect blocked) ---")
        await interaction_func("BLOCK the request for weather in Tokyo") # Callback should catch "BLOCK"

        # 3. Normal greeting (Callback allows root agent, delegation happens)
        print("\n--- Turn 3: Sending a greeting (expect allowed) ---")
        await interaction_func("Hello again")

    # --- Execute the `run_guardrail_test_conversation` async function ---
    # Choose ONE of the methods below based on your environment.

    # METHOD 1: Direct await (Default for Notebooks/Async REPLs)
    # If your environment supports top-level await (like Colab/Jupyter notebooks),
    # it means an event loop is already running, so you can directly await the function.
    print("Attempting execution using 'await' (default for notebooks)...")
    await run_guardrail_test_conversation()

    # METHOD 2: asyncio.run (For Standard Python Scripts [.py])
    # If running this code as a standard Python script from your terminal,
    # the script context is synchronous. `asyncio.run()` is needed to
    # create and manage an event loop to execute your async function.
    # To use this method:
    # 1. Comment out the `await run_guardrail_test_conversation()` line above.
    # 2. Uncomment the following block:
    """
    import asyncio
    if __name__ == "__main__": # Ensures this runs only when script is executed directly
        print("Executing using 'asyncio.run()' (for standard Python scripts)...")
        try:
            # This creates an event loop, runs your async function, and closes the loop.
            asyncio.run(run_guardrail_test_conversation())
        except Exception as e:
            print(f"An error occurred: {e}")
    """

    # --- Inspect final session state after the conversation ---
    # This block runs after either execution method completes.
    # Optional: Check state for the trigger flag set by the callback
    print("\n--- Inspecting Final Session State (After Guardrail Test) ---")
    # Use the session service instance associated with this stateful session
    final_session = await session_service_stateful.get_session(app_name=APP_NAME,
                                                         user_id=USER_ID_STATEFUL,
                                                         session_id=SESSION_ID_STATEFUL)
    if final_session:
        # Use .get() for safer access
        print(f"Guardrail Triggered Flag: {final_session.state.get('guardrail_block_keyword_triggered', 'Not Set (or False)')}")
        print(f"Last Weather Report: {final_session.state.get('last_weather_report', 'Not Set')}") # Should be London weather if successful
        print(f"Temperature Unit: {final_session.state.get('user_preference_temperature_unit', 'Not Set')}") # Should be Fahrenheit
        # print(f"Full State Dict: {final_session.state}") # For detailed view
    else:
        print("\n❌ Error: Could not retrieve final session state.")

else:
    print("\n⚠️ Skipping model guardrail test. Runner ('runner_root_model_guardrail') is not available.")

请观察执行流程:

  1. 伦敦天气: 回调函数会在以下情况下被执行: weather_agent_v5_model_guardrail检查该消息后,系统会输出 “未找到关键词。允许调用大型语言模型(LLM)” 的提示信息,然后返回结果。 None代理继续执行任务,然后拨打了电话。 get_weather_stateful 该工具会根据用户在第 4 步中选择的“华氏度”(Fahrenheit)温度单位来显示天气信息,并返回相应的天气数据。此响应内容会定期更新(即:每次用户访问该工具时,都会显示最新的天气信息)。 last_weather_report 通过;经由 output_key.
  2. **BLOCK Request:** 回调函数会再次被执行。 weather_agent_v5_model_guardrail该程序会检查消息内容,如果发现其中包含“BLOCK”字样,就会输出“Blocking LLM call!”(正在阻止 LLM(Large Language Model)的调用!),同时设置相应的状态标志,最后返回预先定义好的结果。 LlmResponse该代理所使用的底层大型语言模型(LLM)是…… 从未被调用过。 在这个回合中,用户会看到回调函数产生的阻塞信息(即该函数正在等待其他操作完成)。
  3. 《Hello Again:》 回调函数会在以下情况下被执行: weather_agent_v5_model_guardrail这允许请求被处理。随后,根代理(root agent)会将任务委托给其他相关组件或代理进行处理。 greeting_agent. 注意: before_model_callback 在根代理(root agent)上定义的配置或规则,并不会自动应用于子代理(sub-agents)。 The greeting_agent 程序正常运行,调用了它的……(此处“its”指代前文提到的某个函数或方法)。 say_hello 该工具接收用户的输入(例如问候语),并返回相应的问候信息。

您已经成功实现了输入安全防护机制! before_model_callback 提供了一种强大的机制,用于执行规则并控制代理的行为。 在……之前 会进行一些成本高昂或存在潜在风险的 Large Language Model(LLM)调用。接下来,我们将采用类似的方法来为工具的使用过程设置一些限制措施(即“护栏”,以防止不当使用)。

步骤 6:添加安全防护机制——即对工具参数的使用进行限制或监控。before_tool_callback)

在第 5 步中,我们添加了一项安全机制(即“护栏”),用于检查用户输入的内容,并在必要时阻止用户输入某些非法或危险的数据。 在……之前 它已经达到了大型语言模型(LLM)的水平。现在,我们将添加另一层控制机制。 之后;随后 大型语言模型(LLM)决定使用某个工具来完成任务。 在……之前 那个工具实际上会执行相应的操作。这对于验证其功能非常有用。 参数(arguments) 大型语言模型(LLM)希望将这些数据传递给相应的工具进行处理。

ADK 提供了…… before_tool_callback 正是为了这个特定的目的。

“What is” 是一个常见的英语疑问句,用于询问某事物的名称、性质或功能。例如:“What is this book?”(这本书叫什么?) before_tool_callback?

  • 这是一个 Python 函数,仅在需要时被执行。 在……之前 在大型语言模型(LLM)请求使用某个工具功能并确定相关参数后,该工具功能才会被执行。
  • 用途: 验证工具参数;根据特定的输入条件阻止工具的执行;动态修改参数;或强制执行资源使用政策。

常见使用场景:

  • 参数验证(Argument Validation): 检查大型语言模型(LLM)提供的参数是否有效、是否在允许的范围内,以及是否符合预期的格式。
  • 资源保护: 防止工具被使用那些可能会产生高昂成本、导致数据访问受限或引发不良副作用的输入参数来调用(例如,阻止针对某些参数的 API 调用)。
  • 动态参数修改: 在工具运行之前,根据会话状态或其他上下文信息来调整参数。

工作原理:

  1. 定义一个函数,该函数接受一个参数…… tool: BaseTool, args: Dict[str, Any],以及 tool_context: ToolContext.

    • tool:即将被调用的工具对象(inspect) tool.name).
    • args:LLM 为该工具生成的参数字典。
    • tool_context:提供对会话状态(session state)的访问权限。tool_context.state),代理信息(agent info)等。
  2. 在函数内部:

    • 检查(Inspect): 检查…… tool.name 以及 args dictionary.
    • 修改(Modify): 更改其中的值。 args 字典 直接地如果您返回…… None使用这些修改后的参数,该工具就可以正常运行了。
    • 阻止/覆盖(安全防护机制): 返回一个 字典ADK 将这个字典视为…… result 与工具调用的相关内容(即工具调用的所有细节)都被完全记录下来了。 skipping 原始工具功能的执行结果。该字典应理想地符合被该工具拦截的程序所期望的返回格式。
    • 允许: 返回 NoneADK 会使用这些参数(这些参数可能已经被修改过)来执行实际的工具功能。

在这一步中,我们将:

  1. 定义一个…… before_tool_callback function (block_paris_tool_guardrail)该功能专门用于检查是否…… get_weather_stateful 该工具被调用时,使用的城市名称为“Paris”。
  2. 如果检测到 “Paris”,回调函数将阻止该工具的运行,并返回一个自定义的错误字典。
  3. 更新我们的根代理程序(root agent)。weather_agent_v6_tool_guardrail)以包含其中的内容。 两者;双方 the before_model_callback 还有这个新的…… before_tool_callback.
  4. 为该代理创建一个新的运行器(runner),并使用相同的基于会话的状态管理(stateful session management)服务。
  5. 通过为允许访问的城市以及被屏蔽的城市(“巴黎”)请求天气信息来测试整个流程。

1. 定义工具防护栏回调函数(Tool Guardrail Callback Function)

这个函数的目标是…… get_weather_stateful 这个工具用于进行检查(或验证、测试等)。 city 参数。如果参数值为 “Paris”,则会返回一个错误字典(该字典的结构与工具自身的错误响应格式相同);否则,会允许工具正常运行。 None.

# @title 1. Define the before_tool_callback Guardrail

# Ensure necessary imports are available
from google.adk.tools.base_tool import BaseTool
from google.adk.tools.tool_context import ToolContext
from typing import Optional, Dict, Any # For type hints

def block_paris_tool_guardrail(
    tool: BaseTool, args: Dict[str, Any], tool_context: ToolContext
) -> Optional[Dict]:
    """
    Checks if 'get_weather_stateful' is called for 'Paris'.
    If so, blocks the tool execution and returns a specific error dictionary.
    Otherwise, allows the tool call to proceed by returning None.
    """
    tool_name = tool.name
    agent_name = tool_context.agent_name # Agent attempting the tool call
    print(f"--- Callback: block_paris_tool_guardrail running for tool '{tool_name}' in agent '{agent_name}' ---")
    print(f"--- Callback: Inspecting args: {args} ---")

    # --- Guardrail Logic ---
    target_tool_name = "get_weather_stateful" # Match the function name used by FunctionTool
    blocked_city = "paris"

    # Check if it's the correct tool and the city argument matches the blocked city
    if tool_name == target_tool_name:
        city_argument = args.get("city", "") # Safely get the 'city' argument
        if city_argument and city_argument.lower() == blocked_city:
            print(f"--- Callback: Detected blocked city '{city_argument}'. Blocking tool execution! ---")
            # Optionally update state
            tool_context.state["guardrail_tool_block_triggered"] = True
            print(f"--- Callback: Set state 'guardrail_tool_block_triggered': True ---")

            # Return a dictionary matching the tool's expected output format for errors
            # This dictionary becomes the tool's result, skipping the actual tool run.
            return {
                "status": "error",
                "error_message": f"Policy restriction: Weather checks for '{city_argument.capitalize()}' are currently disabled by a tool guardrail."
            }
        else:
             print(f"--- Callback: City '{city_argument}' is allowed for tool '{tool_name}'. ---")
    else:
        print(f"--- Callback: Tool '{tool_name}' is not the target tool. Allowing. ---")


    # If the checks above didn't return a dictionary, allow the tool to execute
    print(f"--- Callback: Allowing tool '{tool_name}' to proceed. ---")
    return None # Returning None allows the actual tool function to run

print("✅ block_paris_tool_guardrail function defined.")

2. 更新根代理(Root Agent),使其同时使用这两种回调机制(callbacks)。

我们再次重新定义了“root agent”(即系统的核心代理组件)。weather_agent_v6_tool_guardrail),这次又增加了…… before_tool_callback 参数与……一起 before_model_callback 来自第 5 步。

关于“自包含执行环境”的说明: 与第 5 步类似,确保所有先决条件(子代理、工具等)都已满足。 before_model_callback这些变量或资源必须在定义该代理之前就已经在执行环境中被定义或准备好(即可被使用)。

# @title 2. Update Root Agent with BOTH Callbacks (Self-Contained)

# --- Ensure Prerequisites are Defined ---
# (Include or ensure execution of definitions for: Agent, LiteLlm, Runner, ToolContext,
#  MODEL constants, say_hello, say_goodbye, greeting_agent, farewell_agent,
#  get_weather_stateful, block_keyword_guardrail, block_paris_tool_guardrail)

# --- Redefine Sub-Agents (Ensures they exist in this context) ---
greeting_agent = None
try:
    # Use a defined model constant
    greeting_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="greeting_agent", # Keep original name for consistency
        instruction="You are the Greeting Agent. Your ONLY task is to provide a friendly greeting using the 'say_hello' tool. Do nothing else.",
        description="Handles simple greetings and hellos using the 'say_hello' tool.",
        tools=[say_hello],
    )
    print(f"✅ Sub-Agent '{greeting_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Greeting agent. Check Model/API Key ({greeting_agent.model}). Error: {e}")

farewell_agent = None
try:
    # Use a defined model constant
    farewell_agent = Agent(
        model=MODEL_GEMINI_FLASH,
        name="farewell_agent", # Keep original name
        instruction="You are the Farewell Agent. Your ONLY task is to provide a polite goodbye message using the 'say_goodbye' tool. Do not perform any other actions.",
        description="Handles simple farewells and goodbyes using the 'say_goodbye' tool.",
        tools=[say_goodbye],
    )
    print(f"✅ Sub-Agent '{farewell_agent.name}' redefined.")
except Exception as e:
    print(f"❌ Could not redefine Farewell agent. Check Model/API Key ({farewell_agent.model}). Error: {e}")

# --- Define the Root Agent with Both Callbacks ---
root_agent_tool_guardrail = None
runner_root_tool_guardrail = None

if ('greeting_agent' in globals() and greeting_agent and
    'farewell_agent' in globals() and farewell_agent and
    'get_weather_stateful' in globals() and
    'block_keyword_guardrail' in globals() and
    'block_paris_tool_guardrail' in globals()):

    root_agent_model = MODEL_GEMINI_FLASH

    root_agent_tool_guardrail = Agent(
        name="weather_agent_v6_tool_guardrail", # New version name
        model=root_agent_model,
        description="Main agent: Handles weather, delegates, includes input AND tool guardrails.",
        instruction="You are the main Weather Agent. Provide weather using 'get_weather_stateful'. "
                    "Delegate greetings to 'greeting_agent' and farewells to 'farewell_agent'. "
                    "Handle only weather, greetings, and farewells.",
        tools=[get_weather_stateful],
        sub_agents=[greeting_agent, farewell_agent],
        output_key="last_weather_report",
        before_model_callback=block_keyword_guardrail, # Keep model guardrail
        before_tool_callback=block_paris_tool_guardrail # <<< Add tool guardrail
    )
    print(f"✅ Root Agent '{root_agent_tool_guardrail.name}' created with BOTH callbacks.")

    # --- Create Runner, Using SAME Stateful Session Service ---
    if 'session_service_stateful' in globals():
        runner_root_tool_guardrail = Runner(
            agent=root_agent_tool_guardrail,
            app_name=APP_NAME,
            session_service=session_service_stateful # <<< Use the service from Step 4/5
        )
        print(f"✅ Runner created for tool guardrail agent '{runner_root_tool_guardrail.agent.name}', using stateful session service.")
    else:
        print("❌ Cannot create runner. 'session_service_stateful' from Step 4/5 is missing.")

else:
    print("❌ Cannot create root agent with tool guardrail. Prerequisites missing.")

3. 通过互动来测试该工具的安全防护机制(即“工具护栏”功能)。

让我们再次使用同一个“有状态的会话”(stateful session)来测试交互流程。SESSION_ID_STATEFUL)来自之前的步骤。

  1. 请求“纽约”的天气信息:该请求会触发两个回调函数,工具会执行相应的操作(并使用用户设置的“华氏度”作为温度单位)。
  2. 请求“巴黎”的天气信息:已通过。 before_model_callback. 大语言模型(LLM)决定发起请求(或进行操作)。 get_weather_stateful(city='Paris'). before_tool_callback 该代理会拦截该工具的请求、阻止其执行,并返回一个包含错误信息的字典。随后,该代理会将这个错误信息传递给其他系统或用户。
  3. 请求“伦敦”的天气信息:两个回调函数都被成功调用,工具正常执行。
# @title 3. Interact to Test the Tool Argument Guardrail
import asyncio # Ensure asyncio is imported

# Ensure the runner for the tool guardrail agent is available
if 'runner_root_tool_guardrail' in globals() and runner_root_tool_guardrail:
    # Define the main async function for the tool guardrail test conversation.
    # The 'await' keywords INSIDE this function are necessary for async operations.
    async def run_tool_guardrail_test():
        print("\n--- Testing Tool Argument Guardrail ('Paris' blocked) ---")

        # Use the runner for the agent with both callbacks and the existing stateful session
        # Define a helper lambda for cleaner interaction calls
        interaction_func = lambda query: call_agent_async(query,
                                                         runner_root_tool_guardrail,
                                                         USER_ID_STATEFUL, # Use existing user ID
                                                         SESSION_ID_STATEFUL # Use existing session ID
                                                        )
        # 1. Allowed city (Should pass both callbacks, use Fahrenheit state)
        print("--- Turn 1: Requesting weather in New York (expect allowed) ---")
        await interaction_func("What's the weather in New York?")

        # 2. Blocked city (Should pass model callback, but be blocked by tool callback)
        print("\n--- Turn 2: Requesting weather in Paris (expect blocked by tool guardrail) ---")
        await interaction_func("How about Paris?") # Tool callback should intercept this

        # 3. Another allowed city (Should work normally again)
        print("\n--- Turn 3: Requesting weather in London (expect allowed) ---")
        await interaction_func("Tell me the weather in London.")

    # --- Execute the `run_tool_guardrail_test` async function ---
    # Choose ONE of the methods below based on your environment.

    # METHOD 1: Direct await (Default for Notebooks/Async REPLs)
    # If your environment supports top-level await (like Colab/Jupyter notebooks),
    # it means an event loop is already running, so you can directly await the function.
    print("Attempting execution using 'await' (default for notebooks)...")
    await run_tool_guardrail_test()

    # METHOD 2: asyncio.run (For Standard Python Scripts [.py])
    # If running this code as a standard Python script from your terminal,
    # the script context is synchronous. `asyncio.run()` is needed to
    # create and manage an event loop to execute your async function.
    # To use this method:
    # 1. Comment out the `await run_tool_guardrail_test()` line above.
    # 2. Uncomment the following block:
    """
    import asyncio
    if __name__ == "__main__": # Ensures this runs only when script is executed directly
        print("Executing using 'asyncio.run()' (for standard Python scripts)...")
        try:
            # This creates an event loop, runs your async function, and closes the loop.
            asyncio.run(run_tool_guardrail_test())
        except Exception as e:
            print(f"An error occurred: {e}")
    """

    # --- Inspect final session state after the conversation ---
    # This block runs after either execution method completes.
    # Optional: Check state for the tool block trigger flag
    print("\n--- Inspecting Final Session State (After Tool Guardrail Test) ---")
    # Use the session service instance associated with this stateful session
    final_session = await session_service_stateful.get_session(app_name=APP_NAME,
                                                         user_id=USER_ID_STATEFUL,
                                                         session_id= SESSION_ID_STATEFUL)
    if final_session:
        # Use .get() for safer access
        print(f"Tool Guardrail Triggered Flag: {final_session.state.get('guardrail_tool_block_triggered', 'Not Set (or False)')}")
        print(f"Last Weather Report: {final_session.state.get('last_weather_report', 'Not Set')}") # Should be London weather if successful
        print(f"Temperature Unit: {final_session.state.get('user_preference_temperature_unit', 'Not Set')}") # Should be Fahrenheit
        # print(f"Full State Dict: {final_session.state}") # For detailed view
    else:
        print("\n❌ Error: Could not retrieve final session state.")

else:
    print("\n⚠️ Skipping tool guardrail test. Runner ('runner_root_tool_guardrail') is not available.")

分析输出结果:

  1. 纽约: The before_model_callback 允许该请求被处理。大型语言模型(LLM)会发起相应的请求。 get_weather_stateful. The before_tool_callback 运行程序并检查参数(args)……{'city': 'New York'}当程序检测到目标地点并非“巴黎”时,它会输出“允许使用该工具……”(“Allowing tool…”),然后继续执行后续操作并返回结果。 None. 实际内容(The actual) get_weather_stateful 该函数会执行相应的操作,从系统中读取“华氏温度”数据,并返回天气报告。代理会接收这些信息并将其保存下来。 output_key.
  2. 巴黎: The before_model_callback 允许该请求被处理。大型语言模型(LLM)会发起相应的请求。 get_weather_stateful(city='Paris'). The before_tool_callback 程序会运行并检查传入的参数(args),检测其中是否包含字符串“Paris”;如果检测到该字符串,就会输出“正在阻止工具的执行!”(“Blocking tool execution!”),同时设置相应的状态标志(state flag),最后返回一个包含错误信息的字典(error dictionary)。 {'status': 'error', 'error_message': 'Policy restriction...'}. 实际内容(The actual) get_weather_stateful ```javascript function is { // 函数实现... } ``` 从未被执行过。代理接收到了错误信息字典(error dictionary)。 就好像这是该工具的输出结果一样…… 然后根据该错误信息生成相应的响应。
  3. 伦敦: 其行为类似于纽约:既会传递回调信息,也会成功执行相关工具。新的伦敦天气报告会覆盖原有的数据。 last_weather_report 处于那种状态(或情况)。

您现在已经添加了一层重要的安全防护机制,该机制不仅能够…… 什么 不仅能够与大型语言模型(LLM)进行交互,还能够…… 如何;怎样 可以根据大型语言模型(LLM)生成的特定参数来使用代理的工具。例如:回调函数(callbacks)等。 before_model_callback 和 before_tool_callback 这些组件对于构建健壮、安全且符合政策要求的代理应用程序至关重要。


结论:您的代理团队已经准备就绪!

恭喜您!您已经成功地使用 Agent Development Kit (ADK) 从构建一个简单的天气信息提供系统,发展到了构建一个由多个代理组成的复杂系统。

让我们回顾一下你所完成的工作:

  • 你从一个……开始。 “fundamental agent”(基本代理) 仅配备了一个工具。)get_weather).
  • 您已经研究了 ADK 的相关内容。 多模型灵活性 使用 LiteLLM,可以运用相同的核心逻辑来运行不同的大型语言模型(LLMs),例如 Gemini、GPT-4o 和 Claude。
  • 你接受了(这个事实或提议)。 模块化(modularity) 通过创建专门的子代理机构……)greeting_agent, farewell_agent)并启用相关功能。 自动委托(即任务或责任的自动转移) 该数据来自一个根代理(root agent)。
  • 你已经将相关任务分配给了你的代理人(agents)。 内存 using 会话状态(Session State)这使他们能够记住用户的偏好设置。temperature_unit)以及过去的互动记录(past interactions)。output_key).
  • 您实现了那些至关重要的功能(或模块)。 安全护栏 同时使用两者 before_model_callback (屏蔽特定的输入关键词)以及 before_tool_callback (根据某些参数(例如城市名称“巴黎”)来阻止工具的执行。)

通过组建这个专注于开发“Weather Bot”(天气机器人)的团队,你们获得了关于 ADK(Adobe Digital Kit)核心概念的实际操作经验;这些概念对于开发复杂、智能的应用程序至关重要。

主要收获:

  • 代理与工具: 这些是定义功能并进行推理的基本构建块。清晰的说明和文档字符串(docstrings)至关重要。
  • Runners & Session Services: 该系统负责管理引擎和内存资源,协调代理程序的执行过程,并维护对话的上下文信息。
  • **Delegation:** (注:根据语境,“Delegation”可以译为“授权”或“委托”。如果是指“代表团”的意思,也可以保留原词。) 设计多智能体团队可以实现专业化分工、模块化结构,并更有效地管理复杂任务。 description 这是实现自动流程(auto-flow)的关键因素。
  • 会话状态(Session State)ToolContext, output_key): 对于创建能够理解上下文、提供个性化服务以及支持多轮对话的智能聊天系统来说,这是必不可少的组件。
  • 回调函数(Callbacks)before_model, before_tool): 强大的钩子功能,可用于实现安全性控制、数据验证、策略执行以及动态数据修改。 在……之前 关键操作(例如大型语言模型(LLM)的调用或工具的执行)。
  • 灵活性(Flexibility)LiteLlm): ADK 使您能够根据具体需求选择最适合的 Large Language Model(LLM),在性能、成本和功能之间实现平衡。

接下来该去哪里?

您的 Weather Bot 团队是一个很好的起点。以下是一些建议,可以帮助您进一步探索 ADK(Adobe Digital Kit)的功能,并提升您的应用程序:

  1. Real Weather API: 将以下内容替换为: **“Replace the”** mock_weather_db 在你的…… get_weather 该工具会调用真实的天气 API(例如 OpenWeatherMap 或 WeatherAPI)来获取天气数据。
  2. 更复杂的状态: 将更多的用户偏好设置(例如首选位置、通知设置)或对话摘要存储在会话状态中。
  3. “优化授权机制”(Refine Delegation): 尝试使用不同的根代理(root agent)指令或子代理(sub-agent)描述,以微调代理之间的任务分配逻辑。能否添加一个名为“forecast”的代理呢?
  4. 高级回调功能(Advanced Callbacks):
    • 使用 after_model_callback (用于)可能对大型语言模型(LLM)的回答进行重新格式化或清理处理。 之后;随后 它已经被生成了。
    • 使用 after_tool_callback 用于处理或记录工具返回的结果。
    • 实现;执行 before_agent_callback 或者 after_agent_callback 用于代理级别的进入/退出逻辑(agent-level entry/exit logic)。
  5. 错误处理: 改进代理处理工具错误或意外 API 响应的方式。可以在工具内部添加重试逻辑。
  6. 持久会话存储(Persistent Session Storage): 可以考虑进行更改。 InMemorySessionService 传递给 ADK 的某个持久化实现(persistent implementation);例如: DatabaseSessionService 该工具基于 SQLAlchemy(一个用于数据库操作的 Python 库),并且是通过相应的安装命令被安装到系统中的。 pip install google-adk[db],或 VertexAiSessionService. 如需更多信息,请参阅 会话(Session) page.
  7. 流式用户界面(Streaming UI): 将您的代理团队与一个 Web 框架(例如 FastAPI,如 ADK Streaming 快速入门指南中所示)集成起来,以创建一个实时聊天界面。

代理开发工具包(Agent Development Kit)为构建基于大型语言模型(LLM)的复杂应用程序提供了坚实的基础。通过掌握本教程中介绍的概念(包括工具、状态管理、任务委托以及回调机制),你将能够轻松应对日益复杂的代理系统(agent systems)。

祝建设顺利!