使用 OpenTelemetry 对 LangGraph ReAct 智能体进行插桩

本文档概述了如何使用 OpenTelemetry 对 LangGraph ReAct 智能体进行插桩,从而从智能体收集遥测数据。用户提示、智能体回答和选择项作为附加到 span 的属性包含在遥测数据中。与包含生成式 AI 事件的 span 相关联的日志条目中也会包含智能体回答。当智能体使用 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 智能体调用的执行情况,请围绕智能体调用创建自定义 span:

如需查看完整示例,请点击 更多,然后选择在 GitHub 上查看

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

您可能需要将上述代码添加到应用代码中的关键位置。

如需详细了解如何添加自定义 span 和指标,请参阅向应用添加自定义跟踪记录和指标

运行示例

此示例是一个使用 OpenTelemetry 插桩的 LangGraph 智能体,用于将包含生成式 AI 提示和回答以及指标的跟踪记录和日志发送到您的Google Cloud 项目。

LangGraph 智能体角色

LangGraph 智能体定义为可完全访问临时 SQLite 数据库的 SQL 专家。该智能体使用 LangGraph 预构建的 ReAct 智能体实现,并使用 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. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 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. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 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/langgraph-sql-agent
      
    3. 配置环境变量:

      # 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
      
    4. 创建虚拟环境并运行示例:

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

      应用会显示类似以下内容的消息:

      Starting agent using ephemeral SQLite DB.
      
    5. 如需创建数据库,请在 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
      );
      
      
    6. 如需退出,请输入 Ctrl-C

    生成式 AI 智能体执行的操作不是确定性的,因此您可能会看到针对同一提示的不同回答。

    查看跟踪记录、指标和日志

    本部分介绍如何查看生成式 AI 事件。

    准备工作

    如需获得查看日志、指标和跟踪记录数据所需的权限,请让管理员为您授予项目的以下 IAM 角色:

    如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

    查看遥测数据

    如需查看生成式 AI 事件,请使用 Trace 探索器页面:

    1. 在 Google Cloud 控制台中,前往 Trace 探索器页面:

      转到 Trace 探索器

      您也可以使用搜索栏查找此页面。

    2. 在工具栏中,依次选择添加过滤条件Span 名称invoke agent

      运行示例部分包含一个执行示例,其中向应用发送了两个提示。下面展示了过滤数据后的 Trace 探索器页面:

      显示跟踪记录 span。

      如果您之前从未使用过 Cloud Trace,Google Cloud Observability 需要创建一个数据库来存储跟踪记录数据。创建数据库可能需要几分钟时间,在此期间,您无法查看任何跟踪记录数据。

    3. 如需浏览 span 和日志数据,请在 Span 表格中选择 span。

      系统会打开详细信息页面。此页面会显示关联的跟踪记录及其 span。页面上的表格会显示您所选 span 的详细信息。这些信息包括:

      • GenAI 标签页会显示生成式 AI 智能体的事件。如需详细了解这些事件,请参阅查看生成式 AI 事件

        以下屏幕截图展示了一条跟踪记录,其中一个 span 的名称为 invoke_agent。该 span 会调用 Gemini。 Gemini span 包含以下生成式 AI 事件:

        显示生成式 AI 事件。

      • 日志和事件标签页会列出与该 span 关联的日志条目和事件。如果您想在 Logs Explorer 中查看日志数据,请在该标签页的工具栏中选择查看日志

        日志数据包含 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 项目,但不会生成任何指标。