This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-genai-token-circuit-breaker

OpenTelemetry GenAI Token Budget & Financial Circuit Breaker Standard

Enforces real-time aggregation of OpenTelemetry semantic convention GenAI span metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across agentic execution graphs. Mandates immediate circuit breaker trips and graceful loop termination when cumulative financial costs or sliding-window latency bounds breach predefined envelopes.

Prohibited Anti-Pattern: Unbounded Agentic Execution Loops Without In-Flight Telemetry-Driven Cost Circuit Breakers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Token Budget & Financial Circuit Breaker Standard - Enforces real-time aggregation of OpenTelemetry semantic convention GenAI span metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across agentic execution graphs. Mandates immediate circuit breaker trips and graceful loop termination when cumulative financial costs or sliding-window latency bounds breach predefined envelopes.
globs: src/agents/**/*.{ts,tsx}, src/telemetry/**/*.{ts,tsx}, src/llm/**/*.{ts,tsx}, src/orchestration/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-genai-token-circuit-breaker"
---

# OpenTelemetry GenAI Token Budget & Financial Circuit Breaker Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Agentic Execution Loops Without In-Flight Telemetry-Driven Cost Circuit Breakers

## System Constraints
You are a Principal DevOps and AI Systems Architect enforcing strict OpenTelemetry GenAI semantic conventions and real-time financial circuit breakers. You must ensure that every LLM call, tool invocation, and recursive agent step records compliant GenAI metrics and validates cumulative usage against dynamic cost and latency budgets before and during invocation. If an agent exceeds its allocated envelope, it must abort gracefully, record an error span event, and prevent cascading financial loss.

## Strict Guidelines
- Services MUST capture standardized OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) on every generative invocation span.
- Engineers MUST wrap agentic execution loops in an active Contextual Token Budget Tracker that intercepts outgoing model dispatches.
- Engineers MUST NOT decouple agentic retry logic from token usage accounting; retries count toward the cumulative financial ceiling.
- The circuit breaker MUST evaluate both cumulative execution cost (USD equivalent) and sliding-window step latency prior to dispatching subsequent graph transitions.
- When a budget threshold is exceeded, the system MUST emit a metric counter with `gen_ai.circuit_breaker.state = tripped`, set span status to `StatusCode.ERROR`, and throw an explicit `BudgetExceededException` to interrupt execution.

## Bad vs Good Implementations
### Unbounded Agent Loop vs. OTel Instrumented Circuit Breaker Loop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The loop relies solely on an arbitrary iteration count, completely ignoring actual token consumption and financial spend. It fails to emit OTel GenAI semantic attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), creating a severe risk of high financial loss if the model generates large context outputs per iteration.
```typescript
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('agent-tracer');

export async function runAgentLoop(prompt: string, llmClient: any): Promise<string> {
  return tracer.startActiveSpan('agent.run', async (span) => {
    let state = prompt;
    let iterations = 0;
    // ANTI-PATTERN: No token usage aggregation, unbounded loop, lack of semantic GenAI metrics
    while (iterations < 50) {
      const response = await llmClient.chat({
        messages: [{ role: 'user', content: state }],
      });
      state = response.text;
      if (response.isDone) {
        span.end();
        return state;
      }
      iterations++;
    }
    span.end();
    throw new Error('Iteration limit reached');
  });
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to OpenTelemetry GenAI semantic conventions by attaching `gen_ai.system`, `gen_ai.request.model`, and usage token counters to every span. The execution relies on a dedicated `TokenCircuitBreaker` that tracks cumulative usage and financial costs across turns, aborting execution immediately when thresholds are breached.
```typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('agent-governance');

export interface BudgetConfig {
  maxTokens: number;
  maxCostUsd: number;
  costPer1kInputTokens: number;
  costPer1kOutputTokens: number;
}

export class TokenCircuitBreaker {
  private totalInputTokens = 0;
  private totalOutputTokens = 0;

  constructor(private readonly config: BudgetConfig) {}

