コンテンツにスキップ

Vertex AI Agent Engineへのデプロイ

python_only

Agent Engineは、開発者が本番環境でAIエージェントをデプロイ、管理、スケーリングできるようにする、フルマネージドのGoogle Cloudサービスです。Agent Engineが本番環境でのエージェントのスケーリングに必要なインフラストラクチャを処理するため、開発者はインテリジェントでインパクトのあるアプリケーションの作成に集中できます。

from vertexai import agent_engines

remote_app = agent_engines.create(
    agent_engine=root_agent,
    requirements=[
        "google-cloud-aiplatform[adk,agent_engines]",
    ]
)

Vertex AI SDKのインストール

Agent Engineは、Vertex AI SDK for Pythonの一部です。詳細については、Agent Engineクイックスタートドキュメントをご覧ください。

Vertex AI SDKのインストール

pip install google-cloud-aiplatform[adk,agent_engines]

Info

Agent Engineがサポートしているのは、Pythonバージョン >=3.9 かつ <=3.12 のみです。

初期化

import vertexai

PROJECT_ID = "your-project-id"  # あなたのプロジェクトID
LOCATION = "us-central1"  # リージョン
STAGING_BUCKET = "gs://your-google-cloud-storage-bucket"  # あなたのGoogle Cloud Storageバケット

vertexai.init(
    project=PROJECT_ID,
    location=LOCATION,
    staging_bucket=STAGING_BUCKET,
)

LOCATIONについては、Agent Engineでサポートされているリージョンのリストを確認してください。

エージェントの作成

以下のサンプルエージェントを使用できます。このエージェントには2つのツール(天気の取得、指定された都市の時刻の取得)があります。

import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent

def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}


root_agent = Agent(
    name="weather_time_agent",
    model="gemini-2.0-flash",
    description=(
        "Agent to answer questions about the time and weather in a city."
    ),
    instruction=(
        "You are a helpful agent who can answer user questions about the time and weather in a city."
    ),
    tools=[get_weather, get_current_time],
)

Agent Engine向けにエージェントを準備する

reasoning_engines.AdkApp()を使用してエージェントをラップし、Agent Engineにデプロイできるようにします。

from vertexai.preview import reasoning_engines

app = reasoning_engines.AdkApp(
    agent=root_agent,
    enable_tracing=True,
)

エージェントをローカルで試す

Agent Engineにデプロイする前に、ローカルで試すことができます。

セッションの作成(ローカル)

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

create_sessionの期待される出力(ローカル):

Session(id='c6a33dae-26ef-410c-9135-b434a528291f', app_name='default-app-name', user_id='u_123', state={}, events=[], last_update_time=1743440392.8689594)

セッションの一覧表示(ローカル)

app.list_sessions(user_id="u_123")

list_sessionsの期待される出力(ローカル):

ListSessionsResponse(session_ids=['c6a33dae-26ef-410c-9135-b434a528291f'])

特定のセッションの取得(ローカル)

session = app.get_session(user_id="u_123", session_id=session.id)
session

get_sessionの期待される出力(ローカル):

Session(id='c6a33dae-26ef-410c-9135-b434a528291f', app_name='default-app-name', user_id='u_123', state={}, events=[], last_update_time=1743681991.95696)

エージェントへのクエリ送信(ローカル)

for event in app.stream_query(
    user_id="u_123",
    session_id=session.id,
    message="whats the weather in new york",
):
print(event)

stream_queryの期待される出力(ローカル):

{'parts': [{'function_call': {'id': 'af-a33fedb0-29e6-4d0c-9eb3-00c402969395', 'args': {'city': 'new york'}, 'name': 'get_weather'}}], 'role': 'model'}
{'parts': [{'function_response': {'id': 'af-a33fedb0-29e6-4d0c-9eb3-00c402969395', 'name': 'get_weather', 'response': {'status': 'success', 'report': 'The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).'}}}], 'role': 'user'}
{'parts': [{'text': 'The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).'}], 'role': 'model'}

エージェントをAgent Engineにデプロイする

from vertexai import agent_engines

remote_app = agent_engines.create(
    agent_engine=root_agent,
    requirements=[
        "google-cloud-aiplatform[adk,agent_engines]"   
    ]
)

このステップは完了までに数分かかることがあります。デプロイされた各エージェントには一意の識別子があります。次のコマンドを実行して、デプロイされたエージェントのresource_name識別子を取得できます。

remote_app.resource_name

応答は次のような文字列になります。

f"projects/{PROJECT_NUMBER}/locations/{LOCATION}/reasoningEngines/{RESOURCE_ID}"

追加の詳細については、Agent Engineドキュメントのエージェントのデプロイおよびデプロイ済みエージェントの管理をご覧ください。

Agent Engine上のエージェントを試す

セッションの作成(リモート)

remote_session = remote_app.create_session(user_id="u_456")
remote_session

create_sessionの期待される出力(リモート):

{'events': [],
'user_id': 'u_456',
'state': {},
'id': '7543472750996750336',
'app_name': '7917477678498709504',
'last_update_time': 1743683353.030133}

idはセッションID、app_nameはAgent EngineにデプロイされたエージェントのリソースIDです。

セッションの一覧表示(リモート)

remote_app.list_sessions(user_id="u_456")

特定のセッションの取得(リモート)

remote_app.get_session(user_id="u_456", session_id=remote_session["id"])

Note

ローカルでエージェントを使用する場合、セッションIDはsession.idに保存されますが、Agent Engine上でリモートでエージェントを使用する場合、セッションIDはremote_session["id"]に保存されます。

エージェントへのクエリ送信(リモート)

for event in remote_app.stream_query(
    user_id="u_456",
    session_id=remote_session["id"],
    message="whats the weather in new york",
):
    print(event)

stream_queryの期待される出力(リモート):

{'parts': [{'function_call': {'id': 'af-f1906423-a531-4ecf-a1ef-723b05e85321', 'args': {'city': 'new york'}, 'name': 'get_weather'}}], 'role': 'model'}
{'parts': [{'function_response': {'id': 'af-f1906423-a531-4ecf-a1ef-723b05e85321', 'name': 'get_weather', 'response': {'status': 'success', 'report': 'The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).'}}}], 'role': 'user'}
{'parts': [{'text': 'The weather in New York is sunny with a temperature of 25 degrees Celsius (41 degrees Fahrenheit).'}], 'role': 'model'}

クリーンアップ

作業が完了したら、クラウドリソースをクリーンアップすることをお勧めします。 デプロイされたAgent Engineインスタンスを削除することで、Google Cloudアカウントでの予期せぬ 課金を避けることができます。

remote_app.delete(force=True)

force=Trueは、セッションなど、デプロイされたエージェントから生成された子リソースも削除します。