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 のエンドポイントを呼び出します。

トレースデータは、OTLP 形式をサポートする Telemetry(OTLP)API を使用して Google Cloud に送信されます。このエンドポイントを介して受信されたデータも OTLP 形式で保存されます。opentelemetry-exporter-otlp-proto-grpc ライブラリは、Telemetry(OTLP)API エンドポイントを呼び出します。

テレメトリーを収集して送信するように 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. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

    Enable the APIs

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

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

    サンプル アプリケーションを起動するには、次の操作を行います。

    1. In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    2. リポジトリのクローンを作成します。

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

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

      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
      
    5. エージェントを操作するには、前の手順でリストされたアドレスにブラウザを開きます。

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

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

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

      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 プロジェクトに送信されますが、指標は生成されません。