开发智能体开发套件智能体

借助 Agent Runtime,您可以使用智能体开发套件 (ADK) 模板开发和部署智能体。通过在 Agent Platform SDK 中使用 AdkApp 类(适用于 Python),您可以创建返回汇率并管理有状态交互的代理。

本文档介绍了如何开发 ADK 智能体,包括定义模型、添加工具以及管理会话和记忆。

如需详细了解如何管理已部署的代理,请参阅管理已部署的代理

准备工作

请确保按照设置环境中的步骤设置您的环境。

定义和配置模型

指定要使用的模型:

model = "gemini-2.0-flash"

可选:配置模型的安全设置。如需详细了解可用于 Gemini 中安全设置的选项,请参阅配置安全属性。 以下示例展示了如何配置安全设置:

from google.genai import types

safety_settings = [
    types.SafetySetting(
        category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold=types.HarmBlockThreshold.OFF,
    ),
]

可选:指定内容生成参数

from google.genai import types

generate_content_config = types.GenerateContentConfig(
   safety_settings=safety_settings,
   temperature=0.28,
   max_output_tokens=1000,
   top_p=0.95,
)

使用模型配置创建 AdkApp

from google.adk.agents import Agent
from vertexai.agent_engines import AdkApp

agent = Agent(
   model=model,                                      # Required.
   name='currency_exchange_agent',                   # Required.
   generate_content_config=generate_content_config,  # Optional.
)
app = AdkApp(agent=agent)

如果您在交互式环境(例如终端或 Colab 笔记本)中运行,则可以使用 AdkApp.async_stream_query 方法运行查询作为中间测试步骤:

async for event in app.async_stream_query(
   user_id="USER_ID",  # Required
   message="What is the exchange rate from US dollars to Swedish currency?",
):
   print(event)
  • USER_ID:自行选择用户 ID,字符数限制为 128。 例如 user-123

响应是类似于以下示例的 Python 字典:

{'actions': {'artifact_delta': {},
             'requested_auth_configs': {},
             'state_delta': {}},
 'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'To provide you with the most accurate '
                                'exchange rate, I need to know the specific '
                                'currencies you\'re asking about. "Swedish '
                                'currency" could refer to:\n'
                                '\n'
                                '*   **Swedish Krona (SEK):** This is the '
                                'official currency of Sweden.\n'
                                '\n'
                                "Please confirm if you're interested in the "
                                'exchange rate between USD and SEK. Once you '
                                'confirm, I can fetch the latest exchange rate '
                                'for you.\n'}],
             'role': 'model'},
 'id': 'LYg7wg8G',
 'invocation_id': 'e-113ca547-0f19-4d50-9dde-f76cbc001dce',
 'timestamp': 1744166956.925927}

可选:定义和使用工具

定义模型后,定义模型用于推理的工具。

定义函数时,请务必添加能完整而清晰地描述函数的参数、函数的用途以及函数返回内容的注释。模型会使用此信息来确定要使用的函数。您还必须在本地测试函数,以确认其是否正常运行。

使用以下代码定义一个返回汇率的函数:

def get_exchange_rate(
    currency_from: str = "USD",
    currency_to: str = "EUR",
    currency_date: str = "latest",
):
    """Retrieves the exchange rate between two currencies on a specified date.

    Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
    exchange rate data.

    Args:
        currency_from: The base currency (3-letter currency code).
            Defaults to "USD" (US Dollar).
        currency_to: The target currency (3-letter currency code).
            Defaults to "EUR" (Euro).
        currency_date: The date for which to retrieve the exchange rate.
            Defaults to "latest" for the most recent exchange rate data.
            Can be specified in YYYY-MM-DD format for historical rates.

    Returns:
        dict: A dictionary containing the exchange rate information.
            Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
                "rates": {"EUR": 0.95534}}
    """
    import requests
    response = requests.get(
        f"https://api.frankfurter.app/{currency_date}",
        params={"from": currency_from, "to": currency_to},
    )
    return response.json()

如需在代理中使用函数之前先对其进行测试,请运行以下命令:

get_exchange_rate(currency_from="USD", currency_to="SEK")

响应应该类似以下内容:

{'amount': 1.0, 'base': 'USD', 'date': '2025-04-03', 'rates': {'SEK': 9.6607}}

如需在 AdkApp 内使用该工具,请将其添加到 tools= 参数下的工具列表中:

