Markdown Editor

LLM and Agent Observability Specification Template (OpenTelemetry GenAI)

LLM/agent telemetry: objectives, span model, gen_ai.* attributes, token/latency/cost metrics, prompt capture controls, eval hooks, dashboards, SLOs, retention

AI & DataLengkapOpenTelemetry semantic conventions for generative AI (Development)llmobservabilityspec

Cara menggunakan: Use it when an LLM application or agent goes to production and you need traces, metrics and quality signals that answer real operator questions. Fill the objectives, the convention baseline and the prompt and completion capture rules first, and get privacy sign-off before any content reaches telemetry. The main pitfall is copying attribute names from older articles, because the OpenTelemetry GenAI conventions are still in Development and names change.

Pratinjau

LLM and Agent Observability Specification: [System name] [version]

Specification of the telemetry an LLM application or agent system must emit and how that telemetry is processed, protected and used: traces for model calls, tool calls, retrieval and agent steps; metrics for tokens, latency, cost, errors and quality; controlled capture of prompts and completions; evaluation hooks; dashboards, alerts and service level objectives. Attribute, span and metric names follow the OpenTelemetry semantic conventions for generative AI, which have Development status and are now maintained in the semantic-conventions-genai repository. Replace every [bracketed] value and every row marked Example. Worked examples use a support agent that calls a hosted chat model, a retrieval service and three tools.

Document control

FieldValue
Document ID[OBS-LLM-001]
System and version[Name] [version]
Semantic convention baselineExample: OpenTelemetry GenAI semantic conventions, semantic-conventions-genai main branch at commit [sha], YYYY-MM-DD
Telemetry backend[Tracing, metrics and log backends]
Version[0.1]
Status[Draft / In review / Approved / Superseded]
Owner[@ai-platform-owner]
Approvers / reviewers[@sre-lead], [@privacy-officer], [@security-lead]
Last updatedYYYY-MM-DD
Classification[Internal]
Related documents[Observability specification], [Guardrails specification], [Agent evaluation plan], [Model monitoring plan], [AI-BOM]

Approvals

