开发 Agent Development Kit 代理

本页介绍了如何使用 Agent Development Kit 模板(Vertex AI SDK for Python 中的 AdkApp 类)开发代理。该代理会返回指定日期两种货币之间的汇率。

按照以下步骤操作:

  1. 定义和配置模型
  2. 定义和使用工具
  3. 管理会话

准备工作

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

定义和配置模型

定义模型版本

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.preview.reasoning_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 笔记本)中运行,则可以作为中间测试步骤运行查询:

for event in app.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。

响应是类似于以下示例的 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.
)

您可以通过对代理发起测试查询在本地测试该代理。运行以下命令,使用美元和瑞典克朗在本地测试代理:

from vertexai.preview.reasoning_engines import AdkApp

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

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

{'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 在本地运行时使用内存中会话,在您将代理部署到 Vertex AI Agent Engine 后,则使用基于云的托管会话。本部分介绍了如何配置 ADK 代理以与受管理的会话搭配使用。

(可选)自定义数据库

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

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

  return InMemorySessionService()

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

from vertexai.preview.reasoning_engines import AdkApp

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

将代理与会话搭配使用

在本地运行代理时,以下说明会使用内存中会话:

为您的代理创建会话:

session = app.create_session(user_id="USER_ID")

列出与您的客服人员关联的会话:

app.list_sessions(user_id="USER_ID")

获取特定会话:

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

其中,SESSION_ID 是您要检索的特定会话的 ID。

使用会话查询代理:

for event in app.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_id 在会话中发送响应(例如 "SEK"):

for event in app.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',
 # ...
}

后续步骤