: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
fix(aio): stop a non-string $ai_model dropping AI enrichment (#95399)
posthog[bot]45ed1faec133
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.tsindex 5b13f03b5d96..6dbbb2efbad1 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts@@ -37,3 +37,16 @@ export const finiteNumberOrUndefined = (value: unknown): number | undefined => {}return undefined}++/**+ * Read a string property from the event's properties bag, or `undefined` when the+ * value is not a string. Optional chaining only guards null and undefined, so a+ * `$ai_model` that arrives as a number, boolean, array or object makes a bare+ * `.toLowerCase()` throw. That throw is caught upstream, which drops every AI+ * enrichment for the event and leaves the user with a generation that has no cost+ * and no error to explain it.+ */+export const stringProperty = (event: PluginEvent, key: string): string | undefined => {+ const value = event.properties?.[key]+ return typeof value === 'string' ? value : undefined+}diff --git a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.tsindex 2526a9bd427a..e71a11e42c9a 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts@@ -4,7 +4,7 @@ import { logger } from '~/common/utils/logger'import { aiCacheExclusiveFallbackCounter } from '~/ingestion/pipelines/ai/metrics'import { PluginEvent } from '~/plugin-scaffold'-import { numericProperty } from './cost-utils'+import { numericProperty, stringProperty } from './cost-utils'import { ResolvedModelCost } from './providers/types'const matchProvider = (event: PluginEvent, provider: string): boolean => {@@ -12,11 +12,11 @@ const matchProvider = (event: PluginEvent, provider: string): boolean => {return false}- const { $ai_provider: eventProvider, $ai_model: eventModel } = event.propertiesconst normalizedProvider = provider.toLowerCase()- const normalizedModel = eventModel?.toLowerCase()+ const normalizedModel = stringProperty(event, '$ai_model')?.toLowerCase()+ const eventProvider = stringProperty(event, '$ai_provider')?.toLowerCase()- if (eventProvider?.toLowerCase() === normalizedProvider || normalizedModel?.includes(normalizedProvider)) {+ if (eventProvider === normalizedProvider || normalizedModel?.includes(normalizedProvider)) {return true}@@ -33,8 +33,8 @@ const usesInclusiveAnthropicInputTokens = (event: PluginEvent): boolean => {return false}- const provider = event.properties['$ai_provider']?.toLowerCase()- const framework = event.properties['$ai_framework']?.toLowerCase()+ const provider = stringProperty(event, '$ai_provider')?.toLowerCase()+ const framework = stringProperty(event, '$ai_framework')?.toLowerCase()// Vercel AI Gateway reports input tokens inclusive of cache read/write tokens.return provider === 'gateway' && framework === 'vercel'diff --git a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.tsindex 26a24e469e6c..1ef0e50020e1 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts@@ -3,7 +3,7 @@ import bigDecimal from 'js-big-decimal'import { logger } from '~/common/utils/logger'import { PluginEvent } from '~/plugin-scaffold'-import { numericProperty } from './cost-utils'+import { numericProperty, stringProperty } from './cost-utils'import { ResolvedModelCost } from './providers/types'const REASONING_COST_MODELS = [/^gemini-2\.5-/, /^gemini-3(\.\d+)?-/]@@ -92,7 +92,8 @@ export const calculateOutputCost = (event: PluginEvent, cost: ResolvedModelCost)}const reasoningTokens = numericProperty(event, '$ai_reasoning_tokens')- if (reasoningTokens && event.properties['$ai_model'] && mustAddReasoningCost(event.properties['$ai_model'])) {+ const model = stringProperty(event, '$ai_model')+ if (reasoningTokens && model && mustAddReasoningCost(model)) {textOutputTokens = bigDecimal.add(textOutputTokens, reasoningTokens)}diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.tsindex 34568b29e4ba..d11816036d4c 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts@@ -1236,6 +1236,33 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 6)})+ // Reasoning tokens make the output-cost path inspect the model as well.+ it.each<{ description: string; properties: Record<string, unknown> }>([+ { description: 'numeric model', properties: { $ai_model: 4 } },+ { description: 'boolean model', properties: { $ai_model: true } },+ { description: 'array model', properties: { $ai_model: ['gpt-4'] } },+ { description: 'object model', properties: { $ai_model: { name: 'gpt-4' } } },+ { description: 'numeric provider', properties: { $ai_provider: 1 } },+ {+ description: 'object framework',+ properties: { $ai_provider: 'anthropic', $ai_framework: { name: 'vercel' } },+ },+ ])('keeps custom pricing when the event carries a $description', ({ properties }) => {+ Object.assign(event.properties!, properties)+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_output_tokens = 50+ event.properties!.$ai_reasoning_tokens = 10++ const result = processAiEvent(event)++ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.2, 6)+ expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Custom)+ })+// Every optional price OpenAI events consume is garbage at once, so dropping// the coercion on any single one puts it back in front of js-big-decimal. The// cache-write rates only apply to Anthropic events, covered separately below.