OpenTelemetry を使用して LangGraph ReAct エージェントを計測する

このドキュメントでは、OpenTelemetry を使用して LangGraph ReAct エージェントを計測し、エージェントからのテレメトリーの収集を有効にする手順について説明します。ユーザー プロンプト、エージェントのレスポンス、選択肢は、スパンに関連付けられた属性としてテレメトリーに含まれます。エージェントのレスポンスは、生成 AI イベントを含むスパンと関連付けられたログエントリにも含まれます。このドキュメントの手順は、エージェントが Langchain の ChatVertexAI を使用して Gemini モデルを呼び出す場合に適用されます。

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

生成 AI アプリケーションを計測してログ、指標、トレースデータを収集するには、次の操作を行います。

  1. OpenTelemetry パッケージをインストールする
  2. テレメトリーを収集して送信するように OpenTelemetry を構成する
  3. 生成 AI エージェントの呼び出しをトレースする

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

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

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

ログデータと指標データは、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 を構成する

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

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

def setup_opentelemetry() -> None:
    credentials, project_id = google.auth.default()
    resource = Resource.create(
        attributes={
            SERVICE_NAME: "langgraph-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()
    VertexAIInstrumentor().instrument()

生成 AI エージェントの呼び出しをトレースする

LangGraph エージェントの呼び出しの実行をトレースするには、エージェントの呼び出しの周囲にカスタムスパンを作成します。

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

# Invoke the agent within a span
with tracer.start_as_current_span("invoke agent"):
    result = agent.invoke({"messages": [prompt]}, config=config)

上記のコードは、アプリケーション コードの重要な場所に含めることが可能です。

カスタムスパンと指標の追加の詳細については、アプリにカスタム トレースとカスタム指標を追加するをご覧ください。

サンプルを実行する

このサンプルは、OpenTelemetry で計測された LangGraph エージェントで、生成 AI プロンプトとレスポンスを含むトレース、ログ、指標をGoogle Cloud プロジェクトに送信します。

LangGraph エージェント ペルソナ

LangGraph エージェントは、エフェメラル SQLite データベースに完全アクセスできる SQL エキスパートとして定義されます。エージェントは LangGraph のビルド済みの ReAct エージェントで実装され、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:

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

サンプルを実行する

サンプルを実行するには、次の操作を行います。

  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/langgraph-sql-agent
    
  4. 環境変数を設定します。

    # Capture GenAI prompts and responses
    export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true
    # Capture application logs automatically
    export OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
    
  5. 仮想環境を作成してサンプルを実行します。

    python -m venv venv/
    source venv/bin/activate
    pip install -r requirements.txt
    python main.py
    

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

    Starting agent using ephemeral SQLite DB.
    
  6. データベースを作成するには、[Talk to the SQL agent >>] プロンプトに値を入力し、Enter キーを押します。

    エージェントが行ったアクションが Cloud Shell に表示されます。

    次の図は、ユーザーとアプリケーションの間のインタラクションの例を示しています。

    Talk to the SQL agent >> Create a new table to hold weather data.
    👤 User: Create a new table to hold weather data.
    🤖 Agent: I need to know what columns the table should have. What information about the weather do you want to store? For example, I could include columns for date, location, temperature, humidity, and precipitation.
    
    Talk to the SQL agent >> Create a new table to hold weather data. Include date, location, temperature, humidity, and precipitation.
    👤 User: Create a new table to hold weather data. Include date, location, temperature, humidity, and precipitation.
    🤖 Agent
    
    CREATE TABLE weather (
      date DATE,
      location VARCHAR(255),
      temperature REAL,
      humidity REAL,
      precipitation REAL
    );
    
    
  7. 終了するには、「Ctrl-C」と入力します。

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

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

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

始める前に

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

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

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

テレメトリーを表示する

生成 AI イベントを表示するには、[Trace エクスプローラ] ページを使用します。

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

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

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

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

    サンプルを実行するセクションには、2 つのプロンプトがアプリに送信される実行例が含まれています。データのフィルタリング後の [Trace エクスプローラ] ページは次のとおりです。

    トレーススパンの表示。

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

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

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

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

      次のスクリーンショットは、1 つのスパンに invoke_agent という名前が付けられているトレースを示しています。このスパンが Gemini を呼び出します。Gemini スパンに生成 AI イベントが含まれます。

      生成 AI イベントの表示。

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

      ログデータには、LangGraph エージェントのレスポンスが含まれます。たとえば、サンプル実行の場合、JSON ペイロードには次の内容が含まれます。

      {
        logName: "projects/my-project/logs/otel_python_inprocess_log_name_temp"
        jsonPayload: {
          finish_reason: "stop"
          message: {
            role: "model"
            content: [
              0: {
                text: "I need to know what columns the table should have. What information about the weather do you want to store? For example, I could include columns for date, location, temperature, humidity, and precipitation."
              }
            ]
          }
        index: 0
        }
      ...
      }
      

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