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

OpenTelemetry GenAI Semantic Convention Standard for Multi-Agent Pipelines

Standardizes OpenTelemetry GenAI semantic conventions across autonomous multi-agent pipelines to ensure deterministic context propagation, token quota observability, and vector retrieval traceability. Prohibits custom ad-hoc telemetry attributes, missing parent trace contexts in asynchronous agent handoffs, and untracked embeddings or model tool calls. Enforces compliance with standard `gen_ai.*` namespace attributes across all LLM inference and vector operations.

Prohibited Anti-Pattern: Uncorrelated Agent Handoffs with Ad-Hoc LLM Metadata and Missing Token Accounting Spans

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Convention Standard for Multi-Agent Pipelines - Standardizes OpenTelemetry GenAI semantic conventions across autonomous multi-agent pipelines to ensure deterministic context propagation, token quota observability, and vector retrieval traceability. Prohibits custom ad-hoc telemetry attributes, missing parent trace contexts in asynchronous agent handoffs, and untracked embeddings or model tool calls. Enforces compliance with standard `gen_ai.*` namespace attributes across all LLM inference and vector operations.
globs: src/**/*.ts, src/**/*.js, services/**/*.ts, agents/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-genai-llm-semantic-conventions"
---

# OpenTelemetry GenAI Semantic Convention Standard for Multi-Agent Pipelines

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Uncorrelated Agent Handoffs with Ad-Hoc LLM Metadata and Missing Token Accounting Spans

## System Constraints
You are a Principal Observability Architect enforcing OpenTelemetry GenAI & LLM Semantic Conventions across distributed agentic microservices. Mandate strict compliance with OpenTelemetry GenAI semantic conventions (specifically `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.*`, and vector database conventions). Require continuous W3C Trace Context (`traceparent`, `tracestate`) injection and extraction across asynchronous agent message queues and RPC boundaries. Prohibit custom, non-standard metric keys or uninstrumented fallback paths.

## Strict Guidelines
- Engineers MUST ALWAYS instrument LLM invocations using standard OpenTelemetry GenAI semantic attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).
- Engineers MUST ALWAYS propagate distributed trace context (W3C `traceparent` and `tracestate`) across inter-agent queues, gRPC calls, and asynchronous worker handoffs using the OpenTelemetry `propagation.inject` and `propagation.extract` APIs.
- Engineers MUST NOT introduce non-standard or ad-hoc telemetry attributes (e.g., `llm.tokens.prompt`, `ai_model_name`, `my_agent_duration`) when standard `gen_ai.*` conventions exist.
- Vector search operations MUST record vector database attributes (`db.system`, `gen_ai.vector.query.top_k`, `db.operation.name: 'vector_search'`) and trace downstream context retrieval as child spans of the invoking agent step.
- Services MUST capture finish reasons (`gen_ai.response.finish_reasons`) and record all tool/function call invocations as structured nested spans linking execution context to the primary LLM generation span.

## Bad vs Good Implementations
### Instrumenting Agent LLM Call and Context Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses non-standard span names and custom attribute keys (`ai.model_used`, `prompt_tokens`) instead of OTel `gen_ai.*` conventions, preventing downstream APM collectors and dashboards from indexing token usage, model identifiers, and agent life cycles.
```typescript
import { trace } from '@opentelemetry/api';
import OpenAI from 'openai';

const tracer = trace.getTracer('agent-service');
const openai = new OpenAI();

export async function invokeAgentTask(taskPrompt: string): Promise<string> {
  return tracer.startActiveSpan('run_agent', async (span) => {
    // ANTI-PATTERN: Ad-hoc, non-standard attributes and missing usage/finish metadata
    span.setAttribute('agent.prompt', taskPrompt);
    span.setAttribute('ai.model_used', 'gpt-4o');

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

    // Custom non-standard token metric keys break unified APM dashboards
    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**: Correctly follows OpenTelemetry Semantic Conventions for Generative AI systems (`gen_ai.system`, `gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), handles span exceptions, and records precise finish reasons.
