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

# Calculate per-trace averages in Monitor with custom measures

export const plans_0 = "Any"

export const deployments_0 = "Any"

export const data_plane_version_0 = undefined

export const use_case_0 = "Use case - Building monitoring charts that show average cost per trace, average LLM calls per trace, and per-user cost metrics when metadata contains multi-value arrays"

<Note>
  **Applies to:**

  * Plan - {plans_0}
  * Deployment - {deployments_0}
  * {data_plane_version_0}
  * {use_case_0}
</Note>

## Summary

**Goal:** Calculate average cost, LLM calls, or spans per trace in Braintrust Monitor.

**Features:** Custom measures, `estimated_cost()`, per-trace averages.

## Configuration steps

### Step 1: Use a custom measure

Use a custom measure when you need a trace-level average. The built-in **Cost** measure computes totals, rather than averages, and using `avg(estimated_cost())` on the Monitor page enables you to [average matching spans](https://www.braintrust.dev/docs/reference/sql#sql-functions), rather than traces.

In the chart's **Measures** section, click the `</>` button next to the measure dropdown to switch from the visual builder to a raw BTQL expression editor.

### Step 2: Divide by distinct traces

You can use `count_distinct(root_span_id)` as the denominator for per-trace metrics.

**Average cost per trace:**

```sql theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
sum(estimated_cost()) / count_distinct(root_span_id)
```

**Average LLM calls per trace:**

```sql theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
sum(span_attributes.type = 'llm') / count_distinct(root_span_id)
```

**Average spans per trace:**

```sql theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
count(1) / count_distinct(root_span_id)
```

### Step 3: Check your filters

These formulas calculate averages over the spans included by the chart's filters. If you filter to a specific span name, span type, or root spans only, the denominator counts only traces represented in that filtered span set. For example, if you added a filter where `span_attributes.name = 'agent'` then the measure `count_distinct(root_span_id)` will only include root spans whose trace contains a span that meets that filter condition.

For average cost per span instead, use:

```sql theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
avg(estimated_cost())
```
