Menginstrumentasikan Agen ReAct LangGraph dengan OpenTelemetry

Dokumen ini menguraikan langkah-langkah untuk melengkapi Agen ReAct LangGraph dengan OpenTelemetry, sehingga memungkinkan pengumpulan telemetri dari agen. Perintah pengguna serta respons dan pilihan agen disertakan dalam telemetri sebagai atribut yang dilampirkan ke rentang. Respons agen juga disertakan dalam entri log yang dikorelasikan dengan rentang yang berisi peristiwa AI generatif. Petunjuk dalam dokumen ini berlaku saat agen menggunakan ChatVertexAI Langchain untuk memanggil model Gemini.

Melengkapi aplikasi AI generatif Anda untuk mengumpulkan telemetri

Untuk menginstrumentasi aplikasi AI generatif Anda guna mengumpulkan data log, metrik, dan aktivitas, lakukan hal berikut:

  1. Instal paket OpenTelemetry
  2. Mengonfigurasi OpenTelemetry untuk mengumpulkan dan mengirim telemetri
  3. Melacak pemanggilan agen AI generatif

Menginstal paket OpenTelemetry

Tambahkan paket instrumentasi dan pengekspor OpenTelemetry berikut:

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

Data log dan metrik dikirim ke project Google Cloud Anda menggunakan Cloud Logging API atau Cloud Monitoring API. Library opentelemetry-exporter-gcp-logging dan opentelemetry-exporter-gcp-monitoring memanggil endpoint di API tersebut.

Data trace dikirim ke Google Cloud menggunakan Telemetry (OTLP) API, yang mendukung format OTLP. Data yang diterima melalui endpoint ini juga disimpan dalam format OTLP. Library opentelemetry-exporter-otlp-proto-grpc memanggil endpoint Telemetry (OTLP) API.

Mengonfigurasi OpenTelemetry untuk mengumpulkan dan mengirim telemetri

Dalam kode inisialisasi agen LangGraph, konfigurasi OpenTelemetry untuk mengambil dan mengirim telemetri ke project Google Cloud Anda:

Untuk melihat contoh lengkap, klik Lainnya, lalu pilih Lihat di 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()

Melacak pemanggilan agen AI generatif

Untuk melacak eksekusi pemanggilan agen LangGraph, buat rentang kustom di sekitar pemanggilan agen:

Untuk melihat contoh lengkap, klik Lainnya, lalu pilih Lihat di GitHub.

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

Anda mungkin ingin menyertakan kode sebelumnya di tempat-tempat penting dalam kode aplikasi Anda.

Untuk mempelajari lebih lanjut cara menambahkan rentang dan metrik kustom, lihat Menambahkan rekaman aktivitas dan metrik kustom ke aplikasi Anda.

Menjalankan contoh

Contoh ini adalah agen LangGraph yang dilengkapi dengan OpenTelemetry untuk mengirimkan trace dan log dengan perintah dan respons AI generatif, serta metrik ke project Google Cloud Anda.

Persona agen LangGraph

Agen LangGraph ditentukan sebagai pakar SQL yang memiliki akses penuh ke database SQLite sementara. Agen diimplementasikan dengan Agen ReAct bawaan LangGraph dan mengakses database, yang awalnya kosong, menggunakan SQLDatabaseToolkit.

