> ## 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.

# Tags and Metadata

> Learn how to set metadata on your traces

export const enrichmentType_6 = "Metadata"

export const enrichmentType_5 = "Metadata"

export const enrichmentType_4 = "Metadata"

export const paramName_3 = "metadata"

export const enrichmentType_3 = "Metadata"

export const paramName_2 = "metadata"

export const enrichmentType_2 = "Metadata"

export const paramName_1 = "metadata"

export const enrichmentType_1 = "Metadata"

export const paramName_0 = "metadata"

export const enrichmentType_0 = "Metadata"

## Introduction

Metadata is a key-value pair that you can add to your traces to provide additional context.

It is provided as a catch-all for arbitrary information or JSON you might want to add to your traces.

The following steps will show you how to set metadata on the entire session.

### Prerequisites

You have already set tracing for your code as [described in our quickstart guide](/introduction/quickstart).

## Setting {enrichmentType_0}

You can set {enrichmentType_0} on both the trace level or the span level. If the {enrichmentType_0} applies to the entire trace, then set it on the trace level. If the {enrichmentType_0} applies to a specific span, then set it on the span level. For more details, refer to the [enrich traces](/tracing/enrich-traces) documentation.

<Tabs>
  <Tab title="Python">
    <Tabs>
      <Tab title="Setting Metadata on Trace Level">
        In Python, you can use the `enrich_session` function to set {enrichmentType_1} on the trace level.

        To pass {enrichmentType_1} to HoneyHive, pass it to the {paramName_0} param in the `enrich_session` function. This function is used to enrich the session with additional information. Remember that `enrich_session` will update, not overwrite, the existing {paramName_0} object on the trace.

        Read more about the `enrich_session` function in the [Python SDK reference](/sdk-reference/python-tracer-ref#enrich-session).

        Here's an example of how to set {enrichmentType_1} on the trace level in Python:

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

        HoneyHiveTracer.init(
          api_key="my-api-key",
          project="my-project",
        )

        # ...

        enrich_session(metadata={
          "experiment-id": 12345,
          # any other custom fields and values as you need
        })
        ```
      </Tab>

      <Tab title="Setting Metadata on Span Level">
        In Python, you can use the `enrich_span` function to set {enrichmentType_3} on the span level.

        To pass {enrichmentType_3} to HoneyHive, pass it to the {paramName_2} param in the `enrich_span` function. This function is used to enrich the span with additional information. Remember that `enrich_span` will update, not overwrite, the existing {paramName_2} object linked to the span.

        Read more about the `enrich_span` function in the [Python SDK reference](/sdk-reference/python-tracer-ref#enrich-span).

        Here's an example of how to set {enrichmentType_3} on the span level in Python:

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

        HoneyHiveTracer.init(
          api_key="my-api-key",
          project="my-project",
        )

        # ...

        @trace
        def my_function(input, something):
          # ...

          enrich_span(metadata={
            "experiment-id": 12345,
            "something": something,
            # any other custom fields and values as you need
          })

          # ...

          return response

        # ...
        ```

        Alternatively, you can also enrich the {enrichmentType_5} field on the decorator in addition to using the `enrich_span` function.

        You can find the complete documentation for this in the [Python SDK reference](/tracing/custom-spans#decorator-based-enrichments).
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="TypeScript">
    <Tabs>
      <Tab title="Setting Metadata on Trace Level">
        In TypeScript, you can use the `tracer.enrichSession` function to set {enrichmentType_2} on the trace level.

        To pass {enrichmentType_2} to HoneyHive, pass it to the {paramName_1} param in the `tracer.enrichSession` function. This function is used to enrich the session with additional information. Remember that `tracer.enrichSession` will update, not overwrite, the existing {paramName_1} object linked to the trace.

        Read more about the `tracer.enrichSession` function in the [TypeScript SDK reference](/sdk-reference/typescript-tracer-ref#enrichsession).

        Here's an example of how to set {enrichmentType_2} on the trace level in TypeScript:

        ```typescript TypeScript theme={null}
        import { HoneyHiveTracer, enrichSession } from "honeyhive";

        // Initialize tracer 
        // Ensure HH_API_KEY and HH_PROJECT are set in your environment
        const tracer = await HoneyHiveTracer.init({
            sessionName: "setting-metadata-session"
            // apiKey and project will be picked from environment variables
        });

        // Wrap the execution logic in tracer.trace()
        await tracer.trace(async () => {
            // Add metadata to the entire trace session
            enrichSession({
              metadata: {
                "experiment-id": 12345,
                "user-group": "beta",
                // any other custom fields and values as you need
              }
            });

            // ... rest of your application logic ...
            console.log("Trace session enriched with metadata.");
        });

        // await tracer.flush(); // If the script exits immediately
        ```
      </Tab>

      <Tab title="Setting Metadata on Span Level">
        In TypeScript, you can use the `tracer.enrichSpan` function to set {enrichmentType_4} on the span level.

        To pass {enrichmentType_4} to HoneyHive, pass it to the {paramName_3} param in the `tracer.enrichSpan` function. This function is used to enrich the span with additional information. Remember that `tracer.enrichSpan` will update, not overwrite, the existing {paramName_3} object linked to the span.

        Read more about the `tracer.enrichSpan` function in the [TypeScript SDK reference](/sdk-reference/typescript-tracer-ref#enrichspan).

        Here's an example of how to set {enrichmentType_4} on the span level in TypeScript:

        ```typescript TypeScript theme={null}
        import { HoneyHiveTracer, traceTool, enrichSpan } from "honeyhive";

        // Initialize tracer 
        // Ensure HH_API_KEY and HH_PROJECT are set in your environment
        const tracer = await HoneyHiveTracer.init({
            sessionName: "setting-metadata-session"
            // apiKey and project will be picked from environment variables
        });

        // Define the traced function using traceTool
        const myTracedFunction = traceTool(
            function my_function ( // Function name is used as span name
                input: string,
                something: any
            ) {
                // Add metadata specific to this span
                enrichSpan({
                    metadata: {
                        "experiment-id": 12345,
                        "something": something,
                        // any other custom fields and values as you need
                    }
                });

                // Your function code here (mock response)
                const response = `Processed input: ${input}`;
                return response;
            }
        );

        // --- Main Execution Logic ---
        // Wrap the execution in tracer.trace() to establish context
        await tracer.trace(async () => {
            const metadataValue = "some-metadata";
            // Execute the traced function within the trace context
            myTracedFunction("This is a mock input", metadataValue);
        });

        // await tracer.flush(); // If the script exits immediately
        ```

        Alternatively, you can also enrich the {enrichmentType_6} field on the decorator in addition to using the `enrichSpan` function.

        You can find the complete documentation for this in the [TypeScript SDK reference](/tracing/custom-spans#decorator-based-enrichments).
      </Tab>
    </Tabs>

    <Note title="Legacy Tracing Method (Deprecated)">
      Previously, tracing and enrichment involved calling methods directly on the `tracer` instance (e.g., `tracer.traceFunction()`, `tracer.enrichSpan()`, `tracer.enrichSession()`). While this pattern still works, it is now deprecated and will be removed in a future major version.

      Please update your code to use the imported functions (`traceTool`, `enrichSpan`, `enrichSession`) along with the `tracer.trace()` wrapper as shown in the examples above. This new approach simplifies usage within nested functions by not requiring the `tracer` instance to be passed around.

      Example of the **deprecated** pattern:

      ```typescript theme={null}
      // OLD (DEPRECATED) PATTERN:
      // const tracer = await HoneyHiveTracer.init({...});
      // tracer.enrichSession({ metadata: {...} }); 
      // const myFunc = tracer.traceFunction()(function(...) { ... });
      // tracer.enrichSpan({ metadata: {...} }); 
      ```
    </Note>
  </Tab>
</Tabs>

## Concepts

### What is Metadata?

Metadata is anything that doesn't describe the quality of inputs / outputs or the system's behavior.
This metadata can be used to filter and group traces in HoneyHive.

Examples include

* Online Experiment IDs
* Offline Experiment IDs
* Token Usage
* Cost
* System-level information

## Reserved Fields

The following metadata fields are reserved and treated specially by HoneyHive:

1. Token Usage
   * `total_tokens`: Total tokens used in the session/event
   * `completion_tokens`: Completion tokens used in the session/event
   * `prompt_tokens`: Prompt tokens used in the session/event
2. Cost
   * `cost`: Cost of the session/event
3. Event Counts
   * `num_events`: Number of events in the session
   * `num_model_events`: Number of model events in the session
   * `has_feedback`: Whether the session has feedback on any of the events
4. Evaluation Run ID
   * `run_id`: Evaluation run ID used to group sessions for an evaluation run

## Learn more

<CardGroup cols={1}>
  <Card title="Grouping charts by metadata" icon="rectangle-terminal" href="/monitoring/charts">
    Learn how to group charts by metadata in HoneyHive
  </Card>
</CardGroup>

## SDK Reference

Read more about the `enrich_session` function in the [Python SDK reference](/sdk-reference/python-tracer-ref#enrich-session).
