> ## Documentation Index
> Fetch the complete documentation index at: https://docs.honeyhive.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Enrich Traces with Metadata and Metrics

> Add metadata, metrics, feedback, config, and user context to HoneyHive traces with enrich_span() and enrich_session() for filtering and evaluation.

Use `enrich_span()` and `enrich_session()` to attach user context, feature tags, evaluator scores, and config snapshots to HoneyHive traces so you can filter, debug, and evaluate production runs. Auto-instrumentation captures what your agent did; enrichments capture why it matters.

## What types of enrichments can you add?

HoneyHive organizes custom attributes into typed namespaces. Each has a dedicated guide.

> [card] [User Properties](https://docs.honeyhive.ai/v2/tracing/setting-user-properties.md)
>
> Attach user IDs, account tiers, and other user context for per-user filtering and analysis.

> [card] [User Feedback](https://docs.honeyhive.ai/v2/tracing/setting-user-feedback.md)
>
> Capture thumbs-up/down ratings, comments, and implicit signals directly on traces.

> [card] [Custom Metrics](https://docs.honeyhive.ai/v2/tracing/client-side-evals.md)
>
> Log evaluation scores, guardrail results, and other numeric measurements computed in your app.

> [card] [Config](https://docs.honeyhive.ai/v2/tracing/configuration-details.md)
>
> Log prompt versions, model parameters, and other configuration context on traces.

> [card] [Online Experiments](https://docs.honeyhive.ai/v2/tracing/online-experimentation.md)
>
> Tag traces with experiment IDs and variant names to analyze A/B tests in HoneyHive.

You can also attach arbitrary key-value pairs as **metadata** (e.g. feature flags, request IDs, environment tags). Any key that doesn't belong to a typed namespace lands in `metadata` by default.

For the full list of namespaces and data types, see the [Schema Reference](https://docs.honeyhive.ai/v2/tracing/enrichment-schema.md).

## How do you enrich traces in code?

There are three functions, each scoped to a different level of your trace. Start from [custom spans](https://docs.honeyhive.ai/v2/tracing/custom-spans.md) if you need to wrap business logic before enriching it.

> [tab] enrich\_session()
>
> Set attributes once and apply them to all traces in the session. Ideal for tenant context, app version, or user tier.
>
> ```python theme={null}
> from honeyhive import HoneyHiveTracer
>
> tracer = HoneyHiveTracer.init()  # Reads HH_INGESTION_API_KEY from your environment
>
> tracer.enrich_session({
>     "tenant_id": "acme_corp",
>     "user_tier": "premium",
>     "app_version": "2.1.0"
> })
> ```
>
> > [!TIP]
> >
> > You can enrich a specific session by ID, which is useful in distributed systems:
> >
> > ```python theme={null}
> > tracer.enrich_session(
> >     session_id="sess_abc123",
> >     metadata={"completed": True}
> > )
> > ```

> [tab] enrich\_span()
>
> Add attributes to the current active span. Use inside any `@trace`-decorated function for per-call context.
>
> ```python theme={null}
> from honeyhive import HoneyHiveTracer, enrich_span, trace
>
> HoneyHiveTracer.init()  # Reads HH_INGESTION_API_KEY from your environment
>
> @trace
> def process_query(query: str, user_id: str):
>     enrich_span({
>         "user_id": user_id,
>         "query_length": len(query),
>         "feature": "search"
>     })
>     # Your logic here...
> ```

> [tab] using\_attributes
>
> Enrich auto-instrumented LLM spans (like OpenAI `ChatCompletion`) without wrapping them in `@trace`. Use the `using_attributes` context manager from OpenInference.
>
> ```python theme={null}
> from honeyhive import HoneyHiveTracer
> from openinference.instrumentation import using_attributes
> from openinference.instrumentation.openai import OpenAIInstrumentor
> import openai
>
> tracer = HoneyHiveTracer.init()  # Reads HH_INGESTION_API_KEY from your environment
> OpenAIInstrumentor().instrument(tracer_provider=tracer.provider)
>
> client = openai.OpenAI()
>
> with using_attributes(
>     user_id="user_12345",
>     metadata={"feature": "chat_support"}
> ):
>     response = client.chat.completions.create(
>         model="gpt-4o-mini",
>         messages=[{"role": "user", "content": "Hello!"}]
>     )
> ```
>
> > [!NOTE]
> >
> > `using_attributes` attaches metadata directly to auto-instrumented spans. For your own functions, use `@trace` with `enrich_span()`.

### Should you use global or instance enrichment methods?

```python theme={null}
from honeyhive import HoneyHiveTracer, enrich_span

# Global function — works within any @trace context
enrich_span({"user_id": "user_123"})

# Instance method — recommended for production
tracer = HoneyHiveTracer.init(...)
tracer.enrich_span({"user_id": "user_123"})
tracer.enrich_session({"tenant_id": "acme"})
```

Use instance methods in production for an explicit tracer reference.

## What invocation patterns does enrich\_span support?

Both `enrich_span()` and `enrich_session()` accept data in several forms.

> [accordion] Simple dictionary
>
> ```python theme={null}
> enrich_span({
>     "user_id": "user_12345",
>     "feature": "chat"
> })
> ```

> [accordion] Keyword arguments
>
> ```python theme={null}
> enrich_span(
>     user_id="user_12345",
>     feature="chat"
> )
> ```

> [accordion] Explicit namespaces
>
> Organize data by type using named parameters:
>
> ```python theme={null}
> enrich_span(
>     metadata={"user_id": "user_12345", "feature": "chat"},
>     metrics={"latency_ms": 150, "score": 0.95},
>     user_properties={"plan": "premium"},
>     feedback={"rating": 5}
> )
> ```

> [accordion] Mixed (namespaces + keywords)
>
> Extra keyword arguments are added to `metadata` automatically:
>
> ```python theme={null}
> enrich_span(
>     metadata={"user_id": "user_12345"},
>     metrics={"score": 0.95},
>     feature="chat",      # → metadata.feature
>     priority="high"      # → metadata.priority
> )
> ```

## What are common enrichment use cases?

> [accordion] User context
>
> Attach user identity and message metadata to every traced call.
>
> ```python theme={null}
> @trace
> def generate_response(user_id: str, message: str):
>     enrich_span(
>         user_properties={"user_id": user_id},
>         metadata={"message_length": len(message)}
>     )
>     # LLM call...
> ```

> [accordion] Feature tracking
>
> Tag traces by feature to compare performance across different parts of your app.
>
> ```python theme={null}
> @trace
> def summarize_document(document: str, feature: str):
>     enrich_span({
>         "feature": feature,
>         "document_length": len(document)
>     })
>     # LLM call...
> ```

> [accordion] Request metadata (Flask)
>
> Capture HTTP request context for correlating traces with API traffic.
>
> ```python theme={null}
> from flask import request
>
> @app.route("/api/chat", methods=["POST"])
> @trace
> def chat_endpoint():
>     enrich_span({
>         "request_id": request.headers.get("X-Request-ID"),
>         "endpoint": "/api/chat"
>     })
>     # Process request...
> ```

> [accordion] Business metrics
>
> Log scores and experiment variants alongside your traces.
>
> ```python theme={null}
> @trace
> def generate_recommendation(product_id: str, user_id: str):
>     enrich_span(
>         user_properties={"user_id": user_id},
>         metadata={"product_id": product_id, "ab_variant": "B"},
>         metrics={"recommendation_score": 0.92}
>     )
>     # LLM call...
> ```

> [accordion] Performance monitoring
>
> Record custom timing and throughput alongside auto-captured latency.
>
> ```python theme={null}
> import time
>
> @trace
> def expensive_operation(data_size: int):
>     start_time = time.perf_counter()
>
>     result = process_data(data_size)
>
>     duration_ms = (time.perf_counter() - start_time) * 1000
>     enrich_span(metrics={
>         "duration_ms": duration_ms,
>         "data_size": data_size,
>         "throughput": data_size / (duration_ms / 1000)
>     })
>     return result
> ```

> [accordion] Error context
>
> Enrich spans with success/failure status and error details for debugging.
>
> ```python theme={null}
> @trace
> def risky_operation(operation_id: str, data: dict):
>     enrich_span(metadata={"operation_id": operation_id})
>
>     try:
>         result = process(data)
>         enrich_span(metadata={"success": True})
>         return result
>     except Exception as e:
>         enrich_span(
>             metadata={"success": False},
>             error=str(e)
>         )
>         raise
> ```

## How do session and span enrichment work together?

This example combines session-level and span-level enrichment in a single application.

> [accordion] Full example: session + span enrichment
>
> ```python theme={null}
> from honeyhive import HoneyHiveTracer, enrich_span, trace
> from openinference.instrumentation.openai import OpenAIInstrumentor
> import openai
>
> tracer = HoneyHiveTracer.init()  # Reads HH_INGESTION_API_KEY from your environment
> OpenAIInstrumentor().instrument(tracer_provider=tracer.provider)
>
> # Session-level context (set once)
> tracer.enrich_session({
>     "tenant_id": "acme_corp",
>     "user_tier": "premium",
>     "app_version": "2.1.0"
> })
>
> client = openai.OpenAI()
>
> # Span-level context (per call)
> @trace
> def chat(message: str, user_id: str):
>     enrich_span({
>         "user_id": user_id,
>         "message_length": len(message),
>         "feature": "chat_support"
>     })
>
>     response = client.chat.completions.create(
>         model="gpt-4o-mini",
>         messages=[{"role": "user", "content": message}]
>     )
>     return response.choices[0].message.content
>
> # Each call inherits session context + gets its own span context
> chat("Hello!", user_id="user_123")
> chat("What's the weather?", user_id="user_456")
> ```

## How do you view enriched data in the dashboard?

**1. Open the Session view**

Go to your project in the HoneyHive dashboard and select **Traces**.

**2. Inspect a session**

Click any session to expand it. Your enriched data appears in the **Metadata** and **Attributes** panels.

**3. Filter and analyze**

Use enriched fields to filter events, build [custom charts](https://docs.honeyhive.ai/v2/monitoring/charts.md), or set up [alerts](https://docs.honeyhive.ai/v2/monitoring/alerts/alerts_overview.md).

## What are trace enrichment best practices?

| Do | Don't |
| - | - |
| Use consistent key names across your app | Include sensitive data (passwords, API keys, PII) |
| Add user/session IDs for debugging | Attach large values (>1KB per field) |
| Include feature and endpoint identifiers | Use random or generated key names |
| Use descriptive names (`user_id` not `uid`) | Duplicate data already captured by auto-instrumentation |

## Where is the SDK reference?

> [card] [Python SDK](https://honeyhiveai.github.io/python-sdk/)
>
> `enrich_span()` and `enrich_session()`


## Related topics

- [HoneyHive Tracing Concepts](https://docs.honeyhive.ai/v2/tracing/concepts.md)
- [How to trace AWS Strands Agents with HoneyHive](https://docs.honeyhive.ai/v2/integrations/strands.md)
- [How to trace DSPy with HoneyHive](https://docs.honeyhive.ai/v2/integrations/dspy.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.