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

OpenTelemetry GenAI Semantic Convention Compliance & Distributed Token Budget Guardrails

Enforces strict conformance with OpenTelemetry GenAI Semantic Conventions across all LLM client calls, proxy pipelines, and multi-agent systems. Mandates standard attributes (system, model, token usage), context propagation across asynchronous boundaries via W3C Trace Context and Baggage, and pre-execution token budget validation to prevent cascading financial exhaustion.

Prohibited Anti-Pattern: Ad-Hoc Uninstrumented LLM Invocations Without Distributed Trace Propagation or Pre-Execution Token Budget Bounds

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Convention Compliance & Distributed Token Budget Guardrails - Enforces strict conformance with OpenTelemetry GenAI Semantic Conventions across all LLM client calls, proxy pipelines, and multi-agent systems. Mandates standard attributes (system, model, token usage), context propagation across asynchronous boundaries via W3C Trace Context and Baggage, and pre-execution token budget validation to prevent cascading financial exhaustion.
globs: src/gateways/**/*.{ts,js,py}, src/services/llm/**/*.{ts,js,py}, src/agents/**/*.{ts,js,py}, src/middleware/**/*.{ts,js,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-genai-semantic-conventions-token-budgeting"
---

# OpenTelemetry GenAI Semantic Convention Compliance & Distributed Token Budget Guardrails

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Ad-Hoc Uninstrumented LLM Invocations Without Distributed Trace Propagation or Pre-Execution Token Budget Bounds

## System Constraints
You are a Principal Software Architect enforcing OpenTelemetry GenAI Semantic Conventions and token budgeting. You MUST ensure that every interaction with an external or internal LLM runtime explicitly establishes a CLIENT or INTERNAL span decorated with standardized 'gen_ai.*' semantic conventions. Furthermore, you MUST ensure that W3C tracecontext and baggage are strictly propagated across agent hops, and distributed token budgets are evaluated and decremented using deterministic pre-flight checks before executing external model requests.

## Strict Guidelines
- Engineers MUST ALWAYS initialize an OpenTelemetry SpanKind.CLIENT or SpanKind.INTERNAL for every LLM invocation using the official OpenTelemetry GenAI semantic conventions ('gen_ai.system', 'gen_ai.operation.name', 'gen_ai.request.model').
- Services MUST extract and inject W3C 'traceparent' and 'baggage' across asynchronous message queues, HTTP proxies, and multi-agent dispatch boundaries.
- Engineers MUST NOT emit raw, unmasked prompt contents or completions into span attributes unless telemetry redaction filters and opt-in capture policies ('gen_ai.prompt', 'gen_ai.completion') are explicitly verified.
- Components NEVER execute an LLM inference call without first verifying that the current baggage contains sufficient 'token_budget_remaining' to cover worst-case 'max_tokens' allocation.
- Engineers MUST ALWAYS record token consumption metrics ('gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens') upon stream completion or API return, setting span status to ERROR on provider exceptions or budget depletion.
- Code SHOULD leverage deterministic token estimation functions prior to invocation to reject requests failing budget thresholds before incurring external cloud provider costs.

## Bad vs Good Implementations
### Ad-Hoc LLM Invocation with Dropped Context and Unmetered Budget

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code fails to create an OpenTelemetry span, neglects standard gen_ai.* attributes (model, token usage, system), omits W3C context/baggage propagation, and lacks any token budget guardrails, risking runaway financial costs and breaking distributed trace continuity.
```typescript
import { OpenAI } from 'openai';

const openai = new OpenAI();

export async function routeUserPrompt(prompt: string, userId: string): Promise<string> {
  // Anti-pattern: No OTel span, missing gen_ai conventions, no budget check, no trace context injection
  console.log(`Routing prompt for user: ${userId}`);
  const response = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.choices[0]?.message?.content ?? '';
}
```

#### Production Standard (Correct)
> **Standard**: Conforms fully to OpenTelemetry GenAI semantic conventions with SpanKind.CLIENT, captures standardized 'gen_ai.*' parameters, validates token budget against context baggage prior to execution, safely handles errors, and records actual token consumption upon resolution.
```typescript
import { context, trace, SpanKind, SpanStatusCode, propagation } from '@opentelemetry/api';
import { OpenAI } from 'openai';

const tracer = trace.getTracer('llm-gateway', '1.0.0');
const openai = new OpenAI();

export class TokenBudgetExceededError extends Error {
  constructor(remaining: number, required: number) {
    super(`Token budget exceeded: required ${required}, remaining ${remaining}`);
    this.name = 'TokenBudgetExceededError';
  }
}

export async function routeUserPrompt(
  prompt: string,
  userId: string,
  maxExpectedTokens: number = 2048
): Promise<string> {
  return tracer.startActiveSpan(
    'chat gpt-4o',
    {
      kind: SpanKind.CLIENT,
      attributes: {
        'gen_ai.system': 'openai',
        'gen_ai.operation.name': 'chat',
        'gen_ai.request.model': 'gpt-4o',
        'gen_ai.request.max_tokens': maxExpectedTokens,
        'enduser.id': userId,
      },
    },
    async (span) => {
      try {
        // Inspect and enforce budget from distributed baggage
        const baggage = propagation.getBaggage(context.active());
        const rawBudget = baggage?.getEntry('token_budget_remaining')?.value;
        const budgetRemaining = rawBudget ? parseInt(rawBudget, 10) : Infinity;

        if (budgetRemaining < maxExpectedTokens) {
          throw new TokenBudgetExceededError(budgetRemaining, maxExpectedTokens);
        }

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

        const usage = response.usage;
        if (usage) {
          span.setAttribute('gen_ai.usage.input_tokens', usage.prompt_tokens);
          span.setAttribute('gen_ai.usage.output_tokens', usage.completion_tokens);
        }
        span.setAttribute('gen_ai.response.model', response.model);
        span.setStatus({ code: SpanStatusCode.OK });

        return response.choices[0]?.message?.content ?? '';
      } catch (error: unknown) {
        span.recordException(error as Error);
        span.setStatus({
          code: SpanStatusCode.ERROR,
          message: error instanceof Error ? error.message : 'Unknown error',
        });
        throw error;
      } finally {
        span.end();
      }
    }
  );
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry GenAI Semantic Convention Compliance & Distributed Token Budget Guardrails

OpenTelemetry GenAI Semantic Convention Compliance & Distributed Token Budget Guardrails defines an industrial-grade behavioral standard for devops engineering. Enforces strict conformance with OpenTelemetry GenAI Semantic Conventions across all LLM client calls, proxy pipelines, and multi-agent systems. Mandates standard attributes (system, model, token usage), context propagation across asynchronous boundaries via W3C Trace Context and Baggage, and pre-execution token budget validation to prevent cascading financial exhaustion. 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 Uninstrumented LLM Invocations Without Distributed Trace Propagation or Pre-Execution Token Budget Bounds 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 Uninstrumented LLM Invocations Without Distributed Trace Propagation or Pre-Execution Token Budget BoundsCritical
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 initialize an OpenTelemetry SpanKind.CLIENT or SpanKind.INTERNAL for every LLM invocation using the official OpenTelemetry GenAI semantic conventions ('gen_ai.system', 'gen_ai.operation.name', 'gen_ai.request.model').

Engineers MUST ALWAYS initialize an OpenTelemetry SpanKind.CLIENT or SpanKind.INTERNAL for every LLM invocation using the official OpenTelemetry GenAI semantic conventions ('gen_ai.system', 'gen_ai.operation.name', 'gen_ai.request.model').

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

Services MUST extract and inject W3C 'traceparent' and 'baggage' across asynchronous message queues, HTTP proxies, and multi-agent dispatch boundaries.

Services MUST extract and inject W3C 'traceparent' and 'baggage' across asynchronous message queues, HTTP proxies, and multi-agent dispatch boundaries.

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 raw, unmasked prompt contents or completions into span attributes unless telemetry redaction filters and opt-in capture policies ('gen_ai.prompt', 'gen_ai.completion') are explicitly verified.

Engineers MUST NOT emit raw, unmasked prompt contents or completions into span attributes unless telemetry redaction filters and opt-in capture policies ('gen_ai.prompt', 'gen_ai.completion') are explicitly verified.

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

Components NEVER execute an LLM inference call without first verifying that the current baggage contains sufficient 'token_budget_remaining' to cover worst-case 'max_tokens' allocation.

Components NEVER execute an LLM inference call without first verifying that the current baggage contains sufficient 'token_budget_remaining' to cover worst-case 'max_tokens' allocation.

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

Engineers MUST ALWAYS record token consumption metrics ('gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens') upon stream completion or API return, setting span status to ERROR on provider exceptions or budget depletion.

Engineers MUST ALWAYS record token consumption metrics ('gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens') upon stream completion or API return, setting span status to ERROR on provider exceptions or budget depletion.

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.
6

Code SHOULD leverage deterministic token estimation functions prior to invocation to reject requests failing budget thresholds before incurring external cloud provider costs.

Code SHOULD leverage deterministic token estimation functions prior to invocation to reject requests failing budget thresholds before incurring external cloud provider costs.

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 Convention Compliance & Distributed Token Budget Guardrails critical for AI coding assistants?

Enforces strict conformance with OpenTelemetry GenAI Semantic Conventions across all LLM client calls, proxy pipelines, and multi-agent systems. Mandates standard attributes (system, model, token usage), context propagation across asynchronous boundaries via W3C Trace Context and Baggage, and pre-execution token budget validation to prevent cascading financial exhaustion. 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 Uninstrumented LLM Invocations Without Distributed Trace Propagation or Pre-Execution Token Budget Bounds) 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