使用 OpenTelemetry 檢測 LangGraph ReAct 代理

本文件概述使用 OpenTelemetry 檢測 LangGraph ReAct Agent 的步驟,以便從代理程式收集遙測資料。使用者提示、代理程式回應和選項會以屬性形式附加至區間,並納入遙測資料中。代理程式回應也會納入記錄項目,這些項目與包含生成式 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-loggingopentelemetry-exporter-gcp-monitoring 程式庫會在這些 API 中叫用端點。

追蹤資料會使用支援 OTLP 格式的 Telemetry (OTLP) API 傳送至 Google Cloud 。透過這個端點收到的資料也會以 OTLP 格式儲存。opentelemetry-exporter-otlp-proto-grpc 程式庫會叫用遙測 (OTLP) API 端點。

設定 OpenTelemetry 收集及傳送遙測資料

在 LangGraph 代理程式的初始化程式碼中,設定 OpenTelemetry 以擷取並傳送遙測資料至 Google Cloud 專案:

如要查看完整範例,請按一下 「更多」,然後選取「前往 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 代理程式是 SQL 專家,可完全存取暫時性 SQLite 資料庫。這個代理程式是使用 LangGraph 預先建構的 ReAct Agent 實作,並使用 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 Explorer」頁面:

  1. 前往 Google Cloud 控制台的「Trace Explorer」頁面:

    前往「Trace Explorer」頁面

    您也可以透過搜尋列找到這個頁面。

  2. 在工具列中,依序選取「新增篩選器」和「Span 名稱」,然後選取 invoke agent

    「Run sample」部分包含執行範例,其中會將兩個提示傳送至應用程式。以下是篩選資料後的「Trace Explorer」頁面:

    顯示追蹤時距。

    如果您從未使用過 Cloud Trace,Google Cloud Observability 就需要建立資料庫來儲存追蹤記錄資料。建立資料庫可能需要幾分鐘的時間,在這段期間,您無法查看追蹤記錄資料。

  3. 如要探索時距和記錄資料,請在「時距」表格中選取所需時距。

    「Details」頁面隨即開啟。這個頁面會顯示相關聯的追蹤記錄及其跨距。頁面上的表格會顯示所選區間的詳細資訊。這項資訊包括:

    • 「GenAI」GenAI分頁會顯示生成式 AI 代理程式的事件。如要進一步瞭解這些事件,請參閱「查看生成式 AI 事件」一文。

      下圖為追蹤記錄,其中一個跨度名稱為 invoke_agent。該時間間隔會叫用 Gemini。Gemini 時距包含生成式 AI 事件:

      顯示生成式 AI 事件。

    • 「Logs & Events」分頁會列出與時距相關聯的記錄項目和事件。如要在記錄檔探索工具中查看記錄資料,請在這個分頁的工具列中選取「查看記錄檔」

      記錄資料包含 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 專案,但不會產生任何指標。