Back to series
· 21 min read

Logs, Traces, and Observability for AI Applications


I. Why AI Applications Need Observability

Observability for traditional web applications mainly revolves around HTTP requests, database access, service calls, and system resources.

The execution path of an AI application is far more complex.

A single user request may involve:

  • An API Gateway receiving the request.
  • Authentication and tenant identification.
  • Prompt template loading.
  • Context construction.
  • Vector retrieval.
  • Reranker re-ranking.
  • Model routing.
  • LLM inference.
  • Tool Calling.
  • External API calls.
  • Multi-turn Agent execution.
  • Output parsing and safety checks.
  • Streaming response delivery.

A problem in any one of these stages can affect the final result.

For example, a user may report:

Why were the answers fine yesterday, but today they've suddenly become slower and the answer quality has dropped?

This is not necessarily a problem with the model itself. It could be:

  • Increased latency in the retrieval service.
  • The vector database returned different documents.
  • The prompt template changed.
  • A model version switch.
  • Requests being routed to different GPU nodes.
  • An increase in context length.
  • Retries in Tool Calling.
  • The model service entering a queued state.
  • A drop in cache hit rate.

If the system only records a single HTTP 200 log line, the problem cannot be located.

Therefore, AI applications need a complete observability system covering requests, models, tools, data, and infrastructure.

1. The Three Core Pillars of Observability

Traditional observability usually consists of three parts: Logs, Metrics, and Traces.

Pillar Chinese term Primary question answered
Logs 日志 What happened at a specific point in time?
Metrics 指标 How is the overall system performing?
Traces 链路追踪 Which services and operations did a request pass through?

Each serves a different purpose:

  • Logs preserve specific events and their context.
  • Metrics describe system state and trends over time.
  • Traces reconstruct the full execution path of a single request.

AI applications also need to pay extra attention to model quality and inference cost, so the framework can be extended into five dimensions of observation:

  1. Infrastructure observability.
  2. Application trace observability.
  3. Model inference observability.
  4. Output quality observability.
  5. Cost and business observability.

2. The Complete Observability System

flowchart TD
    A["AI application request"] --> B["Logs"]
    A --> C["Metrics"]
    A --> D["Traces"]
    A --> E["Model quality evaluation"]
    A --> F["Cost and business metrics"]

    B --> G["Unified observability platform"]
    C --> G
    D --> G
    E --> G
    F --> G

    G --> H["Anomaly detection and alerting"]
    G --> I["Trace analysis and issue localization"]
    G --> J["Quality and cost analysis"]
    H --> K["Operations decisions and continuous optimization"]
    I --> K
    J --> K

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style E fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style F fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#F7EAE7,stroke:#C98D7C,color:#754438
    style I fill:#EAF3EC,stroke:#83A995,color:#315D49
    style J fill:#EAF3EC,stroke:#83A995,color:#315D49
    style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F

II. Observability Architecture for AI Applications

Observability should not be just a matter of adding a few log lines to an application; data collection, transport, storage, correlation, querying, and alerting should all be considered at the architecture design stage.

1. Overall Architecture

A typical AI application observability system can be divided into six layers:

Layer Primary Responsibility Typical Components
Application Layer Generates business events and model invocation data API, RAG, Agent
Instrumentation Layer Collects logs, metrics, and traces OpenTelemetry SDK
Collection Layer Receives, processes, and forwards telemetry data OTel Collector
Storage Layer Stores different types of observability data Loki, Prometheus, Tempo
Analysis Layer Queries, correlates, and analyzes LogQL, PromQL, TraceQL
Presentation Layer Dashboards, alerts, and diagnostics Grafana

Overall data pipeline:

