LIVE
Back to journal
9 min read
Artificial Intelligence

OpenTelemetry GenAI Conventions: Agent Tracing and Continuous Evals

>Implement OpenTelemetry GenAI semantic conventions, distributed tracing for multi-agent workflows, automated Ragas evals, and runtime cost circuit breakers.

ShareXLinkedIn

🎧 Listen — ~9 min

Audio summary not available yet

~9 min
OpenTelemetry GenAI Conventions: Agent Tracing and Continuous Evals
Verified by Essa Mamdani

Traditional Application Performance Monitoring (APM) tools are built around deterministic request-response lifecycles, HTTP status codes, and database query durations. When engineering teams deploy non-deterministic, agentic systems—where a single user prompt may spark a dozen recursive planning loops, tool executions, vector retrievals, and nested model calls—traditional distributed tracing falls blind.

To govern cost, detect silent hallucinations, and debug runaway agent execution paths, teams are standardizing on the OpenTelemetry (OTel) GenAI Semantic Conventions alongside automated evaluation pipelines.

Quick answer

The standard path for AI observability relies on the OpenTelemetry GenAI Semantic Conventions (v1.30+), which define uniform schemas for model spans (gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens), agent execution trees, and tool invocations. Combined with continuous evaluation frameworks (such as Ragas or custom LLM-as-a-judge scorers) and runtime cost circuit breakers, this stack captures token consumption, execution latency, and semantic drift in real time across distributed agent infrastructure.

Key takeaways

  • Unified Schema: OpenTelemetry GenAI conventions replace proprietary vendor schemas with vendor-neutral span attributes for token counts, temperatures, model configurations, and tool calls.
  • Trace Context Propagation: Multi-agent architectures require strict span parenting—nesting orchestration plans, sub-agent delegation, and tool invocations under a unified trace root.
  • Continuous In-Band Evals: Production evaluation cannot wait for offline batch runs. Scoring metrics like context relevance, faithfulness, and answer correctness must attach directly to trace spans.
  • Cost Circuit Breakers: Token anomalies and runaway recursive loops must be halted dynamically at the gateway or tracing layer using pre-configured budget and depth thresholds.

2. Architecture of OpenTelemetry GenAI Conventions

According to maintainer releases documented in engineering playbooks like tanhdev's AI observability guide, OpenTelemetry GenAI Semantic Conventions (v1.30+) establish vendor-agnostic standards for capturing generative model operations. Rather than inventing ad-hoc span tags, teams follow standardized attribute keys.

Core GenAI Attribute Specifications

OpenTelemetry AttributeTypeDescription / Example Values
gen_ai.systemstringThe vendor or framework backing the model (openai, anthropic, cohere, ollama).
gen_ai.request.modelstringThe requested model identifier (claude-3-5-sonnet, gpt-4o).
gen_ai.response.modelstringThe actual model processing the request (capturing system revisions or backend defaults).
gen_ai.request.temperaturedoubleSampling temperature specified in the inference request.
gen_ai.request.max_tokensintMaximum output token ceiling specified for generation.
gen_ai.usage.input_tokensintNumber of tokens processed in the system/prompt context.
gen_ai.usage.output_tokensintNumber of completion tokens generated by the inference call.
gen_ai.response.finish_reasonsstring[]Array describing why completion stopped (stop, length, content_filter, tool_calls).

Agent Span Hierarchy

In a distributed agent architecture, spans must reflect hierarchical execution. A top-level workflow span initiates child spans for each planning step, tool call, and inference call.

diagram

When each sub-agent and tool executes within this hierarchy, context propagation guarantees that tokens, latency, and costs bubble up to the root request ID, pinpointing which sub-task caused a latency spike or budget overrun.


3. Implementation: Instrumenting Multi-Agent Spans

To instrument an agent pipeline using native OpenTelemetry semantics, you configure an OpenTelemetry Tracer that outputs to standard backends (such as Langfuse, SigNoz, Honeycomb, or OpenLLMetry-compatible collectors).

The following production Python pattern demonstrates instrumenting an agent workflow with standard gen_ai.* attributes, parent-child span linkage, and tool metadata.

