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

# Trace Analytics — Custom Queries

Run custom aggregations over your traces. Same chart engine as [Request Analytics — Custom Queries](/reference/request-analytics-custom-analytics), but each query aggregates at one of two levels:

* **Trace-level** (`trace_*` fields) — measure whole traces: durations, cost, tokens, span counts.
* **Span-level** (`span_*` fields) — measure the individual spans *inside* matching traces: e.g. the slowest tools, tool call counts, span duration distributions.

`filter_group` selects which traces participate (by `trace_name`, a `trace_start` range, span conditions, etc.); span-level charts then aggregate across every span of those traces.

## Metrics

`count`, `sum`, `avg`, `min`, `max`, `percentile` (with `percentile` 0–100).

## Metric fields (`metricField`)

| Level | Fields                                                                                                                                            |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| Trace | `trace_duration_ms`, `trace_total_cost_usd`, `trace_total_tokens`, `trace_input_tokens`, `trace_output_tokens`, `trace_span_count`, `trace_depth` |
| Span  | `span_duration_ms`, `span_cost_usd`, `span_tokens`, `span_input_tokens`, `span_output_tokens`                                                     |

> Duration values are returned in **seconds** (converted from milliseconds internally).

## Group-by fields (`groupByField`)

| Level | Fields                                                                                                          |
| ----- | --------------------------------------------------------------------------------------------------------------- |
| Trace | `trace_status`, `trace_name`, `trace_models_used`, `trace_prompt_ids`, `trace_workflow_ids`, `trace_tool_names` |
| Span  | `span_tool_name`, `span_name`, `span_type`, `span_kind`, `span_status`                                          |

## Constraints

* A chart must stay at one level: span-level fields cannot be mixed with trace-level fields in the same chart.
* Span-level charts do not support `timeSeries` or metadata-key breakdowns.
* Chart shapes beyond bar/line/area are supported: `pie`, `donut`, `histogram` (with `histogramField`), `heatmap` (with `secondaryGroupByField`), `treemap`/`sunburst` (with `hierarchyFields`).

## Response shape

Identical to [Request Analytics — Custom Queries](/reference/request-analytics-custom-analytics): each entry in `customCharts` has `id`, `series` descriptors (`{ key, label, unit }`), and `data` rows. Count series are labeled "Traces" for trace-level charts and "Spans" for span-level charts.

## Related

* [Traces](/running-requests/traces)
* [Request Analytics — Custom Queries](/reference/request-analytics-custom-analytics)


## OpenAPI

````yaml POST /api/public/v2/traces/analytics/custom-analytics
openapi: 3.1.0
info:
  title: PromptLayer API
  description: >-
    REST API for PromptLayer: prompt template management, request logging,
    observability, evaluations, and workflows.
  version: 1.0.0
servers: []
security:
  - ApiKeyAuth: []
paths:
  /api/public/v2/traces/analytics/custom-analytics:
    post:
      tags:
        - tracking
      summary: Trace Analytics Custom Queries
      operationId: getTraceAnalyticsCustomAnalytics
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TraceAnalyticsCustomAnalyticsQuery'
            examples:
              slowest_tools:
                summary: Slowest tools across agent traces
                value:
                  filter_group:
                    logic: AND
                    filters:
                      - field: trace_name
                        operator: is
                        value: agent-turn
                      - field: trace_start
                        operator: between
                        value:
                          - '2026-07-01T00:00:00Z'
                          - '2026-07-08T00:00:00Z'
                  customCharts:
                    - id: slowest_tools
                      title: Slowest Tools
                      chartType: bar
                      metric: max
                      metricField: span_duration_ms
                      groupByField: span_tool_name
              tool_call_counts:
                summary: Tool call counts
                value:
                  customCharts:
                    - id: tool_calls
                      chartType: bar
                      metric: count
                      groupByField: span_tool_name
              trace_cost_by_name:
                summary: Trace cost grouped by trace name
                value:
                  customCharts:
                    - id: cost_by_trace
                      chartType: bar
                      metric: sum
                      metricField: trace_total_cost_usd
                      groupByField: trace_name
      responses:
        '200':
          description: Custom chart results in the order requested.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RequestAnalyticsCustomAnalyticsResponse'
        '400':
          description: >-
            Invalid chart spec or filter (e.g. mixed trace- and span-level
            fields in one chart).
        '401':
          description: Authentication failed.
