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.

23.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api, { ApiError } from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'

import { modelPickerLogic, type ModelOption } from '../modelPickerLogic'
import type { ProviderModelGroup } from '../modelPickerLogic'
import { LLMProviderKey, llmProviderKeysLogic, normalizeLLMProvider } from '../settings/llmProviderKeysLogic'
import { llmPlaygroundPromptsLogic, type PromptConfig } from './llmPlaygroundPromptsLogic'
import type { PlaygroundSetupPayload } from './llmPlaygroundPromptsLogic'
import { messagesToDecisionInput } from './playgroundDecisions'
import {
    isTraceLikeSelection,
    matchClosestModel,
    matchClosestModelOption,
    type MatchModelOption,
    resolveProviderKeyForPrompt,
    resolveSavedModelSelection,
    resolveTraceModelSelection,
} from './playgroundModelMatching'

function normalizePromptsToAvailableModels(
    promptConfigs: PromptConfig[],
    pendingTargetModel: string | null,
    availableModels: MatchModelOption[],
    providerKeys: LLMProviderKey[],
    systemOnePromptIds: string[]
): PromptConfig[] {
    return promptConfigs.map((prompt: PromptConfig, index: number) => {
        const isPendingTarget = index === 0 && !!pendingTargetModel
        // A System One model is not in the chat-only list, so matching would swap in a chat model and keep the System One key.
        if (!isPendingTarget && systemOnePromptIds.includes(prompt.id)) {
            return prompt
        }
        const targetModel = index === 0 && pendingTargetModel ? pendingTargetModel : prompt.model
        const matchedModel = matchClosestModelOption(targetModel, availableModels, providerKeys)
        return {
            ...prompt,
            model:
                index === 0 && pendingTargetModel
                    ? (matchedModel?.id ?? pendingTargetModel)
                    : (matchedModel?.id ?? matchClosestModel(targetModel, availableModels)),
            selectedProviderKeyId: matchedModel?.providerKeyId ?? prompt.selectedProviderKeyId,
        }
    })
}

