: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): price cache writes across providers (#84625)
gtpooniwala2949a5eaf78a
diff --git a/docs/onboarding/ai-observability/_snippets/generation-event.tsx b/docs/onboarding/ai-observability/_snippets/generation-event.tsxindex a873075308d0..e9e2872216c6 100644--- a/docs/onboarding/ai-observability/_snippets/generation-event.tsx+++ b/docs/onboarding/ai-observability/_snippets/generation-event.tsx@@ -527,11 +527,14 @@ export const GenerationEvent = (): JSX.Element => {</td><td><p>- <em>(Optional)</em> Number of tokens written to cache (Anthropic-specific)+ <em>(Optional)</em> Number of tokens written to cache<br />- When both TTL-specific counts are present, PostHog uses them instead of this- aggregate. The aggregate should equal their sum; if either count is missing, PostHog- uses the aggregate.+ For Anthropic events, PostHog uses the TTL-specific counts instead of this aggregate+ when both are present. The aggregate should equal their sum. If either count is+ missing, PostHog uses the aggregate.+ <br />+ Built-in Gemini pricing uses normal input rates for cache writes and does not+ estimate cache storage fees. Custom pricing can override these rates.</p></td></tr>diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex e46591060a6b..723f8fb6e6d0 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -188,7 +188,7 @@"type": "Numeric"},"$ai_cache_creation_input_tokens": {- "description": "The number of tokens created in the cache for the input prompt (anthropic only).",+ "description": "The number of tokens created in the cache for the input prompt.","examples": [23],@@ -4845,7 +4845,7 @@"type": "Numeric"},"$ai_cache_creation_input_tokens": {- "description": "The number of tokens created in the cache for the input prompt (anthropic only).",+ "description": "The number of tokens created in the cache for the input prompt.","examples": [23],diff --git a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.tsindex 8455ae306b23..d1fdaa7936e6 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts@@ -557,6 +557,63 @@ describe('calculateInputCost()', () => {expectCostToBeCloseTo(result, 0.002)})+ it.each([+ {+ name: 'prices inclusive cache reads and writes at distinct rates',+ inputTokens: 1000,+ exclusive: false,+ cacheWriteRate: 0.00000125,+ expected: 0.000895,+ },+ {+ name: 'prices cache writes below the prompt rate',+ inputTokens: 1000,+ exclusive: false,+ cacheWriteRate: 0.00000025,+ expected: 0.000595,+ },+ {+ name: 'adds cache buckets to explicitly exclusive input',+ inputTokens: 500,+ exclusive: true,+ cacheWriteRate: 0.00000125,+ expected: 0.000895,+ },+ {+ name: 'falls back to the prompt rate for cache writes',+ inputTokens: 1000,+ exclusive: false,+ cacheWriteRate: undefined,+ expected: 0.00082,+ },+ {+ name: 'preserves an explicit zero cache-write rate',+ inputTokens: 1000,+ exclusive: false,+ cacheWriteRate: 0,+ expected: 0.00052,+ },+ ])('$name', ({ inputTokens, exclusive, cacheWriteRate, expected }) => {+ const model = createTestModel({+ model: 'gpt-4o',+ provider: 'openai',+ cost: {+ prompt_token: 0.000001,+ completion_token: 0.000002,+ cache_read_token: 0.0000001,+ ...(cacheWriteRate !== undefined && { cache_write_token: cacheWriteRate }),+ },+ })+ const event = createOpenAITestEvent(inputTokens, 200, {+ $ai_cache_creation_input_tokens: 300,+ $ai_cache_reporting_exclusive: exclusive,+ })++ const result = calculateInputCost(event, model)++ expectCostToBeCloseTo(result, expected)+ })+it('uses 0.5x multiplier fallback when cache_read_token not defined', () => {const modelWithoutCacheRead = createTestModel({model: 'gpt-4',@@ -611,6 +668,31 @@ describe('calculateInputCost()', () => {})describe('gemini provider - cache handling', () => {+ it.each([+ { inputTokens: 100000, exclusive: false },+ { inputTokens: 50000, exclusive: true },+ ])('prices cache writes as input with exclusive=$exclusive', ({ inputTokens, exclusive }) => {+ const model = createTestModel({+ model: 'google/gemini-2.5-flash',+ provider: 'google-vertex',+ cost: {+ prompt_token: 3e-7,+ completion_token: 0.0000025,+ cache_read_token: 3e-8,+ cache_write_token: 8.333333333e-8,+ },+ })+ const event = createGeminiTestEvent(inputTokens, 20000, {+ $ai_model: 'gemini-2.5-flash',+ $ai_provider: 'vertex',+ $ai_cache_creation_input_tokens: 30000,+ $ai_cache_reporting_exclusive: exclusive,+ })++ expectCostToBeCloseTo(calculateInputCost(event, model), 0.0246)+ expect(event.properties!.$ai_cache_reporting_exclusive).toBe(exclusive)+ })+it('calculates cost with cache read tokens using explicit costs', () => {const event = createGeminiTestEvent(10000, 4000)const result = calculateInputCost(event, GEMINI_MODEL)@@ -1050,7 +1132,7 @@ describe('calculateInputCost()', () => {expectCostToBeCloseTo(result, 0.0001)})- it('handles audio + image input together for multimodal calls', () => {+ it.each([0, 600])('handles audio + image input with %i cache-write tokens', (cacheWriteTokens) => {const multiModalCost: ResolvedModelCost = {model: 'gemini-2.5-flash',provider: 'google',@@ -1059,6 +1141,7 @@ describe('calculateInputCost()', () => {completion_token: 0.0000025,image: 3e-7,audio: 0.000001,+ cache_write_token: 8.333333333e-8,},}const event = createAIEvent({@@ -1067,6 +1150,7 @@ describe('calculateInputCost()', () => {$ai_input_tokens: 1000, // 400 text + 200 audio + 400 image$ai_audio_input_tokens: 200,$ai_image_input_tokens: 400,+ $ai_cache_creation_input_tokens: cacheWriteTokens,})const result = calculateInputCost(event, multiModalCost)diff --git a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.tsindex e71a11e42c9a..723ab0b1f932 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts@@ -230,7 +230,15 @@ export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost):return bigDecimal.add(bigDecimal.add(totalCacheCost, uncachedCost), modalityInputCost)}- const baseRegularTokens = exclusive ? inputTokens : bigDecimal.subtract(inputTokens, cachedTextTokens)+ const cacheWriteTokens = numericProperty(event, '$ai_cache_creation_input_tokens')+ // Gemini's catalog write rate covers storage, not the input charge. Keep writes+ // in normal input pricing (including audio/image rates); storage needs a known duration.+ // https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#caching_storage_costs+ const isGeminiCatalogCost = cost.provider !== 'custom' && /(^|\/)gemini-/.test(cost.model.toLowerCase())+ const separateCacheWriteTokens = isGeminiCatalogCost ? 0 : cacheWriteTokens+ const baseRegularTokens = exclusive+ ? bigDecimal.add(inputTokens, isGeminiCatalogCost ? cacheWriteTokens : 0)+ : bigDecimal.subtract(bigDecimal.subtract(inputTokens, cachedTextTokens), separateCacheWriteTokens)const regularTextTokens = clampTextTokens(bigDecimal.subtract(bigDecimal.subtract(baseRegularTokens, audioInputTokens), imageInputTokens),hasModalityTokens@@ -256,7 +264,9 @@ export const calculateInputCost = (event: PluginEvent, cost: ResolvedModelCost):cacheReadCost = bigDecimal.multiply(bigDecimal.multiply(cost.cost.prompt_token, multiplier), cachedTextTokens)}+ const cacheWriteRate = cost.cost.cache_write_token ?? cost.cost.prompt_token+ const cacheWriteCost = bigDecimal.multiply(cacheWriteRate, separateCacheWriteTokens)const regularCost = bigDecimal.multiply(cost.cost.prompt_token, regularTextTokens)- return bigDecimal.add(bigDecimal.add(cacheReadCost, regularCost), modalityInputCost)+ return bigDecimal.add(bigDecimal.add(bigDecimal.add(cacheReadCost, cacheWriteCost), regularCost), modalityInputCost)}diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.tsindex d11816036d4c..f68d0cf38d93 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts@@ -44,7 +44,12 @@ const costsByModel: Record<string, MockModelRow> = {},'google/gemini-2.5-pro-preview': {model: 'google/gemini-2.5-pro-preview',- cost: { prompt_token: 0.00000125, completion_token: 0.00001, cache_read_token: 3.1e-7 },+ cost: {+ prompt_token: 0.00000125,+ completion_token: 0.00001,+ cache_read_token: 3.1e-7,+ cache_write_token: 3.75e-7,+ },},'gemini-2.5-pro-preview:large': {model: 'gemini-2.5-pro-preview:large',@@ -1060,21 +1065,31 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_output_cost_usd).toBeGreaterThan(0)})- it('handles custom pricing with cache read tokens for OpenAI', () => {- event.properties!.$ai_provider = 'openai'- event.properties!.$ai_input_token_price = 0.001- event.properties!.$ai_output_token_price = 0.002- event.properties!.$ai_cache_read_token_price = 0.0005- event.properties!.$ai_input_tokens = 100- event.properties!.$ai_cache_read_input_tokens = 40- event.properties!.$ai_output_tokens = 50+ it.each([+ { provider: 'openai', model: 'gpt-4o', writeRate: 0.00125, expectedInputCost: 0.085 },+ { provider: 'google', model: 'gemini-2.5-flash', writeRate: 0.00125, expectedInputCost: 0.085 },+ { provider: 'google', model: 'gemini-2.5-flash', writeRate: 0, expectedInputCost: 0.06 },+ ])(+ 'handles custom cache pricing for $provider at write rate $writeRate',+ ({ provider, model, writeRate, expectedInputCost }) => {+ event.properties!.$ai_provider = provider+ event.properties!.$ai_model = model+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_cache_read_token_price = 0.0005+ event.properties!.$ai_cache_write_token_price = writeRate+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_cache_read_input_tokens = 40+ event.properties!.$ai_cache_creation_input_tokens = 20+ event.properties!.$ai_output_tokens = 50- const result = processAiEvent(event)+ const result = processAiEvent(event)- expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)- expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)- expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.18, 6)- })+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(expectedInputCost, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(expectedInputCost + 0.1, 6)+ }+ )it('handles custom pricing with cache tokens for Anthropic', () => {event.properties!.$ai_provider = 'anthropic'@@ -1263,9 +1278,8 @@ describe('processAiEvent()', () => {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.+ // Several optional prices are invalid at once, so dropping the coercion on+ // any single one puts it back in front of js-big-decimal.it('ignores unusable optional prices and keeps custom pricing', () => {event.properties!.$ai_provider = 'openai'event.properties!.$ai_input_token_price = 0.001@@ -1290,8 +1304,8 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.18, 6)})- // Only the Anthropic path consumes the cache-write rates, and only when the- // 5m/1h breakdown is present does it consume both of them.+ // Only the Anthropic TTL path consumes the 1-hour cache-write rate, and only+ // when both TTL counts are present.it('ignores unusable cache write prices on an Anthropic event', () => {event.properties!.$ai_model = 'claude-sonnet-4'event.properties!.$ai_provider = 'anthropic'@@ -1905,11 +1919,17 @@ describe('processAiEvent()', () => {})describe('gemini cache handling', () => {- it('handles cache read tokens with correct cost calculation for gemini-2.5-pro-preview', () => {- event.properties!.$ai_provider = 'gemini'+ it.each([+ { provider: 'gemini', cacheWriteTokens: 0 },+ { provider: 'gemini', cacheWriteTokens: 300 },+ { provider: 'vertex', cacheWriteTokens: 300 },+ { provider: 'openrouter', cacheWriteTokens: 300 },+ ])('prices cache reads and $cacheWriteTokens writes for $provider', ({ provider, cacheWriteTokens }) => {+ event.properties!.$ai_provider = providerevent.properties!.$ai_model = 'gemini-2.5-pro-preview'event.properties!.$ai_input_tokens = 1000event.properties!.$ai_cache_read_input_tokens = 400+ event.properties!.$ai_cache_creation_input_tokens = cacheWriteTokensevent.properties!.$ai_output_tokens = 50const result = processAiEvent(event)diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 84c8afe12dcd..0f54a6f840ed 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2312,7 +2312,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {},"$ai_cache_creation_input_tokens": {"label": "AI cache creation input tokens (LLM)",- "description": "The number of tokens created in the cache for the input prompt (anthropic only).",+ "description": "The number of tokens created in the cache for the input prompt.","examples": [23],},"$ai_cache_creation_5m_input_tokens": {diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex deb0f7706310..de0ef5a028af 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -8272,7 +8272,10 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertNotIn("user_id", decoded)self.assertIn("exp", decoded)+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_returns_proxy_url_when_configured_and_flag_enabled(self):+ reset_sandbox_jwt_key_cache()+task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)@@ -8285,9 +8288,12 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_omits_proxy_url_for_thin_tail_run(self):# Only the Django read leg serves the durable backlog, so a thin-tail run must# never be routed to the agent-proxy even with the proxy flag enabled.+ reset_sandbox_jwt_key_cache()+task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS, state={"stream_thin_tail": True}@@ -8302,7 +8308,10 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertIsNone(response.json()["stream_base_url"])+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_omits_proxy_url_when_flag_disabled(self):+ reset_sandbox_jwt_key_cache()+task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)@@ -8323,7 +8332,10 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertIsNone(response.json()["stream_base_url"])+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_returns_proxy_url_for_pi_when_flag_disabled(self):+ reset_sandbox_jwt_key_cache()+task = self.create_task(runtime=Task.Runtime.PI)run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)@@ -8342,8 +8354,11 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_returns_proxy_url_in_debug_without_flag(self):# Local dev (DEBUG) disables the analytics SDK, so the URL setting alone opts in.+ reset_sandbox_jwt_key_cache()+task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)@@ -8353,8 +8368,11 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["stream_base_url"], "http://localhost:8003")+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_stream_token_omits_proxy_url_when_flag_evaluation_fails(self):# A flag-service outage must fall back to reading from Django, not break token issuance.+ reset_sandbox_jwt_key_cache()+task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)