開發 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',
 # ...
}

後續步驟