export type LLMPlaygroundModelLogicProps = Record<string, never>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface llmPlaygroundModelLogicValues {
    activePromptConfig: PromptConfig // llmPlaygroundPromptsLogic
    pendingTargetIsTrace: boolean // llmPlaygroundPromptsLogic
    pendingTargetModel: string | null // llmPlaygroundPromptsLogic
    pendingTargetProvider: string | null // llmPlaygroundPromptsLogic
    pendingTargetProviderKeyId: string | null // llmPlaygroundPromptsLogic
    promptConfigs: PromptConfig[] // llmPlaygroundPromptsLogic
    providerKeys: LLMProviderKey[] // llmProviderKeysLogic
    providerKeysLoading: boolean // llmProviderKeysLogic
    byokModels: ModelOption[] // modelPickerLogic
    byokModelsLoading: boolean // modelPickerLogic
    hasByokKeys: boolean // modelPickerLogic
    playgroundModels: ModelOption[] // modelPickerLogic
    playgroundModelsLoading: boolean // modelPickerLogic
    playgroundProviderModelGroups: ProviderModelGroup[] // modelPickerLogic
    systemOneModels: ModelOption[] // modelPickerLogic
    activeProviderKeyId: string | null
    allModelOptions: ModelOption[]
    byokModelsSettled: boolean
    effectiveModelOptions: ModelOption[]
    evaluationConfig: {
        active_provider_key: {
            id: string
        } | null
    } | null
    evaluationConfigLoading: boolean
    hasProviderKey: boolean
    playgroundModelsErrorStatus: number | null
    playgroundModelsSettled: boolean
    providerKeyForCurrentModel: LLMProviderKey | null
    providerKeysSettled: boolean
    runnableModelOptions: ModelOption[]
    systemOnePromptIds: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface llmPlaygroundModelLogicActions {
    applySavedModelSelection: (selection: { model: string; provider: string | null; providerKeyId: string | null }) => {
        selection: {
            model: string
            provider: string | null
            providerKeyId: string | null
        }
    } // llmPlaygroundPromptsLogic
    clearPendingTargetModel: () => {
        value: true
    } // llmPlaygroundPromptsLogic
    setDecisionInput: (
        decisionInput: string,
        promptId?: string | undefined
    ) => {
        decisionInput: string
        promptId: string | undefined
    } // llmPlaygroundPromptsLogic
    setModel: (
        model: string,
        providerKeyId?: string | undefined,
        promptId?: string | undefined
    ) => {
        model: string
        promptId: string | undefined
        providerKeyId: string | undefined
    } // llmPlaygroundPromptsLogic
    setPromptConfigs: (promptConfigs: PromptConfig[]) => {
        promptConfigs: PromptConfig[]
    } // llmPlaygroundPromptsLogic
    setupPlaygroundFromEvent: (payload: PlaygroundSetupPayload) => {
        payload: PlaygroundSetupPayload
    } // llmPlaygroundPromptsLogic
    loadProviderKeys: () => any // llmProviderKeysLogic
    loadProviderKeysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // llmProviderKeysLogic
    loadProviderKeysSuccess: (
        providerKeys: LLMProviderKey[],
        payload?: any
    ) => {
        payload?: any
        providerKeys: LLMProviderKey[]
    } // llmProviderKeysLogic
    loadByokModelsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // modelPickerLogic
    loadByokModelsSuccess: (
        byokModels: ModelOption[],
        payload?: any
    ) => {
        byokModels: ModelOption[]
        payload?: any
    } // modelPickerLogic
    loadPlaygroundModelsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // modelPickerLogic
    loadPlaygroundModelsSuccess: (
        playgroundModels: ModelOption[],
        payload?: any
    ) => {
        payload?: any
        playgroundModels: ModelOption[]
    } // modelPickerLogic
    loadEvaluationConfig: () => any
    loadEvaluationConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEvaluationConfigSuccess: (
        evaluationConfig: {
            active_provider_key: {
                id: string
            } | null
        } | null,
        payload?: any
    ) => {
        evaluationConfig: {
            active_provider_key: {
                id: string
            } | null
        } | null
        payload?: any
    }
    setActiveProviderKeyId: (id: string | null) => {
        id: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface llmPlaygroundModelLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        effectiveModelOptions: (
            hasByokKeys: boolean,
            byokModels: ModelOption[],
            playgroundModels: ModelOption[]
        ) => ModelOption[]
        runnableModelOptions: (effectiveModelOptions: ModelOption[], systemOneModels: ModelOption[]) => ModelOption[]
        systemOnePromptIds: (promptConfigs: PromptConfig[], providerKeys: LLMProviderKey[]) => string[]
        allModelOptions: (playgroundModels: ModelOption[], byokModels: ModelOption[]) => ModelOption[]
        providerKeyForCurrentModel: (
            activePromptConfig: PromptConfig,
            effectiveModelOptions: ModelOption[],
            providerKeys: LLMProviderKey[]
        ) => LLMProviderKey | null
        hasProviderKey: (providerKeyForCurrentModel: LLMProviderKey | null) => boolean
    }
}

export type llmPlaygroundModelLogicType = MakeLogicType<
    llmPlaygroundModelLogicValues,
    llmPlaygroundModelLogicActions,
    LLMPlaygroundModelLogicProps,
    llmPlaygroundModelLogicMeta
>

export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([
    path(['products', 'ai_observability', 'frontend', 'playground', 'llmPlaygroundModelLogic']),
    props({} as LLMPlaygroundModelLogicProps),

    connect(() => ({
        values: [
            llmPlaygroundPromptsLogic,
            [
                'promptConfigs',
                'activePromptConfig',
                'pendingTargetModel',
                'pendingTargetProvider',
                'pendingTargetProviderKeyId',
                'pendingTargetIsTrace',
            ],
            modelPickerLogic,
            [
                'generativeByokModels as byokModels',
                'byokModelsLoading',
                'playgroundModels',
                'playgroundModelsLoading',
                'hasByokKeys',
                'playgroundProviderModelGroups',
                'systemOneModels',
            ],
            llmProviderKeysLogic,
            ['providerKeys', 'providerKeysLoading'],
        ],
        actions: [
            llmPlaygroundPromptsLogic,
            [
                'setupPlaygroundFromEvent',
                'applySavedModelSelection',
                'setModel',
                'setPromptConfigs',
                'clearPendingTargetModel',
                'setDecisionInput',
            ],
            modelPickerLogic,
            [
                'loadByokModelsSuccess',
                'loadByokModelsFailure',
                'loadPlaygroundModelsSuccess',
                'loadPlaygroundModelsFailure',
            ],
            llmProviderKeysLogic,
            ['loadProviderKeys', 'loadProviderKeysSuccess', 'loadProviderKeysFailure'],
        ],
    })),

    actions({
        setActiveProviderKeyId: (id: string | null) => ({ id }),
    }),

    reducers({
        playgroundModelsErrorStatus: [
            null as number | null,
            {
                loadPlaygroundModelsSuccess: () => null,
                loadPlaygroundModelsFailure: (_: number | null, { error }: { error: unknown }) => {
                    if (error instanceof ApiError) {
                        return error.status ?? null
                    }
                    return null
                },
            },
        ],
        activeProviderKeyId: [
            null as string | null,
            {
                setActiveProviderKeyId: (_: string | null, { id }: { id: string | null }) => id,
            },
        ],
        providerKeysSettled: [
            false as boolean,
            {
                loadProviderKeys: () => false,
                loadProviderKeysSuccess: () => true,
                loadProviderKeysFailure: () => true,
            },
        ],
        byokModelsSettled: [
            false as boolean,
            {
                loadProviderKeys: () => false,
                loadProviderKeysSuccess: (_: boolean, { providerKeys }: { providerKeys: LLMProviderKey[] }) =>
                    !providerKeys.some((key) => key.state === 'ok'),
                loadByokModelsSuccess: () => true,
                loadByokModelsFailure: () => true,
            },
        ],
        playgroundModelsSettled: [
            false as boolean,
            {
                loadPlaygroundModelsSuccess: () => true,
                loadPlaygroundModelsFailure: () => true,
            },
        ],
    }),

    loaders(() => ({
        evaluationConfig: {
            __default: null as { active_provider_key: { id: string } | null } | null,
            loadEvaluationConfig: async () => {
                const teamId = teamLogic.values.currentTeamId
                if (!teamId) {
                    return null
                }
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use llmAnalyticsEvaluationConfigRetrieve() from 'products/ai_observability/frontend/generated/api' instead.
                    return (await api.get(`/api/environments/${teamId}/llm_analytics/evaluation_config/`)) as {
                        active_provider_key: { id: string } | null
                    }
                } catch (e) {
                    console.warn('Failed to load evaluation config', e)
                    return null
                }
            },
        },
    })),

    selectors({
        effectiveModelOptions: [
            (s) => [s.hasByokKeys, s.byokModels, s.playgroundModels],
            (hasByokKeys: boolean, byokModels: ModelOption[], playgroundModels: ModelOption[]): ModelOption[] =>
                hasByokKeys && byokModels.length > 0 ? byokModels : playgroundModels,
        ],
        // Chat models plus System One models, which the normalizers above leave out because they cannot chat.
        runnableModelOptions: [
            (s) => [s.effectiveModelOptions, s.systemOneModels],
            (effectiveModelOptions: ModelOption[], systemOneModels: ModelOption[]): ModelOption[] => [
                ...effectiveModelOptions,
                ...systemOneModels,
            ],
        ],
        // Read from the selected key, not the loaded models, so a failed model load keeps the panel on System One.
        systemOnePromptIds: [
            (s) => [s.promptConfigs, s.providerKeys],
            (promptConfigs: PromptConfig[], providerKeys: LLMProviderKey[]): string[] =>
                promptConfigs
                    .filter((prompt) =>
                        providerKeys.some(
                            (key) => key.id === prompt.selectedProviderKeyId && key.provider === 'system_one'
                        )
                    )
                    .map((prompt) => prompt.id),
        ],
        allModelOptions: [
            (s) => [s.playgroundModels, s.byokModels],
            (playgroundModels: ModelOption[], byokModels: ModelOption[]): ModelOption[] => [
                ...playgroundModels,
                ...byokModels,
            ],
        ],
        providerKeyForCurrentModel: [
            (s) => [s.activePromptConfig, s.effectiveModelOptions, s.providerKeys],
            (
                activePromptConfig: PromptConfig,
                modelOptions: ModelOption[],
                providerKeys: LLMProviderKey[]
            ): LLMProviderKey | null => resolveProviderKeyForPrompt(activePromptConfig, modelOptions, providerKeys),
        ],
        hasProviderKey: [(s) => [s.providerKeyForCurrentModel], (key: LLMProviderKey | null): boolean => key !== null],
    }),

    listeners(({ actions, values }) => {
        const applyPendingTraceSelection = (targetModel: string): void => {
            const promptId = values.promptConfigs[0]?.id
            if (!promptId) {
                actions.clearPendingTargetModel()
                return
            }
            // pendingTargetProviderKeyId is only set by saved-prompt loads; for trace loads it is
            // null and resolveSavedModelSelection falls through to plain trace matching.
            const { resolvedModelId, providerKeyId } = resolveSavedModelSelection(
                targetModel,
                values.pendingTargetProvider,
                values.pendingTargetProviderKeyId,
                values.allModelOptions,
                values.providerKeys
            )
            actions.setModel(resolvedModelId, providerKeyId, promptId)
            actions.clearPendingTargetModel()
        }

        // Resolve a pending target model once provider keys, BYOK models, and playground models have
        // all settled — whichever of those loads last drives the resolution. Previously this only
        // ran from the playground/BYOK success handlers, so a pending model was silently dropped when
        // playground models loaded before provider keys settled and there were no BYOK keys to fire
        // loadByokModelsSuccess (the resolution would bail on the settled-gate and never retry).
        const resolvePendingTarget = (): void => {
            const pendingTargetModel = values.pendingTargetModel
            if (!pendingTargetModel) {
                return
            }
            if (!values.providerKeysSettled || !values.byokModelsSettled || !values.playgroundModelsSettled) {
                return
            }
            if (values.pendingTargetIsTrace) {
                applyPendingTraceSelection(pendingTargetModel)
                return
            }
            const normalizedPromptsWithTarget = normalizePromptsToAvailableModels(
                values.promptConfigs,
                pendingTargetModel,
                values.effectiveModelOptions,
                values.providerKeys,
                values.systemOnePromptIds
            )
            actions.setPromptConfigs(normalizedPromptsWithTarget)
            actions.clearPendingTargetModel()
        }

        return {
            setModel: ({ promptId }: { promptId?: string }) => {
                const prompt = promptId
                    ? values.promptConfigs.find((candidate) => candidate.id === promptId)
                    : values.promptConfigs[0]
                if (prompt && !prompt.decisionInput.trim() && values.systemOnePromptIds.includes(prompt.id)) {
                    actions.setDecisionInput(messagesToDecisionInput(prompt.messages), prompt.id)
                }
            },
            loadEvaluationConfigSuccess: ({
                evaluationConfig,
            }: {
                evaluationConfig: { active_provider_key: { id: string } | null } | null
            }) => {
                actions.setActiveProviderKeyId(evaluationConfig?.active_provider_key?.id ?? null)
            },
            loadPlaygroundModelsSuccess: ({ playgroundModels }: { playgroundModels: ModelOption[] }) => {
                if (playgroundModels.length === 0) {
                    return
                }

                // Normalize prompts to available playground models
                const pendingTargetModel = values.pendingTargetModel

                const normalizedPrompts = values.promptConfigs.map((prompt, index) => {
                    if (index === 0 && pendingTargetModel) {
                        return prompt
                    }
                    if (
                        (values.hasByokKeys && prompt.selectedProviderKeyId) ||
                        values.systemOnePromptIds.includes(prompt.id)
                    ) {
                        return prompt
                    }

                    const closestMatch = matchClosestModel(prompt.model, playgroundModels)
                    if (prompt.model === closestMatch) {
                        return prompt
                    }
                    return {
                        ...prompt,
                        model: closestMatch,
                        selectedProviderKeyId: null,
                    }
                })

                const changed = normalizedPrompts.some((prompt, index) => prompt !== values.promptConfigs[index])
                if (changed) {
                    actions.setPromptConfigs(normalizedPrompts)
                }

                resolvePendingTarget()
            },
            loadProviderKeysSuccess: () => {
                // If playground models loaded before provider keys settled, the playground handler couldn't
                // resolve the pending target yet. Retry now that keys (and the BYOK-settled flag) are in.
                resolvePendingTarget()
            },
            loadProviderKeysFailure: () => resolvePendingTarget(),
            loadPlaygroundModelsFailure: () => resolvePendingTarget(),
            loadByokModelsFailure: () => resolvePendingTarget(),
            loadByokModelsSuccess: () => {
                const byokModels = values.byokModels
                if (byokModels.length === 0) {
                    return
                }

                const targetModelForFirstPrompt = values.pendingTargetModel
                if (targetModelForFirstPrompt && values.pendingTargetIsTrace) {
                    applyPendingTraceSelection(targetModelForFirstPrompt)
                    return
                }
                const normalizedPrompts = normalizePromptsToAvailableModels(
                    values.promptConfigs,
                    targetModelForFirstPrompt,
                    byokModels,
                    values.providerKeys,
                    values.systemOnePromptIds
                )

                actions.setPromptConfigs(normalizedPrompts)
                actions.clearPendingTargetModel()
            },
            applySavedModelSelection: ({
                selection,
            }: {
                selection: { model: string; provider: string | null; providerKeyId: string | null }
            }) => {
                if (!values.providerKeysSettled || !values.byokModelsSettled || !values.playgroundModelsSettled) {
                    // The pendingTarget* reducers hold the selection; resolvePendingTarget applies
                    // it once the model and key loaders settle.
                    return
                }
                // Saved selections always target the first panel: a prompt load rebuilds the
                // playground to a single panel, and the pending-path fallback resolves against
                // the first panel too, so both paths agree.
                const targetPromptId = values.promptConfigs[0]?.id
                if (!targetPromptId) {
                    actions.clearPendingTargetModel()
                    return
                }
                const { resolvedModelId, providerKeyId } = resolveSavedModelSelection(
                    selection.model,
                    normalizeLLMProvider(selection.provider ?? undefined),
                    selection.providerKeyId,
                    values.allModelOptions,
                    values.providerKeys
                )
                actions.setModel(resolvedModelId, providerKeyId, targetPromptId)
                actions.clearPendingTargetModel()
            },
            setupPlaygroundFromEvent: ({ payload }: { payload: { model?: string; provider?: string } }) => {
                const { model, provider } = payload
                const currentPrompt = values.promptConfigs[0]
                const promptId = currentPrompt?.id
                if (!promptId || !model) {
                    return
                }

                if (!values.providerKeysSettled || !values.byokModelsSettled) {
                    return
                }

                const traceLikeSelection = isTraceLikeSelection(model, provider)
                if (traceLikeSelection) {
                    const { resolvedModelId, providerKeyId } = resolveTraceModelSelection(
                        model,
                        normalizeLLMProvider(provider),
                        values.allModelOptions,
                        values.providerKeys
                    )
                    actions.setModel(resolvedModelId, providerKeyId, promptId)
                } else {
                    const matchedModel = matchClosestModelOption(
                        model,
                        values.effectiveModelOptions,
                        values.providerKeys
                    )
                    actions.setModel(matchedModel?.id ?? model, matchedModel?.providerKeyId, promptId)
                }
                actions.clearPendingTargetModel()
            },
        }
    }),

    afterMount(({ actions }) => {
        actions.loadEvaluationConfig()
    }),
])