OpenTelemetry を使用して ADK アプリケーションを計測する

このドキュメントでは、Agent Development Kit(ADK)フレームワークで構築された AI エージェントを計測する方法について説明します。この計測は、OpenTelemetry を活用したもので、ユーザー プロンプト、エージェントの回答、エージェントの選択を収集できます。

ADK フレームワーク自体も OpenTelemetry で計測され、エージェントの実行の主要なステップからテレメトリーがキャプチャされます。これにより、アプリケーションの貴重なオブザーバビリティをすぐに利用できます。ただし、このオブザーバビリティは、アプリケーションのユースケースには十分でない可能性があります。OpenTelemetry を使用してアプリの他の部分からテレメトリーをキャプチャしたり、独自のカスタム計測を使用してアプリケーション固有のデータをキャプチャしたりして、他の計測ライブラリを追加することで、よりきめ細かいオブザーバビリティを実現できます。

たとえば、アプリケーションで次のような計測コードを記述できます。

  • エージェントが起動したツールのリソース消費量を追跡する。
  • アプリケーション固有の検証の失敗、ビジネスルールの違反、カスタムエラー回復メカニズムを追跡する。
  • ドメイン固有の基準に基づいて、エージェントの回答の品質スコアを追跡する。

生成 AI アプリケーションを計測してテレメトリーを収集する

AI エージェントを計測してログ、指標、トレースデータを収集する手順は次のとおりです。

  1. OpenTelemetry パッケージをインストールする
  2. テレメトリーを収集して送信するように OpenTelemetry を構成する
  3. 構成した OpenTelemetry を挿入するカスタム エントリ ポイントを作成する

このセクションの残りの部分では、上記の手順について説明します。

OpenTelemetry パッケージをインストールする

次の OpenTelemetry 計測パッケージとエクスポータ パッケージを追加します。

pip install 'opentelemetry-instrumentation-google-genai' \
  'opentelemetry-instrumentation-sqlite3' \
  'opentelemetry-exporter-gcp-logging' \
  'opentelemetry-exporter-gcp-monitoring' \
  'opentelemetry-exporter-otlp-proto-grpc' \
  'opentelemetry-instrumentation-vertexai>=2.0b0'

ログデータと指標データは、Cloud Logging API または Cloud Monitoring API を使用して Google Cloud プロジェクトに送信されます。opentelemetry-exporter-gcp-logging ライブラリと opentelemetry-exporter-gcp-monitoring ライブラリは、これらの API のエンドポイントを呼び出します。

トレースデータは、OpenTelemetry OTLP プロトコルを実装する Telemetry(OTLP)API を使用して Google Cloud に送信されます。opentelemetry-exporter-otlp-proto-grpc ライブラリは、Telemetry(OTLP)API エンドポイントを呼び出します。

トレースデータは、通常、OpenTelemetry OTLP プロトコルで定義された proto ファイルと一貫性のある形式で保存されます。ただし、フィールドは保存前に OpenTelemetry 固有のデータ型から JSON データ型に変換されることがあります。ストレージ形式の詳細については、トレースデータのスキーマをご覧ください。

テレメトリーを収集して送信するように OpenTelemetry を構成する

ADK エージェントの初期化コードで、テレメトリーをキャプチャして Google Cloud プロジェクトに送信するように OpenTelemetry を構成するコードを追加します。

サンプル全体を表示するには、[ その他] をクリックして、[GitHub で表示] を選択します。

