Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: Update instrumentation for langgraph (#982)
Ishan Jain71a3c64acc79
diff --git a/langgraph_methods_report.md b/langgraph_methods_report.mdnew file mode 100644index 00000000..e91b7577--- /dev/null+++ b/langgraph_methods_report.md@@ -0,0 +1,68 @@+# LangGraph Methods Report++**Project:** AI Agent Core+**LangGraph:** 0.6.6 | **Checkpoint:** langgraph-checkpoint-postgres 2.0.23++---++## Graph Structure++```+START → extract_user_query → retrieve_rag_documents → plan_troubleshooting_steps+ → classify_user_intent → process_user_intent → generate_model_response → END+```++---++## Methods Used++### Imports++| Import | File |+|--------|------|+| `StateGraph`, `START`, `END` | `app/infrastructure/agent/graph.py:13` |+| `add_messages` | `app/infrastructure/agent/initial_state.py:10` |+| `AsyncPostgresSaver` | `app/main.py:23` |++### Graph Construction++| Method | Location |+|--------|----------|+| `StateGraph(State)` | `graph.py:38` |+| `.add_node()` | `graph.py:41-46` |+| `.add_edge()` | `graph.py:49-55` |+| `.compile(checkpointer)` | `graph.py:58` |++### Graph Execution++| Method | Location | Mode |+|--------|----------|------|+| `.ainvoke()` | `agent.py:83` | Sync execution |+| `.astream()` | `agent.py:124` | Streaming (`stream_mode="messages"`) |+| `.aget_state()` | `agent.py:69,105` / `message.py:93,224,274` | State retrieval |++### Checkpointing++| Method | Location |+|--------|----------|+| `AsyncPostgresSaver(conn)` | `main.py:73` |+| `.setup()` | `main.py:77` |++### State Reducers++| Reducer | Field |+|---------|-------|+| `add_messages` (langgraph) | `messages` |+| `add_last_3` (custom) | `user_intents` |++---++## Instrumentation Targets++| Target | File | Metrics |+|--------|------|---------|+| `ainvoke()` | `agent.py:83` | Latency, tokens |+| `astream()` | `agent.py:124` | TTFT, chunk count |+| `aget_state()` | `agent.py:69` | Retrieval latency |+| `AsyncPostgresSaver` | `main.py:73` | Write latency |+| Node functions (6) | `graph.py:41-46` | Per-node execution time |diff --git a/sdk/python/.pylintrc b/sdk/python/.pylintrcindex bcd02921..ccb952b3 100644--- a/sdk/python/.pylintrc+++ b/sdk/python/.pylintrc@@ -38,6 +38,6 @@ disable=too-many-public-methods,unnecessary-pass,invalid-name,- import-error-+ import-error,+ too-many-nested-blocksdiff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex 49fb1a37..519d7e8c 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.36.5"+version = "1.36.6"description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"authors = ["OpenLIT"]license = "Apache-2.0"diff --git a/sdk/python/src/openlit/_instrumentors.py b/sdk/python/src/openlit/_instrumentors.pyindex 826e4ae4..78eb366f 100644--- a/sdk/python/src/openlit/_instrumentors.py+++ b/sdk/python/src/openlit/_instrumentors.py@@ -21,6 +21,7 @@ MODULE_NAME_MAP = {"google-ai-studio": "google.genai","azure-ai-inference": "azure.ai.inference","langchain": "langchain_core",+ "langgraph": "langgraph","llama_index": "llama_index","haystack": "haystack","mem0": "mem0",@@ -87,6 +88,7 @@ INSTRUMENTOR_MAP = {"google-ai-studio": "openlit.instrumentation.google_ai_studio.GoogleAIStudioInstrumentor","azure-ai-inference": "openlit.instrumentation.azure_ai_inference.AzureAIInferenceInstrumentor","langchain": "openlit.instrumentation.langchain.LangChainInstrumentor",+ "langgraph": "openlit.instrumentation.langgraph.LangGraphInstrumentor","llama_index": "openlit.instrumentation.llamaindex.LlamaIndexInstrumentor","haystack": "openlit.instrumentation.haystack.HaystackInstrumentor","mem0": "openlit.instrumentation.mem0.Mem0Instrumentor",diff --git a/sdk/python/src/openlit/instrumentation/langgraph/__init__.py b/sdk/python/src/openlit/instrumentation/langgraph/__init__.pynew file mode 100644index 00000000..f472c68f--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/langgraph/__init__.py@@ -0,0 +1,410 @@+"""+OpenLIT LangGraph Instrumentation++Provides comprehensive instrumentation for LangGraph applications including:+- Graph construction (StateGraph, compile, add_node, add_edge)+- Graph execution (invoke, ainvoke, stream, astream)+- State management (get_state, aget_state)+- Checkpointing (AsyncPostgresSaver, PostgresSaver)+"""++from typing import Collection+import importlib.metadata+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor+from wrapt import wrap_function_wrapper++from openlit.instrumentation.langgraph.langgraph import (+ general_wrap,+ wrap_compile,+ wrap_add_node,+)+from openlit.instrumentation.langgraph.async_langgraph import (+ async_general_wrap,+ async_checkpoint_wrap,+)++_instruments = ("langgraph >= 0.0.1",)++# === GRAPH EXECUTION OPERATIONS (Always enabled) ===+# These are the core operations users will want to trace+EXECUTION_OPERATIONS = [+ # Sync execution+ ("langgraph.pregel", "Pregel.invoke", "graph_invoke", "sync"),+ ("langgraph.pregel", "Pregel.stream", "graph_stream", "sync"),+ ("langgraph.pregel", "Pregel.get_state", "graph_get_state", "sync"),+ # Async execution+ ("langgraph.pregel", "Pregel.ainvoke", "graph_ainvoke", "async"),+ ("langgraph.pregel", "Pregel.astream", "graph_astream", "async"),+ ("langgraph.pregel", "Pregel.aget_state", "graph_aget_state", "async"),+]++# Alternative module paths for different LangGraph versions+EXECUTION_OPERATIONS_ALT = [+ # Some versions use langgraph.pregel.main+ ("langgraph.pregel.main", "Pregel.invoke", "graph_invoke", "sync"),+ ("langgraph.pregel.main", "Pregel.stream", "graph_stream", "sync"),+ ("langgraph.pregel.main", "Pregel.get_state", "graph_get_state", "sync"),+ ("langgraph.pregel.main", "Pregel.ainvoke", "graph_ainvoke", "async"),+ ("langgraph.pregel.main", "Pregel.astream", "graph_astream", "async"),+ ("langgraph.pregel.main", "Pregel.aget_state", "graph_aget_state", "async"),+]++# === GRAPH CONSTRUCTION OPERATIONS (Detailed tracing only) ===+CONSTRUCTION_OPERATIONS = [+ ("langgraph.graph.state", "StateGraph.__init__", "graph_init", "sync"),+ ("langgraph.graph.state", "StateGraph.add_node", "graph_add_node", "special"),+ ("langgraph.graph.state", "StateGraph.add_edge", "graph_add_edge", "sync"),+ ("langgraph.graph.state", "StateGraph.compile", "graph_compile", "special"),+]++# === CHECKPOINTING OPERATIONS (Detailed tracing only) ===+CHECKPOINT_OPERATIONS = [+ # Async PostgresSaver+ (+ "langgraph.checkpoint.postgres.aio",+ "AsyncPostgresSaver.setup",+ "checkpoint_setup",+ "async",+ ),+ (+ "langgraph.checkpoint.postgres.aio",+ "AsyncPostgresSaver.aput",+ "checkpoint_write",+ "async",+ ),+ (+ "langgraph.checkpoint.postgres.aio",+ "AsyncPostgresSaver.aget_tuple",+ "checkpoint_read",+ "async",+ ),+ # Sync PostgresSaver+ (+ "langgraph.checkpoint.postgres",+ "PostgresSaver.setup",+ "checkpoint_setup",+ "sync",+ ),+ ("langgraph.checkpoint.postgres", "PostgresSaver.put", "checkpoint_write", "sync"),+ (+ "langgraph.checkpoint.postgres",+ "PostgresSaver.get_tuple",+ "checkpoint_read",+ "sync",+ ),+]+++class LangGraphInstrumentor(BaseInstrumentor):+ """+ OpenLIT LangGraph instrumentor with comprehensive coverage.++ Features:+ - Graph execution tracing (invoke, stream, get_state)+ - Async support (ainvoke, astream, aget_state)+ - Per-node instrumentation via add_node wrapping+ - Graph structure capture on compile+ - Checkpointer instrumentation+ - Message and token tracking+ - LLM info extraction from node results+ """++ def instrumentation_dependencies(self) -> Collection[str]:+ return _instruments++ def _instrument(self, **kwargs):+ """Instrument LangGraph."""+ try:+ version = importlib.metadata.version("langgraph")+ except importlib.metadata.PackageNotFoundError:+ version = "unknown"++ environment = kwargs.get("environment", "default")+ application_name = kwargs.get("application_name", "default")+ tracer = kwargs.get("tracer")+ pricing_info = kwargs.get("pricing_info", {})+ capture_message_content = kwargs.get("capture_message_content", False)+ metrics = kwargs.get("metrics_dict")+ disable_metrics = kwargs.get("disable_metrics", False)+ detailed_tracing = kwargs.get("detailed_tracing", False)++ # === EXECUTION OPERATIONS (Always enabled) ===+ self._wrap_execution_operations(+ EXECUTION_OPERATIONS,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # Try alternative module paths+ self._wrap_execution_operations(+ EXECUTION_OPERATIONS_ALT,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # === CONSTRUCTION OPERATIONS (Detailed tracing or always for key operations) ===+ if detailed_tracing:+ self._wrap_construction_operations(+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ # Always wrap compile and add_node for graph structure and per-node tracing+ self._wrap_key_construction_operations(+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # === CHECKPOINTING OPERATIONS (Detailed tracing only) ===+ if detailed_tracing:+ self._wrap_checkpoint_operations(+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ def _wrap_execution_operations(+ self,+ operations,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ):+ """Wrap graph execution operations."""+ for module, method, operation_type, sync_type in operations:+ try:+ if sync_type == "async":+ wrapper = async_general_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ wrapper = general_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ wrap_function_wrapper(module, method, wrapper)+ except Exception:+ # Graceful degradation if module/method doesn't exist+ pass++ def _wrap_construction_operations(+ self,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ):+ """Wrap all graph construction operations."""+ for module, method, operation_type, sync_type in CONSTRUCTION_OPERATIONS:+ try:+ if sync_type == "special":+ if "compile" in method:+ wrapper = wrap_compile(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ elif "add_node" in method:+ wrapper = wrap_add_node(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ wrapper = general_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ wrapper = general_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ wrap_function_wrapper(module, method, wrapper)+ except Exception:+ pass++ def _wrap_key_construction_operations(+ self,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ):+ """Wrap only key construction operations (compile and add_node)."""+ key_operations = [+ (+ "langgraph.graph.state",+ "StateGraph.add_node",+ "graph_add_node",+ "special",+ ),+ ("langgraph.graph.state", "StateGraph.compile", "graph_compile", "special"),+ ]++ for module, method, operation_type, _ in key_operations:+ try:+ if "compile" in method:+ wrapper = wrap_compile(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ elif "add_node" in method:+ wrapper = wrap_add_node(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ continue++ wrap_function_wrapper(module, method, wrapper)+ except Exception:+ pass++ def _wrap_checkpoint_operations(+ self,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ ):+ """Wrap checkpointing operations."""+ for module, method, operation_type, sync_type in CHECKPOINT_OPERATIONS:+ try:+ if sync_type == "async":+ wrapper = async_checkpoint_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )+ else:+ wrapper = general_wrap(+ operation_type,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ wrap_function_wrapper(module, method, wrapper)+ except Exception:+ pass++ def _uninstrument(self, **kwargs):+ """Remove instrumentation."""+ # Note: Full uninstrumentation would require tracking all wrapped functions+ # For now, this is a placeholder+ passdiff --git a/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.py b/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.pynew file mode 100644index 00000000..0b0656dc--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.py@@ -0,0 +1,491 @@+"""+LangGraph async wrapper for instrumentation+"""++import time+import json+from opentelemetry.trace import SpanKind, Status, StatusCode+from opentelemetry import context as context_api+from openlit.__helpers import handle_exception+from openlit.instrumentation.langgraph.utils import (+ process_langgraph_response,+ OPERATION_MAP,+ set_server_address_and_port,+ generate_span_name,+ extract_messages_from_input,+ get_message_content,+ get_message_role,+ extract_config_info,+ SemanticConvention,+)+++def async_general_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Creates a wrapper for async LangGraph operations.++ Args:+ gen_ai_endpoint: The endpoint being wrapped (e.g., "graph_ainvoke")+ version: SDK version+ environment: Deployment environment+ application_name: Application name+ tracer: OpenTelemetry tracer+ pricing_info: Pricing information for cost calculation+ capture_message_content: Whether to capture message content+ metrics: Metrics registry+ disable_metrics: Whether metrics are disabled++ Returns:+ Async wrapper function+ """++ # For astream, we need a sync wrapper that returns an async generator+ if gen_ai_endpoint == "graph_astream":++ def astream_wrapper(wrapped, instance, args, kwargs):+ """+ Wraps the astream method - returns an async generator wrapper.+ """+ # Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Get server address and port+ server_address, server_port = set_server_address_and_port(instance)++ # Get operation type+ operation_type = OPERATION_MAP.get(+ gen_ai_endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )++ # Generate span name+ span_name = generate_span_name(+ operation_type, gen_ai_endpoint, instance, args, kwargs+ )++ # Return an async generator wrapper+ return _create_async_stream_wrapper(+ wrapped,+ instance,+ args,+ kwargs,+ span_name,+ tracer,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ gen_ai_endpoint,+ )++ return astream_wrapper++ # For other async operations (ainvoke, aget_state), use async wrapper+ async def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps the async LangGraph operation with telemetry.+ """+ # Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ # Get server address and port+ server_address, server_port = set_server_address_and_port(instance)++ # Get operation type+ operation_type = OPERATION_MAP.get(+ gen_ai_endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )++ # Generate span name+ span_name = generate_span_name(+ operation_type, gen_ai_endpoint, instance, args, kwargs+ )++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ try:+ # Execute the wrapped async function+ response = await wrapped(*args, **kwargs)++ # Process response+ response = process_langgraph_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ return response++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapper+++async def _create_async_stream_wrapper(+ wrapped,+ instance,+ args,+ kwargs,+ span_name,+ tracer,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ endpoint,+):+ """+ Creates an async generator wrapper for astream.+ """+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set basic attributes+ span.set_attribute("telemetry.sdk.name", "openlit")+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH+ )+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, "unknown")+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)+ span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)+ span.set_attribute(SemanticConvention.GEN_AI_APPLICATION_NAME, application_name)+ span.set_attribute(SemanticConvention.LANGGRAPH_EXECUTION_MODE, "stream")+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM, True)++ # Extract stream mode from kwargs+ stream_mode = kwargs.get("stream_mode", "values")+ span.set_attribute(SemanticConvention.LANGGRAPH_STREAM_MODE, str(stream_mode))++ # Track execution state+ execution_state = {+ "executed_nodes": [],+ "message_count": 0,+ "chunk_count": 0,+ "final_response": None,+ "first_token_time": None,+ }++ # Capture input messages+ input_data = args[0] if args else kwargs.get("input", {})+ messages = extract_messages_from_input(input_data)+ if messages:+ execution_state["message_count"] = len(messages)+ if capture_message_content:+ for i, msg in enumerate(messages[:3]):+ content = get_message_content(msg)+ role = get_message_role(msg)+ if content:+ span.set_attribute(f"gen_ai.prompt.{i}.content", content[:500])+ span.set_attribute(f"gen_ai.prompt.{i}.role", role)++ # Extract config information+ config = kwargs.get("config")+ if config:+ config_info = extract_config_info(config)+ if config_info.get("thread_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_THREAD_ID, config_info["thread_id"]+ )+ if config_info.get("checkpoint_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_CHECKPOINT_ID,+ config_info["checkpoint_id"],+ )++ try:+ # Get the async stream - call without await since it returns async generator+ stream_gen = wrapped(*args, **kwargs)++ async for chunk in stream_gen:+ # Track first token time+ if execution_state["first_token_time"] is None:+ execution_state["first_token_time"] = time.time()+ ttft = execution_state["first_token_time"] - start_time+ span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, ttft)++ execution_state["chunk_count"] += 1++ # Process chunk+ _process_stream_chunk(chunk, execution_state, stream_mode)++ yield chunk++ # Set final attributes+ _finalize_async_stream_span(+ span, execution_state, capture_message_content, start_time+ )++ except Exception as e:+ handle_exception(span, e)+ raise+++def _process_stream_chunk(chunk, execution_state, stream_mode):+ """Process a stream chunk and update execution state."""+ try:+ if isinstance(chunk, dict):+ for key in chunk:+ # Track node executions (exclude special keys)+ if key not in ("__start__", "__end__", "__interrupt__", "messages"):+ if key not in execution_state["executed_nodes"]:+ execution_state["executed_nodes"].append(key)++ # Track messages in chunk+ chunk_value = chunk[key]+ if isinstance(chunk_value, dict) and "messages" in chunk_value:+ msg_list = chunk_value["messages"]+ if isinstance(msg_list, list):+ execution_state["message_count"] += len(msg_list)+ for msg in msg_list:+ content = get_message_content(msg)+ if content:+ execution_state["final_response"] = content+ elif key == "messages" and isinstance(chunk_value, list):+ # Direct messages in chunk+ execution_state["message_count"] += len(chunk_value)+ for msg in chunk_value:+ content = get_message_content(msg)+ if content:+ execution_state["final_response"] = content++ # Handle tuple format (node_name, value) for some stream modes+ elif isinstance(chunk, tuple) and len(chunk) >= 2:+ node_name, value = chunk[0], chunk[1]+ if node_name not in ("__start__", "__end__", "__interrupt__"):+ if node_name not in execution_state["executed_nodes"]:+ execution_state["executed_nodes"].append(node_name)++ if isinstance(value, dict) and "messages" in value:+ msg_list = value["messages"]+ if isinstance(msg_list, list):+ execution_state["message_count"] += len(msg_list)+ for msg in msg_list:+ content = get_message_content(msg)+ if content:+ execution_state["final_response"] = content++ except Exception:+ # Don't fail on chunk processing errors+ pass+++def _finalize_async_stream_span(+ span, execution_state, capture_message_content, start_time+):+ """Finalize async stream span with collected telemetry."""+ end_time = time.time()++ # Set execution attributes+ span.set_attribute(+ SemanticConvention.LANGGRAPH_EXECUTED_NODES,+ json.dumps(execution_state["executed_nodes"]),+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_NODE_EXECUTION_COUNT,+ len(execution_state["executed_nodes"]),+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_MESSAGE_COUNT, execution_state["message_count"]+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_CHUNK_COUNT, execution_state["chunk_count"]+ )++ if execution_state["final_response"] and capture_message_content:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_FINAL_RESPONSE,+ execution_state["final_response"][:500],+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_COMPLETION,+ execution_state["final_response"][:1000],+ )++ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_STATUS, "success")+ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION, end_time - start_time+ )+ span.set_status(Status(StatusCode.OK))+++def async_checkpoint_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Creates a wrapper for async checkpointer operations.++ Args:+ gen_ai_endpoint: The endpoint being wrapped (e.g., "checkpoint_setup")+ version: SDK version+ environment: Deployment environment+ application_name: Application name+ tracer: OpenTelemetry tracer+ pricing_info: Pricing information+ capture_message_content: Whether to capture message content+ metrics: Metrics registry+ disable_metrics: Whether metrics are disabled++ Returns:+ Async wrapper function+ """++ async def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps async checkpointer operations with telemetry.+ """+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ operation_type = OPERATION_MAP.get(+ gen_ai_endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )+ span_name = generate_span_name(+ operation_type, gen_ai_endpoint, instance, args, kwargs+ )++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set basic attributes+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM,+ SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ )+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)+ span.set_attribute(+ SemanticConvention.GEN_AI_APPLICATION_NAME, application_name+ )+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)++ try:+ # Execute the wrapped function+ result = await wrapped(*args, **kwargs)++ end_time = time.time()+ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ end_time - start_time,+ )++ # Set checkpoint-specific attributes based on operation+ if gen_ai_endpoint == "checkpoint_write":+ # Extract config info if available+ config = args[0] if args else kwargs.get("config")+ if config:+ config_info = extract_config_info(config)+ if config_info.get("thread_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_THREAD_ID,+ config_info["thread_id"],+ )++ elif gen_ai_endpoint == "checkpoint_read":+ config = args[0] if args else kwargs.get("config")+ if config:+ config_info = extract_config_info(config)+ if config_info.get("thread_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_THREAD_ID,+ config_info["thread_id"],+ )++ # If result has checkpoint info+ if result and hasattr(result, "checkpoint"):+ checkpoint = result.checkpoint+ if checkpoint and hasattr(checkpoint, "id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_CHECKPOINT_ID,+ str(checkpoint.id),+ )++ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_STATUS, "success")+ span.set_status(Status(StatusCode.OK))++ # Record metrics+ if not disable_metrics and metrics:+ _record_checkpoint_metrics(+ metrics,+ operation_type,+ end_time - start_time,+ environment,+ application_name,+ )++ return result++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapper+++def _record_checkpoint_metrics(+ metrics, operation_type, duration, environment, application_name+):+ """Record checkpoint operation metrics."""+ try:+ attributes = {+ "gen_ai.operation.name": operation_type,+ "gen_ai.system": SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ "service.name": application_name,+ "deployment.environment": environment,+ }++ if "genai_client_operation_duration" in metrics:+ metrics["genai_client_operation_duration"].record(duration, attributes)++ if "genai_requests" in metrics:+ metrics["genai_requests"].add(1, attributes)++ except Exception:+ passdiff --git a/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.pynew file mode 100644index 00000000..c66a4f24--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py@@ -0,0 +1,532 @@+"""+LangGraph sync wrapper for instrumentation+"""++import time+from opentelemetry.trace import SpanKind+from opentelemetry import context as context_api+from openlit.__helpers import handle_exception+from openlit.instrumentation.langgraph.utils import (+ process_langgraph_response,+ OPERATION_MAP,+ set_server_address_and_port,+ generate_span_name,+ set_graph_attributes,+ extract_messages_from_input,+ get_message_content,+ get_message_role,+ SemanticConvention,+)+++def general_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Creates a wrapper for sync LangGraph operations.++ Args:+ gen_ai_endpoint: The endpoint being wrapped (e.g., "graph_invoke")+ version: SDK version+ environment: Deployment environment+ application_name: Application name+ tracer: OpenTelemetry tracer+ pricing_info: Pricing information for cost calculation+ capture_message_content: Whether to capture message content+ metrics: Metrics registry+ disable_metrics: Whether metrics are disabled++ Returns:+ Wrapper function+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps the LangGraph operation with telemetry.+ """+ # Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Get server address and port+ server_address, server_port = set_server_address_and_port(instance)++ # Get operation type+ operation_type = OPERATION_MAP.get(+ gen_ai_endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )++ # Generate span name+ span_name = generate_span_name(+ operation_type, gen_ai_endpoint, instance, args, kwargs+ )++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ try:+ # Handle stream operations specially+ if gen_ai_endpoint == "graph_stream":+ return _handle_stream(+ wrapped,+ instance,+ args,+ kwargs,+ span,+ start_time,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ gen_ai_endpoint,+ )++ # Execute the wrapped function+ response = wrapped(*args, **kwargs)++ # Process response+ response = process_langgraph_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ return response++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapper+++def _handle_stream(+ wrapped,+ instance,+ args,+ kwargs,+ span,+ start_time,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ endpoint,+):+ """+ Handle streaming responses with proper telemetry.++ Returns a generator that wraps the stream and captures telemetry.+ """+ # Set basic attributes directly without using common_framework_span_attributes+ # (since we don't have _end_time for streaming until it completes)+ span.set_attribute("telemetry.sdk.name", "openlit")+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH+ )+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, endpoint)+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, "unknown")+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)+ span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)+ span.set_attribute(SemanticConvention.GEN_AI_APPLICATION_NAME, application_name)++ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(SemanticConvention.LANGGRAPH_EXECUTION_MODE, "stream")+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM, True)++ # Track execution state+ execution_state = {+ "executed_nodes": [],+ "message_count": 0,+ "chunk_count": 0,+ "final_response": None,+ }++ # Capture input messages+ input_data = args[0] if args else kwargs.get("input", {})+ messages = extract_messages_from_input(input_data)+ if messages:+ execution_state["message_count"] = len(messages)+ if capture_message_content:+ for i, msg in enumerate(messages[:3]):+ content = get_message_content(msg)+ role = get_message_role(msg)+ if content:+ span.set_attribute(f"gen_ai.prompt.{i}.content", content[:500])+ span.set_attribute(f"gen_ai.prompt.{i}.role", role)++ try:+ # Get the stream+ stream_gen = wrapped(*args, **kwargs)++ def stream_wrapper():+ try:+ for chunk in stream_gen:+ execution_state["chunk_count"] += 1++ # Process chunk+ if isinstance(chunk, dict):+ for key in chunk:+ # Track node executions+ if key not in ("__start__", "__end__", "__interrupt__"):+ if key not in execution_state["executed_nodes"]:+ execution_state["executed_nodes"].append(key)++ # Track messages in chunk+ chunk_value = chunk[key]+ if (+ isinstance(chunk_value, dict)+ and "messages" in chunk_value+ ):+ msg_list = chunk_value["messages"]+ if isinstance(msg_list, list):+ execution_state["message_count"] += len(msg_list)+ for msg in msg_list:+ content = get_message_content(msg)+ if content:+ execution_state["final_response"] = content++ yield chunk++ # Set final attributes+ _finalize_stream_span(+ span, execution_state, capture_message_content, start_time+ )++ except Exception as e:+ handle_exception(span, e)+ raise++ return stream_wrapper()++ except Exception as e:+ handle_exception(span, e)+ raise+++def _finalize_stream_span(span, execution_state, capture_message_content, start_time):+ """Finalize stream span with collected telemetry."""+ import json+ from opentelemetry.trace import Status, StatusCode++ end_time = time.time()++ # Set execution attributes+ span.set_attribute(+ SemanticConvention.LANGGRAPH_EXECUTED_NODES,+ json.dumps(execution_state["executed_nodes"]),+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_NODE_EXECUTION_COUNT,+ len(execution_state["executed_nodes"]),+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_MESSAGE_COUNT, execution_state["message_count"]+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_CHUNK_COUNT, execution_state["chunk_count"]+ )++ if execution_state["final_response"] and capture_message_content:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_FINAL_RESPONSE,+ execution_state["final_response"][:500],+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_COMPLETION,+ execution_state["final_response"][:1000],+ )++ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_STATUS, "success")+ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION, end_time - start_time+ )+ span.set_status(Status(StatusCode.OK))+++def wrap_compile(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Special wrapper for StateGraph.compile that captures graph structure.+ """++ def wrapper(wrapped, instance, args, kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ server_address, server_port = set_server_address_and_port(instance)+ operation_type = OPERATION_MAP.get(+ gen_ai_endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )+ span_name = generate_span_name(+ operation_type, gen_ai_endpoint, instance, args, kwargs+ )++ with tracer.start_as_current_span(span_name, kind=SpanKind.INTERNAL) as span:+ start_time = time.time()++ try:+ # Execute compile+ result = wrapped(*args, **kwargs)++ # Extract graph structure from instance (StateGraph)+ nodes = []+ edges = []++ if hasattr(instance, "nodes"):+ nodes = (+ list(instance.nodes.keys())+ if hasattr(instance.nodes, "keys")+ else []+ )++ if hasattr(instance, "edges"):+ edge_set = instance.edges+ if isinstance(edge_set, set):+ for edge in edge_set:+ if isinstance(edge, tuple) and len(edge) >= 2:+ edges.append(f"{edge[0]}->{edge[1]}")++ # Set graph attributes+ set_graph_attributes(span, nodes, edges)++ # Set common attributes+ from openlit.__helpers import common_framework_span_attributes++ scope = type("GenericScope", (), {})()+ scope._span = span+ scope._start_time = start_time+ scope._end_time = time.time()++ common_framework_span_attributes(+ scope,+ SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ server_address,+ server_port,+ environment,+ application_name,+ version,+ gen_ai_endpoint,+ instance,+ )++ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_STATUS, "success")++ from opentelemetry.trace import Status, StatusCode++ span.set_status(Status(StatusCode.OK))++ return result++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapper+++def wrap_add_node(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Special wrapper for StateGraph.add_node that wraps node functions for per-node tracing.+ """+ import inspect+ from functools import wraps++ def wrapper(wrapped, instance, args, kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Extract node name and action+ if args:+ node_key = args[0]+ action = args[1] if len(args) > 1 else kwargs.get("action")+ else:+ node_key = kwargs.get("node") or kwargs.get("key")+ action = kwargs.get("action")++ if not action:+ return wrapped(*args, **kwargs)++ # Create wrapped node function for instrumentation+ def create_wrapped_node(original_func, node_name):+ if inspect.iscoroutinefunction(original_func):++ @wraps(original_func)+ async def wrapped_node_async(state, *node_args, **node_kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await original_func(state, *node_args, **node_kwargs)++ span_name = f"invoke_agent {node_name}"+ with tracer.start_as_current_span(+ span_name, kind=SpanKind.CLIENT+ ) as span:+ start_time = time.time()+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM,+ SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_OPERATION,+ SemanticConvention.GEN_AI_OPERATION_TYPE_AGENT,+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_NODE_NAME, node_name+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_ENVIRONMENT, environment+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_APPLICATION_NAME, application_name+ )++ try:+ result = await original_func(+ state, *node_args, **node_kwargs+ )++ # Extract LLM info from result+ from openlit.instrumentation.langgraph.utils import (+ extract_llm_info_from_result,+ )++ extract_llm_info_from_result(span, state, result)++ from opentelemetry.trace import Status, StatusCode++ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ time.time() - start_time,+ )+ span.set_status(Status(StatusCode.OK))+ return result++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapped_node_async+ else:++ @wraps(original_func)+ def wrapped_node_sync(state, *node_args, **node_kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return original_func(state, *node_args, **node_kwargs)++ span_name = f"invoke_agent {node_name}"+ with tracer.start_as_current_span(+ span_name, kind=SpanKind.CLIENT+ ) as span:+ start_time = time.time()+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM,+ SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_OPERATION,+ SemanticConvention.GEN_AI_OPERATION_TYPE_AGENT,+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_NODE_NAME, node_name+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_ENVIRONMENT, environment+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_APPLICATION_NAME, application_name+ )++ try:+ result = original_func(state, *node_args, **node_kwargs)++ # Extract LLM info from result+ from openlit.instrumentation.langgraph.utils import (+ extract_llm_info_from_result,+ )++ extract_llm_info_from_result(span, state, result)++ from opentelemetry.trace import Status, StatusCode++ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ time.time() - start_time,+ )+ span.set_status(Status(StatusCode.OK))+ return result++ except Exception as e:+ handle_exception(span, e)+ raise++ return wrapped_node_sync++ # Wrap the action function+ node_name = str(node_key) if not isinstance(node_key, str) else node_key+ wrapped_action = create_wrapped_node(action, node_name)++ # Call original add_node with wrapped action+ if args and len(args) > 1:+ new_args = (args[0], wrapped_action) + args[2:]+ return wrapped(*new_args, **kwargs)+ else:+ kwargs["action"] = wrapped_action+ if args:+ return wrapped(*args, **kwargs)+ else:+ kwargs["node"] = node_key+ return wrapped(**kwargs)++ return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/langgraph/utils.py b/sdk/python/src/openlit/instrumentation/langgraph/utils.pynew file mode 100644index 00000000..750f06c2--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/langgraph/utils.py@@ -0,0 +1,667 @@+"""+LangGraph utilities for comprehensive telemetry processing and business intelligence+"""++import time+import json+from opentelemetry.trace import Status, StatusCode+from openlit.__helpers import common_framework_span_attributes+from openlit.semcov import SemanticConvention+++# === OPERATION MAPPING - Framework Guide Compliant ===+OPERATION_MAP = {+ # Graph Construction Operations+ "graph_init": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ "graph_add_node": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ "graph_add_edge": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ "graph_compile": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ # Graph Execution Operations+ "graph_invoke": SemanticConvention.GEN_AI_OPERATION_TYPE_GRAPH_EXECUTION,+ "graph_ainvoke": SemanticConvention.GEN_AI_OPERATION_TYPE_GRAPH_EXECUTION,+ "graph_stream": SemanticConvention.GEN_AI_OPERATION_TYPE_GRAPH_EXECUTION,+ "graph_astream": SemanticConvention.GEN_AI_OPERATION_TYPE_GRAPH_EXECUTION,+ # State Management Operations+ "graph_get_state": SemanticConvention.GEN_AI_OPERATION_TYPE_RETRIEVE,+ "graph_aget_state": SemanticConvention.GEN_AI_OPERATION_TYPE_RETRIEVE,+ # Checkpointing Operations+ "checkpoint_setup": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ "checkpoint_write": SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ "checkpoint_read": SemanticConvention.GEN_AI_OPERATION_TYPE_RETRIEVE,+ # Node Execution+ "node_execute": SemanticConvention.GEN_AI_OPERATION_TYPE_AGENT,+}+++def set_server_address_and_port(instance):+ """+ Extract server information from LangGraph instance.++ Args:+ instance: LangGraph instance (StateGraph, CompiledGraph, etc.)++ Returns:+ tuple: (server_address, server_port)+ """+ server_address = "localhost"+ server_port = 8080++ # LangGraph doesn't have a direct server, but we can try to+ # extract checkpointer connection info if available+ try:+ if hasattr(instance, "checkpointer"):+ checkpointer = instance.checkpointer+ if hasattr(checkpointer, "conn"):+ conn = checkpointer.conn+ if hasattr(conn, "info"):+ info = conn.info+ server_address = info.host or "localhost"+ server_port = info.port or 5432+ except Exception:+ pass++ return server_address, server_port+++def ensure_no_none_values(attributes):+ """Filter out None values from attributes dict."""+ return {k: v for k, v in attributes.items() if v is not None}+++def extract_messages_from_input(input_data):+ """+ Extract messages from graph input.++ Args:+ input_data: Input data to the graph (dict or other)++ Returns:+ list: List of message objects+ """+ if isinstance(input_data, dict) and "messages" in input_data:+ return input_data["messages"]+ return []+++def extract_messages_from_output(output_data):+ """+ Extract messages from graph output.++ Args:+ output_data: Output data from the graph (dict or other)++ Returns:+ list: List of message objects+ """+ if isinstance(output_data, dict) and "messages" in output_data:+ return output_data["messages"]+ return []+++def get_message_content(message):+ """+ Get content string from a message object.++ Args:+ message: Message object with content attribute++ Returns:+ str: Content string+ """+ if hasattr(message, "content"):+ content = message.content+ if isinstance(content, str):+ return content+ elif isinstance(content, list):+ # Handle list of content items (multimodal)+ parts = []+ for item in content:+ if isinstance(item, str):+ parts.append(item)+ elif isinstance(item, dict) and "text" in item:+ parts.append(str(item["text"]))+ elif hasattr(item, "text"):+ parts.append(str(item.text))+ return "".join(parts)+ return str(content)+ return ""+++def get_message_role(message):+ """+ Get role/type from a message object.++ Args:+ message: Message object++ Returns:+ str: Role string+ """+ if hasattr(message, "role"):+ return message.role+ elif hasattr(message, "type"):+ return message.type+ elif hasattr(message, "__class__"):+ # Extract role from class name (e.g., HumanMessage -> human)+ class_name = message.__class__.__name__+ return class_name.replace("Message", "").lower()+ return "unknown"+++def set_graph_attributes(span, nodes=None, edges=None):+ """+ Set graph structure attributes on span.++ Args:+ span: OpenTelemetry span+ nodes: List of node names+ edges: Set/list of edge tuples or edge strings+ """+ if nodes:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_GRAPH_NODES, json.dumps(list(nodes))+ )+ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_NODE_COUNT, len(nodes))+ # Set individual node names+ for i, node in enumerate(list(nodes)[:10]): # Limit to first 10+ span.set_attribute(f"langgraph.node.{i}.name", str(node))++ if edges:+ edge_list = []+ for edge in edges:+ if isinstance(edge, tuple) and len(edge) >= 2:+ edge_list.append(f"{edge[0]}->{edge[1]}")+ elif isinstance(edge, str):+ edge_list.append(edge)++ span.set_attribute(+ SemanticConvention.LANGGRAPH_GRAPH_EDGES, json.dumps(edge_list)+ )+ span.set_attribute(+ SemanticConvention.LANGGRAPH_GRAPH_EDGE_COUNT, len(edge_list)+ )+ # Set individual edge info+ for i, edge in enumerate(edge_list[:10]): # Limit to first 10+ parts = edge.split("->")+ if len(parts) == 2:+ span.set_attribute(f"langgraph.edge.{i}.source", parts[0])+ span.set_attribute(f"langgraph.edge.{i}.target", parts[1])+++def extract_llm_info_from_result(span, state, result):+ """+ Extract LLM token usage, model info from node result.++ Args:+ span: OpenTelemetry span+ state: Input state dict+ result: Result from node execution+ """+ try:+ # Extract messages from state for context+ if isinstance(state, dict) and "messages" in state:+ messages = state["messages"]+ # Set prompt content from last few messages+ for i, msg in enumerate(messages[-3:]):+ content = get_message_content(msg)+ role = get_message_role(msg)+ if content:+ span.set_attribute(f"gen_ai.prompt.{i}.content", content[:500])+ span.set_attribute(f"gen_ai.prompt.{i}.role", role)++ # Extract from result+ if isinstance(result, dict) and "messages" in result:+ output_messages = result["messages"]+ if output_messages:+ last_msg = (+ output_messages[-1]+ if isinstance(output_messages, list)+ else output_messages+ )++ # Extract model info from response_metadata+ if hasattr(last_msg, "response_metadata"):+ metadata = last_msg.response_metadata+ if isinstance(metadata, dict):+ # Model name+ model_name = metadata.get("model_name") or metadata.get("model")+ if model_name:+ span.set_attribute(+ SemanticConvention.GEN_AI_REQUEST_MODEL, model_name+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_RESPONSE_MODEL, model_name+ )++ # Token usage+ if "token_usage" in metadata:+ usage = metadata["token_usage"]+ if isinstance(usage, dict):+ if "prompt_tokens" in usage:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ usage["prompt_tokens"],+ )+ if "completion_tokens" in usage:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ usage["completion_tokens"],+ )+ if "total_tokens" in usage:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS,+ usage["total_tokens"],+ )++ # Finish reason+ if "finish_reason" in metadata:+ span.set_attribute(+ SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,+ metadata["finish_reason"],+ )++ # Response ID+ if "id" in metadata and metadata["id"]:+ span.set_attribute(+ SemanticConvention.GEN_AI_RESPONSE_ID, metadata["id"]+ )++ # Extract content+ if hasattr(last_msg, "content"):+ content = get_message_content(last_msg)+ if content:+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_COMPLETION, content[:1000]+ )++ # Extract usage_metadata (alternative location)+ if hasattr(last_msg, "usage_metadata"):+ usage = last_msg.usage_metadata+ if hasattr(usage, "input_tokens"):+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ usage.input_tokens,+ )+ if hasattr(usage, "output_tokens"):+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ usage.output_tokens,+ )+ if hasattr(usage, "total_tokens"):+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS,+ usage.total_tokens,+ )++ # Tool calls+ if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:+ tool_calls_info = []+ for j, tool_call in enumerate(last_msg.tool_calls[:5]):+ tool_info = {}+ if hasattr(tool_call, "name"):+ tool_info["name"] = tool_call.name+ span.set_attribute(+ f"gen_ai.tool_call.{j}.name", tool_call.name+ )+ if hasattr(tool_call, "args"):+ args_str = (+ json.dumps(tool_call.args)+ if isinstance(tool_call.args, dict)+ else str(tool_call.args)+ )+ span.set_attribute(+ f"gen_ai.tool_call.{j}.arguments", args_str[:500]+ )+ if hasattr(tool_call, "id"):+ span.set_attribute(f"gen_ai.tool_call.{j}.id", tool_call.id)+ if tool_info:+ tool_calls_info.append(tool_info)++ if tool_calls_info:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALLS,+ json.dumps(tool_calls_info),+ )++ except Exception:+ # Don't fail the span if we can't extract info+ pass+++def extract_config_info(config):+ """+ Extract configuration information from RunnableConfig.++ Args:+ config: RunnableConfig dict++ Returns:+ dict: Extracted config info (thread_id, checkpoint_id, etc.)+ """+ info = {}+ if not config:+ return info++ try:+ # Extract configurable values+ configurable = config.get("configurable", {})++ if "thread_id" in configurable:+ info["thread_id"] = str(configurable["thread_id"])++ if "checkpoint_id" in configurable:+ info["checkpoint_id"] = str(configurable["checkpoint_id"])++ if "checkpoint_ns" in configurable:+ info["checkpoint_ns"] = str(configurable["checkpoint_ns"])++ except Exception:+ pass++ return info+++def generate_span_name(operation_type, endpoint, instance=None, args=None, kwargs=None):+ """+ Generate proper span name following OpenTelemetry conventions.++ Args:+ operation_type: Standard operation type from OPERATION_MAP+ endpoint: Endpoint name (e.g., "graph_invoke")+ instance: The instance being instrumented+ args: Positional arguments+ kwargs: Keyword arguments++ Returns:+ str: Span name+ """+ # Graph execution operations+ if endpoint in ("graph_invoke", "graph_ainvoke"):+ graph_name = _get_graph_name(instance)+ return f"{operation_type} {graph_name}"++ elif endpoint in ("graph_stream", "graph_astream"):+ graph_name = _get_graph_name(instance)+ return f"{operation_type} {graph_name} stream"++ # State operations+ elif endpoint in ("graph_get_state", "graph_aget_state"):+ return "retrieve graph_state"++ # Graph construction+ elif endpoint == "graph_init":+ return f"{operation_type} graph_init"++ elif endpoint == "graph_compile":+ return f"{operation_type} graph_compile"++ elif endpoint == "graph_add_node":+ node_name = args[0] if args else "node"+ return f"{operation_type} add_node:{node_name}"++ elif endpoint == "graph_add_edge":+ return f"{operation_type} add_edge"++ # Node execution+ elif endpoint == "node_execute":+ node_name = kwargs.get("node_name", "node") if kwargs else "node"+ return f"invoke_agent {node_name}"++ # Checkpointing+ elif endpoint == "checkpoint_setup":+ return f"{operation_type} checkpoint_setup"++ elif endpoint == "checkpoint_write":+ return f"{operation_type} checkpoint_write"++ elif endpoint == "checkpoint_read":+ return "retrieve checkpoint"++ # Default+ return f"{operation_type} {endpoint}"+++def _get_graph_name(instance):+ """Get the name of a graph instance."""+ if instance is None:+ return "graph"++ # Try to get name from instance+ name = getattr(instance, "name", None)+ if name:+ return str(name)++ # Try to get from graph_id+ graph_id = getattr(instance, "graph_id", None)+ if graph_id:+ return str(graph_id)++ # Try class name+ class_name = instance.__class__.__name__+ if class_name not in ("Pregel", "CompiledStateGraph", "StateGraph"):+ return class_name++ return "graph"+++def process_langgraph_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=None,+ **kwargs,+):+ """+ Process LangGraph response with comprehensive business intelligence.++ Args:+ response: The response from the LangGraph operation+ operation_type: Type of operation performed+ server_address: Server address+ server_port: Server port+ environment: Deployment environment+ application_name: Application name+ metrics: Metrics registry+ start_time: Operation start time+ span: OpenTelemetry span+ capture_message_content: Whether to capture message content+ disable_metrics: Whether metrics are disabled+ version: SDK version+ instance: LangGraph instance+ args: Positional arguments+ endpoint: Endpoint name+ **kwargs: Additional keyword arguments++ Returns:+ The original response+ """+ end_time = time.time()++ # Create scope for common_framework_span_attributes+ scope = type("GenericScope", (), {})()+ scope._span = span+ scope._start_time = start_time+ scope._end_time = end_time++ # Get standard operation name+ standard_operation = OPERATION_MAP.get(+ endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK+ )++ # Set common framework attributes+ common_framework_span_attributes(+ scope,+ SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ server_address,+ server_port,+ environment,+ application_name,+ version,+ endpoint,+ instance,+ )++ # Set operation name+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, standard_operation)++ # Set execution mode+ if endpoint in ("graph_invoke", "graph_ainvoke"):+ span.set_attribute(SemanticConvention.LANGGRAPH_EXECUTION_MODE, "invoke")+ elif endpoint in ("graph_stream", "graph_astream"):+ span.set_attribute(SemanticConvention.LANGGRAPH_EXECUTION_MODE, "stream")++ # Extract config information+ config = kwargs.get("config") or (args[1] if len(args) > 1 else None)+ if config:+ config_info = extract_config_info(config)+ if config_info.get("thread_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_THREAD_ID, config_info["thread_id"]+ )+ if config_info.get("checkpoint_id"):+ span.set_attribute(+ SemanticConvention.LANGGRAPH_CHECKPOINT_ID, config_info["checkpoint_id"]+ )++ # Process response based on type+ if endpoint in ("graph_invoke", "graph_ainvoke"):+ _process_invoke_response(span, response, capture_message_content)+ elif endpoint in ("graph_get_state", "graph_aget_state"):+ _process_state_response(span, response)+ elif endpoint == "graph_compile":+ _process_compile_response(span, instance, response)++ # Set success status+ span.set_attribute(SemanticConvention.LANGGRAPH_GRAPH_STATUS, "success")+ span.set_status(Status(StatusCode.OK))++ # Record metrics+ if not disable_metrics and metrics:+ _record_langgraph_metrics(+ metrics,+ standard_operation,+ end_time - start_time,+ environment,+ application_name,+ )++ return response+++def _process_invoke_response(span, response, capture_message_content):+ """Process invoke/ainvoke response."""+ try:+ if isinstance(response, dict):+ # Extract messages+ messages = extract_messages_from_output(response)+ if messages:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_MESSAGE_COUNT, len(messages)+ )++ # Get final response content+ if messages:+ last_msg = messages[-1] if isinstance(messages, list) else messages+ content = get_message_content(last_msg)+ if content and capture_message_content:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_FINAL_RESPONSE, content[:500]+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_CONTENT_COMPLETION, content[:1000]+ )++ # Try to extract LLM info+ extract_llm_info_from_result(span, {}, response)++ except Exception:+ pass+++def _process_state_response(span, response):+ """Process get_state/aget_state response."""+ try:+ if hasattr(response, "values"):+ values = response.values+ if isinstance(values, dict) and "messages" in values:+ span.set_attribute(+ SemanticConvention.LANGGRAPH_MESSAGE_COUNT, len(values["messages"])+ )++ if hasattr(response, "next"):+ next_nodes = response.next+ if next_nodes:+ span.set_attribute(+ "langgraph.state.next_nodes", json.dumps(list(next_nodes))+ )++ except Exception:+ pass+++def _process_compile_response(span, instance, response):+ """Process compile response."""+ try:+ # Extract nodes and edges from the graph+ nodes = []+ edges = []++ if hasattr(instance, "nodes"):+ nodes = (+ list(instance.nodes.keys()) if hasattr(instance.nodes, "keys") else []+ )++ if hasattr(instance, "edges"):+ edge_set = instance.edges+ if hasattr(edge_set, "items"):+ for source, targets in edge_set.items():+ if isinstance(targets, dict):+ for target in targets.values():+ edges.append(f"{source}->{target}")+ elif isinstance(targets, (list, set)):+ for target in targets:+ edges.append(f"{source}->{target}")+ elif hasattr(edge_set, "__iter__"):+ for edge in edge_set:+ if isinstance(edge, tuple) and len(edge) >= 2:+ edges.append(f"{edge[0]}->{edge[1]}")++ set_graph_attributes(span, nodes, edges)++ except Exception:+ pass+++def _record_langgraph_metrics(+ metrics, operation_type, duration, environment, application_name+):+ """Record LangGraph metrics."""+ try:+ attributes = {+ "gen_ai.operation.name": operation_type,+ "gen_ai.system": SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,+ "service.name": application_name,+ "deployment.environment": environment,+ }++ # Record operation duration+ if "genai_client_operation_duration" in metrics:+ metrics["genai_client_operation_duration"].record(duration, attributes)++ # Record operation count+ if "genai_requests" in metrics:+ metrics["genai_requests"].add(1, attributes)++ except Exception:+ passdiff --git a/sdk/python/src/openlit/otel/events.py b/sdk/python/src/openlit/otel/events.pyindex 46a03db2..30a761c3 100644--- a/sdk/python/src/openlit/otel/events.py+++ b/sdk/python/src/openlit/otel/events.py@@ -18,13 +18,14 @@ from opentelemetry.sdk._logs.export import ()from opentelemetry.sdk._logs import LoggerProviderfrom opentelemetry.sdk._logs.export import ConsoleLogExporter+from openlit.__helpers import parse_exporters+# pylint: disable=ungrouped-importsif os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL") == "grpc":from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporterelse:from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter--from openlit.__helpers import parse_exporters+# pylint: enable=ungrouped-importslogger = logging.getLogger(__name__)diff --git a/sdk/python/src/openlit/otel/tracing.py b/sdk/python/src/openlit/otel/tracing.pyindex 20d046d5..80ec27e4 100644--- a/sdk/python/src/openlit/otel/tracing.py+++ b/sdk/python/src/openlit/otel/tracing.py@@ -14,13 +14,14 @@ from opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessorfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter+from openlit.__helpers import parse_exporters+# pylint: disable=ungrouped-importsif os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL") == "grpc":from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporterelse:from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter--from openlit.__helpers import parse_exporters+# pylint: enable=ungrouped-importslogger = logging.getLogger(__name__)diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex fc786afc..6aff949c 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -166,6 +166,24 @@ class SemanticConvention:GEN_AI_SYSTEM_PYDANTIC_AI = "pydantic_ai"GEN_AI_SYSTEM_SARVAM = "sarvam"GEN_AI_SYSTEM_BROWSER_USE = "browser_use"+ GEN_AI_SYSTEM_LANGGRAPH = "langgraph"++ # LangGraph-specific Attributes+ LANGGRAPH_GRAPH_NODES = "langgraph.graph.nodes"+ LANGGRAPH_GRAPH_NODE_COUNT = "langgraph.graph.node_count"+ LANGGRAPH_GRAPH_EDGES = "langgraph.graph.edges"+ LANGGRAPH_GRAPH_EDGE_COUNT = "langgraph.graph.edge_count"+ LANGGRAPH_EXECUTION_MODE = "langgraph.execution.mode"+ LANGGRAPH_EXECUTED_NODES = "langgraph.graph.executed_nodes"+ LANGGRAPH_NODE_EXECUTION_COUNT = "langgraph.graph.node_execution_count"+ LANGGRAPH_MESSAGE_COUNT = "langgraph.graph.message_count"+ LANGGRAPH_CHUNK_COUNT = "langgraph.graph.total_chunks"+ LANGGRAPH_FINAL_RESPONSE = "langgraph.graph.final_response"+ LANGGRAPH_NODE_NAME = "langgraph.node.name"+ LANGGRAPH_GRAPH_STATUS = "langgraph.graph.status"+ LANGGRAPH_THREAD_ID = "langgraph.thread.id"+ LANGGRAPH_CHECKPOINT_ID = "langgraph.checkpoint.id"+ LANGGRAPH_STREAM_MODE = "langgraph.stream.mode"# GenAI Framework Component Attributes (Standard)GEN_AI_FRAMEWORK_COMPONENT_NAME = "gen_ai.framework.component.name"diff --git a/sdk/python/tests/test_langgraph.py b/sdk/python/tests/test_langgraph.pynew file mode 100644index 00000000..c6854c4c--- /dev/null+++ b/sdk/python/tests/test_langgraph.py@@ -0,0 +1,315 @@+# pylint: disable=duplicate-code, no-member, too-few-public-methods, missing-class-docstring+"""+This module contains tests for LangGraph instrumentation using the LangGraph Python library.++Tests cover:+- Graph construction (StateGraph, compile, add_node, add_edge)+- Graph execution (invoke, ainvoke)+- Streaming (stream, astream)+- State management (get_state, aget_state)++These tests validate integration with OpenLIT.++Note: These tests require langgraph to be installed.+"""++from typing import Annotated, TypedDict++import pytest++# Try to import langgraph+try:+ from langgraph.graph import StateGraph, START, END+ from langgraph.graph.message import add_messages++ LANGGRAPH_AVAILABLE = True+except ImportError:+ LANGGRAPH_AVAILABLE = False+ # Define placeholder for type hints when langgraph not available+ add_messages = None+ StateGraph = None+ START = None+ END = None++import openlit++# Initialize OpenLIT monitoring+openlit.init(+ environment="openlit-python-testing",+ application_name="openlit-python-langgraph-test",+)+++# Skip all tests if langgraph is not available+pytestmark = pytest.mark.skipif(+ not LANGGRAPH_AVAILABLE, reason="langgraph not installed"+)+++# Define a simple state for testing - only use add_messages annotation when available+if LANGGRAPH_AVAILABLE:++ class SimpleState(TypedDict):+ """Simple state with messages."""++ messages: Annotated[list, add_messages]+else:++ class SimpleState(TypedDict):+ """Simple state with messages (fallback without add_messages)."""++ messages: list+++def simple_node(state: SimpleState) -> dict:+ """A simple node that echoes the input."""+ return {"messages": [{"role": "assistant", "content": "test response"}]}+++async def async_simple_node(state: SimpleState) -> dict:+ """An async simple node."""+ return {"messages": [{"role": "assistant", "content": "async test response"}]}+++class TestLangGraphInstrumentation:+ """Tests for LangGraph instrumentation."""++ def test_graph_construction(self):+ """+ Tests that StateGraph construction is instrumented.+ """+ try:+ # Create a simple graph+ graph = StateGraph(SimpleState)+ graph.add_node("test_node", simple_node)+ graph.add_edge(START, "test_node")+ graph.add_edge("test_node", END)++ # Compile the graph+ compiled = graph.compile()++ assert compiled is not None++ except Exception as e:+ pytest.fail(f"Error in test_graph_construction: {e}")++ def test_graph_invoke(self):+ """+ Tests synchronous graph execution with invoke.+ """+ try:+ # Create and compile graph+ graph = StateGraph(SimpleState)+ graph.add_node("test_node", simple_node)+ graph.add_edge(START, "test_node")+ graph.add_edge("test_node", END)+ compiled = graph.compile()++ # Invoke the graph+ result = compiled.invoke(+ {"messages": [{"role": "user", "content": "test input"}]}+ )++ assert result is not None+ assert "messages" in result++ except Exception as e:+ pytest.fail(f"Error in test_graph_invoke: {e}")++ def test_graph_stream(self):+ """+ Tests synchronous graph streaming.+ """+ try:+ # Create and compile graph+ graph = StateGraph(SimpleState)+ graph.add_node("test_node", simple_node)+ graph.add_edge(START, "test_node")+ graph.add_edge("test_node", END)+ compiled = graph.compile()++ # Stream the graph+ chunks = list(+ compiled.stream(+ {"messages": [{"role": "user", "content": "test input"}]}+ )+ )++ assert len(chunks) > 0++ except Exception as e:+ pytest.fail(f"Error in test_graph_stream: {e}")++ @pytest.mark.asyncio+ async def test_graph_ainvoke(self):+ """+ Tests async graph execution with ainvoke.+ """+ try:+ # Create and compile graph+ graph = StateGraph(SimpleState)+ graph.add_node("test_node", async_simple_node)+ graph.add_edge(START, "test_node")+ graph.add_edge("test_node", END)+ compiled = graph.compile()++ # Async invoke the graph+ result = await compiled.ainvoke(+ {"messages": [{"role": "user", "content": "test input"}]}+ )++ assert result is not None+ assert "messages" in result++ except Exception as e:+ pytest.fail(f"Error in test_graph_ainvoke: {e}")++ @pytest.mark.asyncio+ async def test_graph_astream(self):+ """+ Tests async graph streaming.+ """+ try:+ # Create and compile graph+ graph = StateGraph(SimpleState)+ graph.add_node("test_node", async_simple_node)+ graph.add_edge(START, "test_node")+ graph.add_edge("test_node", END)+ compiled = graph.compile()++ # Async stream the graph+ chunks = []+ async for chunk in compiled.astream(+ {"messages": [{"role": "user", "content": "test input"}]}+ ):+ chunks.append(chunk)++ assert len(chunks) > 0++ except Exception as e:+ pytest.fail(f"Error in test_graph_astream: {e}")++ def test_graph_with_multiple_nodes(self):+ """+ Tests graph with multiple nodes.+ """++ def node_a(state: SimpleState) -> dict:+ return {"messages": [{"role": "assistant", "content": "from node a"}]}++ def node_b(state: SimpleState) -> dict:+ return {"messages": [{"role": "assistant", "content": "from node b"}]}++ try:+ # Create graph with multiple nodes+ graph = StateGraph(SimpleState)+ graph.add_node("node_a", node_a)+ graph.add_node("node_b", node_b)+ graph.add_edge(START, "node_a")+ graph.add_edge("node_a", "node_b")+ graph.add_edge("node_b", END)+ compiled = graph.compile()++ # Execute+ result = compiled.invoke(+ {"messages": [{"role": "user", "content": "test"}]}+ )++ assert result is not None+ assert "messages" in result+ # Should have messages from both nodes+ assert len(result["messages"]) > 1++ except Exception as e:+ pytest.fail(f"Error in test_graph_with_multiple_nodes: {e}")+++class TestLangGraphInstrumentorUnit:+ """Unit tests for LangGraph instrumentor."""++ def test_instrumentor_import(self):+ """Tests that the instrumentor can be imported."""+ try:+ from openlit.instrumentation.langgraph import LangGraphInstrumentor++ assert LangGraphInstrumentor is not None+ except ImportError as e:+ pytest.fail(f"Failed to import LangGraphInstrumentor: {e}")++ def test_utils_import(self):+ """Tests that utils can be imported."""+ try:+ from openlit.instrumentation.langgraph.utils import (+ OPERATION_MAP,+ extract_messages_from_input,+ )++ assert OPERATION_MAP is not None+ assert extract_messages_from_input is not None+ except ImportError as e:+ pytest.fail(f"Failed to import utils: {e}")++ def test_extract_messages_from_input(self):+ """Tests message extraction from input."""+ from openlit.instrumentation.langgraph.utils import extract_messages_from_input++ # Test with messages+ input_with_messages = {"messages": [{"role": "user", "content": "test"}]}+ result = extract_messages_from_input(input_with_messages)+ assert len(result) == 1++ # Test without messages+ input_without_messages = {"other": "data"}+ result = extract_messages_from_input(input_without_messages)+ assert len(result) == 0++ def test_get_message_role(self):+ """Tests message role extraction."""+ from openlit.instrumentation.langgraph.utils import get_message_role++ # Mock message with role+ class MockMessage:+ role = "assistant"++ result = get_message_role(MockMessage())+ assert result == "assistant"++ # Mock message with type+ class MockMessageWithType:+ type = "human"++ result = get_message_role(MockMessageWithType())+ assert result == "human"++ def test_generate_span_name(self):+ """Tests span name generation."""+ from openlit.instrumentation.langgraph.utils import generate_span_name++ # Test invoke span name+ span_name = generate_span_name("graph_execution", "graph_invoke", None)+ assert "graph_execution" in span_name or "graph" in span_name++ # Test stream span name+ span_name = generate_span_name("graph_execution", "graph_stream", None)+ assert "stream" in span_name++ def test_operation_map_completeness(self):+ """Tests that OPERATION_MAP has all required operations."""+ from openlit.instrumentation.langgraph.utils import OPERATION_MAP++ required_ops = [+ "graph_invoke",+ "graph_ainvoke",+ "graph_stream",+ "graph_astream",+ "graph_get_state",+ "graph_aget_state",+ "graph_compile",+ ]++ for op in required_ops:+ assert op in OPERATION_MAP, f"Missing operation: {op}"+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])