from google.adk.agents import Agent

agent = Agent(
    model=model,                     # Required.
    name='currency_exchange_agent',  # Required.
    tools=[get_exchange_rate],       # Optional.
)

您可以使用 AdkApp.async_stream_query 方法对智能体执行测试查询,从而在本地测试该智能体。运行以下命令,使用美元和瑞典克朗在本地测试代理:

from vertexai.agent_engines import AdkApp

app = AdkApp(agent=agent)
async for event in app.async_stream_query(
    user_id="USER_ID",
    message="What is the exchange rate from US dollars to SEK on 2025-04-03?",
):
    print(event)

其中,USER_ID 是您定义的用户 ID。例如 user-123

响应是一个类似于以下内容的字典序列:

{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
                                                   'currency_from': 'USD',
                                                   'currency_to': 'SEK'},
                                          'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
                                          'name': 'get_exchange_rate'}}],
             'role': 'model'},
 'id': 'zFyIaaif',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_response': {'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
                                              'name': 'get_exchange_rate',
                                              'response': {'amount': 1.0,
                                                           'base': 'USD',
                                                           'date': '2025-04-03',
                                                           'rates': {'SEK': 9.6607}}}}],
             'role': 'user'},
 'id': 'u2YR4Uom',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
                                '2025-04-03 is 9.6607.'}],
             'role': 'model'},
 'id': 'q3jWA3wl',
 # ...
}

可选:管理会话

AdkApp 在本地运行时使用内存中会话,在将智能体部署到 Agent Runtime 后使用基于云的托管式会话。本部分介绍如何配置 ADK 智能体以与托管式会话搭配使用。

可选:自定义会话数据库

如果您想使用自己的数据库替换默认的托管式会话服务,可以按如下方式定义 session_service_builder 函数:

def session_service_builder():
  from google.adk.sessions import InMemorySessionService

  return InMemorySessionService()

将数据库作为 session_service_builder= 传递给 AdkApp

from vertexai.agent_engines import AdkApp

app = AdkApp(
   agent=agent,                                      # Required.
   session_service_builder=session_service_builder,  # Optional.
)

将智能体与会话搭配使用

在本地运行 AdkApp 时,以下指令使用内存中会话。

如需为智能体创建会话,请使用 AdkApp.async_create_session 方法:

session = await app.async_create_session(user_id="USER_ID")
print(session)

会话以 ADK 会话对象的字典表示形式创建。

如需列出与智能体关联的会话,请使用 AdkApp.async_list_sessions 方法:

await app.async_list_sessions(user_id="USER_ID")

如需获取特定会话,请使用 AdkApp.async_get_session 方法:

session = await app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")

其中

  • USER_ID 是您定义的用户 ID。例如 user-123

  • SESSION_ID 是您要检索的特定会话的 ID。

如需异步查询代理,请使用 AdkApp.async_stream_query 方法:

async for event in app.async_stream_query(
    user_id="USER_ID",
    session_id=SESSION_ID, # Optional. you can pass in the session_id when querying the agent
    message="What is the exchange rate from US dollars to Swedish currency on 2025-04-03?",
):
    print(event)

智能体可能会响应请求,以提供以下信息:

{'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'I need to know the Swedish currency code to '
                                'provide you with the exchange rate.'}],
             'role': 'model'},
 'id': 'wIgZAtQ4',
 #...
}

您可以在与 session 对应的会话中代表 USER_ID 发送响应(例如 "SEK"),方法是指定:

async for event in app.async_stream_query(
    user_id="USER_ID",
    session_id=session.id, # Optional. you can pass in the session_id when querying the agent
    message="SEK",
):
    print(event)

您应该会收到类似如下字典序列的连续对话:

{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
                                                   'currency_from': 'USD',
                                                   'currency_to': 'SEK'},
                                          'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
                                          'name': 'get_exchange_rate'}}],
             'role': 'model'},
 'id': 'bOPHtzji',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'function_response': {'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
                                              'name': 'get_exchange_rate',
                                              'response': {'amount': 1.0,
                                                           'base': 'USD',
                                                           'date': '2025-04-03',
                                                           'rates': {'SEK': 9.6607}}}}],
             'role': 'user'},
 'id': '9AoDFmiL',
 # ...
}
{'author': 'currency_exchange_agent',
 'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
                                '2025-04-03 is 1 USD to 9.6607 SEK.'}],
             'role': 'model'},
 'id': 'hmle7trT',
 # ...
}