def setup_opentelemetry() -> None:
    credentials, project_id = google.auth.default()
    resource = Resource.create(
        attributes={
            SERVICE_NAME: "adk-sql-agent",
            # The project to send spans to
            "gcp.project_id": project_id,
        }
    )

    # Set up OTLP auth
    request = google.auth.transport.requests.Request()
    auth_metadata_plugin = AuthMetadataPlugin(credentials=credentials, request=request)
    channel_creds = grpc.composite_channel_credentials(
        grpc.ssl_channel_credentials(),
        grpc.metadata_call_credentials(auth_metadata_plugin),
    )

    # Set up OpenTelemetry Python SDK
    tracer_provider = TracerProvider(resource=resource)
    tracer_provider.add_span_processor(
        BatchSpanProcessor(
            OTLPSpanExporter(
                credentials=channel_creds,
                endpoint="https://telemetry.googleapis.com:443/v1/traces",
            )
        )
    )
    trace.set_tracer_provider(tracer_provider)

    logger_provider = LoggerProvider(resource=resource)
    logger_provider.add_log_record_processor(
        BatchLogRecordProcessor(CloudLoggingExporter())
    )
    logs.set_logger_provider(logger_provider)

    event_logger_provider = EventLoggerProvider(logger_provider)
    events.set_event_logger_provider(event_logger_provider)

    reader = PeriodicExportingMetricReader(CloudMonitoringMetricsExporter())
    meter_provider = MeterProvider(metric_readers=[reader], resource=resource)
    metrics.set_meter_provider(meter_provider)

    # Load instrumentors
    SQLite3Instrumentor().instrument()
    # ADK uses Vertex AI and Google Gen AI SDKs.
    VertexAIInstrumentor().instrument()
    GoogleGenAiSdkInstrumentor().instrument()

構成した OpenTelemetry を使用するカスタム エントリ ポイントを作成する

計測に OpenTelemetry を使用するには、ADK アプリケーションのカスタム エントリ ポイントを作成します。カスタム エントリ ポイントは、ADK エージェントを起動する前に OpenTelemetry を構成する必要があります。

サンプル アプリケーションでは、main メソッドは、OpenTelemetry を初期化してから、エージェントとやり取りできる FastAPI サーバーを起動するカスタム エントリ ポイントとして機能します。

サンプル全体を表示するには、[ その他] をクリックして、[GitHub で表示] を選択します。

def main() -> None:
    # Make sure to set:
    # OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
    # OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true
    # in order to full prompts and responses and logs messages.
    # For this sample, these can be set by loading the `opentelemetry.env` file.
    setup_opentelemetry()

    # Call the function to get the FastAPI app instance.
    # Ensure that the agent director name is the name of directory containing agent subdirectories,
    # where each subdirectory represents a single agent with __init__.py and agent.py files.
    # For this example this would be the current directory containing main.py.
    # Note: Calling this method attempts to set the global tracer provider, which has already been
    # set by the setup_opentelemetry() function.
    app = get_fast_api_app(
        agents_dir=AGENT_DIR,
        session_service_uri=SESSION_DB_URL,
        allow_origins=ALLOWED_ORIGINS,
        web=SERVE_WEB_INTERFACE,
    )

    # Lauch the web interface on port 8080.
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

サンプル アプリケーションをダウンロードして実行する

このサンプルコードは、ADK を使用して構築された生成 AI エージェントを実装します。エージェントは OpenTelemetry で計測され、指標、トレース、ログを Google Cloud プロジェクトに送信するように構成されています。プロジェクトに送信されるテレメトリーには、生成 AI のプロンプトと回答が含まれます。

ADK エージェントのペルソナ