python
1import time
2from typing import Any, Dict, List
3from opentelemetry import trace
4from opentelemetry.trace import Status, StatusCode
5tracer = trace.get_tracer("agent.orchestrator", "1.30.0")
6
7def execute_llm_call(
8    prompt: str, 
9    model: str = "claude-3-5-sonnet",
10    temperature: float = 0.2
11) -> Dict[str, Any]:
12    with tracer.start_as_current_span("gen_ai.generate_content") as span:
13        span.set_attribute("gen_ai.system", "anthropic")
14        span.set_attribute("gen_ai.request.model", model)
15        span.set_attribute("gen_ai.request.temperature", temperature)
16        span.set_attribute("gen_ai.operation.name", "chat")
17        
18        start_time = time.perf_counter()
19        response_text = "Analysis complete: portfolio allocation within limits."
20        input_tokens = len(prompt.split()) * 2  # Simulated approximation
21        output_tokens = len(response_text.split()) * 2
22        span.set_attribute("gen_ai.response.model", model)
23        span.set_attribute("gen_ai.usage.input_tokens", input_tokens)
24        span.set_attribute("gen_ai.usage.output_tokens", output_tokens)
25        span.set_attribute("gen_ai.response.finish_reasons", ["stop"])
26        span.set_status(Status(StatusCode.OK))
27        
28        return {
29            "output": response_text,
30            "tokens": {"input": input_tokens, "output": output_tokens}
31        }
32
33def run_orchestrated_agent(query: str):
34    with tracer.start_as_current_span("agent.workflow.execute") as root_span:
35        root_span.set_attribute("agent.name", "portfolio_analyzer")
36        root_span.set_attribute("agent.user_query", query)
37        with tracer.start_as_current_span("agent.tool.execute") as tool_span:
38            tool_span.set_attribute("tool.name", "vector_store_retrieval")
39            tool_span.set_attribute("tool.query", query)
40            retrieved_chunks = ["Doc A: Risk limits 15%", "Doc B: Cash balance $4.2M"]
41            tool_span.set_attribute("tool.result_count", len(retrieved_chunks))
42            tool_span.set_status(Status(StatusCode.OK))
43        augmented_prompt = f"Context: {retrieved_chunks}\nQuery: {query}"
44        result = execute_llm_call(prompt=augmented_prompt)
45        
46        root_span.set_attribute("agent.status", "completed")
47        return result["output"]

When applied across frameworks like LangGraph, CrewAI, or AutoGen, this structure provides deterministic trace IDs across every tool invocation and sub-agent handoff, ensuring compatibility with platforms reviewed in enterprise tool guardrails and governance.


4. Continuous Evaluation in the Trace Pipeline

As highlighted in Maxim AI's evaluation guides and Leanware's production observability frameworks, logging traces alone does not determine whether an agent performed well. Teams need automated, continuous evaluation embedded directly into observability streams.

Continuous evaluations run in two distinct execution modes:

  • In-Line (Synchronous) Guards: Lightweight checks executed before delivering responses to end-users (e.g., regex pattern redaction, prompt injection heuristics, output schema validation).
  • Asynchronous (Out-of-Band) Evals: Deep semantic scorers evaluating a statistical sample of completed trace spans (e.g., 5% of production traffic) to avoid adding user-facing latency.
diagram

Core Semantic Metrics for Trace Annotation

  1. Faithfulness: Measures whether the agent's output is grounded strictly in the retrieved context chunks, detecting ungrounded claims.
  2. Context Precision & Recall: Verifies that the retrieval tool fetched all necessary information without overwhelming the model's context window with irrelevant noise.
  3. Answer Correctness: Compares the generated response against reference golden sets during staged deployments or canary rollouts.

When evaluation workers process trace IDs asynchronously, they compute these metrics and write them back into the telemetry backend as span attributes (eval.score.faithfulness: 0.94, eval.score.context_relevance: 0.81). This allows monitoring dashboards to trigger alerts when moving-average scores drop below acceptable SLO boundaries.


5. Cost Anomaly Detection and Circuit Breakers

A primary operational failure mode in autonomous multi-agent systems is the recursive runaway loop: an agent attempts to execute an invalid tool parameter, receives an error, re-prompts the model, and repeats the cycle indefinitely.

Without runtime circuit breakers, an unconstrained agent can consume millions of tokens within minutes. Implementing cost anomaly circuit breakers requires intercepting spans at the orchestration gateway.

python
1class AgentBudgetCircuitBreaker:
2    def __init__(self, max_tokens_per_request: int, max_steps: int):
3        self.max_tokens = max_tokens_per_request
4        self.max_steps = max_steps
5        self.current_tokens = 0
6        self.step_count = 0
7
8    def record_usage(self, input_tokens: int, output_tokens: int):
9        self.step_count += 1
10        self.current_tokens += (input_tokens + output_tokens)
11        if self.step_count > self.max_steps:
12            raise RuntimeError(
13                f"AgentCircuitBreaker tripped: Max recursive steps ({self.max_steps}) exceeded."
14            )
15        
16        if self.current_tokens > self.max_tokens:
17            raise RuntimeError(
18                f"AgentCircuitBreaker tripped: Max token budget ({self.max_tokens}) "
19                f"exceeded with usage {self.current_tokens} tokens."
20            )
21circuit_breaker = AgentBudgetCircuitBreaker(max_tokens_per_request=30000, max_steps=8)
22
23try:
24    for iteration in range(10):
25        circuit_breaker.record_usage(input_tokens=4000, output_tokens=800)
26except RuntimeError as circuit_error:
27    trace.get_current_span().set_status(Status(StatusCode.ERROR, str(circuit_error)))
28    trace.get_current_span().record_exception(circuit_error)

By coupling in-memory or Redis-backed token circuit breakers with tracing spans, teams establish an explicit upper bound on blast radius, preventing billing spikes and API quota exhaustion.


6. Tracing Standards & Tooling Matrix

Selecting an observability and evaluation stack requires balancing standard OpenTelemetry compliance, hosting overhead, and native agent support.

Tool / FrameworkOTel GenAI ComplianceAgent Graph TracingAsynchronous EvalsDeployment ModelBest Suited For
OpenLLMetry (Traceloop)Native (Core Contributor)Yes (Hierarchical)Integrates with Ragas / CustomOpen-source SDK + Hosted/Self-HostedTeams standardizing on pure OpenTelemetry collectors.
LangfuseFull OTel IngestionYes (Visual DAGs)Native LLM-as-a-judge + WebhooksOpen-Source & Managed CloudProduction agent teams needing unified tracing, evals, and datasets.
Maxim AICustom with OTel AdaptersYesIntegrated Continuous EvalsSaaSEnterprise teams prioritizing end-to-end evaluation and simulation.
Phoenix (Arize)Native OTel ExportYesNative Evals EngineOpen-Source & CloudData science and ML engineering teams monitoring embedding drift.
Datadog / Dynatrace APMPartial / Custom GenAI integrationsLimited Agent SupportBasic Metric ThresholdsSaaSLegacy enterprises centralizing AI metrics into existing infrastructure APMs.

For engineers already working with typed agent harnesses like Pydantic AI v2, native OTel hooks make it straightforward to export structured payloads without refactoring application logic.


7. Production Verification & Operational Checklist

Before promoting agentic workflows to production, verify your observability and governance infrastructure against this operational checklist:

  • Standard Attribute Compliance: All generative model spans output official gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens, and gen_ai.usage.output_tokens conventions.
  • Context Hierarchy: Every tool invocation and sub-agent step carries the active trace context and correctly links to the orchestrator root span.
  • Data Redaction & Sanitization: PII, API tokens, and credentials are scrubbed by an OpenTelemetry processor before payloads reach external tracing stores.
  • Automated Cost Guards: Maximum step counts and per-request token limits are enforced via gateway-level or in-memory circuit breakers.
  • Asynchronous Quality Sampling: A background evaluation pipeline actively samples traces to monitor faithfulness and relevance scores.
  • Alerting Thresholds: Metric alarms trigger on moving averages of token consumption anomalies, finish reason errors (e.g., content_filter), and eval score regressions.

Frequently asked questions

What are OpenTelemetry GenAI Semantic Conventions?

OpenTelemetry GenAI Semantic Conventions are standardized naming rules and schema definitions maintained by the OpenTelemetry project. They define consistent attribute keys for generative AI systems (such as gen_ai.system, gen_ai.usage.input_tokens, and gen_ai.request.temperature) so engineering teams can switch model providers or observability backends without rewriting their instrumentation code.

How does agent distributed tracing differ from traditional microservice tracing?

Traditional microservice tracing tracks synchronous RPC or HTTP boundaries between deterministic services. Agent distributed tracing must map non-deterministic, multi-step execution graphs—including dynamic reasoning steps, vector database retrievals, tool arguments, and recursive self-reflection loops—under a single parent workflow trace.

What is the performance overhead of continuous evaluations?

Running comprehensive evaluations (like LLM-as-a-judge) synchronously on every request introduces massive latency (often 1–3 seconds) and doubles token costs. In production, teams mitigate this by running evaluations asynchronously on an out-of-band queue (e.g., Kafka or Celery) against a sampled percentage (5–10%) of production spans.

How do cost circuit breakers prevent runaway agent loops?

Cost circuit breakers maintain running counters of step depth and cumulative token consumption for an individual session. If an agent enters an infinite retry loop or generates excessive output, the circuit breaker trips, halts the execution loop, logs an error span, and invokes a fallback response before consuming uncontrolled API budget.


Sources and image references

Keep reading

#OpenTelemetry#AI Observability#Multi-Agent Systems#LLM Tracing#Evaluation
ShareXLinkedIn

⚡ AI Engineering Briefing

AI model releases, practical tutorials, developer tools, and engineering research. Unsubscribe anytime.

Comments

Comments are temporarily unavailable while the public discussion space is being configured.