: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): price ai generations by their served service tier (#94200)
Bernat Torres476104d76a65
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.test.tsindex 97cd30eb0bfd..e298efe14d41 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.test.ts@@ -18,6 +18,26 @@ jest.mock('./providers', () => {openai: { prompt_token: 0.00000015, completion_token: 0.0000006 },},},+ // Mirrors the synced book's real gemini-3-flash-preview row: priority is a literal+ // "-priority" key, not "-fast" as on openai.+ 'google/gemini-3-flash-preview': {+ model: 'google/gemini-3-flash-preview',+ cost: {+ default: { prompt_token: 0.0000005, completion_token: 0.000003 },+ 'google-ai-studio': { prompt_token: 0.0000005, completion_token: 0.000003 },+ 'google-ai-studio-priority': { prompt_token: 0.0000009, completion_token: 0.0000054 },+ },+ },+ // Mirrors the synced book's real gpt-5-mini row.+ 'openai/gpt-5-mini': {+ model: 'openai/gpt-5-mini',+ cost: {+ default: { prompt_token: 0.0000003, completion_token: 0.0000024 },+ openai: { prompt_token: 0.00000025, completion_token: 0.000002, web_search: 0.01 },+ 'openai-flex': { prompt_token: 0.000000125, completion_token: 0.000001, web_search: 0.01 },+ 'openai-fast': { prompt_token: 0.0000005, completion_token: 0.000004 },+ },+ },'anthropic/claude-3.5-sonnet': {model: 'anthropic/claude-3.5-sonnet',cost: {@@ -139,6 +159,69 @@ jest.mock('./providers', () => {}})+describe('service tier pricing', () => {+ it('prices a served flex tier from the openai-flex row', () => {+ const result = findCostFromModel('gpt-5-mini', { $ai_provider: 'openai', $ai_service_tier: 'flex' })+ // Silently pricing flex at standard rates overstates every flex call 2x.+ expect(result?.cost.provider).toBe('openai-flex')+ expect(result?.cost.cost.prompt_token).toBe(0.000000125)+ expect(result?.cost.cost.web_search).toBe(0.01)+ })++ it('prices a served priority tier from the openai-fast row', () => {+ const result = findCostFromModel('gpt-5-mini', { $ai_provider: 'openai', $ai_service_tier: 'priority' })+ // Priority is a 2x surcharge; pricing it standard underreports every token cost by half.+ expect(result?.cost.provider).toBe('openai-fast')+ expect(result?.cost.cost.prompt_token).toBe(0.0000005)+ })++ it('prices a served priority tier from the provider-literal key when the book names it so', () => {+ const result = findCostFromModel('gemini-3-flash-preview', {+ $ai_provider: 'gemini',+ $ai_service_tier: 'priority',+ })+ // Tier-key naming is per-provider; probing only "-fast" here fell back to the+ // standard row and underreported by 44%.+ expect(result?.cost.provider).toBe('google-ai-studio-priority')+ expect(result?.cost.cost.prompt_token).toBe(0.0000009)+ })++ it('falls back to the standard row, not default, when the tier key is missing', () => {+ const result = findCostFromModel('gpt-4', { $ai_provider: 'openai', $ai_service_tier: 'flex' })+ // The default key can carry promotional pricing, so a missing tier key must not reach it.+ expect(result?.cost.provider).toBe('openai')+ expect(result?.cost.cost.prompt_token).toBe(0.00003)+ })++ it.each(['auto', 'default', undefined, '__proto__', 'constructor'])('prices tier %p at standard rates', (tier) => {+ const result = findCostFromModel('gpt-5-mini', { $ai_provider: 'openai', $ai_service_tier: tier })+ expect(result?.cost.provider).toBe('openai')+ expect(result?.cost.cost.prompt_token).toBe(0.00000025)+ })++ it('prices an error event by its explicit tier', () => {+ // $ai_service_tier writers assert served values on error events too: a flex stream+ // that dies mid-way was billed at flex for its partial tokens.+ const result = findCostFromModel('gpt-5-mini', {+ $ai_provider: 'openai',+ $ai_is_error: true,+ $ai_service_tier: 'flex',+ })+ expect(result?.cost.provider).toBe('openai-flex')+ })++ it('never prices from model parameters', () => {+ // Released SDKs wrote the requested tier there on successful events; a request can+ // be refused, so that key has no served-side provenance.+ const result = findCostFromModel('gpt-5-mini', {+ $ai_provider: 'openai',+ $ai_model_parameters: { service_tier: 'flex' },+ })+ expect(result?.cost.provider).toBe('openai')+ expect(result?.cost.cost.prompt_token).toBe(0.00000025)+ })+})+describe('findCostFromModel()', () => {describe('exact matching', () => {it('finds exact match in primary costs with provider', () => {diff --git a/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.ts b/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.tsindex 74ae60acc194..968e954642e6 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/cost-model-matching.ts@@ -71,10 +71,21 @@ const resolveBedrockInferenceProfileProvider = (return regionalProviders.length === 1 ? regionalProviders[0] : provider}-export const findCostFromModel = (model: string, properties: Properties): CostModelResult | undefined => {- const providerProperty: unknown = properties['$ai_provider']+const getAiProvider = (properties: Properties): string | undefined => {+ const provider: unknown = properties['$ai_provider']++ return provider ? String(provider).toLowerCase() : undefined+}- const provider: string | undefined = providerProperty ? String(providerProperty).toLowerCase() : undefined+// $ai_service_tier is the explicit served-tier signal: its writers (the ai-gateway, SDK+// versions that adopted it) assert the tier the provider reported serving, on success and+// error events alike. $ai_model_parameters.service_tier never prices: released SDKs wrote+// the requested tier there, and a request can be refused.+const getServedServiceTier = (properties: Properties): unknown => properties['$ai_service_tier']++export const findCostFromModel = (model: string, properties: Properties): CostModelResult | undefined => {+ const provider = getAiProvider(properties)+ const serviceTier = getServedServiceTier(properties)const manualMatch: ModelCostRow | undefined = findManualCost(model)@@ -82,7 +93,8 @@ export const findCostFromModel = (model: string, properties: Properties): CostMo? resolveModelCostForProvider(manualMatch.cost,resolveBedrockInferenceProfileProvider(model, manualMatch.cost, provider),- manualMatch.model+ manualMatch.model,+ serviceTier): undefined@@ -96,7 +108,8 @@ export const findCostFromModel = (model: string, properties: Properties): CostMo? resolveModelCostForProvider(openRouterMatch.cost,resolveBedrockInferenceProfileProvider(model, openRouterMatch.cost, provider),- openRouterMatch.model+ openRouterMatch.model,+ serviceTier): undefineddiff --git a/nodejs/src/ingestion/pipelines/ai/costs/provider-matching.ts b/nodejs/src/ingestion/pipelines/ai/costs/provider-matching.tsindex 7f013ad19405..2cf4872deb0b 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/provider-matching.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/provider-matching.ts@@ -111,15 +111,42 @@ export const resolveProviderAliases = (provider: string): string => {* @param model - The model name for the resolved cost* @returns The resolved model cost, or undefined if no valid cost is found*/+// Tier-key suffixes per served service tier, in probe order. Naming is per-provider:+// google-ai-studio-priority and xai-priority are literal, while openai-fast and+// anthropic-fast are those providers' names for their priority tier.+const SERVICE_TIER_KEY_SUFFIXES: Record<string, string[]> = {+ flex: ['-flex'],+ priority: ['-priority', '-fast'],+}+export const resolveModelCostForProvider = (providerCosts: ModelCostByProvider,provider: string | undefined,- model: string+ model: string,+ serviceTier?: unknown): ResolvedModelCost | undefined => {if (!providerCosts || Object.keys(providerCosts).length === 0) {return undefined}+ // A served tier resolves by its own provider key, as direct checks: the cascade below+ // falls back to the `default` key, which can carry promotional pricing.+ // Object.hasOwn: the tier is customer-controlled, and "__proto__"/"constructor" would+ // otherwise return inherited non-array values that throw below.+ const tierSuffixes =+ typeof serviceTier === 'string' && Object.hasOwn(SERVICE_TIER_KEY_SUFFIXES, serviceTier)+ ? SERVICE_TIER_KEY_SUFFIXES[serviceTier]+ : undefined+ if (provider && tierSuffixes) {+ const canonical = resolveProviderAliases(provider)+ for (const suffix of tierSuffixes) {+ const tierCost = providerCosts[canonical + suffix]+ if (tierCost) {+ return { model, provider: canonical + suffix, cost: tierCost }+ }+ }+ }+const findProviderMatch = (providerKey: string): ResolvedModelCost | undefined => {const cost: ModelCost | undefined = providerCosts[providerKey]