: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(llma): bill audio and image tokens at modality rates (#56878)
Richard Solomou251bae74fb1c
diff --git a/nodejs/src/ingestion/ai/costs/cost-utils.test.ts b/nodejs/src/ingestion/ai/costs/cost-utils.test.tsnew file mode 100644index 000000000000..ef3c2484c867--- /dev/null+++ b/nodejs/src/ingestion/ai/costs/cost-utils.test.ts@@ -0,0 +1,35 @@+import { PluginEvent } from '~/plugin-scaffold'++import { numericProperty } from './cost-utils'+import { createAIEvent } from './test-helpers'++describe('numericProperty()', () => {+ it.each<{ description: string; value: unknown; expected: number }>([+ { description: 'returns the value when it is a finite number', value: 100, expected: 100 },+ { description: 'preserves negative numbers', value: -50, expected: -50 },+ { description: 'returns 0 for NaN', value: Number.NaN, expected: 0 },+ { description: 'returns 0 for Infinity', value: Number.POSITIVE_INFINITY, expected: 0 },+ { description: 'parses numeric strings', value: '100', expected: 100 },+ { description: 'parses negative numeric strings', value: '-25', expected: -25 },+ { description: 'parses decimal numeric strings', value: '12.5', expected: 12.5 },+ { description: 'returns 0 for non-numeric strings', value: 'not-a-number', expected: 0 },+ { description: 'returns 0 for empty strings', value: '', expected: 0 },+ { description: 'returns 0 for null', value: null, expected: 0 },+ { description: 'returns 0 for undefined', value: undefined, expected: 0 },+ { description: 'returns 0 for objects', value: { foo: 'bar' }, expected: 0 },+ { description: 'returns 0 for booleans', value: true, expected: 0 },+ ])('$description', ({ value, expected }) => {+ const event = createAIEvent({ $ai_audio_input_tokens: value })+ expect(numericProperty(event, '$ai_audio_input_tokens')).toBe(expected)+ })++ it('returns 0 when the event has no properties', () => {+ const event = { ...createAIEvent(), properties: undefined } as PluginEvent+ expect(numericProperty(event, '$ai_audio_input_tokens')).toBe(0)+ })++ it('returns 0 when the property is absent', () => {+ const event = createAIEvent({ other_prop: 100 })+ expect(numericProperty(event, '$ai_audio_input_tokens')).toBe(0)+ })+})diff --git a/nodejs/src/ingestion/ai/costs/cost-utils.ts b/nodejs/src/ingestion/ai/costs/cost-utils.tsnew file mode 100644index 000000000000..4f3e088cee13--- /dev/null+++ b/nodejs/src/ingestion/ai/costs/cost-utils.ts@@ -0,0 +1,20 @@+import { PluginEvent } from '~/plugin-scaffold'++/**+ * Read a numeric property from the event's properties bag, returning zero for+ * any value that is missing, non-finite, or not numeric. Accepts numeric+ * strings (e.g. `"100"`) as well as numbers — third-party SDKs and OTel+ * collectors occasionally serialise token counts as strings, and the cost+ * pipeline must bill those tokens correctly rather than silently zeroing them.+ */+export const numericProperty = (event: PluginEvent, key: string): number => {+ const value = event.properties?.[key]+ if (typeof value === 'number') {+ return Number.isFinite(value) ? value : 0+ }+ if (typeof value === 'string' && value.length > 0) {+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : 0+ }+ return 0+}diff --git a/nodejs/src/ingestion/ai/costs/input-costs.test.ts b/nodejs/src/ingestion/ai/costs/input-costs.test.tsindex e800ccee52b3..daf8e3fa8e09 100644--- a/nodejs/src/ingestion/ai/costs/input-costs.test.ts+++ b/nodejs/src/ingestion/ai/costs/input-costs.test.ts@@ -2,22 +2,7 @@ import { PluginEvent } from '~/plugin-scaffold'import { calculateInputCost, resolveCacheReportingExclusive } from './input-costs'import { ResolvedModelCost } from './providers/types'--// Test helper functions-function createTestEvent(overrides: Partial<PluginEvent> = {}): PluginEvent {- return {- event: '$ai_generation',- properties: {},- ip: '',- site_url: '',- team_id: 0,- now: '',- distinct_id: '',- uuid: '',- timestamp: '',- ...overrides,- }-}+import { createAIEvent } from './test-helpers'function createTestModel(overrides: Partial<ResolvedModelCost> = {}): ResolvedModelCost {return {@@ -37,15 +22,13 @@ function createAnthropicTestEvent(cacheWriteTokens?: number,additionalProps: Record<string, any> = {}): PluginEvent {- return createTestEvent({- properties: {- $ai_provider: 'anthropic',- $ai_model: 'claude-3-5-sonnet',- $ai_input_tokens: inputTokens,- ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),- ...(cacheWriteTokens !== undefined && { $ai_cache_creation_input_tokens: cacheWriteTokens }),- ...additionalProps,- },+ return createAIEvent({+ $ai_provider: 'anthropic',+ $ai_model: 'claude-3-5-sonnet',+ $ai_input_tokens: inputTokens,+ ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),+ ...(cacheWriteTokens !== undefined && { $ai_cache_creation_input_tokens: cacheWriteTokens }),+ ...additionalProps,})}@@ -54,14 +37,12 @@ function createOpenAITestEvent(cacheReadTokens?: number,additionalProps: Record<string, any> = {}): PluginEvent {- return createTestEvent({- properties: {- $ai_provider: 'openai',- $ai_model: 'gpt-4o',- $ai_input_tokens: inputTokens,- ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),- ...additionalProps,- },+ return createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o',+ $ai_input_tokens: inputTokens,+ ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),+ ...additionalProps,})}@@ -70,14 +51,12 @@ function createGeminiTestEvent(cacheReadTokens?: number,additionalProps: Record<string, any> = {}): PluginEvent {- return createTestEvent({- properties: {- $ai_provider: 'google',- $ai_model: 'gemini-2.5-pro',- $ai_input_tokens: inputTokens,- ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),- ...additionalProps,- },+ return createAIEvent({+ $ai_provider: 'google',+ $ai_model: 'gemini-2.5-pro',+ $ai_input_tokens: inputTokens,+ ...(cacheReadTokens !== undefined && { $ai_cache_read_input_tokens: cacheReadTokens }),+ ...additionalProps,})}@@ -186,7 +165,17 @@ describe('resolveCacheReportingExclusive()', () => {expected: false,},])('$name', ({ properties, expected }) => {- const event = createTestEvent({ properties } as any)+ const event = {+ event: '$ai_generation',+ properties,+ ip: '',+ site_url: '',+ team_id: 0,+ now: '',+ distinct_id: '',+ uuid: '',+ timestamp: '',+ } as PluginEventexpect(resolveCacheReportingExclusive(event)).toBe(expected)})})@@ -299,13 +288,11 @@ describe('calculateInputCost()', () => {})it('matches provider in model string', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_model: 'anthropic/claude-3-5-sonnet',- $ai_input_tokens: 1000,- $ai_cache_creation_input_tokens: 200,- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_model: 'anthropic/claude-3-5-sonnet',+ $ai_input_tokens: 1000,+ $ai_cache_creation_input_tokens: 200,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -318,15 +305,13 @@ describe('calculateInputCost()', () => {})it('uses inclusive token accounting for Vercel gateway Anthropic events', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_framework: 'vercel',- $ai_model: 'anthropic/claude-sonnet-4.5',- $ai_input_tokens: 14013,- $ai_cache_read_input_tokens: 13306,- $ai_cache_creation_input_tokens: 701,- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_framework: 'vercel',+ $ai_model: 'anthropic/claude-sonnet-4.5',+ $ai_input_tokens: 14013,+ $ai_cache_read_input_tokens: 13306,+ $ai_cache_creation_input_tokens: 701,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -339,15 +324,13 @@ describe('calculateInputCost()', () => {})it('handles string token values correctly for inclusive accounting', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_framework: 'vercel',- $ai_model: 'anthropic/claude-sonnet-4.5',- $ai_input_tokens: '14013',- $ai_cache_read_input_tokens: '13306',- $ai_cache_creation_input_tokens: '701',- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_framework: 'vercel',+ $ai_model: 'anthropic/claude-sonnet-4.5',+ $ai_input_tokens: '14013',+ $ai_cache_read_input_tokens: '13306',+ $ai_cache_creation_input_tokens: '701',})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -360,14 +343,12 @@ describe('calculateInputCost()', () => {// When inputTokens < cacheReadTokens + cacheWriteTokens, the tokens can't be inclusive.// This happens when SDKs (e.g., posthog-ai) report Anthropic-style exclusive counts// through the Vercel gateway. Without this guard, uncachedTokens goes negative.- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_framework: 'vercel',- $ai_model: 'anthropic/claude-opus-4.6',- $ai_input_tokens: 247,- $ai_cache_read_input_tokens: 6287,- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_framework: 'vercel',+ $ai_model: 'anthropic/claude-opus-4.6',+ $ai_input_tokens: 247,+ $ai_cache_read_input_tokens: 6287,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -428,13 +409,11 @@ describe('calculateInputCost()', () => {})it('matches provider in model string for gateway', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_model: 'openai/gpt-4o',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 400,- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_model: 'openai/gpt-4o',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 400,})const result = calculateInputCost(event, OPENAI_MODEL)@@ -471,13 +450,11 @@ describe('calculateInputCost()', () => {const customModel = createTestModel()it('uses 0.5x multiplier for cache read when provider unknown', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'custom-provider',- $ai_model: 'custom-model',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 400,- },+ const event = createAIEvent({+ $ai_provider: 'custom-provider',+ $ai_model: 'custom-model',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 400,})const result = calculateInputCost(event, customModel)@@ -489,12 +466,10 @@ describe('calculateInputCost()', () => {})it('handles no provider field', () => {- const event = createTestEvent({- properties: {- $ai_model: 'custom-model',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 400,- },+ const event = createAIEvent({+ $ai_model: 'custom-model',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 400,})const result = calculateInputCost(event, customModel)@@ -511,16 +486,14 @@ describe('calculateInputCost()', () => {const testModel = createTestModel()it('returns 0 when properties is undefined', () => {- const event = createTestEvent()+ const event = createAIEvent()const result = calculateInputCost(event, testModel)expect(result).toBe('0')})it('returns 0 when input tokens is 0', () => {- const event = createTestEvent({- properties: { $ai_input_tokens: 0 },- })+ const event = createAIEvent({ $ai_input_tokens: 0 })const result = calculateInputCost(event, testModel)@@ -528,9 +501,7 @@ describe('calculateInputCost()', () => {})it('handles undefined input tokens', () => {- const event = createTestEvent({- properties: { $ai_model: 'test-model' },- })+ const event = createAIEvent({ $ai_model: 'test-model' })const result = calculateInputCost(event, testModel)@@ -564,14 +535,12 @@ describe('calculateInputCost()', () => {})it('handles null cache token values', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'anthropic',- $ai_model: 'claude-3-5-sonnet',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: null as any,- $ai_cache_creation_input_tokens: null as any,- },+ const event = createAIEvent({+ $ai_provider: 'anthropic',+ $ai_model: 'claude-3-5-sonnet',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: null as any,+ $ai_cache_creation_input_tokens: null as any,})const result = calculateInputCost(event, testModel)@@ -585,9 +554,7 @@ describe('calculateInputCost()', () => {const testModel = createTestModel()it('handles undefined provider and model', () => {- const event = createTestEvent({- properties: { $ai_input_tokens: 1000 },- })+ const event = createAIEvent({ $ai_input_tokens: 1000 })const result = calculateInputCost(event, testModel)@@ -596,12 +563,10 @@ describe('calculateInputCost()', () => {})it('matches provider when only model contains provider name', () => {- const event = createTestEvent({- properties: {- $ai_model: 'anthropic-claude-sonnet',- $ai_input_tokens: 1000,- $ai_cache_creation_input_tokens: 200,- },+ const event = createAIEvent({+ $ai_model: 'anthropic-claude-sonnet',+ $ai_input_tokens: 1000,+ $ai_cache_creation_input_tokens: 200,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -623,13 +588,11 @@ describe('calculateInputCost()', () => {},})- const event = createTestEvent({- properties: {- $ai_provider: 'custom',- $ai_model: 'my-anthro-model',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 400,- },+ const event = createAIEvent({+ $ai_provider: 'custom',+ $ai_model: 'my-anthro-model',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 400,})const result = calculateInputCost(event, anthropicModel)@@ -650,13 +613,11 @@ describe('calculateInputCost()', () => {},})- const event = createTestEvent({- properties: {- $ai_provider: 'gateway',- $ai_model: 'ANTHROPIC/claude-sonnet',- $ai_input_tokens: 1000,- $ai_cache_creation_input_tokens: 200,- },+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_model: 'ANTHROPIC/claude-sonnet',+ $ai_input_tokens: 1000,+ $ai_cache_creation_input_tokens: 200,})const result = calculateInputCost(event, anthropicModel)@@ -671,13 +632,11 @@ describe('calculateInputCost()', () => {it('matches Anthropic path for Claude models via Vertex provider', () => {// This tests the fix for negative costs when Claude models are accessed via Vertex// Vertex reports inputTokens excluding cache tokens (like Anthropic), not including them- const event = createTestEvent({- properties: {- $ai_provider: 'vertex',- $ai_model: 'claude-haiku-4-5',- $ai_input_tokens: 457,- $ai_cache_read_input_tokens: 36216,- },+ const event = createAIEvent({+ $ai_provider: 'vertex',+ $ai_model: 'claude-haiku-4-5',+ $ai_input_tokens: 457,+ $ai_cache_read_input_tokens: 36216,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -690,13 +649,11 @@ describe('calculateInputCost()', () => {})it('matches Anthropic path for Claude models via Google provider', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'google',- $ai_model: 'claude-3-5-sonnet',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 500,- },+ const event = createAIEvent({+ $ai_provider: 'google',+ $ai_model: 'claude-3-5-sonnet',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 500,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -709,13 +666,11 @@ describe('calculateInputCost()', () => {})it('matches Anthropic path for Claude models with uppercase via non-Anthropic provider', () => {- const event = createTestEvent({- properties: {- $ai_provider: 'bedrock',- $ai_model: 'Claude-3-Opus',- $ai_input_tokens: 1000,- $ai_cache_read_input_tokens: 400,- },+ const event = createAIEvent({+ $ai_provider: 'bedrock',+ $ai_model: 'Claude-3-Opus',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 400,})const result = calculateInputCost(event, ANTHROPIC_MODEL)@@ -761,4 +716,484 @@ describe('calculateInputCost()', () => {expect(event.properties!['$ai_cache_reporting_exclusive']).toBe(true)})})++ describe('audio input - modality cost handling', () => {+ // gpt-4o-audio-preview pricing:+ // - text input: $2.50/1M ($0.0000025/token)+ // - audio input: $40/1M ($0.00004/token)+ const audioModel: ResolvedModelCost = {+ model: 'gpt-4o-audio-preview',+ provider: 'openai',+ cost: {+ prompt_token: 0.0000025,+ completion_token: 0.00001,+ audio: 0.00004,+ },+ }++ it('bills audio input tokens at the audio rate, not the prompt rate', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o-audio-preview',+ $ai_input_tokens: 1000, // 800 text + 200 audio+ $ai_audio_input_tokens: 200,+ })++ const result = calculateInputCost(event, audioModel)++ // Text: (1000 - 200) × 0.0000025 = 0.002+ // Audio: 200 × 0.00004 = 0.008+ // Total: 0.010+ expectCostToBeCloseTo(result, 0.01)+ })++ it('falls back to prompt rate when no audio rate is defined', () => {+ const modelWithoutAudioRate: ResolvedModelCost = {+ model: 'some-text-model',+ provider: 'openai',+ cost: { prompt_token: 0.000001, completion_token: 0.000002 },+ }+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'some-text-model',+ $ai_input_tokens: 1000,+ $ai_audio_input_tokens: 200,+ })++ const result = calculateInputCost(event, modelWithoutAudioRate)++ // Audio falls back to prompt rate, so total stays at 1000 × 0.000001 = 0.001+ expectCostToBeCloseTo(result, 0.001)+ })++ it('handles audio input combined with cache read tokens', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o-audio-preview',+ $ai_input_tokens: 1000, // 500 text + 200 audio + 300 cached (inclusive)+ $ai_cache_read_input_tokens: 300,+ $ai_audio_input_tokens: 200,+ })++ const result = calculateInputCost(event, {+ ...audioModel,+ cost: { ...audioModel.cost, cache_read_token: 0.00000125 },+ })++ // Text (uncached): (1000 - 300 - 200) × 0.0000025 = 0.00125+ // Cache read: 300 × 0.00000125 = 0.000375+ // Audio: 200 × 0.00004 = 0.008+ // Total: 0.00125 + 0.000375 + 0.008 = 0.009625+ expectCostToBeCloseTo(result, 0.009625)+ })+ })++ describe('image input - modality cost handling', () => {+ const imageInputModel: ResolvedModelCost = {+ model: 'gemini-2.5-flash',+ provider: 'google',+ cost: {+ prompt_token: 3e-7,+ completion_token: 0.0000025,+ image: 3e-7,+ },+ }++ it('bills image input tokens separately when image rate is defined', () => {+ const event = createAIEvent({+ $ai_provider: 'google',+ $ai_model: 'gemini-2.5-flash',+ $ai_input_tokens: 1000,+ $ai_image_input_tokens: 400,+ })++ const result = calculateInputCost(event, imageInputModel)++ // Text: (1000 - 400) × 3e-7 = 0.00018+ // Image: 400 × 3e-7 = 0.00012+ // Total: 0.0003+ expectCostToBeCloseTo(result, 0.0003)+ })++ it('clamps the text pool to zero when modality tokens exceed it', () => {+ // 500 input total, 400 cache read, 200 audio — the residual text pool+ // would be 500 - 400 - 200 = -100; clamp to 0 so we don't silently+ // understate the audio-billed cost via a negative text contribution.+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o-audio-preview',+ $ai_input_tokens: 500,+ $ai_cache_read_input_tokens: 400,+ $ai_audio_input_tokens: 200,+ })++ const result = calculateInputCost(event, {+ ...imageInputModel,+ model: 'gpt-4o-audio-preview',+ cost: {+ prompt_token: 0.0000025,+ completion_token: 0.00001,+ cache_read_token: 0.00000125,+ audio: 0.00004,+ },+ })++ // Text (clamped to 0): 0+ // Cache read: 400 × 0.00000125 = 0.0005+ // Audio: 200 × 0.00004 = 0.008+ // Total: 0.0085+ expectCostToBeCloseTo(result, 0.0085)+ })++ it('clamps the Anthropic uncached text pool to zero when modality tokens exceed it', () => {+ const event = createAIEvent({+ $ai_provider: 'anthropic',+ $ai_model: 'claude-3-5-sonnet',+ $ai_input_tokens: 100,+ $ai_image_input_tokens: 200, // exceeds inputTokens+ })+ const anthropicWithImage: ResolvedModelCost = {+ ...ANTHROPIC_MODEL,+ cost: { ...ANTHROPIC_MODEL.cost, image: 5e-7 },+ }++ const result = calculateInputCost(event, anthropicWithImage)++ // Anthropic exclusive: uncachedTokens = 100 - 200 = -100 (clamped to 0)+ // Image: 200 × 5e-7 = 0.0001+ // No cache costs+ // Total: 0.0001+ expectCostToBeCloseTo(result, 0.0001)+ })++ it('handles audio + image input together for multimodal calls', () => {+ const multiModalCost: ResolvedModelCost = {+ model: 'gemini-2.5-flash',+ provider: 'google',+ cost: {+ prompt_token: 3e-7,+ completion_token: 0.0000025,+ image: 3e-7,+ audio: 0.000001,+ },+ }+ const event = createAIEvent({+ $ai_provider: 'google',+ $ai_model: 'gemini-2.5-flash',+ $ai_input_tokens: 1000, // 400 text + 200 audio + 400 image+ $ai_audio_input_tokens: 200,+ $ai_image_input_tokens: 400,+ })++ const result = calculateInputCost(event, multiModalCost)++ // Text: 400 × 3e-7 = 0.00012+ // Audio: 200 × 0.000001 = 0.0002+ // Image: 400 × 3e-7 = 0.00012+ // Total: 0.00044+ expectCostToBeCloseTo(result, 0.00044)+ })+ })++ describe('cached audio input - cache modality cost handling', () => {+ // gpt-audio-mini pricing (representative — real numbers from llm-costs.json):+ // - text input: $0.15/1M+ // - text cache read: $0.075/1M+ // - audio input: $1.00/1M+ // - cached audio: $0.10/1M+ const audioCacheModel: ResolvedModelCost = {+ model: 'gpt-audio-mini',+ provider: 'openai',+ cost: {+ prompt_token: 0.00000015,+ completion_token: 0.0000006,+ cache_read_token: 0.000000075,+ audio: 0.000001,+ input_audio_cache: 0.0000001,+ },+ }++ it('bills cached audio at the cache rate and uncached audio at the audio rate', () => {+ // 1000 input total: 500 text uncached, 250 text cached, 50 audio cached, 150 audio uncached, 50 image+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-audio-mini',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 300, // 250 text + 50 audio+ $ai_audio_input_tokens: 200, // 150 uncached + 50 cached+ $ai_cache_read_audio_tokens: 50,+ })++ const result = calculateInputCost(event, audioCacheModel)++ // Cached text: 250 × 0.000000075 = 0.00001875+ // Uncached text: (1000 - 250 - 200) × 0.00000015 = 550 × 0.00000015 = 0.0000825+ // Uncached audio: 150 × 0.000001 = 0.00015+ // Cached audio: 50 × 0.0000001 = 0.000005+ // Total: 0.00001875 + 0.0000825 + 0.00015 + 0.000005 = 0.00025625+ expectCostToBeCloseTo(result, 0.00025625, 8)+ })++ it('falls back to text cache rate when input_audio_cache is undefined', () => {+ const modelWithoutAudioCacheRate: ResolvedModelCost = {+ model: 'mystery-audio-model',+ provider: 'openai',+ cost: {+ prompt_token: 0.00000015,+ completion_token: 0.0000006,+ cache_read_token: 0.000000075,+ audio: 0.000001,+ // no input_audio_cache+ },+ }+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'mystery-audio-model',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 300,+ $ai_audio_input_tokens: 200,+ $ai_cache_read_audio_tokens: 50,+ })++ const result = calculateInputCost(event, modelWithoutAudioCacheRate)++ // Cached text: 250 × 0.000000075 = 0.00001875+ // Cached audio (falls back to text cache rate): 50 × 0.000000075 = 0.000003750+ // Uncached text: 550 × 0.00000015 = 0.0000825+ // Uncached audio: 150 × 0.000001 = 0.00015+ // Total: 0.00001875 + 0.00000375 + 0.0000825 + 0.00015 = 0.000255+ expectCostToBeCloseTo(result, 0.000255, 7)+ })++ it('falls back to prompt × 0.5 when no cache rate is configured at all', () => {+ const modelWithNoCacheRates: ResolvedModelCost = {+ model: 'no-cache-model',+ provider: 'openai',+ cost: {+ prompt_token: 0.000001,+ completion_token: 0.000002,+ audio: 0.00004,+ // no cache_read_token, no input_audio_cache+ },+ }+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'no-cache-model',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 300,+ $ai_audio_input_tokens: 200,+ $ai_cache_read_audio_tokens: 50,+ })++ const result = calculateInputCost(event, modelWithNoCacheRates)++ // Cached text (default 0.5 multiplier): 250 × 0.000001 × 0.5 = 0.000125+ // Cached audio (default 0.5 multiplier on prompt): 50 × 0.000001 × 0.5 = 0.000025+ // Uncached text: 550 × 0.000001 = 0.00055+ // Uncached audio: 150 × 0.00004 = 0.006+ // Total: 0.000125 + 0.000025 + 0.00055 + 0.006 = 0.0067+ expectCostToBeCloseTo(result, 0.0067, 6)+ })++ it('clamps cached_audio when it exceeds audio_input', () => {+ // Malformed event: cached_audio claims to be 300 but audio_input is only 100.+ // Bound it at 100 so we don't subtract more audio than we have.+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-audio-mini',+ $ai_input_tokens: 500,+ $ai_cache_read_input_tokens: 400,+ $ai_audio_input_tokens: 100,+ $ai_cache_read_audio_tokens: 300, // > audio_input+ })++ const result = calculateInputCost(event, audioCacheModel)++ // Effective cached_audio = min(300, 100, 400) = 100+ // Cached text: (400 - 100) × 0.000000075 = 300 × 0.000000075 = 0.0000225+ // Uncached text: (500 - 300 - 100) × 0.00000015 = 100 × 0.00000015 = 0.000015+ // Uncached audio: 0 × audio_rate = 0+ // Cached audio: 100 × 0.0000001 = 0.00001+ // Total: 0.0000225 + 0.000015 + 0.00001 = 0.0000475+ expectCostToBeCloseTo(result, 0.0000475, 8)+ })++ it('clamps cached_audio when it exceeds cache_read total', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-audio-mini',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 50, // smaller than claimed cached_audio+ $ai_audio_input_tokens: 200,+ $ai_cache_read_audio_tokens: 200, // > cache_read total+ })++ const result = calculateInputCost(event, audioCacheModel)++ // Effective cached_audio = min(200, 200, 50) = 50+ // Cached text: (50 - 50) × cache_rate = 0+ // Uncached text: (1000 - 0 - 200) × 0.00000015 = 800 × 0.00000015 = 0.00012+ // Uncached audio: (200 - 50) × 0.000001 = 0.00015+ // Cached audio: 50 × 0.0000001 = 0.000005+ // Total: 0.00012 + 0.00015 + 0.000005 = 0.000275+ expectCostToBeCloseTo(result, 0.000275, 7)+ })++ it('handles cached_audio = 0 (no-op)', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-audio-mini',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 300,+ $ai_audio_input_tokens: 200,+ $ai_cache_read_audio_tokens: 0,+ })++ const result = calculateInputCost(event, audioCacheModel)++ // Same as no $ai_cache_read_audio_tokens at all:+ // Cached text: 300 × 0.000000075 = 0.0000225+ // Uncached text: 500 × 0.00000015 = 0.000075+ // Audio: 200 × 0.000001 = 0.0002+ // Total: 0.0000225 + 0.000075 + 0.0002 = 0.0002975+ expectCostToBeCloseTo(result, 0.0002975, 7)+ })++ it('still works in Anthropic exclusive mode (cache and input pools are disjoint)', () => {+ // Hypothetical: Anthropic ever adds audio + cache. The exclusive flag+ // means cache_read is its own bucket, separate from input_tokens.+ const anthropicWithAudioCache: ResolvedModelCost = {+ model: 'claude-with-audio',+ provider: 'anthropic',+ cost: {+ prompt_token: 0.000003,+ completion_token: 0.000015,+ cache_read_token: 3e-7,+ cache_write_token: 0.00000375,+ audio: 0.000005,+ input_audio_cache: 5e-7,+ },+ }+ const event = createAIEvent({+ $ai_provider: 'anthropic',+ $ai_model: 'claude-with-audio',+ $ai_input_tokens: 800, // text + audio (cache is separate in exclusive mode)+ $ai_cache_read_input_tokens: 200,+ $ai_audio_input_tokens: 100,+ $ai_cache_read_audio_tokens: 30,+ })++ const result = calculateInputCost(event, anthropicWithAudioCache)++ // Anthropic exclusive: input_tokens does NOT include cached.+ // Cached text: (200 - 30) × 3e-7 = 170 × 3e-7 = 0.000051+ // Uncached text: (800 - 100) × 0.000003 = 700 × 0.000003 = 0.0021+ // Uncached audio: (100 - 30) × 0.000005 = 70 × 0.000005 = 0.00035+ // Cached audio: 30 × 5e-7 = 0.000015+ // No cache_write tokens.+ // Total: 0.000051 + 0.0021 + 0.00035 + 0.000015 = 0.002516+ expectCostToBeCloseTo(result, 0.002516, 6)+ })++ it('clamps negative $ai_cache_read_audio_tokens to zero', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-audio-mini',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 300,+ $ai_audio_input_tokens: 200,+ $ai_cache_read_audio_tokens: -50, // malformed+ })++ const result = calculateInputCost(event, audioCacheModel)++ // Negative clamps to 0; result should match the no-cached-audio case.+ // Cached text: 300 × 0.000000075 = 0.0000225+ // Uncached text: 500 × 0.00000015 = 0.000075+ // Audio: 200 × 0.000001 = 0.0002+ // Total: 0.0002975+ expectCostToBeCloseTo(result, 0.0002975, 7)+ })++ it('handles cached audio together with cache_write tokens (Anthropic-style)', () => {+ const anthropicAudioCacheModel: ResolvedModelCost = {+ model: 'claude-with-audio',+ provider: 'anthropic',+ cost: {+ prompt_token: 0.000003,+ completion_token: 0.000015,+ cache_read_token: 3e-7,+ cache_write_token: 0.00000375,+ audio: 0.000005,+ input_audio_cache: 5e-7,+ },+ }+ const event = createAIEvent({+ $ai_provider: 'anthropic',+ $ai_model: 'claude-with-audio',+ $ai_input_tokens: 800,+ $ai_cache_read_input_tokens: 200,+ $ai_cache_creation_input_tokens: 100, // cache write+ $ai_audio_input_tokens: 100,+ $ai_cache_read_audio_tokens: 30,+ })++ const result = calculateInputCost(event, anthropicAudioCacheModel)++ // Anthropic exclusive: input excludes both cache_read and cache_write.+ // Cache write: 100 × 0.00000375 = 0.000375+ // Cached text: (200 - 30) × 3e-7 = 0.000051+ // Uncached text: (800 - 100) × 0.000003 = 0.0021+ // Uncached audio: (100 - 30) × 0.000005 = 0.00035+ // Cached audio: 30 × 5e-7 = 0.000015+ // Total: 0.000375 + 0.000051 + 0.0021 + 0.00035 + 0.000015 = 0.002891+ expectCostToBeCloseTo(result, 0.002891, 6)+ })++ it('handles cached audio with Anthropic-via-Vercel inclusive reporting', () => {+ // Vercel AI Gateway flips Anthropic to inclusive cache reporting.+ // Same input pool semantics as OpenAI: input_tokens includes cached.+ const vercelAnthropicAudioModel: ResolvedModelCost = {+ model: 'claude-with-audio-vercel',+ provider: 'anthropic',+ cost: {+ prompt_token: 0.000003,+ completion_token: 0.000015,+ cache_read_token: 3e-7,+ cache_write_token: 0.00000375,+ audio: 0.000005,+ input_audio_cache: 5e-7,+ },+ }+ const event = createAIEvent({+ $ai_provider: 'gateway',+ $ai_framework: 'vercel',+ $ai_model: 'anthropic/claude-with-audio',+ // Token totals consistent with inclusive reporting:+ // input_tokens already includes cache_read + cache_creation.+ $ai_input_tokens: 1100, // 800 text + 100 audio + 200 cache_read+ $ai_cache_read_input_tokens: 200,+ $ai_cache_creation_input_tokens: 0,+ $ai_audio_input_tokens: 100,+ $ai_cache_read_audio_tokens: 30,+ })++ const result = calculateInputCost(event, vercelAnthropicAudioModel)++ // Inclusive: input_tokens INCLUDES cache. So:+ // uncached_text = input - cached_text - audio - image+ // = 1100 - (200 - 30) - 100 - 0 = 830+ // But wait, we also subtract cache_write_tokens=0. So uncached_text = 830.+ // Cache write: 0+ // Cached text: 170 × 3e-7 = 0.000051+ // Uncached text: 830 × 0.000003 = 0.00249+ // Uncached audio: 70 × 0.000005 = 0.00035+ // Cached audio: 30 × 5e-7 = 0.000015+ // Total: 0.000051 + 0.00249 + 0.00035 + 0.000015 = 0.002906+ expectCostToBeCloseTo(result, 0.002906, 6)+ // The auto-detector should have flipped cache reporting to inclusive+ // because the Vercel gateway sums input + cache.+ expect(event.properties!['$ai_cache_reporting_exclusive']).toBe(false)+ })+ })})diff --git a/nodejs/src/ingestion/ai/costs/input-costs.ts b/nodejs/src/ingestion/ai/costs/input-costs.tsindex 00326bb34404..f832d40c2f8b 100644--- a/nodejs/src/ingestion/ai/costs/input-costs.ts+++ b/nodejs/src/ingestion/ai/costs/input-costs.ts@@ -3,6 +3,7 @@ import bigDecimal from 'js-big-decimal'import { PluginEvent } from '~/plugin-scaffold'import { logger } from '../../../utils/logger'+import { numericProperty } from './cost-utils'import { ResolvedModelCost } from './providers/types'const matchProvider = (event: PluginEvent, provider: string): boolean => {@@ -56,12 +57,85 @@ export const resolveCacheReportingExclusive = (event: PluginEvent): boolean => {return true}- const inputTokens = Number(event.properties['$ai_input_tokens'] || 0)- const cacheReadTokens = Number(event.properties['$ai_cache_read_input_tokens'] || 0)- const cacheWriteTokens = Number(event.properties['$ai_cache_creation_input_tokens'] || 0)+ const inputTokens = numericProperty(event, '$ai_input_tokens')+ const cacheReadTokens = numericProperty(event, '$ai_cache_read_input_tokens')+ const cacheWriteTokens = numericProperty(event, '$ai_cache_creation_input_tokens')return inputTokens < cacheReadTokens + cacheWriteTokens}+/**+ * Clamp the residual text-token pool to zero when modality tokens are present+ * and the subtraction would push it negative. This guards against modality+ * counts that overlap with cache tokens or exceed the reported input total —+ * either case would otherwise produce a negative text contribution that+ * silently offsets the modality bill.+ */+const clampTextTokens = (value: string | number, hasModalityTokens: boolean): string | number => {+ if (!hasModalityTokens) {+ return value+ }+ const num = Number(value)+ return Number.isFinite(num) && num < 0 ? '0' : value+}++const warnMissingModalityRate = (+ event: PluginEvent,+ cost: ResolvedModelCost,+ modality: 'audio' | 'image' | 'audio_cache'+): void => {+ logger.warn('Missing modality rate; falling back to default rate', {+ modality,+ model: cost.model,+ provider: event.properties?.['$ai_provider'] || 'unknown',+ })+}++const computeAudioInputCost = (event: PluginEvent, cost: ResolvedModelCost, audioInputTokens: number): string => {+ if (audioInputTokens <= 0) {+ return '0'+ }+ if (cost.cost.audio === undefined) {+ warnMissingModalityRate(event, cost, 'audio')+ return bigDecimal.multiply(cost.cost.prompt_token, audioInputTokens)+ }+ return bigDecimal.multiply(cost.cost.audio, audioInputTokens)+}++const computeImageInputCost = (event: PluginEvent, cost: ResolvedModelCost, imageInputTokens: number): string => {+ if (imageInputTokens <= 0) {+ return '0'+ }+ if (cost.cost.image === undefined) {+ warnMissingModalityRate(event, cost, 'image')+ return bigDecimal.multiply(cost.cost.prompt_token, imageInputTokens)+ }+ return bigDecimal.multiply(cost.cost.image, imageInputTokens)+}++/**+ * Bill cached audio input tokens at the model's audio-cache rate. Falls back+ * to the text cache rate, then to `prompt_token × 0.5` (the same default+ * multiplier used by the standard cache-read fallback) when no rate is+ * configured. We emit a warning either way so missing rates are visible.+ */+const computeCachedAudioInputCost = (+ event: PluginEvent,+ cost: ResolvedModelCost,+ cachedAudioTokens: number+): string => {+ if (cachedAudioTokens <= 0) {+ return '0'+ }+ if (cost.cost.input_audio_cache !== undefined) {+ return bigDecimal.multiply(cost.cost.input_audio_cache, cachedAudioTokens)+ }+ warnMissingModalityRate(event, cost, 'audio_cache')+ if (cost.cost.cache_read_token !== undefined) {+ return bigDecimal.multiply(cost.cost.cache_read_token, cachedAudioTokens)+ }+ return bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, 0.5), cachedAudioTokens)+}+export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost): string => {if (!event.properties) {return '0'@@ -70,11 +144,40 @@ export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost):const exclusive = resolveCacheReportingExclusive(event)event.properties['$ai_cache_reporting_exclusive'] = exclusive- const cacheReadTokens = event.properties['$ai_cache_read_input_tokens'] || 0- const inputTokens = event.properties['$ai_input_tokens'] || 0+ const inputTokens = numericProperty(event, '$ai_input_tokens')+ const cacheReadTokens = numericProperty(event, '$ai_cache_read_input_tokens')+ const audioInputTokens = numericProperty(event, '$ai_audio_input_tokens')+ const imageInputTokens = numericProperty(event, '$ai_image_input_tokens')++ // Cached audio is a subset of both audio_input and cache_read_input.+ // Clamp defensively so a malformed event can't produce a deduction that+ // exceeds either parent pool. The clamp is load-bearing — `cachedTextTokens`+ // below relies on `cachedAudioInputTokens <= cacheReadTokens` to stay+ // non-negative. This assumes audio_input is reported as the *total* audio+ // (cached + uncached), matching the OpenAI/Gemini convention; providers+ // that report audio_input as uncached-only with a disjoint cached pool+ // would under-bill here.+ const rawCachedAudioTokens = numericProperty(event, '$ai_cache_read_audio_tokens')+ const cachedAudioInputTokens = Math.max(0, Math.min(rawCachedAudioTokens, audioInputTokens, cacheReadTokens))++ // Audio/image input tokens are reported by providers (OpenAI, Gemini) as a subset+ // of the total input token count. We bill them separately at modality rates and+ // subtract them from the text pool to avoid double-counting at the prompt rate.+ // For audio, split further into cached / uncached so cached audio bills at the+ // (typically much cheaper) audio-cache rate.+ const uncachedAudioInputTokens = audioInputTokens - cachedAudioInputTokens+ const audioInputCost = computeAudioInputCost(event, cost, uncachedAudioInputTokens)+ const cachedAudioInputCost = computeCachedAudioInputCost(event, cost, cachedAudioInputTokens)+ const imageInputCost = computeImageInputCost(event, cost, imageInputTokens)+ const modalityInputCost = bigDecimal.add(bigDecimal.add(audioInputCost, cachedAudioInputCost), imageInputCost)+ const hasModalityTokens = audioInputTokens > 0 || imageInputTokens > 0++ // Text-only portion of the cache pool. Subtracting cached_audio gives us+ // the cached-text count, which we bill at the standard cache_read rate.+ const cachedTextTokens = cacheReadTokens - cachedAudioInputTokensif (matchProvider(event, 'anthropic')) {- const cacheWriteTokens = event.properties['$ai_cache_creation_input_tokens'] || 0+ const cacheWriteTokens = numericProperty(event, '$ai_cache_creation_input_tokens')const writeCost =cost.cost.cache_write_token !== undefined@@ -83,30 +186,38 @@ export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost):const cacheReadCost =cost.cost.cache_read_token !== undefined- ? bigDecimal.multiply(cost.cost.cache_read_token, cacheReadTokens)- : bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, 0.1), cacheReadTokens)+ ? bigDecimal.multiply(cost.cost.cache_read_token, cachedTextTokens)+ : bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, 0.1), cachedTextTokens)const totalCacheCost = bigDecimal.add(writeCost, cacheReadCost)- const uncachedTokens = exclusive+ const baseUncachedTokens = exclusive? inputTokens- : bigDecimal.subtract(bigDecimal.subtract(inputTokens, cacheReadTokens), cacheWriteTokens)- const uncachedCost = bigDecimal.multiply(cost.cost.prompt_token, uncachedTokens)-- return bigDecimal.add(totalCacheCost, uncachedCost)+ : bigDecimal.subtract(bigDecimal.subtract(inputTokens, cachedTextTokens), cacheWriteTokens)+ const uncachedTextTokens = clampTextTokens(+ bigDecimal.subtract(bigDecimal.subtract(baseUncachedTokens, audioInputTokens), imageInputTokens),+ hasModalityTokens+ )+ const uncachedCost = bigDecimal.multiply(cost.cost.prompt_token, uncachedTextTokens)++ return bigDecimal.add(bigDecimal.add(totalCacheCost, uncachedCost), modalityInputCost)}- const regularTokens = exclusive ? inputTokens : bigDecimal.subtract(inputTokens, cacheReadTokens)+ const baseRegularTokens = exclusive ? inputTokens : bigDecimal.subtract(inputTokens, cachedTextTokens)+ const regularTextTokens = clampTextTokens(+ bigDecimal.subtract(bigDecimal.subtract(baseRegularTokens, audioInputTokens), imageInputTokens),+ hasModalityTokens+ )let cacheReadCost: stringif (cost.cost.cache_read_token !== undefined) {// Use explicit cache read cost if available- cacheReadCost = bigDecimal.multiply(cost.cost.cache_read_token, cacheReadTokens)+ cacheReadCost = bigDecimal.multiply(cost.cost.cache_read_token, cachedTextTokens)} else {// Use default multiplier of 0.5 for all providers when cache_read_token is not definedconst multiplier = 0.5- if (cacheReadTokens > 0) {+ if (cachedTextTokens > 0) {logger.warn('Using default cache read multiplier for model', {multiplier,model: cost.model,@@ -114,10 +225,10 @@ export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost):})}- cacheReadCost = bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, multiplier), cacheReadTokens)+ cacheReadCost = bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, multiplier), cachedTextTokens)}- const regularCost = bigDecimal.multiply(cost.cost.prompt_token, regularTokens)+ const regularCost = bigDecimal.multiply(cost.cost.prompt_token, regularTextTokens)- return bigDecimal.add(cacheReadCost, regularCost)+ return bigDecimal.add(bigDecimal.add(cacheReadCost, regularCost), modalityInputCost)}diff --git a/nodejs/src/ingestion/ai/costs/modality-tokens.test.ts b/nodejs/src/ingestion/ai/costs/modality-tokens.test.tsindex 750573e11321..0a2dc6f640cb 100644--- a/nodejs/src/ingestion/ai/costs/modality-tokens.test.ts+++ b/nodejs/src/ingestion/ai/costs/modality-tokens.test.ts@@ -1,18 +1,6 @@-import { EventWithProperties, extractModalityTokens } from './modality-tokens'--function createAIEvent(properties?: Record<string, any>): EventWithProperties {- return {- event: '$ai_generation',- properties: properties || {},- ip: '',- site_url: '',- team_id: 0,- now: '',- distinct_id: '',- uuid: '',- timestamp: '',- }-}+import { aiCostModalityExtractionCounter } from '../metrics'+import { extractModalityTokens } from './modality-tokens'+import { createAIEvent } from './test-helpers'describe('extractModalityTokens()', () => {describe('Gemini direct usage metadata', () => {@@ -441,4 +429,456 @@ describe('extractModalityTokens()', () => {expect(result.properties['$ai_usage']).toBeUndefined()})})++ describe('cache modality extraction', () => {+ it('extracts cached audio tokens from Gemini cacheTokensDetails array format', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokenCount: 1000,+ cachedContentTokenCount: 300,+ cacheTokensDetails: [+ { modality: 'TEXT', tokenCount: 250 },+ { modality: 'AUDIO', tokenCount: 50 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ expect(result.properties['$ai_usage']).toBeUndefined()+ })++ it('extracts cached audio from Gemini cacheTokensDetails object format (defensive)', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokenCount: 1000,+ cacheTokensDetails: { audioTokens: 50 },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ })++ it('does not set $ai_cache_read_audio_tokens when cacheTokensDetails has no audio entry', () => {+ const event = createAIEvent({+ $ai_usage: {+ cacheTokensDetails: [{ modality: 'TEXT', tokenCount: 300 }],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBeUndefined()+ })++ it('extracts cached audio from OpenAI prompt_tokens_details.cached_tokens_details', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_tokens: 1000,+ prompt_tokens_details: {+ cached_tokens: 300,+ audio_tokens: 200,+ cached_tokens_details: {+ audio_tokens: 50,+ },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ expect(result.properties['$ai_usage']).toBeUndefined()+ })++ it('does not set $ai_cache_read_audio_tokens when OpenAI cached_tokens_details has no audio', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_tokens: 1000,+ prompt_tokens_details: {+ cached_tokens: 300,+ cached_tokens_details: { text_tokens: 300 },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBeUndefined()+ })++ it('extracts cached audio from Vercel-wrapped Gemini metadata', () => {+ const event = createAIEvent({+ $ai_usage: {+ rawResponse: {+ usageMetadata: {+ cacheTokensDetails: [{ modality: 'AUDIO', tokenCount: 100 }],+ },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(100)+ })++ it('ignores zero or negative cached audio counts', () => {+ const event = createAIEvent({+ $ai_usage: {+ cacheTokensDetails: [{ modality: 'AUDIO', tokenCount: 0 }],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBeUndefined()+ })+ })++ describe('input modality extraction', () => {+ it('extracts audio + text input tokens from Gemini promptTokensDetails array format', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokenCount: 200,+ promptTokensDetails: [+ { modality: 'AUDIO', tokenCount: 120 },+ { modality: 'TEXT', tokenCount: 80 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(120)+ expect(result.properties['$ai_text_input_tokens']).toBe(80)+ expect(result.properties['$ai_usage']).toBeUndefined()+ })++ it('extracts image + text input tokens from Gemini promptTokensDetails', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokensDetails: [+ { modality: 'IMAGE', tokenCount: 400 },+ { modality: 'TEXT', tokenCount: 50 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_image_input_tokens']).toBe(400)+ expect(result.properties['$ai_text_input_tokens']).toBe(50)+ })++ it('extracts input modality from object format (defensive fallback)', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokensDetails: { audioTokens: 120, textTokens: 80 },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(120)+ expect(result.properties['$ai_text_input_tokens']).toBe(80)+ })++ it('handles case-insensitive Gemini modality values', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokensDetails: [+ { modality: 'audio', tokenCount: 120 },+ { modality: 'Text', tokenCount: 80 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(120)+ expect(result.properties['$ai_text_input_tokens']).toBe(80)+ })++ it('does not set audio input when token count is zero', () => {+ const event = createAIEvent({+ $ai_usage: {+ promptTokensDetails: [+ { modality: 'AUDIO', tokenCount: 0 },+ { modality: 'TEXT', tokenCount: 100 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBeUndefined()+ expect(result.properties['$ai_text_input_tokens']).toBe(100)+ })++ it('extracts input modality from Vercel-wrapped Gemini metadata', () => {+ const event = createAIEvent({+ $ai_usage: {+ rawResponse: {+ usageMetadata: {+ promptTokensDetails: [{ modality: 'AUDIO', tokenCount: 120 }],+ },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(120)+ })++ it('extracts input modality from providerMetadata.google', () => {+ const event = createAIEvent({+ $ai_usage: {+ providerMetadata: {+ google: {+ promptTokensDetails: [{ modality: 'AUDIO', tokenCount: 120 }],+ },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(120)+ })++ it('extracts total prompt audio from OpenAI prompt_tokens_details.audio_tokens', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_tokens: 300,+ prompt_tokens_details: {+ audio_tokens: 200, // total audio in prompt (cached + uncached)+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(200)+ })++ it('extracts both total and cached audio from OpenAI prompt_tokens_details', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_tokens: 300,+ prompt_tokens_details: {+ audio_tokens: 200,+ cached_tokens_details: { audio_tokens: 50 },+ },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(200)+ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ })++ it('does not set audio input when OpenAI prompt audio_tokens is zero', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_tokens_details: { audio_tokens: 0 },+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBeUndefined()+ })+ })++ describe('snake_case Gemini metadata (posthog-python shape)', () => {+ // posthog-python forwards Gemini's protobuf usage_metadata via to_dict()+ // / vars(), which produces snake_case keys (prompt_tokens_details with+ // modality/token_count entries). Production traces from Python users+ // use this shape exclusively; the camelCase shape comes from the Vercel+ // AI SDK on Node.js.++ it('extracts audio + text input from snake_case prompt_tokens_details', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_token_count: 1348,+ prompt_tokens_details: [+ { modality: 'AUDIO', token_count: 750 },+ { modality: 'TEXT', token_count: 598 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(750)+ expect(result.properties['$ai_text_input_tokens']).toBe(598)+ expect(result.properties['$ai_usage']).toBeUndefined()+ })++ it('extracts output modality from snake_case candidates_tokens_details', () => {+ const event = createAIEvent({+ $ai_usage: {+ candidates_tokens_details: [+ { modality: 'TEXT', token_count: 100 },+ { modality: 'IMAGE', token_count: 1290 },+ ],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_text_output_tokens']).toBe(100)+ expect(result.properties['$ai_image_output_tokens']).toBe(1290)+ })++ it('extracts cached audio from snake_case cache_tokens_details', () => {+ const event = createAIEvent({+ $ai_usage: {+ cache_tokens_details: [{ modality: 'AUDIO', token_count: 50 }],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ })++ it('handles snake_case input + output + cache together (full Gemini event)', () => {+ const event = createAIEvent({+ $ai_usage: {+ prompt_token_count: 1348,+ candidates_token_count: 100,+ cached_content_token_count: 50,+ prompt_tokens_details: [+ { modality: 'AUDIO', token_count: 750 },+ { modality: 'TEXT', token_count: 598 },+ ],+ candidates_tokens_details: [{ modality: 'TEXT', token_count: 100 }],+ cache_tokens_details: [{ modality: 'AUDIO', token_count: 50 }],+ },+ })++ const result = extractModalityTokens(event)++ expect(result.properties['$ai_audio_input_tokens']).toBe(750)+ expect(result.properties['$ai_text_input_tokens']).toBe(598)+ expect(result.properties['$ai_text_output_tokens']).toBe(100)+ expect(result.properties['$ai_cache_read_audio_tokens']).toBe(50)+ })+ })++ describe('extraction counter labels', () => {+ const labelsSpy = jest.spyOn(aiCostModalityExtractionCounter, 'labels')++ beforeEach(() => {+ labelsSpy.mockClear()+ })++ afterAll(() => {+ labelsSpy.mockRestore()+ })++ it('emits status=no_details, source=none when nothing extracts', () => {+ extractModalityTokens(createAIEvent({ $ai_usage: { candidatesTokenCount: 100 } }))++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'no_details', source: 'none' })+ })++ it('emits source=gemini_output for output-only extractions', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ candidatesTokensDetails: [{ modality: 'IMAGE', tokenCount: 1290 }],+ },+ })+ )++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'extracted', source: 'gemini_output' })+ })++ it('emits source=gemini_cache for cache-only Gemini extractions', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ cacheTokensDetails: [{ modality: 'AUDIO', tokenCount: 50 }],+ },+ })+ )++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'extracted', source: 'gemini_cache' })+ })++ it('emits source=openai_cache for OpenAI cached_tokens_details extractions', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ prompt_tokens_details: { cached_tokens_details: { audio_tokens: 50 } },+ },+ })+ )++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'extracted', source: 'openai_cache' })+ })++ it('emits source=gemini_input for Gemini promptTokensDetails extractions', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ promptTokensDetails: [{ modality: 'AUDIO', tokenCount: 120 }],+ },+ })+ )++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'extracted', source: 'gemini_input' })+ })++ it('emits source=openai_input for OpenAI prompt_tokens_details.audio_tokens extractions', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ prompt_tokens_details: { audio_tokens: 200 },+ },+ })+ )++ expect(labelsSpy).toHaveBeenCalledTimes(1)+ expect(labelsSpy).toHaveBeenCalledWith({ status: 'extracted', source: 'openai_input' })+ })++ it('emits one increment per source when an event hits multiple extractors', () => {+ extractModalityTokens(+ createAIEvent({+ $ai_usage: {+ promptTokensDetails: [{ modality: 'AUDIO', tokenCount: 120 }],+ candidatesTokensDetails: [{ modality: 'IMAGE', tokenCount: 1290 }],+ cacheTokensDetails: [{ modality: 'AUDIO', tokenCount: 50 }],+ prompt_tokens_details: {+ audio_tokens: 200,+ cached_tokens_details: { audio_tokens: 60 },+ },+ },+ })+ )++ // Five different sources fire; each gets its own increment.+ // Order is alphabetical by source for determinism.+ expect(labelsSpy).toHaveBeenCalledTimes(5)+ expect(labelsSpy).toHaveBeenNthCalledWith(1, { status: 'extracted', source: 'gemini_cache' })+ expect(labelsSpy).toHaveBeenNthCalledWith(2, { status: 'extracted', source: 'gemini_input' })+ expect(labelsSpy).toHaveBeenNthCalledWith(3, { status: 'extracted', source: 'gemini_output' })+ expect(labelsSpy).toHaveBeenNthCalledWith(4, { status: 'extracted', source: 'openai_cache' })+ expect(labelsSpy).toHaveBeenNthCalledWith(5, { status: 'extracted', source: 'openai_input' })+ })+ })})diff --git a/nodejs/src/ingestion/ai/costs/modality-tokens.ts b/nodejs/src/ingestion/ai/costs/modality-tokens.tsindex 1d6dd1cbde79..61133413debb 100644--- a/nodejs/src/ingestion/ai/costs/modality-tokens.ts+++ b/nodejs/src/ingestion/ai/costs/modality-tokens.ts@@ -6,10 +6,44 @@ export interface EventWithProperties extends PluginEvent {properties: Properties}+const isObject = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++/**+ * Look up a metadata key under either the camelCase or snake_case form. Gemini+ * arrives camelCased through the Vercel AI SDK (Node.js, raw API JSON) and+ * snake_cased through posthog-python (protobuf to_dict / vars). Both shapes are+ * routinely seen in production.+ */+const pick = (metadata: Record<string, unknown>, ...keys: string[]): unknown => {+ for (const key of keys) {+ const value = metadata[key]+ if (value !== undefined && value !== null) {+ return value+ }+ }+ return undefined+}++const tokenCountOf = (detail: Record<string, unknown>): number | null => {+ const tokenCount = detail['tokenCount'] ?? detail['token_count']+ return typeof tokenCount === 'number' ? tokenCount : null+}++const modalityOf = (detail: Record<string, unknown>): string | null => {+ const modality = detail['modality']+ return typeof modality === 'string' ? modality.toLowerCase() : null+}++type ExtractionSource = 'gemini_input' | 'gemini_output' | 'gemini_cache' | 'openai_input' | 'openai_cache'+/*** Extract modality-specific token counts from raw provider usage metadata.- * Currently supports Gemini's candidatesTokensDetails for image token breakdown.- * Removes $ai_usage from properties after extraction.+ * Supports Gemini's promptTokensDetails (input modality), candidatesTokensDetails+ * (output modality), and cacheTokensDetails (cache modality), plus the OpenAI+ * equivalents under prompt_tokens_details. Removes $ai_usage from properties+ * after extraction so it does not get persisted to ClickHouse.*/export const extractModalityTokens = (event: EventWithProperties): EventWithProperties => {const usage = event.properties['$ai_usage']@@ -20,140 +54,219 @@ export const extractModalityTokens = (event: EventWithProperties): EventWithProp}try {- let extractedTokens = false+ const extractedSources = new Set<ExtractionSource>()- // Helper function to extract tokens from either array or object format- const extractTokensFromDetails = (tokenDetails: unknown): void => {+ // Gemini's promptTokensDetails / prompt_tokens_details shape (input modality).+ // Array form: [{ modality: "AUDIO", tokenCount: 750 }, { modality: "TEXT", tokenCount: 598 }]+ // (token_count snake_case also accepted via tokenCountOf).+ // Object form: { audioTokens: 750, textTokens: 598 } (defensive fallback).+ const extractInputModality = (tokenDetails: unknown): void => {if (!tokenDetails) {return}- // Array format: [{ modality: "TEXT", tokenCount: 10 }, { modality: "IMAGE", tokenCount: 1290 }]- // Gemini returns uppercase modality values (TEXT, IMAGE, AUDIO)if (Array.isArray(tokenDetails)) {for (const detail of tokenDetails) {- if (detail && typeof detail === 'object') {- const modality = (detail as Record<string, unknown>)['modality']- const tokenCount = (detail as Record<string, unknown>)['tokenCount']-- if (typeof modality === 'string' && typeof tokenCount === 'number') {- const modalityLower = modality.toLowerCase()-- if (modalityLower === 'image' && tokenCount > 0) {- event.properties['$ai_image_output_tokens'] = tokenCount- extractedTokens = true- }- if (modalityLower === 'text') {- event.properties['$ai_text_output_tokens'] = tokenCount- extractedTokens = true- }- }+ if (!isObject(detail)) {+ continue+ }+ const modality = modalityOf(detail)+ const tokenCount = tokenCountOf(detail)+ if (modality === null || tokenCount === null) {+ continue+ }+ if (modality === 'audio' && tokenCount > 0) {+ event.properties['$ai_audio_input_tokens'] = tokenCount+ extractedSources.add('gemini_input')+ }+ if (modality === 'image' && tokenCount > 0) {+ event.properties['$ai_image_input_tokens'] = tokenCount+ extractedSources.add('gemini_input')+ }+ if (modality === 'text') {+ event.properties['$ai_text_input_tokens'] = tokenCount+ extractedSources.add('gemini_input')}}- }- // Object format fallback: { textTokens: number, imageTokens: number }- // Defensive handling in case format changes or for testing- else if (typeof tokenDetails === 'object') {- const details = tokenDetails as Record<string, unknown>-- if (typeof details['imageTokens'] === 'number' && details['imageTokens'] > 0) {- event.properties['$ai_image_output_tokens'] = details['imageTokens']- extractedTokens = true+ } else if (isObject(tokenDetails)) {+ if (typeof tokenDetails['audioTokens'] === 'number' && tokenDetails['audioTokens'] > 0) {+ event.properties['$ai_audio_input_tokens'] = tokenDetails['audioTokens']+ extractedSources.add('gemini_input')}-- if (typeof details['textTokens'] === 'number') {- event.properties['$ai_text_output_tokens'] = details['textTokens']- extractedTokens = true+ if (typeof tokenDetails['imageTokens'] === 'number' && tokenDetails['imageTokens'] > 0) {+ event.properties['$ai_image_input_tokens'] = tokenDetails['imageTokens']+ extractedSources.add('gemini_input')+ }+ if (typeof tokenDetails['textTokens'] === 'number') {+ event.properties['$ai_text_input_tokens'] = tokenDetails['textTokens']+ extractedSources.add('gemini_input')}}}- // Handle Gemini's candidatesTokensDetails (or outputTokenDetails in some versions)- // Gemini returns: [{ modality: "TEXT", tokenCount: 10 }, { modality: "IMAGE", tokenCount: 1290 }]- // Also supports object format as defensive fallback: { textTokens: 10, imageTokens: 1290 }- const tokenDetails =- (usage as Record<string, unknown>)['candidatesTokensDetails'] ??- (usage as Record<string, unknown>)['outputTokenDetails']+ // Gemini's candidatesTokensDetails / candidates_tokens_details shape (output modality).+ const extractOutputModality = (tokenDetails: unknown): void => {+ if (!tokenDetails) {+ return+ }- extractTokensFromDetails(tokenDetails)+ if (Array.isArray(tokenDetails)) {+ for (const detail of tokenDetails) {+ if (!isObject(detail)) {+ continue+ }+ const modality = modalityOf(detail)+ const tokenCount = tokenCountOf(detail)+ if (modality === null || tokenCount === null) {+ continue+ }+ if (modality === 'image' && tokenCount > 0) {+ event.properties['$ai_image_output_tokens'] = tokenCount+ extractedSources.add('gemini_output')+ }+ if (modality === 'text') {+ event.properties['$ai_text_output_tokens'] = tokenCount+ extractedSources.add('gemini_output')+ }+ }+ } else if (isObject(tokenDetails)) {+ if (typeof tokenDetails['imageTokens'] === 'number' && tokenDetails['imageTokens'] > 0) {+ event.properties['$ai_image_output_tokens'] = tokenDetails['imageTokens']+ extractedSources.add('gemini_output')+ }+ if (typeof tokenDetails['textTokens'] === 'number') {+ event.properties['$ai_text_output_tokens'] = tokenDetails['textTokens']+ extractedSources.add('gemini_output')+ }+ }+ }- // Check for Vercel AI SDK with rawResponse at top level: { rawResponse: { usageMetadata: {...} } }- // This is the current path when using Vercel AI SDK with Google provider- const topLevelRawResponse = (usage as Record<string, unknown>)['rawResponse']- if (topLevelRawResponse && typeof topLevelRawResponse === 'object') {- const topLevelUsageMetadata = (topLevelRawResponse as Record<string, unknown>)['usageMetadata']- if (topLevelUsageMetadata && typeof topLevelUsageMetadata === 'object') {- const topLevelTokenDetails =- (topLevelUsageMetadata as Record<string, unknown>)['candidatesTokensDetails'] ??- (topLevelUsageMetadata as Record<string, unknown>)['outputTokenDetails']+ // Gemini's cacheTokensDetails / cache_tokens_details shape (cache modality).+ const extractCacheModality = (tokenDetails: unknown): void => {+ if (!tokenDetails) {+ return+ }- extractTokensFromDetails(topLevelTokenDetails)+ if (Array.isArray(tokenDetails)) {+ for (const detail of tokenDetails) {+ if (!isObject(detail)) {+ continue+ }+ const modality = modalityOf(detail)+ const tokenCount = tokenCountOf(detail)+ if (modality === null || tokenCount === null) {+ continue+ }+ if (modality === 'audio' && tokenCount > 0) {+ event.properties['$ai_cache_read_audio_tokens'] = tokenCount+ extractedSources.add('gemini_cache')+ }+ }+ } else if (+ isObject(tokenDetails) &&+ typeof tokenDetails['audioTokens'] === 'number' &&+ tokenDetails['audioTokens'] > 0+ ) {+ event.properties['$ai_cache_read_audio_tokens'] = tokenDetails['audioTokens']+ extractedSources.add('gemini_cache')}}- // Check for Vercel AI SDK structure: { usage: {...}, providerMetadata: { google: {...} } }- const providerMetadata = (usage as Record<string, unknown>)['providerMetadata']- if (providerMetadata && typeof providerMetadata === 'object') {- const googleMetadata = (providerMetadata as Record<string, unknown>)['google']- if (googleMetadata && typeof googleMetadata === 'object') {- const googleTokenDetails =- (googleMetadata as Record<string, unknown>)['candidatesTokensDetails'] ??- (googleMetadata as Record<string, unknown>)['outputTokenDetails']+ // OpenAI shape: { prompt_tokens_details: { audio_tokens: 200, cached_tokens_details: { audio_tokens: 50 } } }+ // gpt-audio / gpt-realtime expose total prompt audio at audio_tokens, and+ // cached audio inside cached_tokens_details.audio_tokens.+ const extractOpenAIInputModality = (metadata: Record<string, unknown>): void => {+ const promptDetails = metadata['prompt_tokens_details']+ if (!isObject(promptDetails)) {+ return+ }+ const audioTokens = promptDetails['audio_tokens']+ if (typeof audioTokens === 'number' && audioTokens > 0) {+ event.properties['$ai_audio_input_tokens'] = audioTokens+ extractedSources.add('openai_input')+ }+ }- extractTokensFromDetails(googleTokenDetails)+ const extractOpenAICacheModality = (metadata: Record<string, unknown>): void => {+ const promptDetails = metadata['prompt_tokens_details']+ if (!isObject(promptDetails)) {+ return+ }+ const cachedDetails = promptDetails['cached_tokens_details']+ if (!isObject(cachedDetails)) {+ return+ }+ const audioTokens = cachedDetails['audio_tokens']+ if (typeof audioTokens === 'number' && audioTokens > 0) {+ event.properties['$ai_cache_read_audio_tokens'] = audioTokens+ extractedSources.add('openai_cache')}}- // Check for nested rawUsage structure: { rawUsage: { providerMetadata: { google: {...} } } }- // This happens when the SDK wraps the raw provider response- const rawUsage = (usage as Record<string, unknown>)['rawUsage']- if (rawUsage && typeof rawUsage === 'object') {- const rawProviderMetadata = (rawUsage as Record<string, unknown>)['providerMetadata']- if (rawProviderMetadata && typeof rawProviderMetadata === 'object') {- const rawGoogleMetadata = (rawProviderMetadata as Record<string, unknown>)['google']- if (rawGoogleMetadata && typeof rawGoogleMetadata === 'object') {- const rawGoogleTokenDetails =- (rawGoogleMetadata as Record<string, unknown>)['candidatesTokensDetails'] ??- (rawGoogleMetadata as Record<string, unknown>)['outputTokenDetails']-- extractTokensFromDetails(rawGoogleTokenDetails)- }+ // Walk each `usage`-shaped metadata object encountered across the SDK+ // wrapper variants and pull every modality breakdown it exposes.+ // Gemini metadata arrives camelCased through the Vercel AI SDK and+ // snake_cased through posthog-python; check both forms for each key.+ const extractFromMetadata = (metadata: unknown): void => {+ if (!isObject(metadata)) {+ return}+ extractInputModality(pick(metadata, 'promptTokensDetails', 'prompt_tokens_details'))+ extractOutputModality(+ pick(metadata, 'candidatesTokensDetails', 'candidates_tokens_details', 'outputTokenDetails')+ )+ extractCacheModality(pick(metadata, 'cacheTokensDetails', 'cache_tokens_details'))+ extractOpenAIInputModality(metadata)+ extractOpenAICacheModality(metadata)+ }- // Check for Vercel AI SDK V3 structure: { rawUsage: { usage: { raw: {...} } } }- // In Vercel AI SDK, Gemini's raw response is at usage.raw.candidatesTokensDetails- const rawUsageUsage = (rawUsage as Record<string, unknown>)['usage']- if (rawUsageUsage && typeof rawUsageUsage === 'object') {- const rawUsageRaw = (rawUsageUsage as Record<string, unknown>)['raw']- if (rawUsageRaw && typeof rawUsageRaw === 'object') {- const vercelRawTokenDetails =- (rawUsageRaw as Record<string, unknown>)['candidatesTokensDetails'] ??- (rawUsageRaw as Record<string, unknown>)['outputTokenDetails']+ extractFromMetadata(usage)- extractTokensFromDetails(vercelRawTokenDetails)- }+ // Vercel AI SDK with rawResponse at top level: { rawResponse: { usageMetadata: {...} } }+ const topLevelRawResponse = (usage as Record<string, unknown>)['rawResponse']+ if (isObject(topLevelRawResponse)) {+ extractFromMetadata(topLevelRawResponse['usageMetadata'])+ }++ // Vercel AI SDK V2 structure: { providerMetadata: { google: {...} } }+ const providerMetadata = (usage as Record<string, unknown>)['providerMetadata']+ if (isObject(providerMetadata)) {+ extractFromMetadata(providerMetadata['google'])+ }++ // Vercel AI SDK V3 / nested rawUsage variants:+ // { rawUsage: { providerMetadata: { google: {...} } } }+ // { rawUsage: { usage: { raw: {...} } } }+ // { rawUsage: { rawResponse: { usageMetadata: {...} } } }+ const rawUsage = (usage as Record<string, unknown>)['rawUsage']+ if (isObject(rawUsage)) {+ const rawProviderMetadata = rawUsage['providerMetadata']+ if (isObject(rawProviderMetadata)) {+ extractFromMetadata(rawProviderMetadata['google'])}- // Check for Vercel AI SDK with rawResponse: { rawUsage: { rawResponse: { usageMetadata: {...} } } }- // This is the path when using Vercel AI SDK with Google provider- const rawResponse = (rawUsage as Record<string, unknown>)['rawResponse']- if (rawResponse && typeof rawResponse === 'object') {- const usageMetadata = (rawResponse as Record<string, unknown>)['usageMetadata']- if (usageMetadata && typeof usageMetadata === 'object') {- const rawResponseTokenDetails =- (usageMetadata as Record<string, unknown>)['candidatesTokensDetails'] ??- (usageMetadata as Record<string, unknown>)['outputTokenDetails']+ const rawUsageUsage = rawUsage['usage']+ if (isObject(rawUsageUsage)) {+ extractFromMetadata(rawUsageUsage['raw'])+ }- extractTokensFromDetails(rawResponseTokenDetails)- }+ const rawResponse = rawUsage['rawResponse']+ if (isObject(rawResponse)) {+ extractFromMetadata(rawResponse['usageMetadata'])}}- // Track extraction outcomes for monitoring- if (extractedTokens) {- aiCostModalityExtractionCounter.labels({ status: 'extracted' }).inc()+ // Emit one counter increment per source that found something. An event+ // with both Gemini output and Gemini cache extraction increments twice+ // (once with source=gemini_output, once with source=gemini_cache). Sort+ // for deterministic ordering across runs — useful for tests and for+ // anyone reasoning about the metric stream.+ if (extractedSources.size === 0) {+ aiCostModalityExtractionCounter.labels({ status: 'no_details', source: 'none' }).inc()} else {- aiCostModalityExtractionCounter.labels({ status: 'no_details' }).inc()+ for (const source of [...extractedSources].sort()) {+ aiCostModalityExtractionCounter.labels({ status: 'extracted', source }).inc()+ }}} finally {// CRITICAL: Always delete $ai_usage to prevent it from being stored in ClickHousediff --git a/nodejs/src/ingestion/ai/costs/output-costs.test.ts b/nodejs/src/ingestion/ai/costs/output-costs.test.tsindex abd5b753e4a9..02211e338e9c 100644--- a/nodejs/src/ingestion/ai/costs/output-costs.test.ts+++ b/nodejs/src/ingestion/ai/costs/output-costs.test.ts@@ -1,22 +1,6 @@-import { PluginEvent } from '~/plugin-scaffold'-import { calculateOutputCost } from './output-costs'import { ResolvedModelCost } from './providers/types'--// Helper function to create a PluginEvent with default values-function createAIEvent(properties?: Record<string, any>): PluginEvent {- return {- event: '$ai_generation',- properties: properties || {},- ip: '',- site_url: '',- team_id: 0,- now: '',- distinct_id: '',- uuid: '',- timestamp: '',- }-}+import { createAIEvent } from './test-helpers'// Helper function to create a ModelRow with defaultsfunction createModel(@@ -528,4 +512,141 @@ describe('calculateOutputCost()', () => {expectCost(result, 0.00075)})})++ describe('audio output tokens - modality cost calculation', () => {+ // gpt-4o-audio-preview pricing:+ // - text output: $10/1M ($0.00001/token)+ // - audio output: $80/1M ($0.00008/token)+ const audioModel: ResolvedModelCost = {+ model: 'gpt-4o-audio-preview',+ provider: 'openai',+ cost: {+ prompt_token: 0.0000025,+ completion_token: 0.00001,+ audio: 0.00004,+ audio_output: 0.00008,+ },+ }++ it('bills audio output at the audio_output rate, separate from text', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o-audio-preview',+ $ai_output_tokens: 1000, // 200 text + 800 audio+ $ai_audio_output_tokens: 800,+ })++ const result = calculateOutputCost(event, audioModel)++ // Text: (1000 - 800) × 0.00001 = 0.002+ // Audio: 800 × 0.00008 = 0.064+ // Total: 0.066+ expectCost(result, 0.066, 5)+ })++ it('falls back to completion rate when no audio_output rate is defined', () => {+ const modelWithoutAudioOutput: ResolvedModelCost = {+ model: 'some-model',+ provider: 'unknown',+ cost: { prompt_token: 0.000001, completion_token: 0.000002 },+ }+ const event = createAIEvent({+ $ai_provider: 'unknown',+ $ai_model: 'some-model',+ $ai_output_tokens: 1000,+ $ai_audio_output_tokens: 800,+ })++ const result = calculateOutputCost(event, modelWithoutAudioOutput)++ // No separate rate, audio falls back to completion rate.+ // Total stays at 1000 × 0.000002 = 0.002+ expectCost(result, 0.002)+ })++ it('combines audio output with image output for fully multimodal models', () => {+ const multiModalModel: ResolvedModelCost = {+ model: 'multi-modal',+ provider: 'imaginary',+ cost: {+ prompt_token: 0.000001,+ completion_token: 0.000002,+ image_output: 0.00003,+ audio_output: 0.00004,+ },+ }+ const event = createAIEvent({+ $ai_provider: 'imaginary',+ $ai_model: 'multi-modal',+ $ai_output_tokens: 2000, // 200 text + 800 audio + 1000 image+ $ai_audio_output_tokens: 800,+ $ai_image_output_tokens: 1000,+ })++ const result = calculateOutputCost(event, multiModalModel)++ // Text: 200 × 0.000002 = 0.0004+ // Audio: 800 × 0.00004 = 0.032+ // Image: 1000 × 0.00003 = 0.03+ // Total: 0.0624+ expectCost(result, 0.0624, 5)+ })+ })++ describe('text output tokens type handling', () => {+ const basicModel: ResolvedModelCost = {+ model: 'test-model',+ provider: 'openai',+ cost: { prompt_token: 0.000001, completion_token: 0.000002 },+ }++ it('uses explicit numeric $ai_text_output_tokens when provided', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'test-model',+ $ai_output_tokens: 999, // ignored because text is explicit+ $ai_text_output_tokens: 100,+ })++ // 100 × 0.000002 = 0.0002+ expectCost(calculateOutputCost(event, basicModel), 0.0002)+ })++ it('uses string-encoded $ai_text_output_tokens (some SDKs serialise as strings)', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'test-model',+ $ai_output_tokens: 999,+ $ai_text_output_tokens: '100',+ })++ // bigDecimal accepts strings; "100" × 0.000002 = 0.0002+ expectCost(calculateOutputCost(event, basicModel), 0.0002)+ })++ it('falls back to derivation when $ai_text_output_tokens is null', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'test-model',+ $ai_output_tokens: 100,+ $ai_text_output_tokens: null as any,+ })++ // Derived = 100; cost = 100 × 0.000002 = 0.0002+ expectCost(calculateOutputCost(event, basicModel), 0.0002)+ })++ it('treats unparseable $ai_text_output_tokens as zero rather than poisoning the total', () => {+ const event = createAIEvent({+ $ai_provider: 'openai',+ $ai_model: 'test-model',+ $ai_output_tokens: 100,+ $ai_text_output_tokens: 'abc' as any, // garbage from a malformed SDK payload+ })++ // numericProperty returns 0 for non-numeric strings, so text cost is 0.+ // No NaN propagation through bigDecimal.+ expectCost(calculateOutputCost(event, basicModel), 0)+ })+ })})diff --git a/nodejs/src/ingestion/ai/costs/output-costs.ts b/nodejs/src/ingestion/ai/costs/output-costs.tsindex 1ab833da8bb8..b992724ee124 100644--- a/nodejs/src/ingestion/ai/costs/output-costs.ts+++ b/nodejs/src/ingestion/ai/costs/output-costs.ts@@ -2,6 +2,8 @@ import bigDecimal from 'js-big-decimal'import { PluginEvent } from '~/plugin-scaffold'+import { logger } from '../../../utils/logger'+import { numericProperty } from './cost-utils'import { ResolvedModelCost } from './providers/types'const REASONING_COST_MODELS = [/^gemini-2\.5-/, /^gemini-3(\.\d+)?-/]@@ -10,64 +12,82 @@ const mustAddReasoningCost = (model: string): boolean => {return REASONING_COST_MODELS.some((candidate) => candidate.test(model.toLowerCase()))}+const warnMissingModalityRate = (event: PluginEvent, cost: ResolvedModelCost, modality: 'audio' | 'image'): void => {+ logger.warn('Missing modality output rate; falling back to completion rate', {+ modality,+ model: cost.model,+ provider: event.properties?.['$ai_provider'] || 'unknown',+ })+}++const computeAudioOutputCost = (event: PluginEvent, cost: ResolvedModelCost, audioOutputTokens: number): string => {+ if (audioOutputTokens <= 0) {+ return '0'+ }+ if (cost.cost.audio_output === undefined) {+ warnMissingModalityRate(event, cost, 'audio')+ return bigDecimal.multiply(cost.cost.completion_token, audioOutputTokens)+ }+ return bigDecimal.multiply(cost.cost.audio_output, audioOutputTokens)+}++const computeImageOutputCost = (event: PluginEvent, cost: ResolvedModelCost, imageOutputTokens: number): string => {+ if (imageOutputTokens <= 0) {+ return '0'+ }+ if (cost.cost.image_output === undefined) {+ warnMissingModalityRate(event, cost, 'image')+ return bigDecimal.multiply(cost.cost.completion_token, imageOutputTokens)+ }+ return bigDecimal.multiply(cost.cost.image_output, imageOutputTokens)+}+/**- * Calculate output cost, including image output tokens if present.- *- * For multimodal models like Gemini with image generation:- * - If $ai_image_output_tokens is present and image_output pricing exists,- * calculate image cost separately at the image output rate.- * - Text output tokens are calculated at the standard completion rate.+ * Calculate output cost. Audio and image output tokens are billed at their+ * dedicated rates when the model exposes them, falling back to the standard+ * completion rate otherwise (and emitting a warning so the missing rate is+ * visible). Modality tokens are subtracted from the text pool to avoid+ * double-counting.*- * Example for gemini-2.5-flash-image:- * - Text output: $2.50/1M tokens- * - Image output: $30/1M tokens (1290 tokens per image = $0.039/image)+ * Reasoning tokens are added to the text pool for Gemini 2.5/3 — those models+ * report reasoning separately but still bill it at the completion rate.*/export const calculateOutputCost = (event: PluginEvent, cost: ResolvedModelCost): string => {if (!event.properties) {return '0'}- const imageOutputTokens = event.properties['$ai_image_output_tokens']- const hasImageTokens = typeof imageOutputTokens === 'number' && imageOutputTokens > 0- const hasImagePricing = cost.cost.image_output !== undefined && cost.cost.image_output > 0+ const audioOutputTokens = numericProperty(event, '$ai_audio_output_tokens')+ const imageOutputTokens = numericProperty(event, '$ai_image_output_tokens')- // If we have image tokens and image pricing, calculate costs separately- if (hasImageTokens && hasImagePricing) {- // Calculate image output cost- const imageCost = bigDecimal.multiply(cost.cost.image_output!, imageOutputTokens)+ const audioOutputCost = computeAudioOutputCost(event, cost, audioOutputTokens)+ const imageOutputCost = computeImageOutputCost(event, cost, imageOutputTokens)+ const modalityOutputCost = bigDecimal.add(audioOutputCost, imageOutputCost)- // Calculate text output cost- // If we have explicit text tokens, use those; otherwise use total - image- let textOutputTokens = event.properties['$ai_text_output_tokens']- if (textOutputTokens === undefined) {- const totalOutputTokens = event.properties['$ai_output_tokens'] || 0- textOutputTokens = Math.max(0, Number(totalOutputTokens) - imageOutputTokens)- }+ const rawTextOutputTokens = event.properties['$ai_text_output_tokens']+ const hasExplicitText = rawTextOutputTokens !== undefined && rawTextOutputTokens !== null- // Add reasoning tokens to text tokens for Gemini models that report them separately- if (- event.properties['$ai_reasoning_tokens'] &&- event.properties['$ai_model'] &&- mustAddReasoningCost(event.properties['$ai_model'])- ) {- textOutputTokens = bigDecimal.add(textOutputTokens, event.properties['$ai_reasoning_tokens'])- }-- const textCost = bigDecimal.multiply(cost.cost.completion_token, textOutputTokens)-- return bigDecimal.add(imageCost, textCost)+ let textOutputTokens: number | string+ if (hasExplicitText) {+ // Route through numericProperty so numeric strings ("100") still parse+ // but garbage ("abc") yields 0 instead of poisoning bigDecimal with NaN.+ textOutputTokens = numericProperty(event, '$ai_text_output_tokens')+ } else {+ const totalOutputTokens = numericProperty(event, '$ai_output_tokens')+ const derived = totalOutputTokens - audioOutputTokens - imageOutputTokens+ // Clamp to zero when modality tokens exceed the total output count.+ // Without modality tokens, negatives flow through so callers can spot+ // data-integrity issues via negative totals (some test fixtures rely on+ // this to assert behaviour against synthetic negative inputs).+ textOutputTokens = audioOutputTokens > 0 || imageOutputTokens > 0 ? Math.max(0, derived) : derived}- // Standard path: no image tokens or no image pricing- let outputTokens = event.properties['$ai_output_tokens'] || 0-- if (- event.properties['$ai_reasoning_tokens'] &&- event.properties['$ai_model'] &&- mustAddReasoningCost(event.properties['$ai_model'])- ) {- outputTokens = bigDecimal.add(outputTokens, event.properties['$ai_reasoning_tokens'])+ const reasoningTokens = event.properties['$ai_reasoning_tokens']+ if (reasoningTokens && event.properties['$ai_model'] && mustAddReasoningCost(event.properties['$ai_model'])) {+ textOutputTokens = bigDecimal.add(textOutputTokens, reasoningTokens)}- return bigDecimal.multiply(cost.cost.completion_token, outputTokens)+ const textCost = bigDecimal.multiply(cost.cost.completion_token, textOutputTokens)++ return bigDecimal.add(textCost, modalityOutputCost)}diff --git a/nodejs/src/ingestion/ai/costs/providers/llm-costs.json b/nodejs/src/ingestion/ai/costs/providers/llm-costs.jsonindex b9117376376d..fb106a0c196b 100644--- a/nodejs/src/ingestion/ai/costs/providers/llm-costs.json+++ b/nodejs/src/ingestion/ai/costs/providers/llm-costs.json@@ -4436,12 +4436,14 @@"default": {"prompt_token": 0.0000025,"completion_token": 0.00001,- "audio": 0.00004+ "audio": 0.00004,+ "audio_output": 0.00008},"openai": {"prompt_token": 0.0000025,"completion_token": 0.00001,- "audio": 0.00004+ "audio": 0.00004,+ "audio_output": 0.00008}}},@@ -5037,12 +5039,14 @@"default": {"prompt_token": 0.0000025,"completion_token": 0.00001,- "audio": 0.000032+ "audio": 0.000032,+ "audio_output": 0.000064},"openai": {"prompt_token": 0.0000025,"completion_token": 0.00001,- "audio": 0.000032+ "audio": 0.000032,+ "audio_output": 0.000064}}},@@ -5052,12 +5056,14 @@"default": {"prompt_token": 6e-7,"completion_token": 0.0000024,- "audio": 6e-7+ "audio": 6e-7,+ "audio_output": 0.0000024},"openai": {"prompt_token": 6e-7,"completion_token": 0.0000024,- "audio": 6e-7+ "audio": 6e-7,+ "audio_output": 0.0000024}}},diff --git a/nodejs/src/ingestion/ai/costs/providers/types.ts b/nodejs/src/ingestion/ai/costs/providers/types.tsindex f4918fe3f273..36eac4abb26f 100644--- a/nodejs/src/ingestion/ai/costs/providers/types.ts+++ b/nodejs/src/ingestion/ai/costs/providers/types.ts@@ -8,6 +8,7 @@ export interface ModelCost {image?: numberimage_output?: numberaudio?: number+ audio_output?: numberinput_audio_cache?: numberinternal_reasoning?: number}diff --git a/nodejs/src/ingestion/ai/costs/scripts/update-ai-costs.ts b/nodejs/src/ingestion/ai/costs/scripts/update-ai-costs.tsindex a8443d815fce..63e6031896ab 100644--- a/nodejs/src/ingestion/ai/costs/scripts/update-ai-costs.ts+++ b/nodejs/src/ingestion/ai/costs/scripts/update-ai-costs.ts@@ -12,6 +12,7 @@ interface ModelCost {image?: numberimage_output?: numberaudio?: number+ audio_output?: numberinput_audio_cache?: numberinternal_reasoning?: number}@@ -79,6 +80,7 @@ const buildModelCost = (pricing: Record<string, unknown> | undefined): ModelCost['image', 'image'],['image_output', 'image_output'],['audio', 'audio'],+ ['audio_output', 'audio_output'],['input_audio_cache', 'input_audio_cache'],['internal_reasoning', 'internal_reasoning'],]diff --git a/nodejs/src/ingestion/ai/costs/test-helpers.ts b/nodejs/src/ingestion/ai/costs/test-helpers.tsnew file mode 100644index 000000000000..a91f35a108a8--- /dev/null+++ b/nodejs/src/ingestion/ai/costs/test-helpers.ts@@ -0,0 +1,22 @@+import { Properties } from '~/plugin-scaffold'++import { EventWithProperties } from './modality-tokens'++/**+ * Build an `$ai_generation` PluginEvent with a properties bag for cost-pipeline+ * tests. Returns `EventWithProperties` (a `PluginEvent` with non-optional+ * `properties`) so it can be passed to extractors and cost calculators alike.+ */+export function createAIEvent(properties: Properties = {}): EventWithProperties {+ return {+ event: '$ai_generation',+ properties,+ ip: '',+ site_url: '',+ team_id: 0,+ now: '',+ distinct_id: '',+ uuid: '',+ timestamp: '',+ }+}diff --git a/nodejs/src/ingestion/ai/metrics.ts b/nodejs/src/ingestion/ai/metrics.tsindex 04fafb3e7f17..4d34fe9d0ca2 100644--- a/nodejs/src/ingestion/ai/metrics.ts+++ b/nodejs/src/ingestion/ai/metrics.ts@@ -14,8 +14,8 @@ export const aiErrorNormalizationCounter = new Counter({export const aiCostModalityExtractionCounter = new Counter({name: 'llma_ai_cost_modality_extraction_total',- help: 'AI cost modality token extraction outcomes',- labelNames: ['status'],+ help: 'AI cost modality token extraction outcomes by source',+ labelNames: ['status', 'source'],})export const aiCostTotalOutcomeCounter = new Counter({diff --git a/nodejs/src/ingestion/ai/process-ai-event.test.ts b/nodejs/src/ingestion/ai/process-ai-event.test.tsindex c2d2ffa12cc9..a9a3c3b9a2f2 100644--- a/nodejs/src/ingestion/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/ai/process-ai-event.test.ts@@ -73,6 +73,43 @@ const costsByModel: Record<string, MockModelRow> = {model: 'model-with-request-only',cost: { prompt_token: 0.0000015, completion_token: 0.000006, request: 0.002 },},+ 'openai/gpt-4o-audio-preview': {+ model: 'openai/gpt-4o-audio-preview',+ cost: {+ prompt_token: 0.0000025,+ completion_token: 0.00001,+ audio: 0.00004,+ audio_output: 0.00008,+ },+ },+ 'openai/gpt-audio-mini': {+ model: 'openai/gpt-audio-mini',+ cost: {+ prompt_token: 0.00000015,+ completion_token: 0.0000006,+ cache_read_token: 0.000000075,+ audio: 0.000001,+ input_audio_cache: 0.0000001,+ },+ },+ 'google/gemini-2.5-flash-image': {+ model: 'google/gemini-2.5-flash-image',+ cost: {+ prompt_token: 3e-7,+ completion_token: 0.0000025,+ image: 3e-7,+ image_output: 0.00003,+ },+ },+ 'google/gemini-3-flash-preview': {+ model: 'google/gemini-3-flash-preview',+ cost: {+ prompt_token: 5e-7,+ completion_token: 3e-6,+ audio: 0.0000015,+ input_audio_cache: 1.5e-7,+ },+ },}jest.mock('./costs/providers', () => {@@ -94,6 +131,10 @@ jest.mock('./costs/providers', () => {'mistralai/mistral-7b-instruct-v0.1': 'mistralai','perplexity/sonar-pro': 'perplexity','model-with-request-only': 'custom',+ 'openai/gpt-4o-audio-preview': 'openai',+ 'openai/gpt-audio-mini': 'openai',+ 'google/gemini-2.5-flash-image': 'google-ai-studio',+ 'google/gemini-3-flash-preview': 'google-ai-studio',}let cachedMocks:@@ -228,6 +269,103 @@ describe('processAiEvent()', () => {})})+ describe('modality cost calculation', () => {+ it('rolls audio token costs into input/output for audio-capable models', () => {+ event.properties!.$ai_model = 'gpt-4o-audio-preview'+ event.properties!.$ai_input_tokens = 1000 // 800 text + 200 audio+ event.properties!.$ai_output_tokens = 1000 // 200 text + 800 audio+ event.properties!.$ai_audio_input_tokens = 200+ event.properties!.$ai_audio_output_tokens = 800++ const result = processAiEvent(event)++ // Input: text (800 × 0.0000025) + audio (200 × 0.00004) = 0.002 + 0.008 = 0.01+ // Output: text (200 × 0.00001) + audio (800 × 0.00008) = 0.002 + 0.064 = 0.066+ // Total: input + output = 0.076 (request and web search are 0)+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.01, 5)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.066, 5)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.076, 5)+ // We do not expose a separate modality breakdown property+ expect(result.properties!.$ai_audio_cost_usd).toBeUndefined()+ })++ it('rolls image token costs into input/output for image-capable models', () => {+ event.properties!.$ai_model = 'gemini-2.5-flash-image'+ event.properties!.$ai_provider = 'google'+ event.properties!.$ai_input_tokens = 600 // 200 text + 400 image+ event.properties!.$ai_output_tokens = 1300 // 10 text + 1290 image+ event.properties!.$ai_image_input_tokens = 400+ event.properties!.$ai_image_output_tokens = 1290++ const result = processAiEvent(event)++ // Input: text (200 × 3e-7) + image (400 × 3e-7) = 6e-5 + 0.00012 = 0.00018+ // Output: text (10 × 0.0000025) + image (1290 × 0.00003) = 0.000025 + 0.0387 = 0.038725+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00018, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.038725, 6)+ expect(result.properties!.$ai_image_cost_usd).toBeUndefined()+ })++ it('bills cached audio at the audio-cache rate end-to-end', () => {+ event.properties!.$ai_model = 'gpt-audio-mini'+ event.properties!.$ai_input_tokens = 1000 // 500 text uncached + 250 text cached + 50 audio cached + 150 audio uncached+ event.properties!.$ai_output_tokens = 100+ event.properties!.$ai_cache_read_input_tokens = 300 // 250 text + 50 audio+ event.properties!.$ai_audio_input_tokens = 200 // 150 uncached + 50 cached+ event.properties!.$ai_cache_read_audio_tokens = 50++ const result = processAiEvent(event)++ // Cached text: 250 × 0.000000075 = 0.00001875+ // Uncached text: 550 × 0.00000015 = 0.0000825+ // Uncached audio: 150 × 0.000001 = 0.00015+ // Cached audio: 50 × 0.0000001 = 0.000005+ // Input total: 0.00025625+ // Output: 100 × 0.0000006 = 0.00006+ // Grand total: 0.00031625+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00025625, 8)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00006, 8)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00031625, 8)+ })++ it('extracts Gemini audio input tokens from snake_case $ai_usage and bills at audio rate', () => {+ // Simulates a Gemini transcription event coming from posthog-python:+ // the SDK forwards usage_metadata via to_dict() / vars() which+ // produces snake_case keys (prompt_tokens_details with token_count+ // entries) rather than the camelCase form Vercel uses. Ingestion+ // must extract from this shape and bill the audio portion at the+ // audio rate even though $ai_audio_input_tokens is not pre-set.+ event.properties!.$ai_model = 'gemini-3-flash-preview'+ event.properties!.$ai_provider = 'gemini'+ event.properties!.$ai_input_tokens = 1000 // 750 audio + 250 text+ event.properties!.$ai_output_tokens = 100+ event.properties!.$ai_usage = {+ prompt_token_count: 1000,+ candidates_token_count: 100,+ prompt_tokens_details: [+ { modality: 'AUDIO', token_count: 750 },+ { modality: 'TEXT', token_count: 250 },+ ],+ }++ const result = processAiEvent(event)++ // After extraction, the audio token property should be populated.+ expect(result.properties!.$ai_audio_input_tokens).toBe(750)+ expect(result.properties!.$ai_text_input_tokens).toBe(250)+ // $ai_usage is always stripped after extraction.+ expect(result.properties!.$ai_usage).toBeUndefined()++ // Input billing: text (250 × 5e-7) + audio (750 × 0.0000015)+ // = 0.000125 + 0.001125 = 0.00125+ // Output: 100 × 3e-6 = 0.0003+ // Total: 0.00155+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00125, 7)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0003, 7)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00155, 7)+ })+ })+describe('cost calculation', () => {it('calculates correct cost for prompt and completion tokens', () => {const result = processAiEvent(event)