Sebelum memulai

  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. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  4. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    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. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  10. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    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. Jika Anda menjalankan sampel di Cloud Shell, di Google Cloud resource, atau di lingkungan pengembangan lokal, izin yang tercantum di bagian ini sudah cukup. Untuk aplikasi produksi, biasanya akun layanan menyediakan kredensial untuk menulis data log, metrik, dan trace.

    Untuk mendapatkan izin yang Anda perlukan agar aplikasi contoh dapat menulis data log, metrik, dan rekaman aktivitas, minta administrator Anda untuk memberi Anda peran IAM berikut di project Anda:

  15. Jalankan contoh

    Untuk menjalankan contoh, lakukan hal berikut:

    1. Di Cloud Shell, jalankan perintah berikut:

      git clone https://github.com/GoogleCloudPlatform/opentelemetry-operations-python.git
      
    2. Buka direktori contoh:

      cd opentelemetry-operations-python/samples/langgraph-sql-agent
      
    3. Konfigurasi variabel lingkungan:

      # 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. Buat lingkungan virtual dan jalankan contoh:

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

      Aplikasi akan menampilkan pesan yang mirip dengan berikut ini:

      Starting agent using ephemeral SQLite DB.
      
    5. Untuk membuat database, masukkan nilai pada perintah Talk to the SQL agent >>, lalu tekan Enter.

      Tindakan yang dilakukan oleh agen kemudian ditampilkan di Cloud Shell Anda.

      Berikut ini menggambarkan contoh interaksi antara pengguna dan aplikasi:

      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. Untuk keluar, masukkan Ctrl-C.

    Tindakan yang dilakukan oleh agen AI generatif tidak deterministik, sehingga Anda mungkin melihat respons yang berbeda untuk perintah yang sama.

    Melihat rekaman aktivitas, metrik, dan log

    Bagian ini menjelaskan cara melihat peristiwa AI generatif.

    Sebelum memulai

    Untuk mendapatkan izin yang Anda perlukan guna melihat data log, metrik, dan rekaman aktivitas, minta administrator Anda untuk memberi Anda peran IAM berikut di project Anda:

    Untuk mengetahui informasi selengkapnya tentang pemberian peran, lihat Mengelola akses ke project, folder, dan organisasi.

    Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran kustom atau peran yang telah ditentukan lainnya.

    Melihat telemetri

    Untuk melihat peristiwa AI generatif, gunakan halaman Trace Explorer:

    1. Di konsol Google Cloud , buka halaman Trace explorer:

      Buka Trace explorer

      Anda juga dapat menemukan halaman ini dengan menggunakan kotak penelusuran.

    2. Di toolbar, pilih Tambahkan filter, pilih Nama rentang, lalu pilih invoke agent.

      Bagian Jalankan sampel menyertakan contoh eksekusi saat dua perintah dikirim ke aplikasi. Berikut ini menggambarkan halaman Trace Explorer setelah memfilter data:

      Tampilan rentang aktivitas.

      Jika Anda belum pernah menggunakan Cloud Trace, Google Cloud Observability perlu membuat database untuk menyimpan data rekaman aktivitas Anda. Pembuatan database dapat memerlukan waktu beberapa menit dan selama periode tersebut, tidak ada data rekaman aktivitas yang tersedia untuk dilihat.

    3. Untuk menjelajahi data rentang dan log, di tabel Rentang, pilih rentang.

      Halaman Detail akan terbuka. Halaman ini menampilkan rekaman aktivitas terkait dan rentang waktunya. Tabel di halaman menampilkan informasi mendetail untuk rentang yang Anda pilih. Informasi ini mencakup hal berikut:

      • Tab GenAI menampilkan peristiwa untuk agen AI generatif. Untuk mempelajari peristiwa ini lebih lanjut, lihat artikel Melihat peristiwa AI generatif.

        Screenshot berikut mengilustrasikan rekaman aktivitas, dengan satu rentang memiliki nama invoke_agent. Rentang tersebut memanggil Gemini. Rentang Gemini mencakup peristiwa AI generatif:

        Menampilkan peristiwa AI generatif.

      • Tab Log & Peristiwa mencantumkan entri log dan peristiwa yang terkait dengan rentang. Jika Anda ingin melihat data log di Logs Explorer, pilih Lihat log di toolbar tab ini.

        Data log mencakup respons agen LangGraph. Misalnya, untuk contoh run, payload JSON mencakup konten berikut:

        {
          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
          }
        ...
        }
        

    Contoh diinstrumentasikan untuk mengirim data metrik ke project Google Cloud Anda, tetapi tidak menghasilkan metrik apa pun.