This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-genai-semantic-conventions-distributed-tracing

OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows

Standardizes token accounting, guardrail evaluation latency, and distributed trace context propagation across asynchronous, multi-agent LLM inference topologies. Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions and W3C Trace Context propagation across message brokers and task queues.

Prohibited Anti-Pattern: Ad-Hoc Unstandardized GenAI Telemetry with Broken Distributed Context and Unmeasured Guardrail Overhead

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows - Standardizes token accounting, guardrail evaluation latency, and distributed trace context propagation across asynchronous, multi-agent LLM inference topologies. Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions and W3C Trace Context propagation across message brokers and task queues.
globs: src/telemetry/**/*.{ts,js,py}, src/agents/**/*.{ts,js,py}, src/services/llm/**/*.{ts,js,py}, src/guardrails/**/*.{ts,js,py}, src/queues/**/*.{ts,js,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-genai-semantic-conventions-distributed-tracing"
---

# OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Ad-Hoc Unstandardized GenAI Telemetry with Broken Distributed Context and Unmeasured Guardrail Overhead

## System Constraints
You are a Principal Observability and Infrastructure Architect enforcing OpenTelemetry GenAI Semantic Conventions across all LLM inference pipelines, guardrails, and asynchronous multi-agent coordination layers. Reject any ad-hoc log-based token reporting, missing W3C Trace Context carriers across async boundaries, or monolithic spans that bundle model latency with input/output safety guardrail evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS instrument GenAI operations using OpenTelemetry GenAI Semantic Conventions (e.g., `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).
- Engineers MUST ALWAYS isolate safety and compliance guardrails into distinct child spans with explicit evaluation outcome attributes and execution latency to avoid skewing raw LLM inference metrics.
- Engineers MUST ALWAYS inject and extract W3C `traceparent` and `tracestate` across asynchronous messaging boundaries (e.g., BullMQ, Kafka, SQS) to maintain causal parent-child trace graphs across multi-agent handoffs.
- Services MUST capture streaming token counts deterministically using server-sent event (SSE) accumulators or stream end-events without truncating or buffering stream responses.
- Components NEVER log raw unredacted prompt or completion payloads directly into span attributes unless explicitly configured through an approved, sampled, PII-scrubbed redaction pipeline.

## Bad vs Good Implementations
### Asynchronous Multi-Agent Telemetry with Guardrail Isolation and W3C Context Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example fails to inject/extract W3C Trace Context across BullMQ, breaking trace continuity. It nests guardrail execution inside a generic span without dedicated latency tracking, and it records custom attributes ('prompt_tokens') instead of standardized OpenTelemetry GenAI semantic conventions ('gen_ai.usage.input_tokens').
```typescript
import { trace } from '@opentelemetry/api';
import { Queue, Worker } from 'bullmq';
import { openai } from './client';

const tracer = trace.getTracer('agent-tracer');
const agentQueue = new Queue('agent-tasks');

export async function dispatchAgentTask(taskData: { prompt: string }) {
  // Anti-Pattern: Context lost across queue boundary; payload dumped to logs
  await agentQueue.add('execute-task', taskData);
}

new Worker('agent-tasks', async (job) => {
  // Anti-Pattern: Unstandardized span name, monolithic span combining guardrail and LLM,
  // missing gen_ai.* standard attributes, and no parent trace linkage
  return await tracer.startActiveSpan('run_agent_job', async (span) => {
    const guardrailPassed = await checkSafety(job.data.prompt);
    if (!guardrailPassed) throw new Error('Guardrail violation');

    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: job.data.prompt }]
    });

    // Ad-hoc logging instead of GenAI semantic conventions
    span.setAttribute('prompt_tokens', response.usage?.prompt_tokens ?? 0);
    span.setAttribute('completion_tokens', response.usage?.completion_tokens ?? 0);
    span.end();
    return response.choices[0].message.content;
  });
});
```

#### Production Standard (Correct)
> **Standard**: This implementation injects and extracts W3C context headers across the BullMQ message queue, maintaining unbroken traces across asynchronous workers. Guardrail evaluation latency is isolated into its own span with semantic classification, and the LLM inference operation strictly adheres to OpenTelemetry GenAI Semantic Conventions with standard attribute keys ('gen_ai.system', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').
```typescript
import { trace, context, propagation, SpanStatusCode, SpanKind } from '@opentelemetry/api';
import { Queue, Worker, Job } from 'bullmq';
import { openai } from './client';
import { evaluateGuardrail } from './safety';

const tracer = trace.getTracer('agent-orchestrator', '1.0.0');
const agentQueue = new Queue('agent-tasks');

interface AgentJobPayload {
  prompt: string;
  traceCarrier: Record<string, string>;
}

export async function dispatchAgentTask(prompt: string): Promise<void> {
  await tracer.startActiveSpan('agent.dispatch', { kind: SpanKind.PRODUCER }, async (span) => {
    try {
      const traceCarrier: Record<string, string> = {};
      propagation.inject(context.active(), traceCarrier);
      await agentQueue.add('execute-task', { prompt, traceCarrier });
    } catch (error) {
      span.recordException(error as Error);
      span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
      throw error;
    } finally {
      span.end();
    }
  });
}

