: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
feat(aio): use Vercel AI Gateway reported cost for LLM generations (#88457)
Marco Gancitanofa95ef8172bb
diff --git a/docs/onboarding/ai-observability/_snippets/generation-event.tsx b/docs/onboarding/ai-observability/_snippets/generation-event.tsxindex 45cefadc90d6..a873075308d0 100644--- a/docs/onboarding/ai-observability/_snippets/generation-event.tsx+++ b/docs/onboarding/ai-observability/_snippets/generation-event.tsx@@ -373,6 +373,18 @@ export const GenerationEvent = (): JSX.Element => {</p></td></tr>+ <tr>+ <td style={propertyColumnStyle}>+ <code>$ai_cost_passthrough</code>+ </td>+ <td>+ <p>+ <em>(Optional)</em> Set this when your provider reports the real cost, such as an+ LLM gateway. We keep your <code>$ai_total_cost_usd</code> and leave the input and+ output costs unset.+ </p>+ </td>+ </tr></tbody></table></div>diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 6b70c4396d82..9cb10069ed31 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -259,6 +259,13 @@],"label": "AI cost model source (LLM)"},+ "$ai_cost_passthrough": {+ "description": "Set this to keep the reported total cost and skip PostHog's token-based estimate. Use it when the provider reports an authoritative cost, such as an LLM gateway. The input and output cost split is left unset.",+ "examples": [+ true+ ],+ "label": "AI cost passthrough (LLM)"+ },"$ai_error": {"description": "The error message from a failed AI event.","examples": [@@ -4850,6 +4857,13 @@],"label": "AI cost model source (LLM)"},+ "$ai_cost_passthrough": {+ "description": "Set this to keep the reported total cost and skip PostHog's token-based estimate. Use it when the provider reports an authoritative cost, such as an LLM gateway. The input and output cost split is left unset.",+ "examples": [+ true+ ],+ "label": "AI cost passthrough (LLM)"+ },"$ai_error": {"description": "The error message from a failed AI event.","examples": [diff --git a/nodejs/src/ingestion/common/ai-event-types.ts b/nodejs/src/ingestion/common/ai-event-types.tsindex c416b55598b0..83728202b7a9 100644--- a/nodejs/src/ingestion/common/ai-event-types.ts+++ b/nodejs/src/ingestion/common/ai-event-types.ts@@ -20,3 +20,9 @@ export const AI_EVENT_TYPES = new Set(['$ai_trace_summary','$ai_evaluation_report',])++// Anything that writes a cost onto an event must gate on this set. A cost on any+// other event type is never priced or labeled by processCost, and the AI+// observability usage report sums $ai_total_cost_usd across every AI event type,+// so a cost on a span is counted a second time.+export const COSTED_AI_EVENT_TYPES = new Set(['$ai_generation', '$ai_embedding', '$ai_evaluation'])diff --git a/nodejs/src/ingestion/pipelines/ai/costs/index.ts b/nodejs/src/ingestion/pipelines/ai/costs/index.tsindex 806114d6f6c3..583d7811409d 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/index.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/index.ts@@ -175,6 +175,9 @@ const isString = (property: unknown): property is string => {return typeof property === 'string'}+// Ingestion can deliver the flag JSON-serialized, so the string "true" also counts as set.+const isCostPassthrough = (value: unknown): boolean => value === true || value === 'true'+/*** Process cost calculation for AI generation/embedding events.* Calculates input, output, request, and web search costs based on model pricing.@@ -214,6 +217,20 @@ export const processCost = (event: EventWithProperties): EventWithProperties =>return event}+ // $ai_cost_passthrough keeps a caller-reported total and skips estimation.+ // Require a usable total, so an empty cost is never labeled passthrough.+ // Zero is a usable total here because a gateway that charges nothing, such as+ // under BYOK, reports zero. The branch above instead reads a zero input or+ // output cost as absent.+ if (isCostPassthrough(event.properties['$ai_cost_passthrough'])) {+ const total = event.properties['$ai_total_cost_usd']+ if (typeof total === 'number') {+ event.properties['$ai_cost_model_source'] = CostModelSource.Passthrough+ trackCostOutcome(total)+ return event+ }+ }+// A non-numeric price throws inside js-big-decimal, so treat one as absent and// fall back to model pricing rather than billing at a rate of zero.const inputTokenPrice = finiteNumberOrUndefined(event.properties['$ai_input_token_price'])diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.tsindex 5b16e909dd2b..aa4de524f128 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.test.ts@@ -137,6 +137,62 @@ describe('vercel-ai middleware', () => {expect(event.properties!['$ai_stop_reason']).toBe('stop')})+ it('maps the Vercel AI Gateway reported cost to $ai_total_cost_usd', () => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ 'gen_ai.response.model': 'gpt-4o-mini',+ 'gen_ai.usage.input_tokens': 23,+ 'gen_ai.usage.output_tokens': 14,+ 'ai.response.providerMetadata': JSON.stringify({ gateway: { cost: '0.001234' } }),+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_total_cost_usd']).toBe(0.001234)+ expect(event.properties!['$ai_cost_passthrough']).toBe(true)+ expect(event.properties!['ai.response.providerMetadata']).toBeUndefined()+ })++ it('does not override a total cost the caller already set', () => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ $ai_total_cost_usd: 0.5,+ 'ai.response.providerMetadata': JSON.stringify({ gateway: { cost: '0.001234' } }),+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_total_cost_usd']).toBe(0.5)+ expect(event.properties!['$ai_cost_passthrough']).toBeUndefined()+ })++ // The AI SDK records the same providerMetadata on the parent ai.generateText span.+ it('leaves the gateway cost off the parent span', () => {+ const event = createEvent('$ai_span', {+ 'ai.operationId': 'ai.generateText',+ $ai_parent_id: 'parent-1',+ 'ai.response.providerMetadata': JSON.stringify({ gateway: { cost: '0.001234' } }),+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_total_cost_usd']).toBeUndefined()+ expect(event.properties!['$ai_cost_passthrough']).toBeUndefined()+ })++ it.each([+ ['no gateway cost', JSON.stringify({ gateway: { generationId: 'gen-1' } })],+ ['non-numeric cost', JSON.stringify({ gateway: { cost: 'free' } })],+ ['no gateway metadata', '{}'],+ ['malformed json', 'not json'],+ ])('leaves cost unset when providerMetadata has %s', (_label, providerMetadata) => {+ const event = createEvent('$ai_generation', {+ 'ai.operationId': 'ai.generateText.doGenerate',+ 'ai.response.providerMetadata': providerMetadata,+ })+ convertOtelEvent(event)++ expect(event.properties!['$ai_total_cost_usd']).toBeUndefined()+ expect(event.properties!['$ai_cost_passthrough']).toBeUndefined()+ })+it('ignores empty functionId telemetry', () => {const event = createEvent('$ai_generation', {'ai.operationId': 'ai.generateText.doGenerate',diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.tsindex 79af8a6957bb..e97d0bce3f78 100644--- a/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/vercel-ai.ts@@ -1,4 +1,6 @@import { parseJSON } from '~/common/utils/json-parse'+import { COSTED_AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'+import { finiteNumberOrUndefined } from '~/ingestion/pipelines/ai/costs/cost-utils'import { mustAddReasoningCost } from '~/ingestion/pipelines/ai/costs/output-costs'import { PluginEvent } from '~/plugin-scaffold'@@ -143,6 +145,29 @@ function promptToMessages(prompt: unknown): unknown[] | null {return null}+// Vercel AI Gateway reports the real charged cost at+// providerMetadata.gateway.cost, which the token-based estimate cannot match+// under BYOK rates, discounts, or per-request fallback. The OTel attribute+// arrives as a JSON string, but accept a parsed object too.+function extractGatewayCost(providerMetadata: unknown): number | undefined {+ let parsed = providerMetadata+ if (typeof parsed === 'string') {+ try {+ parsed = parseJSON(parsed)+ } catch {+ return undefined+ }+ }+ if (parsed === null || typeof parsed !== 'object') {+ return undefined+ }+ const gateway = (parsed as Record<string, unknown>).gateway+ if (gateway === null || typeof gateway !== 'object') {+ return undefined+ }+ return finiteNumberOrUndefined((gateway as Record<string, unknown>).cost)+}+function numericValue(value: unknown): number | null {if (typeof value === 'number' && Number.isFinite(value)) {return value@@ -354,6 +379,18 @@ function process(event: PluginEvent, next: () => void): void {delete props['ai.response.finishReason']delete props['gen_ai.response.finish_reasons']+ // The gateway reports only a total with no input/output split, so flag+ // passthrough to stop the pipeline estimating one. The AI SDK records the same+ // providerMetadata on the parent ai.generateText and ai.streamText spans, which+ // are not costed events, so the gate keeps the cost on the generation.+ if (COSTED_AI_EVENT_TYPES.has(event.event) && props['$ai_total_cost_usd'] === undefined) {+ const gatewayCost = extractGatewayCost(props['ai.response.providerMetadata'])+ if (gatewayCost !== undefined) {+ props['$ai_total_cost_usd'] = gatewayCost+ props['$ai_cost_passthrough'] = true+ }+ }+if (eveSpan) {const eveSessionId = props['eve.session.id']if (props['$ai_session_id'] === undefined && isNonEmptyString(eveSessionId)) {diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.tsindex 543c3523e60a..34568b29e4ba 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts@@ -301,6 +301,28 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_tool_call_count).toBe(2)})+ // The middleware writes $ai_cost_passthrough and processCost reads it. Both+ // halves have their own tests, so only a test through the whole pipeline+ // catches the two sides drifting apart.+ it('keeps the Vercel AI Gateway reported cost end to end', () => {+ event.properties = {+ $ai_ingestion_source: 'otel',+ 'ai.operationId': 'ai.generateText.doGenerate',+ 'gen_ai.provider.name': 'gateway',+ 'gen_ai.response.model': 'openai/gpt-4o-mini',+ 'gen_ai.usage.input_tokens': 100,+ 'gen_ai.usage.output_tokens': 50,+ 'ai.response.providerMetadata': JSON.stringify({ gateway: { cost: '0.001234' } }),+ }++ const result = processAiEvent(event)++ expect(result.properties!.$ai_total_cost_usd).toBe(0.001234)+ expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)+ expect(result.properties!.$ai_input_cost_usd).toBeUndefined()+ expect(result.properties!.$ai_output_cost_usd).toBeUndefined()+ })+it('uses total output tokens for non-Gemini AI SDK v7 reasoning models', () => {event.properties = {$ai_ingestion_source: 'otel',@@ -852,6 +874,11 @@ describe('processAiEvent()', () => {const result = processAiEvent(event)expect(result.properties!.$ai_total_cost_usd).toBe(0.5)+ // Without the passthrough flag, a supplied total does not skip the+ // estimate: the input/output split is still computed from the model.+ expect(result.properties!.$ai_input_cost_usd).toBe(20)+ expect(result.properties!.$ai_output_cost_usd).toBe(10)+ expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)})it('preserves user-provided request_cost when model-based calculation happens', () => {@@ -905,6 +932,37 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)})+ it.each([true, 'true'])('passes the total through when $ai_cost_passthrough is %p', (flag) => {+ event.properties!.$ai_cost_passthrough = flag+ event.properties!.$ai_total_cost_usd = 0.000372++ const result = processAiEvent(event)++ expect(result.properties!.$ai_total_cost_usd).toBe(0.000372)+ expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)+ expect(result.properties!.$ai_input_cost_usd).toBeUndefined()+ expect(result.properties!.$ai_output_cost_usd).toBeUndefined()+ })++ it('ignores $ai_cost_passthrough when no usable total is present', () => {+ event.properties!.$ai_cost_passthrough = true++ const result = processAiEvent(event)++ expect(result.properties!.$ai_total_cost_usd).toBe(30)+ expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)+ })++ // "false" must read as off, not as a truthy string.+ it('treats a non-truthy $ai_cost_passthrough as off', () => {+ event.properties!.$ai_cost_passthrough = 'false'++ const result = processAiEvent(event)++ expect(result.properties!.$ai_input_cost_usd).toBe(20)+ expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)+ })+// A usable cost has to come out as the parsed number, not the original string,// since these properties are read as floats downstream.it('parses pre-calculated costs supplied as numeric strings', () => {diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.tsindex 1bc84aca4261..a46cec21bb12 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts@@ -8,7 +8,7 @@* - Model parameter extraction (for generation/embedding/evaluation events)*/import { logger } from '~/common/utils/logger'-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'+import { AI_EVENT_TYPES, COSTED_AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { PluginEvent } from '~/plugin-scaffold'import { convertRawEvent } from './convert-raw-event'@@ -47,13 +47,7 @@ export const processAiEvent = (event: PluginEvent): PluginEvent | EventWithPrope// Normalize error messages for all AI events with errors.const withErrorNormalization = processAiErrorNormalization(normalized)- // Only generation/embedding/evaluation events get cost processing and model param extraction.- const isCosted =- withErrorNormalization.event === '$ai_generation' ||- withErrorNormalization.event === '$ai_embedding' ||- withErrorNormalization.event === '$ai_evaluation'-- if (!isCosted) {+ if (!COSTED_AI_EVENT_TYPES.has(withErrorNormalization.event)) {return withErrorNormalization}diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 2e7804550fb3..b0c82972161e 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2342,6 +2342,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "Where the cost data for this model was sourced from.","examples": ["openrouter", "manual", "custom", "passthrough"],},+ "$ai_cost_passthrough": {+ "label": "AI cost passthrough (LLM)",+ "description": "Set this to keep the reported total cost and skip PostHog's token-based estimate. Use it when the provider reports an authoritative cost, such as an LLM gateway. The input and output cost split is left unset.",+ "examples": [True],+ },"$ai_cost_model_provider": {"label": "AI cost model provider (LLM)","description": "The provider used to look up the cost for this model.",