components:
  schemas:
    TraceAnalyticsCustomAnalyticsQuery:
      type: object
      required:
        - customCharts
      properties:
        filter_group:
          $ref: '#/components/schemas/TraceStructuredFilterGroup'
        customCharts:
          type: array
          minItems: 1
          maxItems: 10
          items:
            $ref: '#/components/schemas/TraceCustomChartSpec'
    RequestAnalyticsCustomAnalyticsResponse:
      type: object
      title: RequestAnalyticsCustomAnalyticsResponse
      required:
        - success
        - customCharts
      properties:
        success:
          type: boolean
          enum:
            - true
        customCharts:
          type: array
          description: Results in the same order as the input `customCharts` array.
          items:
            $ref: '#/components/schemas/CustomAnalyticsResult'
    TraceStructuredFilterGroup:
      type: object
      description: >-
        Nested filter tree. AND/OR are cross-span; SPAN_AND/SPAN_OR require one
        and the same span to satisfy every/any branch (span-level fields only).
      required:
        - filters
      properties:
        logic:
          type: string
          enum:
            - AND
            - OR
            - SPAN_AND
            - SPAN_OR
          default: AND
        filters:
          type: array
          items:
            oneOf:
              - $ref: '#/components/schemas/TraceStructuredFilter'
              - $ref: '#/components/schemas/TraceStructuredFilterGroup'
    TraceCustomChartSpec:
      type: object
      description: >-
        One analytics query. Each chart must use all trace-level or all
        span-level fields — mixed levels are rejected. Span-level charts do not
        support timeSeries or metadata breakdowns.
      required:
        - id
        - chartType
      properties:
        id:
          type: string
          description: Stable chart id, unique within the request
        title:
          type: string
        chartType:
          type: string
          enum:
            - bar
            - line
            - area
            - pie
            - donut
            - histogram
            - heatmap
            - treemap
            - sunburst
        metric:
          type: string
          enum:
            - count
            - sum
            - avg
            - min
            - max
            - percentile
        metricField:
          type: string
          enum:
            - trace_duration_ms
            - trace_total_cost_usd
            - trace_total_tokens
            - trace_input_tokens
            - trace_output_tokens
            - trace_span_count
            - trace_depth
            - span_duration_ms
            - span_cost_usd
            - span_tokens
            - span_input_tokens
            - span_output_tokens
        percentile:
          type: number
          minimum: 0
          maximum: 100
          description: Required when metric is percentile
        groupByField:
          type: string
          enum:
            - trace_status
            - trace_name
            - trace_models_used
            - trace_prompt_ids
            - trace_workflow_ids
            - trace_tool_names
            - span_tool_name
            - span_name
            - span_type
            - span_kind
            - span_status
        secondaryGroupByField:
          type: string
          enum:
            - trace_status
            - trace_name
            - trace_models_used
            - trace_prompt_ids
            - trace_workflow_ids
            - trace_tool_names
            - span_tool_name
            - span_name
            - span_type
            - span_kind
            - span_status
          description: Heatmap charts only
        histogramField:
          type: string
          enum:
            - trace_duration_ms
            - trace_total_cost_usd
            - trace_total_tokens
            - trace_input_tokens
            - trace_output_tokens
            - trace_span_count
            - trace_depth
            - span_duration_ms
            - span_cost_usd
            - span_tokens
            - span_input_tokens
            - span_output_tokens
          description: Histogram charts only
        histogramInterval:
          type: number
          exclusiveMinimum: 0
        hierarchyFields:
          type: array
          items:
            type: string
            enum:
              - trace_status
              - trace_name
              - trace_models_used
              - trace_prompt_ids
              - trace_workflow_ids
              - trace_tool_names
              - span_tool_name
              - span_name
              - span_type
              - span_kind
              - span_status
          minItems: 2
          maxItems: 5
          description: Treemap and sunburst charts only
        timeSeries:
          type: boolean
          description: Not supported with span-level fields
        timeBucket:
          type: string
          enum:
            - auto
            - day
            - week
            - month
        limit:
          type: integer
          minimum: 1
          maximum: 100
          default: 25
        series:
          type: array
          minItems: 2
          description: Multi-series mode; omit metric/metricField when using this
          items:
            type: object
            required:
              - key
              - label
              - metric
              - metricField
            properties:
              key:
                type: string
              label:
                type: string
              metric:
                type: string
                enum:
                  - sum
                  - avg
                  - min
                  - max
                  - percentile
              metricField:
                type: string
                enum:
                  - trace_duration_ms
                  - trace_total_cost_usd
                  - trace_total_tokens
                  - trace_input_tokens
                  - trace_output_tokens
                  - trace_span_count
                  - trace_depth
                  - span_duration_ms
                  - span_cost_usd
                  - span_tokens
                  - span_input_tokens
                  - span_output_tokens
              percentile:
                type: number
                minimum: 0
                maximum: 100
    CustomAnalyticsResult:
      type: object
      title: CustomAnalyticsResult
      description: Computed result for a single custom analytics query.
      properties:
        id:
          type: string
          description: Echoes the chart id from the request.
        title:
          type: string
          description: Chart title (echoed from request, or defaults to id).
        chartType:
          type: string
          enum:
            - bar
            - line
            - area
        series:
          type: array
          description: >-
            Series descriptors (one entry per series). For single-metric charts
            the only entry has key `value`.
          items:
            $ref: '#/components/schemas/CustomAnalyticsSeriesMeta'
        data:
          type: array
          description: >-
            Rows of chart data. Each row has a `label` string and one numeric
            key per series. Time-series rows also include `bucketKey` (ISO date
            string).
          items:
            additionalProperties: true
            type: object
        derivedInsights:
          type: array
          nullable: true
          description: Computed ratio insights (multi-series charts only).
          items:
            $ref: '#/components/schemas/DerivedRatioInsightResult'
    TraceStructuredFilter:
      type: object
      description: >-
        Trace structured filter. field accepts trace-level (trace_*) and
        span-level (span_*) names.
      required:
        - field
        - operator
      properties:
        field:
          type: string
          description: >-
            Trace or span field, e.g. trace_name, trace_start, span_tool_name,
            span_duration_ms
        operator:
          type: string
          description: Filter operator, e.g. is, in, contains, gt, between, is_not_empty
        value:
          description: Filter value (type depends on operator)
        nested_key:
          type: string
          description: >-
            Key name for nested span field operators (span_attributes,
            span_resource, span_input_variables)
    CustomAnalyticsSeriesMeta:
      type: object
      title: CustomAnalyticsSeriesMeta
      description: Metadata describing one series in a custom analytics query response.
      properties:
        key:
          type: string
          description: Series key (matches keys in each data row).
        label:
          type: string
          description: Human-readable label.
        unit:
          type: string
          enum:
            - count
            - tokens
            - currency
            - duration_seconds
            - number
          description: Unit hint for rendering axes.
    DerivedRatioInsightResult:
      type: object
      title: DerivedRatioInsightResult
      description: A computed ratio insight in the response.
      properties:
        type:
          type: string
          enum:
            - ratio
        label:
          type: string
        numeratorSeriesKey:
          type: string
        denominatorSeriesKey:
          type: string
        value:
          type: number
          description: Ratio of numerator total to denominator total.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-KEY

````