  public recordUsage(inputTokens: number, outputTokens: number): void {
    this.totalInputTokens += inputTokens;
    this.totalOutputTokens += outputTokens;

    const totalCost = 
      (this.totalInputTokens / 1000) * this.config.costPer1kInputTokens +
      (this.totalOutputTokens / 1000) * this.config.costPer1kOutputTokens;

    if (
      this.totalInputTokens + this.totalOutputTokens > this.config.maxTokens ||
      totalCost > this.config.maxCostUsd
    ) {
      throw new Error(`TokenBudgetExceeded: Cost $${totalCost.toFixed(4)} breached ceiling.`);
    }
  }
}

export async function runAgentLoop(
  prompt: string,
  llmClient: any,
  budget: BudgetConfig
): Promise<string> {
  const breaker = new TokenCircuitBreaker(budget);
  return tracer.startActiveSpan('gen_ai.agent.execution', async (agentSpan) => {
    try {
      let state = prompt;
      let done = false;

      while (!done) {
        await tracer.startActiveSpan('gen_ai.client.request', async (llmSpan) => {
          llmSpan.setAttribute('gen_ai.system', 'openai');
          llmSpan.setAttribute('gen_ai.request.model', 'gpt-4o');

          const response = await llmClient.chat({ messages: [{ role: 'user', content: state }] });
          
          const inputTokens = response.usage.prompt_tokens;
          const outputTokens = response.usage.completion_tokens;

          llmSpan.setAttribute('gen_ai.usage.input_tokens', inputTokens);
          llmSpan.setAttribute('gen_ai.usage.output_tokens', outputTokens);

          breaker.recordUsage(inputTokens, outputTokens);

          state = response.text;
          done = response.isDone;
          llmSpan.setStatus({ code: SpanStatusCode.OK });
          llmSpan.end();
        });
      }
      agentSpan.setStatus({ code: SpanStatusCode.OK });
      return state;
    } catch (err: unknown) {
      agentSpan.recordException(err as Error);
      agentSpan.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
      throw err;
    } finally {
      agentSpan.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 Token Budget & Financial Circuit Breaker Standard

OpenTelemetry GenAI Token Budget & Financial Circuit Breaker Standard defines an industrial-grade behavioral standard for devops engineering. Enforces real-time aggregation of OpenTelemetry semantic convention GenAI span metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across agentic execution graphs. Mandates immediate circuit breaker trips and graceful loop termination when cumulative financial costs or sliding-window latency bounds breach predefined envelopes. 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: Unbounded Agentic Execution Loops Without In-Flight Telemetry-Driven Cost Circuit Breakers 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 DriftUnbounded Agentic Execution Loops Without In-Flight Telemetry-Driven Cost Circuit BreakersCritical
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 capture standardized OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) on every generative invocation span.

Services MUST capture standardized OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) on every generative invocation span.

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 wrap agentic execution loops in an active Contextual Token Budget Tracker that intercepts outgoing model dispatches.

Engineers MUST wrap agentic execution loops in an active Contextual Token Budget Tracker that intercepts outgoing model dispatches.

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 decouple agentic retry logic from token usage accounting

Engineers MUST NOT decouple agentic retry logic from token usage accounting; retries count toward the cumulative financial ceiling.

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

The circuit breaker MUST evaluate both cumulative execution cost (USD equivalent) and sliding-window step latency prior to dispatching subsequent graph transitions.

The circuit breaker MUST evaluate both cumulative execution cost (USD equivalent) and sliding-window step latency prior to dispatching subsequent graph transitions.

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

When a budget threshold is exceeded, the system MUST emit a metric counter with `gen_ai.circuit_breaker.state = tripped`, set span status to `StatusCode.ERROR`, and throw an explicit `BudgetExceededException` to interrupt execution.

When a budget threshold is exceeded, the system MUST emit a metric counter with `gen_ai.circuit_breaker.state = tripped`, set span status to `StatusCode.ERROR`, and throw an explicit `BudgetExceededException` to interrupt execution.

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 Token Budget & Financial Circuit Breaker Standard critical for AI coding assistants?

Enforces real-time aggregation of OpenTelemetry semantic convention GenAI span metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across agentic execution graphs. Mandates immediate circuit breaker trips and graceful loop termination when cumulative financial costs or sliding-window latency bounds breach predefined envelopes. 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 (Unbounded Agentic Execution Loops Without In-Flight Telemetry-Driven Cost Circuit Breakers) 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