Agent Development Kit エージェントを開発する

このページでは、エージェント開発キット テンプレート(Vertex AI SDK for Python の AdkApp クラス)を使用してエージェントを開発する方法について説明します。エージェントは、指定した日付の 2 つの通貨間の為替レートを返します。

次の操作を行います。

  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 は文字数制限が 128 のユーザー定義 ID です。

回答として、次の例に示すような 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',
 #...
}

セッション内でレスポンスを送信するには("SEK" など)、session_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="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',
 # ...
}

次のステップ