: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import type { z } from 'zod'
import { wrapError } from '@/lib/errors'
import { withUiApp } from '@/resources/ui-apps'
import { AIObservabilityGetCostsSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase } from '@/tools/types'
const schema = AIObservabilityGetCostsSchema
type Params = z.infer<typeof schema>
type Result = WithPostHogUrl<{ results: unknown[] }>
export const getLLMCostsHandler: ToolBase<typeof schema, Result>['handler'] = async (
context: Context,
params: Params
) => {
const { days } = params
const projectId = params.projectId ? String(params.projectId) : await context.stateManager.getProjectId()
const trendsQuery = {
kind: 'TrendsQuery',
dateRange: {
date_from: `-${days || 6}d`,
date_to: null,
},
filterTestAccounts: true,
series: [
{
event: '$ai_generation',
name: '$ai_generation',
math: 'sum',
math_property: '$ai_total_cost_usd',
kind: 'EventsNode',
},
],
breakdownFilter: {
breakdown_type: 'event',
breakdown: '$ai_model',
},
}
const costsResult = await context.api.query({ projectId }).execute({ queryBody: trendsQuery })
if (!costsResult.success) {
throw wrapError(`Failed to get LLM costs: ${costsResult.error.message}`, costsResult.error)
}
return withPostHogUrl(context, { results: costsResult.data.results }, '/ai-observability')
}
export default (): ToolBase<typeof schema, Result> =>
withUiApp('llm-costs', {
name: 'get-llm-total-costs-for-project',
schema,
handler: getLLMCostsHandler,
})