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

OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Invariant

Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions across federated LLM routing gateways and proxy layers. Guarantees immutable propagation of W3C trace context, standardized gen_ai.* metric naming, and explicit exemplar linkage between financial token cost metrics and active spans for SLA audits.

Prohibited Anti-Pattern: Fragmented Ad-Hoc Metric Payloads and Broken W3C Exemplar Linkage in Gateway Dispatchers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Invariant - Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions across federated LLM routing gateways and proxy layers. Guarantees immutable propagation of W3C trace context, standardized gen_ai.* metric naming, and explicit exemplar linkage between financial token cost metrics and active spans for SLA audits.
globs: src/gateway/**/*.ts, src/telemetry/**/*.ts, src/services/llm/**/*.ts, src/orchestration/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-genai-semantic-conventions-exemplar-invariant"
---

# OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Fragmented Ad-Hoc Metric Payloads and Broken W3C Exemplar Linkage in Gateway Dispatchers

## System Constraints
You are a Principal Observability and Infrastructure Architect enforcing OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Context Invariants. You must ensure all outbound LLM requests, model dispatch operations, and token metric recordings adhere to OpenTelemetry GenAI conventions (v1.28.0+), maintain W3C traceparent context propagation, and explicitly bind trace IDs to metric updates via exemplars for continuous cost auditability.

## Strict Guidelines
- Services MUST emit spans matching `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens` adhering strictly to official OTel semantic conventions.
- Engineers MUST ALWAYS extract and inject W3C Distributed Tracing headers (`traceparent`, `tracestate`) across federated upstream router boundaries before making downstream provider API calls.
- Engineers MUST NOT emit custom or unstandardized token counter metrics (e.g., `llm_cost_total` or `prompt_tokens_used`); all token recording MUST bind directly to `gen_ai.client.token.usage` histogram or counter instruments with explicit Exemplars containing the current `trace_id` and `span_id`.
- Spans MUST transition to an `ERROR` status code and explicitly set `error.type` when model invocation fails or rate limits trigger, without swallowing stack traces or trace context.
- Gateways NEVER record raw user prompts or generated model completions into trace attributes unless explicitly masked and gated behind an opt-in privacy flag (`gen_ai.capture_message_content=true`).

## Bad vs Good Implementations
### LLM Routing Gateway Telemetry and Exemplar Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Violates OpenTelemetry GenAI conventions by using custom Prometheus counters instead of standard semantic convention metrics, drops W3C trace propagation headers completely, and fails to record exemplars linking token consumption to the active distributed span.
```typescript
import { Counter } from 'prom-client';
import axios from 'axios';

const tokenCounter = new Counter({
  name: 'llm_tokens_total',
  help: 'Total tokens used by LLMs',
  labelNames: ['model', 'type']
});

export async function routeToModel(prompt: string, model: string) {
  // Missing distributed context propagation
  // Non-standard metric naming without trace exemplars
  const response = await axios.post('https://api.openai.com/v1/chat/completions', {
    model,
    messages: [{ role: 'user', content: prompt }]
  });

  tokenCounter.inc({ model, type: 'prompt' }, response.data.usage.prompt_tokens);
  tokenCounter.inc({ model, type: 'completion' }, response.data.usage.completion_tokens);
  return response.data;
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to OpenTelemetry GenAI Semantic Conventions v1.28+, instruments spans with standardized attributes, passes execution context to token metrics to retain exemplars linking metrics to traces, and maintains end-to-end auditability.
```typescript
import { trace, metrics, SpanKind, SpanStatusCode, context } from '@opentelemetry/api';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';

const tracer = trace.getTracer('llm-federated-gateway', '1.0.0');
const meter = metrics.getMeter('llm-federated-gateway', '1.0.0');

const tokenUsageCounter = meter.createCounter('gen_ai.client.token.usage', {
  description: 'Measures number of input and output tokens consumed',
  unit: '{token}'
});