new Worker('agent-tasks', async (job: Job<AgentJobPayload>) => {
  const parentContext = propagation.extract(context.active(), job.data.traceCarrier);

  return await context.with(parentContext, async () => {
    return await tracer.startActiveSpan('agent.execute', { kind: SpanKind.CONSUMER }, async (consumerSpan) => {
      try {
        // 1. Isolated Guardrail Span
        await tracer.startActiveSpan('guardrail.input_evaluation', async (guardSpan) => {
          guardSpan.setAttribute('gen_ai.guardrail.name', 'content_safety');
          const result = await evaluateGuardrail(job.data.prompt);
          guardSpan.setAttribute('gen_ai.guardrail.action', result.action);
          guardSpan.setAttribute('gen_ai.guardrail.allowed', result.allowed);
          guardSpan.end();
          if (!result.allowed) {
            throw new Error(`Guardrail violation: ${result.reason}`);
          }
        });

        // 2. Standardized GenAI Chat Span
        const response = await tracer.startActiveSpan(
          'chat gpt-4o',
          { kind: SpanKind.CLIENT },
          async (llmSpan) => {
            llmSpan.setAttribute('gen_ai.operation.name', 'chat');
            llmSpan.setAttribute('gen_ai.system', 'openai');
            llmSpan.setAttribute('gen_ai.request.model', 'gpt-4o');
            llmSpan.setAttribute('gen_ai.request.temperature', 0.7);

            const res = await openai.chat.completions.create({
              model: 'gpt-4o',
              messages: [{ role: 'user', content: job.data.prompt }],
              temperature: 0.7
            });

            llmSpan.setAttribute('gen_ai.response.model', res.model);
            llmSpan.setAttribute('gen_ai.response.id', res.id);
            llmSpan.setAttribute('gen_ai.response.finish_reasons', res.choices.map(c => c.finish_reason).filter(Boolean) as string[]);
            if (res.usage) {
              llmSpan.setAttribute('gen_ai.usage.input_tokens', res.usage.prompt_tokens);
              llmSpan.setAttribute('gen_ai.usage.output_tokens', res.usage.completion_tokens);
            }
            llmSpan.end();
            return res;
          }
        );

        consumerSpan.setStatus({ code: SpanStatusCode.OK });
        return response.choices[0].message.content;
      } catch (error) {
        consumerSpan.recordException(error as Error);
        consumerSpan.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
        throw error;
      } finally {
        consumerSpan.end();
      }
    });
  });
});
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows

OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows defines an industrial-grade behavioral standard for devops engineering. Standardizes token accounting, guardrail evaluation latency, and distributed trace context propagation across asynchronous, multi-agent LLM inference topologies. Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions and W3C Trace Context propagation across message brokers and task queues. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Ad-Hoc Unstandardized GenAI Telemetry with Broken Distributed Context and Unmeasured Guardrail Overhead Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAd-Hoc Unstandardized GenAI Telemetry with Broken Distributed Context and Unmeasured Guardrail OverheadCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS instrument GenAI operations using OpenTelemetry GenAI Semantic Conventions (e.g., `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).

Engineers MUST ALWAYS instrument GenAI operations using OpenTelemetry GenAI Semantic Conventions (e.g., `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS isolate safety and compliance guardrails into distinct child spans with explicit evaluation outcome attributes and execution latency to avoid skewing raw LLM inference metrics.

Engineers MUST ALWAYS isolate safety and compliance guardrails into distinct child spans with explicit evaluation outcome attributes and execution latency to avoid skewing raw LLM inference metrics.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ALWAYS inject and extract W3C `traceparent` and `tracestate` across asynchronous messaging boundaries (e.g., BullMQ, Kafka, SQS) to maintain causal parent-child trace graphs across multi-agent handoffs.

Engineers MUST ALWAYS inject and extract W3C `traceparent` and `tracestate` across asynchronous messaging boundaries (e.g., BullMQ, Kafka, SQS) to maintain causal parent-child trace graphs across multi-agent handoffs.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST capture streaming token counts deterministically using server-sent event (SSE) accumulators or stream end-events without truncating or buffering stream responses.

Services MUST capture streaming token counts deterministically using server-sent event (SSE) accumulators or stream end-events without truncating or buffering stream responses.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER log raw unredacted prompt or completion payloads directly into span attributes unless explicitly configured through an approved, sampled, PII-scrubbed redaction pipeline.

Components NEVER log raw unredacted prompt or completion payloads directly into span attributes unless explicitly configured through an approved, sampled, PII-scrubbed redaction pipeline.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTelemetry GenAI Semantic Conventions for Asynchronous Agentic Workflows critical for AI coding assistants?

Standardizes token accounting, guardrail evaluation latency, and distributed trace context propagation across asynchronous, multi-agent LLM inference topologies. Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions and W3C Trace Context propagation across message brokers and task queues. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Ad-Hoc Unstandardized GenAI Telemetry with Broken Distributed Context and Unmeasured Guardrail Overhead) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenTelemetry