|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""LangGraph + manual handler instrumentation example. |
| 3 | +
|
| 4 | +Demonstrates combining auto-instrumented LangGraph agent spans with manual |
| 5 | +handler.start_tool_call() / handler.start_step() calls inside async node |
| 6 | +bodies. All spans end up on the same trace with correct parent-child |
| 7 | +relationships. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + # Start an OTel collector on localhost:4317, then: |
| 11 | + export OTEL_SERVICE_NAME=langgraph-manual-demo |
| 12 | + export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 |
| 13 | + export OTEL_EXPORTER_OTLP_PROTOCOL=grpc |
| 14 | + export OTEL_INSTRUMENTATION_GENAI_EMITTERS=span_metric_event |
| 15 | + export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true |
| 16 | + python langgraph_manual_tool_calls.py |
| 17 | +""" |
| 18 | + |
| 19 | +import asyncio |
| 20 | + |
| 21 | +from opentelemetry import _events, _logs, metrics, trace |
| 22 | +from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter |
| 23 | +from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter |
| 24 | +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter |
| 25 | +from opentelemetry.sdk._events import EventLoggerProvider |
| 26 | +from opentelemetry.sdk._logs import LoggerProvider |
| 27 | +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor |
| 28 | +from opentelemetry.sdk.metrics import MeterProvider |
| 29 | +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader |
| 30 | +from opentelemetry.sdk.trace import TracerProvider |
| 31 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 32 | + |
| 33 | + |
| 34 | +def configure_instrumentation(): |
| 35 | + """Set up OTel providers and SDOT instrumentors.""" |
| 36 | + trace.set_tracer_provider(TracerProvider()) |
| 37 | + trace.get_tracer_provider().add_span_processor( |
| 38 | + BatchSpanProcessor(OTLPSpanExporter()) |
| 39 | + ) |
| 40 | + reader = PeriodicExportingMetricReader(OTLPMetricExporter()) |
| 41 | + metrics.set_meter_provider(MeterProvider(metric_readers=[reader])) |
| 42 | + _logs.set_logger_provider(LoggerProvider()) |
| 43 | + _logs.get_logger_provider().add_log_record_processor( |
| 44 | + BatchLogRecordProcessor(OTLPLogExporter()) |
| 45 | + ) |
| 46 | + _events.set_event_logger_provider(EventLoggerProvider()) |
| 47 | + |
| 48 | + from opentelemetry.instrumentation.langchain import LangchainInstrumentor |
| 49 | + |
| 50 | + LangchainInstrumentor().instrument() |
| 51 | + |
| 52 | + |
| 53 | +# Must be called before importing LangGraph / LangChain |
| 54 | +configure_instrumentation() |
| 55 | + |
| 56 | +from typing import TypedDict # noqa: E402 |
| 57 | + |
| 58 | +from langgraph.graph import StateGraph # noqa: E402 |
| 59 | +from opentelemetry.util.genai.handler import get_telemetry_handler # noqa: E402 |
| 60 | +from opentelemetry.util.genai.types import ToolCall, Step # noqa: E402 |
| 61 | + |
| 62 | + |
| 63 | +class State(TypedDict): |
| 64 | + query: str |
| 65 | + result: str |
| 66 | + |
| 67 | + |
| 68 | +# -- Async node functions with manual tool/step instrumentation -- |
| 69 | + |
| 70 | + |
| 71 | +async def lookup_node(state: State) -> State: |
| 72 | + """Async node: looks up data using a manual ToolCall span.""" |
| 73 | + handler = get_telemetry_handler() |
| 74 | + |
| 75 | + # Create a manual ToolCall — the handler automatically parents it |
| 76 | + # to the current agent span (even inside LangGraph async nodes). |
| 77 | + tool = ToolCall( |
| 78 | + name="database_lookup", |
| 79 | + tool_type="datastore", |
| 80 | + tool_description="Look up customer record in database", |
| 81 | + arguments={"query": state["query"]}, |
| 82 | + agent_name="lookup-agent", |
| 83 | + ) |
| 84 | + handler.start_tool_call(tool) |
| 85 | + |
| 86 | + # Simulate database query |
| 87 | + await asyncio.sleep(0.05) |
| 88 | + result = f"Found record for: {state['query']}" |
| 89 | + |
| 90 | + tool.tool_result = result |
| 91 | + handler.stop_tool_call(tool) |
| 92 | + |
| 93 | + return {"query": state["query"], "result": result} |
| 94 | + |
| 95 | + |
| 96 | +async def analysis_node(state: State) -> State: |
| 97 | + """Async node: analyses data using a manual Step span.""" |
| 98 | + handler = get_telemetry_handler() |
| 99 | + |
| 100 | + step = Step( |
| 101 | + name="sentiment_analysis", |
| 102 | + objective="Analyse sentiment of the query", |
| 103 | + step_type="processing", |
| 104 | + source="agent", |
| 105 | + assigned_agent="analysis-agent", |
| 106 | + ) |
| 107 | + handler.start_step(step) |
| 108 | + |
| 109 | + await asyncio.sleep(0.03) |
| 110 | + analysis = f"Analysis complete for: {state['result']}" |
| 111 | + |
| 112 | + handler.stop_step(step) |
| 113 | + |
| 114 | + return {"query": state["query"], "result": analysis} |
| 115 | + |
| 116 | + |
| 117 | +async def main(): |
| 118 | + builder = StateGraph(State) |
| 119 | + |
| 120 | + # metadata={"agent_name": ...} makes the auto-instrumented span carry |
| 121 | + # gen_ai.agent.name, and enables the handler's agent context stack. |
| 122 | + builder.add_node("lookup", lookup_node, metadata={"agent_name": "lookup-agent"}) |
| 123 | + builder.add_node( |
| 124 | + "analysis", analysis_node, metadata={"agent_name": "analysis-agent"} |
| 125 | + ) |
| 126 | + builder.add_edge("__start__", "lookup") |
| 127 | + builder.add_edge("lookup", "analysis") |
| 128 | + builder.add_edge("analysis", "__end__") |
| 129 | + |
| 130 | + graph = builder.compile() |
| 131 | + |
| 132 | + result = await graph.ainvoke({"query": "customer 42 order status", "result": ""}) |
| 133 | + print(f"Result: {result['result']}") |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + try: |
| 138 | + asyncio.run(main()) |
| 139 | + finally: |
| 140 | + # Flush all providers before exit |
| 141 | + try: |
| 142 | + trace.get_tracer_provider().force_flush(timeout_millis=5000) |
| 143 | + except Exception: |
| 144 | + pass |
| 145 | + try: |
| 146 | + metrics.get_meter_provider().force_flush(timeout_millis=5000) |
| 147 | + except Exception: |
| 148 | + pass |
| 149 | + try: |
| 150 | + _logs.get_logger_provider().force_flush(timeout_millis=5000) |
| 151 | + except Exception: |
| 152 | + pass |
0 commit comments