Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.2 KB
Raw Blame
import { lemonToast } from '@posthog/lemon-ui'

import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { downloadFile } from 'lib/utils/dom'
import { slugify } from 'lib/utils/strings'

import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'

import { EnrichedTraceTreeNode } from './aiObservabilityTraceDataLogic'
import { normalizeMessages } from './messageNormalization'
import { CompatMessage } from './types'
import { formatLLMEventTitle, readAiOutput } from './utils'

interface EventMetrics {
    latency?: number
    time_to_first_token?: number
    tokens?: {
        input: number
        output: number
    }
    cost?: number
}

interface TokenUsage {
    input: number
    output: number
}

interface MinimalTraceExport {
    trace_id: string
    name?: string
    timestamp: string
    total_cost?: number
    total_tokens: TokenUsage
    events: MinimalEventExport[]
}

interface MinimalEventExport {
    type: 'generation' | 'span' | 'trace'
    name: string
    model?: string
    provider?: string
    messages?: CompatMessage[]
    input?: unknown
    output?: unknown
    available_tools?: unknown[]
    error?: string | Record<string, unknown>
    metrics?: EventMetrics
    children?: MinimalEventExport[]
}

function buildEventExport(event: LLMTraceEvent, children?: EnrichedTraceTreeNode[]): MinimalEventExport {
    const isGeneration = event.event === '$ai_generation'
    const type = isGeneration ? 'generation' : 'span'

    const result: MinimalEventExport = {
        type,
        name: formatLLMEventTitle(event),
    }

    // Add model and provider for generations
    if (isGeneration) {
        if (event.properties.$ai_model) {
            result.model = event.properties.$ai_model
        }
        if (event.properties.$ai_provider) {
            result.provider = event.properties.$ai_provider
        }
    }

    // Handle input/output based on event type
    if (isGeneration) {
        // For generations, normalize messages without tools
        const inputMessages: CompatMessage[] = normalizeMessages(event.properties.$ai_input, 'user').messages
        const outputMessages: CompatMessage[] = normalizeMessages(readAiOutput(event.properties), 'assistant').messages

        const messages: CompatMessage[] = []
        if (inputMessages.length > 0) {
            messages.push(...inputMessages)
        }
        if (outputMessages.length > 0) {
            messages.push(...outputMessages)
        }
        if (messages.length > 0) {
            result.messages = messages
        }

        // Add available tools separately if present
        if (event.properties.$ai_tools) {
            result.available_tools = event.properties.$ai_tools
        }
    } else {
        // For spans, include raw input/output
        if (event.properties.$ai_input_state !== undefined) {
            result.input = event.properties.$ai_input_state
        }
        if (event.properties.$ai_output_state !== undefined) {
            result.output = event.properties.$ai_output_state
        }
    }

    // Add error information if present
    if (event.properties.$ai_error) {
        result.error = event.properties.$ai_error
    } else if (event.properties.$ai_is_error) {
        result.error = 'Error occurred (details not available)'
    }

    // Add metrics
    const metrics: EventMetrics = {}
    if (event.properties.$ai_latency) {
        metrics.latency = event.properties.$ai_latency
    }
    if (event.properties.$ai_time_to_first_token) {
        metrics.time_to_first_token = event.properties.$ai_time_to_first_token
    }
    if (event.properties.$ai_input_tokens || event.properties.$ai_output_tokens) {
        metrics.tokens = {
            input: event.properties.$ai_input_tokens || 0,
            output: event.properties.$ai_output_tokens || 0,
        }
    }
    // `!= null` keeps a genuine $0 cost, which ingestion now reports for a
    // generation that priced to zero, rather than dropping it as falsy.
    if (event.properties.$ai_total_cost_usd != null) {
        metrics.cost = event.properties.$ai_total_cost_usd
    }

    if (Object.keys(metrics).length > 0) {
        result.metrics = metrics
    }

    // Add children if they exist
    if (children && children.length > 0) {
        result.children = children.map((child) => buildEventExport(child.event, child.children))
    }

    return result
}

export function buildMinimalTraceJSON(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): MinimalTraceExport {
    const result: MinimalTraceExport = {
        trace_id: trace.id,
        timestamp: trace.createdAt,
        total_tokens: {
            input: trace.inputTokens || 0,
            output: trace.outputTokens || 0,
        },
        events: tree.map((node) => buildEventExport(node.event, node.children)),
    }

    // Add trace name if available
    if (trace.traceName) {
        result.name = trace.traceName
    }

    // Add total cost if reported. `!= null` keeps a genuine $0, which the trace
    // header now shows, so the export agrees with it.
    if (trace.totalCost != null) {
        result.total_cost = trace.totalCost
    }

    return result
}

function buildTraceJSONString(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): string {
    return JSON.stringify(buildMinimalTraceJSON(trace, tree), null, 2)
}

function pushEventFragments(event: MinimalEventExport, fragments: string[]): void {
    const { children, ...eventWithoutChildren } = event
    if (!children?.length) {
        fragments.push(JSON.stringify(event))
        return
    }
    // Drop the closing brace so the children array can be streamed into the same object.
    fragments.push(`${JSON.stringify(eventWithoutChildren).slice(0, -1)},"children":[`)
    children.forEach((child, index) => {
        if (index > 0) {
            fragments.push(',')
        }
        pushEventFragments(child, fragments)
    })
    fragments.push(']}')
}

/**
 * Serializes a trace as JSON fragments, one per event, instead of a single string.
 * A large trace exceeds V8's maximum string length, which `JSON.stringify` cannot
 * produce at all. `Blob` concatenates the fragments natively, so only each event
 * has to fit in a string.
 */
export function buildTraceJSONFragments(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): string[] {
    const { events, ...traceMetadata } = buildMinimalTraceJSON(trace, tree)
    const fragments = [`${JSON.stringify(traceMetadata).slice(0, -1)},"events":[`]
    events.forEach((event, index) => {
        if (index > 0) {
            fragments.push(',')
        }
        pushEventFragments(event, fragments)
    })
    fragments.push(']}')
    return fragments
}

export async function exportTraceToClipboard(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): Promise<void> {
    let traceJSON: string
    try {
        traceJSON = buildTraceJSONString(trace, tree)
    } catch {
        lemonToast.error('This trace is too large to copy. Use "Download file" instead.')
        return
    }
    await copyToClipboard(traceJSON, 'trace data')
}

export function exportTraceToFile(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): void {
    const filename = `${slugify(trace.id || 'trace')}.trace.json`
    const file = new File(buildTraceJSONFragments(trace, tree), filename, { type: 'application/json' })
    downloadFile(file)
}