```typescript
import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import OpenAI from 'openai';

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

export async function invokeAgentTask(taskPrompt: string): Promise<string> {
  // Invariant: Span name adheres to GenAI convention '{operation} {target}'
  return tracer.startActiveSpan(
    'chat gpt-4o',
    { kind: SpanKind.CLIENT },
    async (span) => {
      try {
        span.setAttributes({
          'gen_ai.operation.name': 'chat',
          'gen_ai.system': 'openai',
          'gen_ai.request.model': 'gpt-4o',
          'gen_ai.request.max_tokens': 4096,
          'gen_ai.request.temperature': 0.7,
        });

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

        span.setAttributes({
          'gen_ai.response.model': response.model,
          'gen_ai.response.id': response.id,
          'gen_ai.usage.input_tokens': response.usage?.prompt_tokens ?? 0,
          'gen_ai.usage.output_tokens': response.usage?.completion_tokens ?? 0,
          'gen_ai.response.finish_reasons': response.choices.map((c) => c.finish_reason),
        });

        span.setStatus({ code: SpanStatusCode.OK });
        return response.choices[0].message.content ?? '';
      } catch (err: unknown) {
        span.recordException(err instanceof Error ? err : new Error(String(err)));
        span.setStatus({ code: SpanStatusCode.ERROR, message: err instanceof Error ? err.message : 'LLM Invocation Failed' });
        throw err;
      } 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 Convention Standard for Multi-Agent Pipelines

OpenTelemetry GenAI Semantic Convention Standard for Multi-Agent Pipelines defines an industrial-grade behavioral standard for devops engineering. Standardizes OpenTelemetry GenAI semantic conventions across autonomous multi-agent pipelines to ensure deterministic context propagation, token quota observability, and vector retrieval traceability. Prohibits custom ad-hoc telemetry attributes, missing parent trace contexts in asynchronous agent handoffs, and untracked embeddings or model tool calls. Enforces compliance with standard `gen_ai.*` namespace attributes across all LLM inference and vector operations. 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: Uncorrelated Agent Handoffs with Ad-Hoc LLM Metadata and Missing Token Accounting Spans 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 DriftUncorrelated Agent Handoffs with Ad-Hoc LLM Metadata and Missing Token Accounting SpansCritical
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 LLM invocations using standard OpenTelemetry GenAI semantic attributes (`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 LLM invocations using standard OpenTelemetry GenAI semantic attributes (`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 propagate distributed trace context (W3C `traceparent` and `tracestate`) across inter-agent queues, gRPC calls, and asynchronous worker handoffs using the OpenTelemetry `propagation.inject` and `propagation.extract` APIs.

Engineers MUST ALWAYS propagate distributed trace context (W3C `traceparent` and `tracestate`) across inter-agent queues, gRPC calls, and asynchronous worker handoffs using the OpenTelemetry `propagation.inject` and `propagation.extract` APIs.

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 introduce non-standard or ad-hoc telemetry attributes (e.g., `llm.tokens.prompt`, `ai_model_name`, `my_agent_duration`) when standard `gen_ai.*` conventions exist.

Engineers MUST NOT introduce non-standard or ad-hoc telemetry attributes (e.g., `llm.tokens.prompt`, `ai_model_name`, `my_agent_duration`) when standard `gen_ai.*` conventions exist.

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

Vector search operations MUST record vector database attributes (`db.system`, `gen_ai.vector.query.top_k`, `db.operation.name

Vector search operations MUST record vector database attributes (`db.system`, `gen_ai.vector.query.top_k`, `db.operation.name: 'vector_search'`) and trace downstream context retrieval as child spans of the invoking agent step.

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

Services MUST capture finish reasons (`gen_ai.response.finish_reasons`) and record all tool/function call invocations as structured nested spans linking execution context to the primary LLM generation span.

Services MUST capture finish reasons (`gen_ai.response.finish_reasons`) and record all tool/function call invocations as structured nested spans linking execution context to the primary LLM generation 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.
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 Standard for Multi-Agent Pipelines critical for AI coding assistants?

Standardizes OpenTelemetry GenAI semantic conventions across autonomous multi-agent pipelines to ensure deterministic context propagation, token quota observability, and vector retrieval traceability. Prohibits custom ad-hoc telemetry attributes, missing parent trace contexts in asynchronous agent handoffs, and untracked embeddings or model tool calls. Enforces compliance with standard `gen_ai.*` namespace attributes across all LLM inference and vector operations. 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 (Uncorrelated Agent Handoffs with Ad-Hoc LLM Metadata and Missing Token Accounting Spans) 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