使用 OpenTelemetry 檢測 LangGraph ReAct 代理

本文將說明如何使用 OpenTelemetry 檢測 LangGraph ReAct Agent,以便從該 Agent 收集遙測資料。使用者提示、代理程式回覆和選項會以附加至範圍的屬性形式,納入遙測資料。與包含生成式 AI 事件的範圍相關聯的記錄項目,也會包含代理程式回覆。如果代理程式使用 Langchain 的 ChatVertexAI 呼叫 Gemini 模型,請按照本文中的操作說明進行。

檢測生成式 AI 應用程式,收集遙測資料

如要為生成式 AI 應用程式進行檢測,以收集記錄、指標和追蹤資料,請執行下列操作:

  1. 安裝 OpenTelemetry 套件
  2. 設定 OpenTelemetry,收集及傳送遙測資料
  3. 追蹤生成式 AI 虛擬服務專員的呼叫

安裝 OpenTelemetry 套件

新增下列 OpenTelemetry 檢測和匯出工具套件:

pip install 'opentelemetry-instrumentation-vertexai>=2.0b0' \
  'opentelemetry-instrumentation-sqlite3' \
  '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 格式的遙測 (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 代理程式實作,並使用 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/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 >>」(與 SQL 代理程式對話 >>) 提示中輸入值,然後按下 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

    8. 生成式 AI 代理程式執行的動作並非確定性,因此即使輸入相同的提示,回覆內容也可能不同。

      查看追蹤記錄、指標和記錄

      本節說明如何查看生成式 AI 事件。

      事前準備

      如要取得查看記錄、指標和追蹤資料所需的權限,請要求管理員為您授予專案的下列 IAM 角色:

      如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

      您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

      查看遙測資料

      如要查看生成式 AI 事件,請使用「Trace Explorer」頁面:

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

        前往「Trace Explorer」頁面

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

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

        「執行範例」一節包含範例執行作業,其中兩個提示會傳送至應用程式。下圖顯示篩選資料後的「追蹤記錄探索工具」頁面:

        顯示追蹤記錄時距。

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

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

        「詳細資料」頁面隨即開啟。這個頁面會顯示相關聯的追蹤記錄及其範圍。頁面上的表格會顯示所選時間範圍的詳細資訊。這類資訊包括:

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

          下圖顯示追蹤記錄,其中一個範圍的名稱為 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 專案,但不會產生任何指標。