RoleNameDecisionDate
AI platform owner[@name][Approved / Changes requested]YYYY-MM-DD
SRE lead[@name][Decision]YYYY-MM-DD
Privacy officer[@name][Decision]YYYY-MM-DD
Security lead[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft
1.0YYYY-MM-DD[@name]Example: Approved with content capture limited to external store
1.1YYYY-MM-DD[@name]Example: Moved token metrics to gen_ai.client.inference.usage.* after convention update

Contents

1. Objectives and scope

1.1 Objectives

IDQuestion telemetry must answerPrimary users
OBJ-001 (Example)Is the assistant available and fast enough for customers right now?On-call SRE
OBJ-002 (Example)Which step of a slow or failed conversation caused the problem: model, retrieval, tool or guardrail?Engineers
OBJ-003 (Example)How many tokens and how much money does each feature, tenant and model consume?Product, finance
OBJ-004 (Example)Are answers grounded, safe and helpful, and is quality drifting?AI quality team
OBJ-005 (Example)Did an agent take an action it should not have, and can we reconstruct why?Security, incident response
[OBJ-nnn][Question][Users]

1.2 Scope

In scopeOut of scope
Example: Assistant API, agent runtime, retrieval service, tool serversTraining pipelines (see model monitoring plan)
Example: Calls to hosted and self-hosted modelsProvider-internal telemetry we cannot see
Example: Online evaluation and guardrail decisionsOffline benchmark runs
[Item][Item]

2. Telemetry architecture

[Describe the pipeline. Example: "Services use the OpenTelemetry SDK with GenAI instrumentation for the model client and agent framework. Spans and metrics go to a central Collector that applies redaction and tail-based sampling. Prompts and completions are never stored in span attributes in production; an in-process hook writes them, after redaction, to a restricted content store and records a reference on the span."]

3. Signals and span model

3.1 Span model

The tree below shows the spans for one customer turn in which the agent plans, calls the model, retrieves documents, uses one tool and answers.

3.2 Span catalogue

IDOperationSpan name patternKindEmitted byNotes
SPN-001 (Example)Model inference (chat, text_completion, generate_content){gen_ai.operation.name} {gen_ai.request.model}ClientModel client instrumentationOne span per logical call, including automatic retries
SPN-002 (Example)Embeddings (embeddings){gen_ai.operation.name} {gen_ai.request.model}ClientRetrieval service
SPN-003 (Example)Retrieval (retrieval){gen_ai.operation.name} {gen_ai.data_source.id}ClientRetrieval serviceRecords top-k and data source
SPN-004 (Example)Tool execution (execute_tool)execute_tool {gen_ai.tool.name}InternalAgent runtimeOne per tool call, linked by gen_ai.tool.call.id
SPN-005 (Example)Agent invocation (invoke_agent)invoke_agent {gen_ai.agent.name}Internal or clientAgent runtimeParent of the agent's steps
SPN-006 (Example)Planning (plan)plan {gen_ai.agent.name}InternalAgent runtimeOptional
SPN-007 (Example)Workflow (invoke_workflow)invoke_workflow {gen_ai.workflow.name}InternalOrchestratorFor multi-agent flows
SPN-008 (Example)MCP request{mcp.method.name} {target}Client and serverMCP client and serverPer the MCP section of the conventions
SPN-009 (Example)Guardrail checkguardrail {policy}InternalGuardrail serviceCustom: no convention yet; see 4.3
[SPN-nnn][Operation][Pattern][Kind][Emitter][Notes]

3.3 Context propagation

Propagate trace context (W3C Trace Context) across every hop: API to agent runtime, agent runtime to tool servers, and into asynchronous work such as queued tool executions. For MCP over HTTP, use the standard headers; for transports without headers, follow the MCP section of the conventions. Record gen_ai.conversation.id on every span of a conversation so that a multi-turn session can be reassembled without relying on one trace per turn.

4. Attributes and semantic conventions

4.1 Convention baseline

ItemValue
Convention setOpenTelemetry semantic conventions for generative AI
StatusDevelopment (names and semantics may change)
Locationgithub.com/open-telemetry/semantic-conventions-genai (moved from the main semantic conventions repository from release v1.42.0)
Pinned version[Release tag, or main branch commit and date if no release exists]
Core conventions used with itExample: Semantic conventions v1.44.0 for server.*, error.type, HTTP and resource attributes
Review triggerAny new release of the GenAI conventions; quarterly otherwise

4.2 Attribute register

AttributeApplies toOur requirementSourceNotes
gen_ai.operation.nameAll GenAI spansRequiredConventionchat, embeddings, retrieval, execute_tool, invoke_agent and other listed values
gen_ai.provider.nameModel, embedding, retrieval spansRequiredConventionExample: anthropic, openai, aws.bedrock; set to best knowledge when behind a proxy
gen_ai.request.modelModel spansRequiredConventionModel name as requested
gen_ai.response.modelModel spansRequired when returnedConventionExact snapshot that answered; join key to the AI-BOM
gen_ai.response.idModel spansRecommendedConventionCorrelates evaluations and provider support cases
gen_ai.response.finish_reasonsModel spansRequiredConventionDetects truncation, tool calls, content filter stops
gen_ai.request.temperature, gen_ai.request.top_p, gen_ai.request.max_tokensModel spansRequired when setConventionNeeded to reproduce behaviour
gen_ai.usage.input_tokens, gen_ai.usage.output_tokensModel spansRequiredConventionBasis for cost in section 11
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.reasoning.output_tokensModel spansRequired when reportedConventionCached and reasoning tokens are priced differently
gen_ai.conversation.idAll spans of a conversationRequiredConventionPseudonymous ID, never an email or account number
gen_ai.agent.name, gen_ai.agent.idAgent spansRequiredConventionJoin key to the agent specification
gen_ai.tool.name, gen_ai.tool.type, gen_ai.tool.call.idTool spansRequiredConventionTool call arguments and results follow section 7
gen_ai.data_source.idRetrieval spansRequiredConventionIndex or collection identifier
gen_ai.prompt.name, gen_ai.prompt.versionModel spansRequired when a named template is usedConventionJoin key to the prompt registry
gen_ai.output.typeModel spansRecommendedConventionText, JSON, image or speech
server.address, server.portClient spansRecommendedCore conventionsEndpoint and region identification
error.typeAll spansRequired on errorCore conventions (Stable)Low-cardinality error class
gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions, gen_ai.tool.definitionsModel spansOff by defaultConvention (opt-in)Governed by section 7
[Attribute][Spans][Level][Source][Notes]

4.3 Custom attributes

Use a reserved organisation namespace for anything the conventions do not cover, register each attribute here, and propose it upstream when it is generally useful.

AttributeTypeMeaningCardinalityExample
[org].tenant.id (Example)stringCustomer tenant for cost and quotaMedium (bounded by tenant count)t-0042
[org].feature (Example)stringProduct feature that issued the callLowhelp-answer
[org].guardrail.policy (Example)stringGuardrail policy evaluatedLowoutput-safety-v6
[org].guardrail.decision (Example)stringAllow, block, redact or escalateLowblock
[org].cost.usd (Example)doubleEstimated cost of the callHigh (value, not label)0.0042
[Attribute][Type][Meaning][Cardinality][Example]

5. Metrics

5.1 Convention metrics

MetricInstrument and unitUseNotes
gen_ai.client.inference.durationHistogram, sEnd-to-end latency of a model callSame value as the inference span duration
gen_ai.client.inference.time_to_first_chunkHistogram, sStreaming responsivenessStreaming calls only
gen_ai.client.inference.time_per_output_chunkHistogram, sGeneration speedStreaming calls only
gen_ai.client.inference.usage.input_tokens, gen_ai.client.inference.usage.output_tokensCounters, tokensToken consumption and cost proxyBroken down by gen_ai.token.modality
gen_ai.client.inference.usage.cache_read.input_tokens, gen_ai.client.inference.usage.reasoning.output_tokensCounters, tokensCache effectiveness, reasoning shareSubsets of the input and output counters
gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokensHistograms, tokensPer-call size percentiles and outliersDo not sum these for totals
gen_ai.client.operation.durationHistogram, sDuration of non-inference GenAI operations
gen_ai.server.request.duration, gen_ai.server.time_to_first_token, gen_ai.server.time_per_output_tokenHistograms, sSelf-hosted model serversOnly where we operate the server
gen_ai.invoke_workflow.durationHistogram, sMulti-agent workflow latency
mcp.client.operation.duration, mcp.server.operation.durationHistograms, sTool server latencyMCP section of the conventions

5.2 Derived metrics

IDMetricDefinitionLabelsObjective
MET-001 (Example)Error rateModel spans with error.type set / all model spansprovider, model, featureOBJ-001
MET-002 (Example)Tool failure rateexecute_tool spans with error / all tool spanstoolOBJ-002
MET-003 (Example)Truncation rateResponses with finish reason length / all responsesmodel, featureOBJ-004
MET-004 (Example)Refusal rateResponses classified as refusal by the online evaluator / all responsesfeatureOBJ-004
MET-005 (Example)Guardrail block rateGuardrail decisions block / all guardrail checkspolicy, directionOBJ-004, OBJ-005
MET-006 (Example)Groundedness scoreMean gen_ai.evaluation.score.value for evaluation groundednessfeatureOBJ-004
MET-007 (Example)Steps per taskCount of child spans of invoke_agentagentOBJ-002
MET-008 (Example)Cost per conversationSum of [org].cost.usd over a conversationfeature, tenant tierOBJ-003
[MET-nnn][Metric][Definition][Labels][Objective]

5.3 Cardinality budget

LabelAllowed on metricsReason
gen_ai.request.model, gen_ai.provider.name, gen_ai.operation.nameYesBounded
gen_ai.tool.name, gen_ai.agent.nameYesBounded by registry
[org].tenant.idOnly on cost metricsBounded, but large
gen_ai.conversation.id, gen_ai.response.id, gen_ai.tool.call.idNoUnbounded; use traces

6. Logs and events

EventSourceContentCorrelation
gen_ai.evaluation.resultOnline evaluatorsgen_ai.evaluation.name, gen_ai.evaluation.score.value, gen_ai.evaluation.score.label, gen_ai.evaluation.explanationParent span or gen_ai.response.id
gen_ai.client.inference.operation.detailsModel client (opt-in)Request and response details, including content when enabledInference span
gen_ai.client.operation.exceptionModel clientException detailsFailing span
[org].guardrail.decision (Example)Guardrail servicePolicy, decision, category, no raw contentGuardrail span
[org].agent.action (Example)Agent runtimeSide-effecting action, target, confirmation statusTool span
[Event][Source][Content][Correlation]

Agent actions with side effects (refunds, emails, data changes) are also written to the audit log with the trace ID, so that security can reconstruct an action even when trace sampling dropped the trace.

7. Prompt and completion capture

7.1 Capture modes

ModeDescriptionAllowed in
M0 OffNo content recorded; metadata onlyAll environments (default)
M1 On span attributesgen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions on spansExample: Development and test with synthetic data only
M2 External store with referenceContent written by an in-process hook to a restricted store; span holds a referenceExample: Production, sampled, after redaction
M3 Full for an incidentTemporary M2 at 100% sampling for one tenant or featureExample: Production, with approval, maximum [7] days

7.2 Controls

ControlRule
Consent and noticeExample: Privacy notice states that conversations may be reviewed for quality; enterprise tenants can opt out contractually, and opted-out tenants are M0
RedactionExample: Hook removes payment card numbers, government IDs, secrets and access tokens by pattern and classifier before storage; redaction counts recorded as metrics
SamplingExample: M2 at [5]% of conversations, stratified by feature; 100% of conversations with a guardrail block or negative feedback
Tool arguments and resultsExample: gen_ai.tool.call.arguments and gen_ai.tool.call.result follow the same mode and redaction as messages
Retrieved documentsExample: Store document IDs and scores, not document text
TruncationExample: Message content truncated at [n] characters while preserving JSON structure
ConfigurationExample: Capture enabled only through deployment configuration reviewed by privacy; instrumentation flags such as OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT are off in production images
Data subject requestsExample: Content store indexed by pseudonymous conversation ID so that erasure requests can be honoured
[Control][Rule]

8. Evaluation hooks

IDEvaluatorTypeInputSampleOutputOwner
EVH-001 (Example)GroundednessLLM-as-judge with rubricAnswer and retrieved document IDs resolved from the content store[5]% of M2 conversationsgen_ai.evaluation.result, name groundedness, score 0 to 1[@quality-owner]
EVH-002 (Example)Refusal detectorClassifierAnswer text100% (runs in-process, stores label only)Event with label refusal or answer[@quality-owner]
EVH-003 (Example)Task successRule on outcomeTicket closed without escalation within [24] hours100%Event joined by conversation ID[@product-owner]
EVH-004 (Example)User feedbackExplicit thumbs up or downUI event100%Event with label[@product-owner]
[EVH-nnn][Evaluator][Type][Input][Sample][Output][@owner]

Evaluator models are themselves recorded in the AI-BOM and their spans are tagged with [org].feature set to evaluation so that their cost and latency do not pollute production figures.

9. Dashboards

DashboardAudiencePanelsObjective
DSH-001 (Example) Service healthOn-callRequest rate, error rate (MET-001), p50/p95/p99 gen_ai.client.inference.duration, time to first chunk, provider statusOBJ-001
DSH-002 (Example) Agent behaviourEngineersSteps per task (MET-007), tool failure rate (MET-002), top slow spans, trace exemplarsOBJ-002
DSH-003 (Example) Tokens and costProduct, financeTokens by model and feature, cache read share, cost per conversation (MET-008), budget burnOBJ-003
DSH-004 (Example) Quality and safetyAI quality teamGroundedness (MET-006), refusal rate (MET-004), guardrail block rate (MET-005), feedback ratio, truncation rateOBJ-004
DSH-005 (Example) Agent actionsSecuritySide-effecting actions by tool, confirmations, blocked actions, anomaliesOBJ-005
[DSH-nnn][Audience][Panels][Objective]

10. Alerts and service level objectives

10.1 Service level objectives

IDSLITargetWindowMeasurement
SLO-001 (Example)Share of chat requests that complete without error[99.5]%28 daysServer spans without error.type / all server spans
SLO-002 (Example)Share of streaming answers with first chunk under [2] s[95]%28 daysgen_ai.client.inference.time_to_first_chunk
SLO-003 (Example)Share of evaluated answers with groundedness at least [0.8][90]%7 daysEVH-001 events
[SLO-nnn][SLI][Target][Window][Query]

10.2 Alerts

IDConditionSeverityRouteRunbook
ALR-001 (Example)SLO-001 burn rate above [14] over 1 hourPageOn-call SRERB-LLM-01 provider failover
ALR-002 (Example)Tool failure rate above [5]% for 15 minutes for any toolPageAgent platform on-callRB-LLM-02
ALR-003 (Example)Guardrail block rate doubles against 7-day baselineTicket, page if above [2]%AI quality and securityRB-LLM-03 possible attack or regression
ALR-004 (Example)Daily cost above [120]% of budgetTicketPlatform ownerRB-LLM-04
ALR-005 (Example)Side-effecting tool calls without confirmation eventPageSecurityRB-LLM-05 agent containment
ALR-006 (Example)gen_ai.response.model changes without a releaseTicketAI platformRB-LLM-06 unannounced model change
[ALR-nnn][Condition][Severity][Route][Runbook]

11. Cost attribution

ItemRule
Price sourceExample: Price table [repo]/pricing.yaml, versioned, owned by finance; one row per provider, model and token category
CalculationInput, cached input, output and reasoning tokens multiplied by their unit prices; result stored as [org].cost.usd on the span
Attribution keys[org].feature, [org].tenant.id, gen_ai.agent.name, gen_ai.request.model
Shared costsExample: Embedding and evaluator calls allocated to the feature that triggered them
ReconciliationExample: Monthly comparison with provider invoices; difference above [3]% investigated
BudgetsExample: Monthly budget per feature with alert ALR-004

12. Data retention and access control

Data classExamplesRetentionAccessStorage
MetricsConvention and derived metricsExample: 13 monthsEngineering, product, financeMetrics backend
Traces without contentSpan metadataExample: 30 daysEngineeringTrace backend
Captured content (M2, M3)Redacted prompts, completions, tool argumentsExample: 30 days, then deletedNamed reviewers in the AI quality team; access loggedContent store, encrypted, separate keys
Evaluation eventsScores and labelsExample: 13 monthsAI quality teamLog backend
Agent action audit logSide-effecting actionsExample: [n] years per records policySecurity, auditAudit store, append-only
[Class][Examples][Retention][Access][Storage]

Access reviews run every [quarter]. Exports of content outside the content store require approval from the privacy officer and are logged.

13. Rollout and verification

IDCheckMethodPass criterion
VER-001 (Example)Span names and attributes match section 4Automated test against recorded traces100% of required attributes present
VER-002 (Example)Redaction removes seeded secrets and identifiersInject synthetic records in stagingZero seeded values in the content store
VER-003 (Example)Content capture off in production imagesConfiguration scan in CIFlag absent or false
VER-004 (Example)Token counts match provider usageCompare one day of metrics with provider consoleWithin [1]%
VER-005 (Example)Every alert fires in a game dayFault injectionAll alerts reach the right route
[VER-nnn][Check][Method][Criterion]

14. Glossary and references

TermMeaning in this document
SpanA timed operation in a trace, such as one model call or one tool execution
Semantic conventionsAgreed names and meanings for telemetry attributes, spans, metrics and events
Development statusOpenTelemetry stability level meaning a convention may still change without a deprecation period
Content captureRecording prompts, instructions, retrieved text, tool arguments or completions in telemetry
GroundednessDegree to which an answer is supported by the retrieved sources
Burn rateSpeed at which an SLO error budget is being consumed

References:

Standard and licence note

Based on the OpenTelemetry semantic conventions for generative AI (Development status, semantic-conventions-genai repository, checked 2026-10-22) and the OpenTelemetry core semantic conventions v1.44.0, published by the OpenTelemetry project under the Apache License 2.0. Attribute, span and metric names are cited for interoperability; all explanatory text is original. Because these conventions are still in Development, check the current version in the repository before instrumenting and update section 4.1. Template licence: MIT.

Templat terkait