flowchart TD
    A["AI Application Service"] --> B["OpenTelemetry SDK"]
    B --> C["Logs"]
    B --> D["Metrics"]
    B --> E["Traces"]

    C --> F["OpenTelemetry Collector"]
    D --> F
    E --> F

    F --> G["Data Filtering and Processing"]
    G --> H["Log Storage"]
    G --> I["Metrics Storage"]
    G --> J["Trace Storage"]

    H --> K["Grafana"]
    I --> K
    J --> K

    K --> L["Dashboards and Alerts"]
    L --> M["Fault Localization and Optimization"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#EAF3EC,stroke:#83A995,color:#315D49
    style D fill:#EAF3EC,stroke:#83A995,color:#315D49
    style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style I fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style J fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style K fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style L fill:#EAF3EC,stroke:#83A995,color:#315D49
    style M fill:#DCEFE5,stroke:#4F8B70,color:#24563F

2. Why Choose OpenTelemetry

OpenTelemetry, abbreviated as OTel

Project: OpenTelemetry

OpenTelemetry is an open-source observability standard and tooling ecosystem for uniformly collecting, processing, and exporting Logs, Metrics, and Traces.

It solves an important problem: data collection methods are inconsistent across different services, languages, and monitoring backends.

Without a unified standard, the following may happen:

  • Python services use one log format.
  • Java services use another Trace SDK.
  • Node.js services use custom metrics.
  • Different monitoring platforms use different data structures.
  • Services cannot pass a unified Trace Context between one another.

OpenTelemetry provides:

API

Defines the programming interface for telemetry data.

SDK

Provides concrete capabilities for data generation, sampling, processing, and export.

Semantic Conventions

Defines unified naming conventions for common operations and resource attributes.

OTLP

OpenTelemetry Protocol, used to transmit telemetry data between services and collection components.

Collector

A standalone data collection and processing component that can receive, process, and export telemetry data.

One of its important design principles is: applications are responsible for generating telemetry data, while the backend is responsible for storage, querying, and analysis.

This reduces coupling between applications and specific monitoring platforms.

3. OpenTelemetry Data Flow

flowchart TD
    A["Application Code"] --> B["Instrumentation"]
    B --> C["OpenTelemetry API"]
    C --> D["OpenTelemetry SDK"]
    D --> E["Batch Processor"]
    E --> F["OTLP Exporter"]
    F --> G["OTel Collector"]
    G --> H["Processor"]
    H --> I["Exporter"]
    I --> J["Observability Backend"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#EAF3EC,stroke:#83A995,color:#315D49
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#EAF3EC,stroke:#83A995,color:#315D49
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style H fill:#EAF3EC,stroke:#83A995,color:#315D49
    style I fill:#EAF3EC,stroke:#83A995,color:#315D49
    style J fill:#DCEFE5,stroke:#4F8B70,color:#24563F

III. Logs: Logging System Design

Logs are the primary way to record system runtime events.

In AI applications, logs must record not only service startup, exceptions, and HTTP requests, but also model calls, retrieval results, tool executions, and task status.

1. Basic Log Categories

Access Logs

Record request entry and response information:

  • Request path.
  • HTTP method.
  • Request status code.
  • Request duration.
  • User or tenant identifier.
  • Request ID.

Application Logs

Record internal application execution events:

  • Business state changes.
  • Task start and end.
  • Configuration loading.
  • Key operations.
  • Exception information.

Model Call Logs

Record metadata for model requests and responses:

  • Model name.
  • Model version.
  • Input token count.
  • Output token count.
  • Model response duration.
  • Finish Reason.
  • Request status.

Tool Call Logs

Record external tool calls made by an Agent or model:

  • Tool name.
  • Tool parameter summary.
  • Tool execution time.
  • Execution result status.
  • Error information.
  • Retry count.

Audit Logs

Record important security and permission events:

  • User identity.
  • Accessed resource.
  • Permission decisions.
  • Data export.
  • Sensitive operations.
  • Administrator operations.

Audit logs and ordinary application logs should be managed separately; in particular, access permissions and retention periods need to be controlled.

2. Why Structured Logging Should Be Used

Traditional logs are usually plain text:

2026-11-23 10:20:30 INFO model request completed in 1200ms

Such logs are readable but unsuitable for complex queries.

For example, to calculate statistics such as:

  • The number of failures for a given model over the past hour.
  • Token consumption for a given tenant.
  • P95 model call latency.
  • All tool calls under a given Trace.

If logs are only plain text, extensive string parsing is required.

Structured JSON logs are recommended:

{
  "timestamp": "2026-11-23T10:20:30.123Z",
  "level": "INFO",
  "service": "ai-gateway",
  "event": "llm.request.completed",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "request_id": "req_8a123",
  "model": "model-v2",
  "model_version": "2026-11-20",
  "input_tokens": 1024,
  "output_tokens": 256,
  "duration_ms": 1200,
  "status": "success"
}

Structured logs offer several advantages:

  1. Fields can be indexed and queried directly.
  2. Aggregation and analysis become possible.
  3. They can be correlated with Metrics and Traces.
  4. Automated alerting is easier to implement.
  5. Different services can follow a unified field specification.

3. Log Level Design

Level Purpose Example
TRACE Extremely fine-grained execution information Internal state changes
DEBUG Debugging information Summary of the Prompt construction process
INFO Normal business events Model call completed
WARN Potential anomalies Retries, degradation, cache misses
ERROR Request or task failure Model service timeout
FATAL Process cannot continue running Failed to start a critical component

In production environments, high-volume DEBUG or TRACE logging should generally not be enabled for extended periods.

Otherwise, it may lead to:

  • Rapid growth in disk usage.
  • Higher log collection costs.
  • Slower query performance.
  • Increased risk of sensitive data exposure.

4. Log Field Specification for AI Applications

It is recommended to establish a unified field naming convention.

Field Description
timestamp Time the event occurred
severity Log level
service.name Service name
service.version Service version
environment Environment
trace_id Trace ID
span_id Current Span ID
request_id Business request ID
session_id Session ID
tenant_id Tenant ID
user_id User identifier
model.name Model name
model.version Model version
operation Operation type
duration_ms Operation duration
status Execution status
error.type Error type

OpenTelemetry defines a number of common semantic attributes, but business fields still need to be extended according to the actual scenario.

It is recommended to manage common fields and business fields separately, so that different teams do not attach different meanings to the same field.

5. Logs Should Not Record Every Prompt and Response Directly

The most common log design mistake in AI applications is writing the complete user input and model output directly into logs.

This may lead to:

  • Leakage of user privacy.
  • Leakage of API Keys.
  • Exposure of passwords and access tokens.
  • Leakage of internal corporate documents.
  • Leakage of personally identifiable information.
  • A sharp rise in log storage costs.

A more reasonable design is to separate content data from telemetry metadata.

Data Default Handling Recommendation
Full Prompt text Do not record by default
Full Response text Do not record by default
Token count May be recorded
Model name May be recorded
Request duration May be recorded
Trace ID May be recorded
User identifier Use masked or irreversible identifiers
API Key Must not be recorded
Sensitive tool parameters Mask or do not record
Error stack trace Record after removing sensitive fields

If the business genuinely needs to retain Prompts and Responses, a separate, controlled data storage mechanism should be established, with:

  • Clear data retention periods.
  • Access control.
  • Encrypted storage.
  • Masking policies.
  • Audit records.
  • User consent and compliance policies.

Do not treat the log system as a database of model conversations.

6. Log Collection and Processing Pipeline

flowchart TD
    A["Business event occurs"] --> B["Generate structured logs"]
    B --> C["Field standardization"]
    C --> D["Sensitive information check"]
    D --> E{"Contains sensitive content?"}
    E -->|Yes| F["Mask or discard"]
    E -->|No| G["Log buffering"]
    F --> G
    G --> H["Batch sending"]
    H --> I["Log collection platform"]
    I --> J["Indexing and storage"]
    J --> K["Query, analysis, and alerting"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#EAF3EC,stroke:#83A995,color:#315D49
    style D fill:#EAF3EC,stroke:#83A995,color:#315D49
    style E fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style F fill:#F7EAE7,stroke:#C98D7C,color:#754438
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style J fill:#EAF3EC,stroke:#83A995,color:#315D49
    style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F

IV. Metrics: Designing the Metric System

Metrics are numeric data collected at fixed time intervals or when events occur.

Logs record individual events, while metrics aggregate a large number of events into time series that can be continuously observed.

For example:

Log:

model request completed in 1200ms

Metric:

model_request_duration_seconds

With metrics, you can observe latency changes over the past 5 minutes, 1 hour, or 24 hours.

1. Basic Metric Types

Common Prometheus metric types include Counter, Gauge, Histogram, and Summary.

Counter: Counter

A Counter can only increase or reset to zero, making it suitable for recording cumulative event counts.

For example:

  • Total number of requests.
  • Total number of errors.
  • Cumulative token consumption.
  • Number of tool calls.
http_requests_total

Counters usually need rate() to calculate the rate of change per unit time:

rate(http_requests_total[5m])

This represents the average per-second request growth rate over the last 5 minutes.

Gauge: Gauge

A Gauge can increase or decrease, making it suitable for describing the state at a certain moment.

For example:

  • Current number of concurrent requests.
  • GPU memory usage.
  • Current queue length.
  • Number of active Agents.
active_requests

Unlike a Counter, a Gauge cannot be used to infer change trends simply from its cumulative value.

Histogram: Histogram

A Histogram is used to collect statistics on the distribution of values.

For example, request latency:

http_request_duration_seconds

It usually includes:

  • Bucket: the cumulative number of observations in different intervals.
  • Sum: the total of observed values.
  • Count: the total number of observations.

Assume the latency Buckets are:

0.1s
0.3s
0.5s
1.0s
2.5s

You can then analyze the request latency distribution and calculate quantiles such as P95 and P99.

Summary: Summary

A Summary can calculate quantiles of observed values on the client side.

For example:

  • P50.
  • P90.
  • P95.
  • P99.

However, Summary quantiles usually cannot be aggregated flexibly on the server side the way Histogram quantiles can.

Therefore, in scenarios that require aggregating latency distributions across instances, Histogram is usually preferred.

2. Core Metric Categories for AI Applications

Metrics for AI applications should not focus only on CPU and memory; they also need to cover models, retrieval, tools, and business tasks.

A. Service-Layer Metrics

Metric Meaning
http_requests_total Total HTTP requests
http_request_duration_seconds HTTP request latency
http_requests_failed_total Number of failed requests
active_requests Currently active requests
request_queue_length Request queue length
connection_pool_active Number of active connections

B. Model Inference Metrics

Metric Meaning
llm_requests_total Total model requests
llm_request_duration_seconds Model call duration
llm_time_to_first_token_seconds Time to first token
llm_time_per_output_token_seconds Average interval between output tokens
llm_input_tokens_total Total input tokens
llm_output_tokens_total Total output tokens
llm_tokens_per_second Token generation rate
llm_request_errors_total Number of model call errors
llm_fallback_total Number of model fallbacks

C. RAG Metrics

Metric Meaning
retrieval_requests_total Total retrieval requests
retrieval_duration_seconds Retrieval duration
retrieval_documents_count Number of returned documents
retrieval_cache_hit_total Number of retrieval cache hits
rerank_duration_seconds Reranking duration
retrieval_empty_results_total Number of empty retrieval results

D. Agent and Tool Metrics

Metric Meaning
agent_tasks_total Total Agent tasks
agent_task_duration_seconds Task execution time
agent_steps_total Number of Agent execution steps
tool_calls_total Number of tool calls
tool_call_duration_seconds Tool call duration
tool_call_errors_total Number of tool call failures
agent_task_success_total Number of successful tasks
agent_max_steps_reached_total Number of times the maximum number of steps was reached

E. Resource Layer Metrics

Metric Meaning
gpu_utilization GPU utilization
gpu_memory_used_bytes GPU memory usage
gpu_memory_total_bytes Total GPU memory
cpu_usage CPU usage
memory_usage_bytes Memory usage
kv_cache_usage_ratio KV Cache usage ratio
gpu_power_watts GPU power consumption

3. AI Application Metrics System

flowchart TD
    A["AI Application Metrics"] --> B["Service Metrics"]
    A --> C["Model Metrics"]
    A --> D["RAG Metrics"]
    A --> E["Agent Metrics"]
    A --> F["Resource Metrics"]
    A --> G["Business Metrics"]

    B --> B1["QPS, error rate, latency"]
    C --> C1["TTFT, TPOT, Token TPS"]
    D --> D1["Retrieval latency, hit rate, document count"]
    E --> E1["Task success rate, step count, tool errors"]
    F --> F1["GPU, CPU, VRAM, KV Cache"]
    G --> G1["User satisfaction, task completion rate, cost"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style F fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style B1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style C1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style D1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style E1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style F1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style G1 fill:#F5F8F4,stroke:#B5CBBB,color:#40594A

4. Prometheus Metric Design

Project: Prometheus

Prometheus is a common open-source monitoring system that uses a time series model to store metrics.

A Prometheus time series is usually determined by the combination of a metric name and labels.

For example:

llm_requests_total{
  model="model-v2",
  status="success",
  region="ap-southeast-1"
}

Different label combinations form different time series.

Pay special attention to Cardinality, i.e., metric cardinality.

Suppose a metric has the following labels:

  • model: 5 values.
  • status: 3 values.
  • region: 4 values.
  • tenant_id: 10,000 values.
  • request_id: different for each request.

The number of combinations can grow rapidly.

In particular, high-cardinality fields such as request_id, user_id, full URLs, and raw prompts should not be used directly as Prometheus labels.

The reason is that each label combination can create an independent time series, leading to:

  • Increased memory usage.
  • Higher indexing costs.
  • Slower queries.
  • Increased storage pressure on Prometheus.

The correct principles are:

  • Metrics use low-cardinality labels.
  • Logs store specific event context.
  • Traces store request-level correlation information.

5. Histogram and P95 Latency

Suppose we define a Histogram:

llm_request_duration_seconds_bucket
llm_request_duration_seconds_sum
llm_request_duration_seconds_count

You can calculate the P95 for the past 5 minutes with PromQL:

histogram_quantile(
  0.95,
  sum by (le) (
    rate(llm_request_duration_seconds_bucket[5m])
  )
)

Here:

  • rate() calculates the rate of change of Bucket counts.
  • sum by (le) aggregates Buckets across different instances.
  • histogram_quantile() estimates quantiles from cumulative Buckets.

If you also want to break it down by model:

histogram_quantile(
  0.95,
  sum by (le, model) (
    rate(llm_request_duration_seconds_bucket[5m])
  )
)

Make sure that Histograms participating in the aggregation use consistent Bucket boundaries.


V. Traces: Distributed Tracing

Trace is used to record the complete execution process of a request across multiple services and operations.

For AI applications, Trace is especially important because a single request may go through multiple model calls, retrieval operations, and tool executions.

1. Trace, Span, and Span Context

To understand distributed tracing, you first need to grasp three concepts.

Trace

A complete request trace.

A Trace can contain multiple Spans.

Span

An independent operation or execution stage.

For example:

  • HTTP Request.
  • Retrieval.
  • Rerank.
  • LLM Generate.
  • Tool Call.

Span Context

Context used to propagate trace correlation information between different services.

The most important parts are:

  • Trace ID.
  • Span ID.
  • Trace Flags.
  • Trace State.

Trace ID identifies the entire trace.

Span ID identifies a specific operation within the trace.

Parent Span ID is used to establish parent-child relationships.

2. Hierarchical Relationships of a Trace

Suppose a user requests a RAG question-answering service:

flowchart TD
    A["HTTP Request"] --> B["Build Context"]
    B --> C["Vector Retrieval"]
    C --> D["Rerank"]
    D --> E["LLM Generate"]
    E --> F["Post Processing"]
    F --> G["HTTP Response"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#EAF3EC,stroke:#83A995,color:#315D49
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#DCEFE5,stroke:#4F8B70,color:#24563F

The above is the business execution flow.

The actual Trace also records the following for each Span:

  • Start time.
  • End time.
  • Duration.
  • Parent Span.
  • Attributes.
  • Events.
  • Status.
  • Exception information.

For example:

Trace ID: 4bf92f3577b34da6a3ce929d0e0e4736

HTTP Request
├── Build Context
├── Vector Retrieval
│   ├── Query Embedding
│   └── Vector Search
├── Rerank
└── LLM Generate
    └── Post Processing

Using the start and end times of Spans, you can analyze how much each stage contributes to overall latency.

3. Trace ID and Span ID

A common Trace ID length is 16 bytes, i.e., 32 hexadecimal characters.

A Span ID is 8 bytes long, i.e., 16 hexadecimal characters.

For example:

trace_id:
4bf92f3577b34da6a3ce929d0e0e4736

span_id:
00f067aa0ba902b7

Different Spans in the same Trace:

  • Have the same Trace ID.
  • Have different Span IDs.
  • Have Parent Span IDs determined based on the parent-child relationship.

Trace ID is used to associate the entire request trace.

Span ID is used to precisely locate a specific operation within it.

4. How Trace Context Propagates Across Services

Services in a distributed system usually run in different processes, or even on different machines.

Without a context propagation mechanism, Service A cannot know which request Service B's operation belongs to.

OpenTelemetry typically uses the W3C Trace Context standard.

The most common propagation field is:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01

Format:

version-trace-id-parent-id-trace-flags

They represent:

  • version: protocol version.
  • trace-id: Trace ID.
  • parent-id: Span ID in the current propagated context.
  • trace-flags: sampling flags and other information.

When Service A calls Service B, it injects the current Trace Context into the request headers.

After Service B extracts the context, it creates a new child Span.

sequenceDiagram
    participant U as User
    participant A as API Gateway
    participant B as RAG Service
    participant C as Model Service

    U->>A: HTTP Request
    A->>A: Create Root Span
    A->>B: Request + traceparent
    B->>B: Extract Context
    B->>B: Create Child Span
    B->>C: Request + traceparent
    C->>C: Extract Context
    C->>C: Create Child Span
    C-->>B: Model Response
    B-->>A: RAG Response
    A-->>U: HTTP Response

5. Trace Propagation in Asynchronous Tasks

Synchronous HTTP calls can usually propagate Trace Context through request headers.

However, AI applications often use message queues and asynchronous tasks.

For example:

  • A user request enters the task queue.
  • A Worker executes the Agent in the background.
  • The Agent calls multiple tools.
  • After the task completes, the user is notified via WebSocket.

In this case, you cannot rely on thread-local or process-local context for automatic propagation.

Trace Context should be injected into the message metadata and extracted on the consumer side.

Producer
   ↓
Inject Trace Context
   ↓
Message Headers
   ↓
Message Queue
   ↓
Consumer
   ↓
Extract Trace Context
   ↓
Create Processing Span

If a message is processed in parallel by multiple consumers, multiple sub-traces may form.

If a task involves batching and merging multiple requests, there may also be multiple parent contexts.

In this case, you need to choose parent-child relationships or Span Links based on the actual semantics, rather than forcibly placing all operations into a single simple parent-child tree.


6. Trace Design for AI Applications

Traditional distributed tracing focuses on service calls.

AI applications also need to incorporate model execution, Prompt construction, retrieval, and tool calls into the Trace.

1. What Should Be Traced in a Single AI Request

It is recommended to split a complete AI request into the following Spans:

Span What Is Traced
http.request Request entry
auth.check Identity authentication
prompt.build Prompt construction
retrieval.query Vector retrieval
retrieval.rerank Re-ranking
llm.request Model request
llm.prefill Prefill phase (optional)
llm.decode Decode phase (optional)
tool.execute Tool execution
agent.step Single Agent step execution
response.format Output formatting
safety.check Safety check

Not every application is required to split out all Spans.

Design should be based on the actual execution path, avoiding producing too many meaningless Spans in pursuit of detail.

2. RAG Chain Tracing

RAG requests typically involve multiple stages.

```mermaid flowchart TD A["User Request"] --> B["Query Preprocessing"] B --> C["Embedding"] C --> D["Vector Retrieval"] D --> E["Document Filtering"] E --> F["Reranking"] F --> G["Context Assembly"] G --> H["LLM Generation"] H --> I["Response Validation"] I --> J["Return Answer"] style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F style B fill:#EAF3EC,stroke:#83A995,color:#315D49 style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style E fill:#EAF3EC,stroke:#83A995,color:#315D49 style F fill:#EAE8FA,stroke:#A49BD5,color:#51477D style G fill:#EAF3EC,stroke:#83A995,color:#315D49 style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style I fill:#F7F4E8,stroke:#C7B77A,color:#675A2D style J fill:#DCEFE5,stroke:#4F8B70,color:#24563F ```

Each stage can record:

Embedding

  • Embedding model name.
  • Number of input tokens.
  • Embedding generation latency.
  • Vector dimensions.
  • Cache hit status.

Vector Retrieval

  • Vector database name.
  • Query latency.
  • Top-K.
  • Number of documents returned.
  • Retrieval score distribution.
  • Summary of filter conditions.

Reranking

  • Reranker model.
  • Number of candidate documents.
  • Reranking latency.
  • Number of documents finally kept.

Context Assembly

  • Context token count.
  • Number of truncated documents.
  • Prompt template version.
  • Context assembly latency.

LLM Generation

  • Model name and version.
  • Input tokens.
  • Output tokens.
  • TTFT.
  • TPOT.
  • Generation latency.
  • Finish Reason.

With these spans, you can pinpoint whether a slow RAG request is slowing down at the retrieval, reranking, or model inference stage.

3. Agent Tracing

Agent execution is usually not a simple linear sequence of calls.

A single task may involve:

  • Task planning.
  • Model inference.
  • Tool selection.
  • Tool invocation.
  • Observation of tool results.
  • Reasoning again.
  • Final answer.

Each round of execution can be designed as an Agent Step.

```mermaid flowchart TD A["Agent Task"] --> B["Planning"] B --> C["LLM Decision"] C --> D{"Need a tool?"} D -->|Yes| E["Tool Selection"] E --> F["Tool Execution"] F --> G["Observation"] G --> C D -->|No| H["Final Response"] H --> I["Task Completed"] style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F style B fill:#EAF3EC,stroke:#83A995,color:#315D49 style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style D fill:#F7F4E8,stroke:#C7B77A,color:#675A2D style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D style F fill:#EAF3EC,stroke:#83A995,color:#315D49 style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style H fill:#DCEFE5,stroke:#4F8B70,color:#24563F style I fill:#DCEFE5,stroke:#4F8B70,color:#24563F ```

Each Agent Step can include:

  • step_index。
  • step_type。
  • model_name。
  • tool_name。
  • duration。
  • input_tokens。
  • output_tokens。
  • status。
  • retry_count。

For example:

Agent Task
├── Step 1: Planning
│   └── LLM Call
├── Step 2: Tool Selection
│   └── LLM Call
├── Step 3: Tool Execution
│   └── Search API
├── Step 4: Observation
│   └── LLM Call
└── Step 5: Final Response
    └── LLM Call

Note that an Agent may have far more Spans than a typical API request.

For long-running Agents, you should not create Spans for every internal detail without limit.

You can trace important steps and supplement details through events or structured logs.

4. Key Attributes of Model Call Spans

It is recommended to record:

gen_ai.operation.name
gen_ai.request.model
gen_ai.response.model
gen_ai.request.max_tokens
gen_ai.request.temperature
gen_ai.usage.input_tokens
gen_ai.usage.output_tokens

Verify the exact attribute names against the version of the OpenTelemetry GenAI Semantic Conventions you use.

GenAI semantic conventions are still evolving, and different SDKs and backends may vary in their support for some fields.

Business extension attributes can include:

app.prompt_template.version
app.model.route
app.model.fallback
app.request.priority
app.session.type

Model call Spans should also record:

  • Request start time.
  • Time to first token.
  • Request completion time.
  • Error type.
  • Model routing result.
  • Whether a retry occurred.
  • Whether fallback was triggered.

It is not recommended to write full prompts, model outputs, or sensitive tool parameters directly into Span Attributes.

Traces may also be exported to third-party platforms and must be handled in accordance with sensitive data management requirements.


VII. How Logs, Metrics, and Traces Are Correlated

If logs, metrics, and traces are isolated from one another, they cannot support complete troubleshooting.

They need to be correlated through a unified context.

1. Trace ID Is the Core Correlation Identifier

For example, when a user initiates a request:

request_id = req_001
trace_id   = 4bf92f3577b34da6a3ce929d0e0e4736

Throughout the execution process:

  • The API service generates ingress logs.
  • The RAG service generates retrieval logs.
  • The model service generates inference logs.
  • The tool service generates execution logs.

As long as these logs carry the same Trace ID, you can query the same request chain.

2. Correlating Logs with Traces

Record the following in structured logs:

{
  "level": "ERROR",
  "message": "LLM request timeout",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "model": "model-v2",
  "error_type": "timeout"
}

Using the Trace ID, you can jump from a log to the full Trace.

Using the Span ID, you can further locate the specific model call operation.

3. Correlating Metrics with Traces

Metrics are usually aggregated data and are not suitable for carrying the Trace ID of each request.

However, Exemplars can be used to correlate some metric samples with specific Traces.

For example:

llm_request_duration_seconds_bucket

A Histogram sample can be correlated with a Trace ID.

When an abnormal P95 latency is detected, you can jump from the metric sample to the specific Trace to analyze the actual execution path of the slow request.

4. Relationship Among the Three

flowchart TD
    A["User Request"] --> B["Trace ID"]
    B --> C["Multiple Spans"]
    B --> D["Structured Logs"]
    C --> E["Request Latency and Execution Path"]
    D --> F["Event and Exception Details"]
    E --> G["Metrics Aggregation"]
    F --> H["Error Localization"]
    G --> I["Metric Anomaly Detection"]
    I --> J["Correlated Trace"]
    J --> K["Full Problem Diagnosis"]
    H --> K

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style D fill:#EAF3EC,stroke:#83A995,color:#315D49
    style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#F7EAE7,stroke:#C98D7C,color:#754438
    style I fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F

8. OpenTelemetry in Practice

Below, Python is used to demonstrate how to integrate OpenTelemetry into an AI application.

The example uses:

  • OpenTelemetry SDK.
  • OTLP HTTP Exporter.
  • FastAPI.
  • HTTPX.
  • Prometheus.

1. Install Dependencies

pip install \
  fastapi \
  uvicorn \
  httpx \
  opentelemetry-api \
  opentelemetry-sdk \
  opentelemetry-exporter-otlp \
  opentelemetry-instrumentation-fastapi \
  opentelemetry-instrumentation-httpx

2. Initialize OpenTelemetry

Create telemetry.py:

from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
    OTLPSpanExporter,
)

resource = Resource.create({
    "service.name": "ai-assistant",
    "service.version": "1.0.0",
    "deployment.environment.name": "production",
})

provider = TracerProvider(
    resource=resource
)

exporter = OTLPSpanExporter(
    endpoint="http://localhost:4318/v1/traces"
)

processor = BatchSpanProcessor(exporter)

provider.add_span_processor(processor)

trace.set_tracer_provider(provider)

tracer = trace.get_tracer(
    "ai-assistant"
)

Several key operations are completed here:

  1. Create a Resource to identify the current service.
  2. Create a TracerProvider.
  3. Create an OTLP Exporter.
  4. Use BatchSpanProcessor to export spans in batches.
  5. Set the global TracerProvider.
  6. Obtain the business Tracer.

In production, you should also configure sampling, export timeouts, queue capacity, and flush behavior on shutdown.

3. Automatic Instrumentation for FastAPI

Create main.py:

from fastapi import FastAPI

from opentelemetry.instrumentation.fastapi import (
    FastAPIInstrumentor,
)

from opentelemetry.instrumentation.httpx import (
    HTTPXClientInstrumentor,
)

from telemetry import tracer

app = FastAPI()

FastAPIInstrumentor.instrument_app(app)

HTTPXClientInstrumentor().instrument()


@app.get("/health")
async def health():
    return {
        "status": "ok"
    }


@app.get("/chat")
async def chat():
    with tracer.start_as_current_span(
        "chat.process"
    ) as span:

        span.set_attribute(
            "app.operation",
            "chat"
        )

        return {
            "message": "Hello AI"
        }

FastAPI Instrumentation can automatically collect HTTP request spans.

HTTPX Instrumentation can automatically trace HTTP client requests.

Note that automatic instrumentation can only cover supported operations and does not automatically understand all business semantics.

For example, model prompt construction, RAG retrieval, and agent steps still require proactive instrumentation in business code.

4. Manually Create a Model Call Span

from opentelemetry import trace

tracer = trace.get_tracer("ai-model")

def generate_answer(question, client, model):
    with tracer.start_as_current_span(
        "llm.generate"
    ) as span:

        span.set_attribute(
            "gen_ai.operation.name",
            "chat"
        )

        span.set_attribute(
            "gen_ai.request.model",
            model
        )

        span.set_attribute(
            "app.input.length",
            len(question)
        )

        response = client.chat.completions.create(
            model=model,
            messages=[
                {
                    "role": "user",
                    "content": question,
                }
            ],
        )

        usage = response.usage

        if usage:
            span.set_attribute(
                "gen_ai.usage.input_tokens",
                usage.prompt_tokens
            )

            span.set_attribute(
                "gen_ai.usage.output_tokens",
                usage.completion_tokens
            )

        span.set_attribute(
            "app.model.status",
            "success"
        )

        return response.choices[0].message.content

This example records the model name, input length, and token usage.

Real applications should also add information such as exception status, timeouts, retry counts, and model version.

5. Exception Recording

For failed operations, associate the exception with the current span.

from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer("ai-service")


def execute_model_call():
    with tracer.start_as_current_span(
        "llm.request"
    ) as span:

        try:
            # Execute model call
            result = call_model()

            span.set_attribute(
                "app.status",
                "success"
            )

            return result

        except Exception as exc:
            span.record_exception(exc)

            span.set_status(
                Status(
                    StatusCode.ERROR,
                    str(exc)
                )
            )

            raise

Recording exceptions lets the Trace UI directly display the failed operation and exception stack trace.

However, exception information may contain sensitive content. In production, you need to redact it and restrict access to stack trace data.

6. Correlate Traces with Structured Logs

import logging

from opentelemetry import trace

logger = logging.getLogger("ai-service")


def log_model_result(model, duration_ms):
    span_context = (
        trace.get_current_span().get_span_context()
    )

    logger.info(
        "model request completed",
        extra={
            "trace_id": format(
                span_context.trace_id,
                "032x"
            ),
            "span_id": format(
                span_context.span_id,
                "016x"
            ),
            "model": model,
            "duration_ms": duration_ms,
        }
    )

This code demonstrates how to get the Trace ID and Span ID from the current Span Context.

In actual use, ensure that the log formatter can output the extra field as JSON.

In addition, if there is no valid Span currently, avoid treating an invalid Trace ID as a real trace identifier.

7. Metrics Instrumentation Example

from prometheus_client import (
    Counter,
    Histogram,
    Gauge,
)

LLM_REQUESTS = Counter(
    "llm_requests_total",
    "Total LLM requests",
    ["model", "status"],
)

LLM_DURATION = Histogram(
    "llm_request_duration_seconds",
    "LLM request duration",
    ["model"],
    buckets=[
        0.1,
        0.3,
        0.5,
        1.0,
        2.0,
        5.0,
        10.0,
    ],
)

ACTIVE_REQUESTS = Gauge(
    "llm_active_requests",
    "Active LLM requests",
    ["model"],
)

Record metrics:

import time

def monitored_generate(model, call):
    ACTIVE_REQUESTS.labels(
        model=model
    ).inc()

    start = time.perf_counter()

    try:
        result = call()

        LLM_REQUESTS.labels(
            model=model,
            status="success"
        ).inc()

        return result

    except Exception:
        LLM_REQUESTS.labels(
            model=model,
            status="error"
        ).inc()

        raise

    finally:
        duration = time.perf_counter() - start

        LLM_DURATION.labels(
            model=model
        ).observe(duration)

        ACTIVE_REQUESTS.labels(
            model=model
        ).dec()

This example uses prometheus_client to record Prometheus metrics independently.

If the project standardizes on OpenTelemetry Metrics, you can also achieve the same goal with the OTel Meter and Metric Exporter.

In real projects, choose a unified metrics collection approach to avoid collecting and counting the same metric multiple times.


9. OpenTelemetry Collector Deployment

The OpenTelemetry Collector is a key component in observability data collection architectures.

It can be deployed:

  • On each host.
  • On each Kubernetes node.
  • In each service cluster.
  • As a standalone telemetry data gateway.

1. Core components of the Collector

The Collector typically consists of three parts:

Receiver

Receives telemetry data.

For example:

  • OTLP.
  • Prometheus.
  • Jaeger.
  • Zipkin.

Processor

Processes received data.

For example:

  • Batch: batch processing.
  • Memory Limiter: memory protection.
  • Attributes: attribute modification.
  • Filter: filters data.
  • Tail Sampling: tail sampling.

Exporter

Exports data to storage or analytics platforms.

For example:

  • OTLP.
  • Prometheus Remote Write.
  • Loki-compatible log export option.
  • Tempo-compatible trace export option.