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.

3.1 KB
Raw Blame
/**
 * Main orchestrator for AI event processing.
 *
 * This module coordinates all AI event enrichment:
 * - Trace property normalization (for all AI events)
 * - Error normalization (for AI events with errors)
 * - Cost calculation (for generation/embedding/evaluation events)
 * - Model parameter extraction (for generation/embedding/evaluation events)
 */
import { logger } from '~/common/utils/logger'
import { COSTED_AI_EVENT_TYPES, isAiEventName } from '~/ingestion/common/ai-event-types'
import { PluginEvent } from '~/plugin-scaffold'

import { convertRawEvent } from './convert-raw-event'
import { EventWithProperties, extractCoreModelParams, processCost } from './costs'
import { processAiErrorNormalization } from './errors'
import { processAiToolCallExtraction } from './tools'

export type { EventWithProperties } from './costs'

const isEventWithProperties = (event: PluginEvent): event is EventWithProperties => {
    return event.properties !== undefined && event.properties !== null
}

/**
 * Process an AI event through the enrichment pipeline.
 *
 * Pipeline steps:
 * 1. Normalize trace properties (all AI events)
 * 2. Normalize error messages (events with $ai_is_error=true)
 * 3. Calculate costs (generation/embedding events only)
 * 4. Extract model parameters (generation/embedding events only)
 * 5. Extract tool calls (generation events only)
 */
export const processAiEvent = (event: PluginEvent): PluginEvent | EventWithProperties => {
    // Map OTel attribute names to PostHog property names before any other processing.
    convertRawEvent(event)

    // If the event doesn't carry properties, there's nothing to do.
    if (!isEventWithProperties(event)) {
        return event
    }

    // Normalize trace properties for all AI events.
    const normalized: EventWithProperties = isAiEventName(event.event) ? normalizeTraceProperties(event) : event

    // Normalize error messages for all AI events with errors.
    const withErrorNormalization = processAiErrorNormalization(normalized)

    if (!COSTED_AI_EVENT_TYPES.has(withErrorNormalization.event)) {
        return withErrorNormalization
    }

    const eventWithCosts = processCost(withErrorNormalization)

    const withModelParams = extractCoreModelParams(eventWithCosts)

    return processAiToolCallExtraction(withModelParams)
}

/**
 * Normalize trace properties to ensure they are strings.
 * Handles conversion of numbers, booleans, and bigints to strings.
 */
export const normalizeTraceProperties = (event: EventWithProperties): EventWithProperties => {
    const keys = ['$ai_trace_id', '$ai_parent_id', '$ai_span_id', '$ai_generation_id', '$ai_session_id']

    for (const key of keys) {
        const value: unknown = event.properties[key]

        if (value === null || value === undefined) {
            continue
        }

        const valueType = typeof value

        if (valueType === 'string' || valueType === 'number' || valueType === 'boolean' || valueType === 'bigint') {
            event.properties[key] = String(value)
        } else {
            event.properties[key] = undefined

            logger.warn(`Unexpected type for trace property ${key}: ${valueType}`)
        }
    }

    return event
}