可选:管理回忆

默认情况下,AdkApp 在本地运行时使用智能体内存的内存中实现,在将智能体部署到 Agent Runtime 后使用 Agent Platform Memory Bank

开发 ADK 智能体时,您可以添加一个 PreloadMemoryTool,用于控制智能体何时检索记忆以及如何在提示中包含记忆。以下示例代理总会在每个回合开始时检索记忆,然后将记忆包含在系统指令中:

from google.adk.agents import Agent
from google.adk.tools.preload_memory_tool import PreloadMemoryTool
from vertexai.agent_engines import AdkApp

agent = Agent(
    model="gemini-2.0-flash",
    name='stateful_agent',
    instruction="""You are a Vehicle Voice Agent, designed to assist users with information and in-vehicle actions.

1.  **Direct Action:** If a user requests a specific vehicle function (e.g., "turn on the AC"), execute it immediately using the corresponding tool. You don't have the outcome of the actual tool execution, so provide a hypothetical tool execution outcome.
2.  **Information Retrieval:** Respond concisely to general information requests with your own knowledge (e.g., restaurant recommendation).
3.  **Clarity:** When necessary, try to seek clarification to better understand the user's needs and preference before taking an action.
4.  **Brevity:** Limit responses to under 30 words.
""",
    tools=[PreloadMemoryTool()],
)

app = AdkApp(agent=agent)

可选:自定义内存服务

如果您想替换默认的内存服务,可以定义一个返回 BaseMemoryServicememory_service_builder 函数,如下所示:

def memory_service_builder():
  from google.adk.memory import InMemoryMemoryService

  return InMemoryMemoryService()

将数据库作为 memory_service_builder= 传递给 AdkApp

from vertexai.agent_engines import AdkApp

app = AdkApp(
   agent=agent,                                    # Required.
   memory_service_builder=memory_service_builder,  # Optional.
)

将智能体与记忆搭配使用

测试具有记忆功能的 ADK 智能体:

  1. 创建会话并与代理互动:

    initial_session = await app.async_create_session(user_id="USER_ID")
    
    async for event in app.async_stream_query(
        user_id="USER_ID",
        session_id=initial_session.id,
        message="Can you update the temperature to my preferred temperature?",
    ):
        print(event)
    

    由于在第一个会话期间没有可用的记忆,并且代理不知道任何用户偏好,因此代理可能会回复“您偏好的温度是多少?”等消息。您可以使用以下命令进行回复:

    async for event in app.async_stream_query(
        user_id="USER_ID",
        session_id=initial_session.id,
        message="I like it at 71 degrees",
    ):
        print(event)
    

    智能体可能会返回“将温度设为 71 华氏度”之类的回答。已成功更改温度。”智能体的回答可能会因您使用的模型而异。

  2. 从对话中生成记忆。如需存储会话中的信息以供日后会话使用,请使用 async_add_session_to_memory 方法:

    await app.async_add_session_to_memory(session=initial_session)
    
  3. 通过创建新会话并提示智能体,测试智能体是否保留了会话的记忆(使用 PreloadMemoryTool):

    new_session = await app.async_create_session(user_id="USER_ID")
    async for event in app.async_stream_query(
        user_id="USER_ID",
        session_id=initial_session.id,
        message="Fix the temperature!",
    ):
        print(event)
    

    智能体可能会返回“将温度设为 71 度”之类的回答。这是否正确?"智能体的回答可能会因您使用的模型和记忆服务提供商而异。

  4. 使用 async_search_memory 方法显示代理的记忆:

    response = await app.async_search_memory(
        user_id="USER_ID",
        query="Fix the temperature!",
    )
    print(response)
    

后续步骤

指南

了解根据您的开发需求,在 Agent Platform Runtime 上部署代理的五种方式。

概览

了解如何使用会话来维护与代理的对话状态。

概览

了解如何使用记忆库来存储长期用户偏好设置和事实。

指南

将智能体开发套件 (ADK) 智能体与 Agent Platform Runtime 搭配使用。

指南

创建并部署基本智能体,然后使用 Gen AI Evaluation Service 评估该智能体

问题排查

了解如何解决创建自定义代理时出现的常见错误。

资源

查找 Google Agent Platform 的相关资源和支持。