export async function routeToModel(prompt: string, targetModel: string): Promise<Record<string, unknown>> {
  return tracer.startActiveSpan(`chat ${targetModel}`, { kind: SpanKind.CLIENT }, async (span) => {
    span.setAttributes({
      'gen_ai.system': 'openai',
      'gen_ai.request.model': targetModel,
      'gen_ai.operation.name': 'chat'
    });

    const currentCtx = context.active();
    try {
      const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
        },
        body: JSON.stringify({ model: targetModel, messages: [{ role: 'user', content: prompt }] })
      });

      if (!response.ok) {
        throw new Error(`Upstream gateway error: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      const inputTokens: number = data.usage?.prompt_tokens ?? 0;
      const outputTokens: number = data.usage?.completion_tokens ?? 0;
      const actualModel: string = data.model ?? targetModel;

      span.setAttributes({
        'gen_ai.response.model': actualModel,
        'gen_ai.usage.input_tokens': inputTokens,
        'gen_ai.usage.output_tokens': outputTokens,
        'gen_ai.response.finish_reasons': data.choices?.map((c: { finish_reason: string }) => c.finish_reason)
      });

      // Exemplar attachment through current execution context
      tokenUsageCounter.add(inputTokens, { 'gen_ai.token.type': 'input', 'gen_ai.response.model': actualModel }, currentCtx);
      tokenUsageCounter.add(outputTokens, { 'gen_ai.token.type': 'output', 'gen_ai.response.model': actualModel }, currentCtx);

      span.setStatus({ code: SpanStatusCode.OK });
      return data;
    } catch (error) {
      span.recordException(error as Error);
      span.setStatus({
        code: SpanStatusCode.ERROR,
        message: error instanceof Error ? error.message : 'Unknown routing error'
      });
      span.setAttribute('error.type', error instanceof Error ? error.name : 'UnknownError');
      throw error;
    } finally {
      span.end();
    }
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Invariant

OpenTelemetry GenAI Semantic Conventions and Exemplar Trace Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions across federated LLM routing gateways and proxy layers. Guarantees immutable propagation of W3C trace context, standardized gen_ai.* metric naming, and explicit exemplar linkage between financial token cost metrics and active spans for SLA audits. 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: Fragmented Ad-Hoc Metric Payloads and Broken W3C Exemplar Linkage in Gateway Dispatchers 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 DriftFragmented Ad-Hoc Metric Payloads and Broken W3C Exemplar Linkage in Gateway DispatchersCritical
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

Services MUST emit spans matching `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens` adhering strictly to official OTel semantic conventions.

Services MUST emit spans matching `gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens` adhering strictly to official OTel semantic conventions.

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 extract and inject W3C Distributed Tracing headers (`traceparent`, `tracestate`) across federated upstream router boundaries before making downstream provider API calls.

Engineers MUST ALWAYS extract and inject W3C Distributed Tracing headers (`traceparent`, `tracestate`) across federated upstream router boundaries before making downstream provider API calls.

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 NOT emit custom or unstandardized token counter metrics (e.g., `llm_cost_total` or `prompt_tokens_used`)

Engineers MUST NOT emit custom or unstandardized token counter metrics (e.g., `llm_cost_total` or `prompt_tokens_used`); all token recording MUST bind directly to `gen_ai.client.token.usage` histogram or counter instruments with explicit Exemplars containing the current `trace_id` and `span_id`.

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

Spans MUST transition to an `ERROR` status code and explicitly set `error.type` when model invocation fails or rate limits trigger, without swallowing stack traces or trace context.

Spans MUST transition to an `ERROR` status code and explicitly set `error.type` when model invocation fails or rate limits trigger, without swallowing stack traces or trace context.

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

Gateways NEVER record raw user prompts or generated model completions into trace attributes unless explicitly masked and gated behind an opt-in privacy flag (`gen_ai.capture_message_content=true`).

Gateways NEVER record raw user prompts or generated model completions into trace attributes unless explicitly masked and gated behind an opt-in privacy flag (`gen_ai.capture_message_content=true`).

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 and Exemplar Trace Invariant critical for AI coding assistants?

Enforces strict compliance with OpenTelemetry GenAI Semantic Conventions across federated LLM routing gateways and proxy layers. Guarantees immutable propagation of W3C trace context, standardized gen_ai.* metric naming, and explicit exemplar linkage between financial token cost metrics and active spans for SLA audits. 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 (Fragmented Ad-Hoc Metric Payloads and Broken W3C Exemplar Linkage in Gateway Dispatchers) 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