本頁說明如何使用 Agent Development Kit 範本 (Vertex AI SDK for Python 中的 AdkApp
類別) 開發代理程式。代理程式會傳回指定日期的兩種貨幣匯率。
操作步驟如下:
事前準備
請按照「設定環境」一文中的步驟,確認環境已設定完成。
定義及設定模型
定義模型版本:
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 筆記本等互動式環境中執行作業,可以執行查詢做為中繼測試步驟:
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 個。
回應是類似下列範例的 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)
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)
回應是一連串類似下列內容的字典:
{'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 = await app.async_create_session(user_id="USER_ID")
列出與代理程式相關聯的工作階段:
await app.async_list_sessions(user_id="USER_ID")
取得特定工作階段:
session = await app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")
其中 SESSION_ID 是要擷取的特定工作階段 ID。
使用工作階段查詢代理程式:
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',
#...
}
您可以在工作階段中傳送回覆 (例如 "SEK"
),方法是指定 session_id
:
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',
# ...
}
後續步驟
- 評估代理程式。
- 部署代理程式。
- 排解開發代理程式的問題。
- 取得支援。