Summary: OpenTelemetry tracing integration bridging AgentScope applications and Langfuse. Auto-instruments LLMs, manages request-level root traces, maps sessions/tokens, and injects Kubernetes/OTel metadata directly into Langfuse.

🚀 Quick Start

  • Install: pip install agentscope-otel-langfuse
  • Initialization: Bootstraps OTel tracer, activates AgentScope @trace_llm, and safely handles no-op if disabled.
from agentscope_otel_langfuse import OTelConfig, init, trace_request
 
init(OTelConfig.from_env(service_name="my-agentscope-app"))
 
# Sync or Async context block
async with trace_request(session_id="s-1", user_id="u-1", user_input="hello") as trace:
    res = await agent(messages)
    trace.set_output(res)
    trace.set_usage({"input_tokens": 100, "output_tokens": 50})

🔧 Configuration

  • Initialization Strategy: Use OTelConfig.from_env() to automatically merge environment variables with explicit code overrides.
Env VariableRequirementDescription
OTEL_ENABLED🚨 Opt-inMust be true to trace. Defaults to false (no-op).
OTEL_EXPORTER_OTLP_ENDPOINTRequired if enabledBase URL (e.g., http://collector:4318). Auto-appends /v1/traces.
OTEL_RESOURCE_ATTRIBUTESOptionalComma-separated pairs (e.g., deployment.environment=prod).

📦 Kubernetes Downward API Injection

  • Automatic K8s Mapping: Binds K8s environment variables directly to OTel resource attributes and Langfuse metadata. It mirrors pairs like k8s.pod.name to langfuse.trace.metadata.k8s_pod_name.
  • Supported Env Vars: K8S_POD_NAME, K8S_POD_NAMESPACE, K8S_POD_UID, K8S_POD_IP, K8S_NODE_NAME, K8S_DEPLOYMENT_NAME, K8S_POD_LABEL_APP, K8S_POD_LABEL_VERSION, K8S_POD_LABEL_ENV.

💡 Best Practices (Patterns)

  • Rely on Native No-Op: Do not write manual telemetry conditionals in your application code. The library natively executes as a no-op when OTEL_ENABLED=false.
  • Complete the Context: Always call trace.set_output() and trace.set_usage() before exiting the trace_request block. This ensures Langfuse calculates costs and renders inputs/outputs.
  • Error Handling: Use trace.set_error() or trace.finish(error=True) if a step fails.
  • K8s FieldRef Injection: Use Kubernetes valueFrom.fieldRef in pod manifests to dynamically inject K8S_POD_NAME and K8S_POD_NAMESPACE directly into the container environment.

🚨 Gotchas & Anti-Patterns

  • Anti-Pattern (Silent Failure): Assuming tracing is active by default. You must explicitly set OTEL_ENABLED="true" or traces are silently bypassed.
  • Anti-Pattern (Double Pathing): Manually appending /v1/traces to the OTEL_EXPORTER_OTLP_ENDPOINT. The SDK automatically appends this path if omitted.
  • Gotcha (Missing Metadata): If K8s attributes do not appear in Langfuse, verify executions are wrapped in trace_request(). Metadata is strictly bound to the root span generated by this context manager.

🔍 Research / References