生成 AI エージェントは、エフェメラル SQLite データベースへの完全アクセス権を持つ SQL エキスパートとして定義されます。エージェントは Agent Development Kit で構築され、SQLDatabaseToolkit を使用してデータベースにアクセスします。データベースは最初は空です。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. 外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。

  4. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI, Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable aiplatform.googleapis.com telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com cloudtrace.googleapis.com
  8. Install the Google Cloud CLI.

  9. 外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。

  10. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  11. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Verify that billing is enabled for your Google Cloud project.

  13. Enable the Vertex AI, Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable aiplatform.googleapis.com telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com cloudtrace.googleapis.com
  14. Cloud Shell、 Google Cloudリソース、ローカル開発環境でサンプルを実行する場合は、このセクションに記載されている権限で十分です。本番環境アプリケーションの場合、通常、サービス アカウントはログ、指標、トレースデータを書き込む認証情報を提供します。

    サンプル アプリケーションがログデータ、指標データ、トレースデータを書き込むために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

  15. アプリケーションを起動する

    サンプルアプリケーションを起動する手順は次のとおりです。

    1. Cloud Shell で、次のコマンドを実行します。

      git clone https://github.com/GoogleCloudPlatform/opentelemetry-operations-python.git
      
    2. サンプル ディレクトリに移動します。

      cd opentelemetry-operations-python/samples/adk-sql-agent
      
    3. 仮想環境を作成してサンプルを実行します。

      python -m venv venv/
      source venv/bin/activate
      pip install -r requirements.txt
      env $(cat opentelemetry.env | xargs) python main.py
      

      アプリケーションにより、次のようなメッセージが表示されます。

      Appplication startup complete
      Uvicorn running on http://0.0.0.0:8080
      
    4. エージェントとやり取りするには、ブラウザを開き、前の手順に記載されたアドレスに移動します。

    5. [Select an agent] を開き、エージェントのリストから sql_agent を選択します。

    エージェントとやり取りする

    エージェントに質問したり、指示を出したりして、エージェントとやり取りします。たとえば、次のような質問をします。

    What can you do for me ?
    

    同様に、sql_agent のペルソナは SQL エキスパートであるため、アプリケーションのテーブルを作成し、作成したテーブルを操作するクエリを記述するように依頼することもできます。エージェントは、アプリケーションを実行しているマシンで作成された .db ファイルを使用するエフェメラル データベースのみを作成できます。

    sql_agent とユーザーのやり取りの例を以下に示します。

    Create a table for me to store weather data and also insert sample data in
    the table. At the end show all data in the table you created.
    

    sql_agent とのやり取りの表示。

    生成 AI エージェントによって実行されるアクションは決定的ではないため、同じプロンプトでも回答が異なる場合があります。

    アプリケーションを終了する

    アプリケーションを終了するには、アプリケーションの起動に使用したシェルで Ctrl-C キーを押します。

    トレース、指標、ログを表示する

    このセクションでは、生成 AI イベントを表示する方法について説明します。

    始める前に

    ログ、指標、トレースデータを表示するために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

    ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

    必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

    テレメトリーを表示する

    アプリケーションによって作成された生成 AI イベントを表示するには、[Trace エクスプローラ] ページを使用します。

    1. Google Cloud コンソールで、[Trace エクスプローラ] ページに移動します。

      [Trace エクスプローラ] に移動

      このページは、検索バーを使用して見つけることもできます。

    2. ツールバーで [フィルタを追加]、[スパン名]、[call_llm] の順に選択します。

      データのフィルタリング後の [Trace エクスプローラ] ページを以下に示します。

      トレーススパンの表示。

      Cloud Trace を初めて使用する場合は、Google Cloud Observability によって、トレースデータを保存するデータベースが作成される必要があります。データベースの作成には数分かかることがあり、その間トレースデータを表示することはできません。

    3. スパンデータとログデータを調べるには、[スパン] テーブルでスパンを選択します。

      [詳細] ページが開きます。このページには、関連するトレースとそのスパンが表示されます。ページ上のテーブルには、選択したスパンの詳細情報が表示されます。詳細情報には次の情報が含まれます。

      • [生成 AI] タブには、生成 AI エージェントのイベントが表示されます。これらのイベントの詳細については、生成 AI イベントを表示するをご覧ください。

        次のスクリーンショットは、1 つのスパンに call_llm という名前が付けられているトレースを示しています。このスパンは、このエージェントで使用される LLM(大規模言語モデル)を呼び出します。このサンプルでは、Gemini です。Gemini スパンには生成 AI イベントが含まれます。

        生成 AI イベントの表示。

      • [ログとイベント] タブには、スパンに関連付けられているログエントリとイベントが一覧表示されます。ログ エクスプローラでログデータを表示する場合は、このタブのツールバーで [ログを表示] を選択します。

        ログデータには、sql_agent の回答が含まれます。たとえば、サンプル実行の場合、JSON ペイロードには次の内容が含まれます。

        {
          "logName": "projects/my-project/logs/otel_python_inprocess_log_name_temp",
          "jsonPayload": {
            "content": {
              "role": "model",
              "parts": [
                {
                  "executable_code": null,
                  "inline_data": null,
                  "thought": null,
                  "video_metadata": null,
                  "code_execution_result": null,
                  "function_response": null,
                  "thought_signature": null,
                  "text": "Okay, I will create a table named `weather` with columns `id`, `city`, `temperature`, and `date`. Then I will insert some sample rows into the table and display all the data in the table.\n",
                  "file_data": null,
                  "function_call": null
                }
              ]
            }
          },
          ...
        }
        

    サンプルが計測され、指標データが Google Cloud プロジェクトに送信されますが、指標は生成されません。