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.4 KB
Raw Blame
import { MakeLogicType, afterMount, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { dayjs } from 'lib/dayjs'

import { llmAnalyticsPersonalSpendList } from 'products/ai_observability/frontend/generated/api'
import type {
    PersonalSpendAnalysisResponseApi,
    _ModelBreakdownRowApi,
} from 'products/ai_observability/frontend/generated/api.schemas'

import { AgentSpendTotals, agentSpendTotals } from './agentUsageTotals'

export const AGENT_SPEND_PRODUCT = 'posthog_code'
export const AGENT_SPEND_WINDOW_DAYS = 30
const TOP_MODEL_COUNT = 5

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentUsageLogicValues {
    spend: PersonalSpendAnalysisResponseApi | null
    spendFailed: boolean
    spendLoading: boolean
    topModels: _ModelBreakdownRowApi[]
    totals: AgentSpendTotals | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentUsageLogicActions {
    loadSpend: () => any
    loadSpendFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSpendSuccess: (
        spend: PersonalSpendAnalysisResponseApi,
        payload?: any
    ) => {
        spend: PersonalSpendAnalysisResponseApi
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentUsageLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        totals: (spend: PersonalSpendAnalysisResponseApi | null) => AgentSpendTotals | null
        topModels: (spend: PersonalSpendAnalysisResponseApi | null) => _ModelBreakdownRowApi[]
    }
}

export type agentUsageLogicType = MakeLogicType<
    agentUsageLogicValues,
    agentUsageLogicActions,
    Record<string, any>,
    agentUsageLogicMeta
>

export const agentUsageLogic = kea<agentUsageLogicType>([
    path(['scenes', 'settings', 'environment', 'agentUsageLogic']),
    loaders({
        spend: [
            null as PersonalSpendAnalysisResponseApi | null,
            {
                loadSpend: async () => {
                    const response = await llmAnalyticsPersonalSpendList({
                        product: AGENT_SPEND_PRODUCT,
                        date_from: `-${AGENT_SPEND_WINDOW_DAYS}d`,
                    })
                    return response as unknown as PersonalSpendAnalysisResponseApi
                },
            },
        ],
    }),
    reducers({
        spendFailed: [
            false,
            {
                loadSpend: () => false,
                loadSpendSuccess: () => false,
                loadSpendFailure: () => true,
            },
        ],
    }),
    selectors({
        totals: [
            (s) => [s.spend],
            (spend: PersonalSpendAnalysisResponseApi | null): AgentSpendTotals | null =>
                spend ? agentSpendTotals(spend.by_day.items, dayjs.utc().format('YYYY-MM-DD')) : null,
        ],
        topModels: [
            (s) => [s.spend],
            (spend: PersonalSpendAnalysisResponseApi | null): _ModelBreakdownRowApi[] =>
                [...(spend?.by_model.items ?? [])]
                    .filter((row) => row.cost_usd > 0)
                    .sort((a, b) => b.cost_usd - a.cost_usd)
                    .slice(0, TOP_MODEL_COUNT),
        ],
    }),
    afterMount(({ actions }) => {
        actions.loadSpend()
    }),
])