Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(model-runtime): price token-range lookup cards from usage (#22079)

YuTengjing48f063b8ae3a
diff --git a/packages/model-bank/src/aiModels/hunyuan.ts b/packages/model-bank/src/aiModels/hunyuan.ts
index 719bfbff0af..fb726e3b84b 100644
--- a/packages/model-bank/src/aiModels/hunyuan.ts
+++ b/packages/model-bank/src/aiModels/hunyuan.ts
@@ -84,7 +84,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0.016, 0.032]': 1.6,
'[0.032, infinity]': 2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -97,7 +97,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0.016, 0.032]': 6.4,
'[0.032, infinity]': 8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -135,7 +135,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 3.975,
'[0.032, infinity]': 5.3,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -147,7 +147,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 15.9,
'[0.032, infinity]': 21.2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -184,7 +184,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 3.18,
'[0.032, infinity]': 4.505,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -196,7 +196,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 7.95,
'[0.032, infinity]': 11.13,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -263,7 +263,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, infinity]': 8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -275,7 +275,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, infinity]': 28,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -324,7 +324,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 5,
'[0.032, infinity]': 7,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -336,7 +336,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 22,
'[0.032, infinity]': 26,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -384,7 +384,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 4,
'[0.032, infinity]': 6,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -396,7 +396,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 18,
'[0.032, infinity]': 22,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -447,7 +447,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 5,
'[0.032, infinity]': 7,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -459,7 +459,7 @@ const hunyuanChatModels: AIChatModelCard[] = [
'[0, 0.032]': 22,
'[0.032, infinity]': 26,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
diff --git a/packages/model-bank/src/aiModels/siliconcloud.ts b/packages/model-bank/src/aiModels/siliconcloud.ts
index c72c1bffb74..1623e8484d2 100644
--- a/packages/model-bank/src/aiModels/siliconcloud.ts
+++ b/packages/model-bank/src/aiModels/siliconcloud.ts
@@ -272,7 +272,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 0.8,
'[0.128, infinity]': 2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -284,7 +284,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 4.8,
'[0.128, infinity]': 12,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -321,7 +321,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 0.8,
'[0.128, infinity]': 2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -333,7 +333,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 6.4,
'[0.128, infinity]': 16,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -370,7 +370,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 0.4,
'[0.128, infinity]': 1.6,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -382,7 +382,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 3.2,
'[0.128, infinity]': 12.8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -419,7 +419,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 0.6,
'[0.128, infinity]': 1.8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -431,7 +431,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 4.8,
'[0.128, infinity]': 14.4,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -468,7 +468,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 0.5,
'[0.128, infinity]': 1.5,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -480,7 +480,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.128]': 4,
'[0.128, infinity]': 12,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -591,7 +591,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 1.3,
'[0.032, infinity]': 2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput_cacheRead',
strategy: 'lookup',
@@ -603,7 +603,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, infinity]': 8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -615,7 +615,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, infinity]': 28,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -650,7 +650,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 1.3,
'[0.032, infinity]': 2,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput_cacheRead',
strategy: 'lookup',
@@ -662,7 +662,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, infinity]': 8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -674,7 +674,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, infinity]': 28,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
diff --git a/packages/model-bank/src/aiModels/streamlake.ts b/packages/model-bank/src/aiModels/streamlake.ts
index d9d71e70141..c6671773c3d 100644
--- a/packages/model-bank/src/aiModels/streamlake.ts
+++ b/packages/model-bank/src/aiModels/streamlake.ts
@@ -112,7 +112,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 1.2,
'[0.032, infinity]': 1.8,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput_cacheRead',
strategy: 'lookup',
@@ -124,7 +124,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 5,
'[0.032, infinity]': 7,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -136,7 +136,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 22,
'[0.032, infinity]': 26,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -172,7 +172,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 1,
'[0.032, infinity]': 1.5,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput_cacheRead',
strategy: 'lookup',
@@ -184,7 +184,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 4,
'[0.032, infinity]': 6,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -196,7 +196,7 @@ const streamlakeModels: AIChatModelCard[] = [
'[0, 0.032]': 18,
'[0.032, infinity]': 22,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
diff --git a/packages/model-bank/src/aiModels/wenxin.ts b/packages/model-bank/src/aiModels/wenxin.ts
index be09e7cc475..cd23b66ac52 100644
--- a/packages/model-bank/src/aiModels/wenxin.ts
+++ b/packages/model-bank/src/aiModels/wenxin.ts
@@ -27,7 +27,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 4,
'[0.032, 0.128]': 6,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -39,7 +39,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 18,
'[0.032, 0.128]': 22,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -79,7 +79,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, 0.128]': 10,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -91,7 +91,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, 0.128]': 40,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -130,7 +130,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, 0.128]': 10,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -142,7 +142,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, 0.128]': 40,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -181,7 +181,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, 0.128]': 10,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -193,7 +193,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 24,
'[0.032, 0.128]': 40,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
@@ -762,7 +762,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 2,
'[0.032, 0.064]': 4,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textInput',
strategy: 'lookup',
@@ -774,7 +774,7 @@ const wenxinChatModels: AIChatModelCard[] = [
'[0, 0.032]': 6,
'[0.032, 0.064]': 12,
},
- pricingParams: ['textInput'],
+ pricingParams: ['textInputRange'],
},
name: 'textOutput',
strategy: 'lookup',
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tokenRangeLookup.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tokenRangeLookup.test.ts
new file mode 100644
index 00000000000..795d44f7a9c
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tokenRangeLookup.test.ts
@@ -0,0 +1,152 @@
+import type { ModelTokensUsage } from '@lobechat/types';
+import type { AIChatModelCard, LookupPricingUnit } from 'model-bank';
+import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+import qwenChatModels from 'model-bank/qwen';
+import volcengineChatModels from 'model-bank/volcengine';
+import { describe, expect, it } from 'vitest';
+
+import { computeChatCost } from './computeChatCost';
+
+const creditsOf = (result: ReturnType<typeof computeChatCost>, unitName: string) =>
+ result?.breakdown.find((item) => item.unit.name === unitName);
+
+const qwenPlusPricing = qwenChatModels.find((model) => model.id === 'qwen-plus')?.pricing;
+
+describe('computeChatCost token-range lookups', () => {
+ it('prices qwen-plus input and output from the request token counts', () => {
+ const usage: ModelTokensUsage = {
+ inputTextTokens: 1_000_000,
+ outputTextTokens: 1_000_000,
+ totalInputTokens: 1_000_000,
+ totalOutputTokens: 1_000_000,
+ };
+
+ const result = computeChatCost(qwenPlusPricing, usage);
+
+ expect(result?.issues).toEqual([]);
+ // Above 256K input tokens, non-thinking: input $1.2/M, output $3.6/M.
+ expect(creditsOf(result, 'textInput')).toMatchObject({
+ credits: 1_200_000,
+ lookupKey: '[0.256, infinity]',
+ });
+ expect(creditsOf(result, 'textOutput')).toMatchObject({
+ credits: 3_600_000,
+ lookupKey: '[0.256, infinity]_[false]',
+ });
+ expect(result?.totalCost).toBeCloseTo(4.8);
+ });
+
+ it('uses the lower range up to and including its upper bound', () => {
+ const usage: ModelTokensUsage = {
+ inputTextTokens: 256_000,
+ outputTextTokens: 1000,
+ totalInputTokens: 256_000,
+ totalOutputTokens: 1000,
+ };
+
+ const result = computeChatCost(qwenPlusPricing, usage);
+
+ expect(creditsOf(result, 'textInput')?.lookupKey).toBe('[0, 0.256]');
+ expect(creditsOf(result, 'textOutput')?.lookupKey).toBe('[0, 0.256]_[false]');
+ });
+
+ it('selects the input range from total prompt tokens, including cache reads', () => {
+ const usage: ModelTokensUsage = {
+ inputCacheMissTokens: 100_000,
+ inputCachedTokens: 200_000,
+ outputTextTokens: 1000,
+ totalInputTokens: 300_000,
+ totalOutputTokens: 1000,
+ };
+
+ const result = computeChatCost(qwenPlusPricing, usage);
+
+ expect(result?.issues).toEqual([]);
+ expect(creditsOf(result, 'textInput')).toMatchObject({
+ credits: 120_000,
+ lookupKey: '[0.256, infinity]',
+ });
+ expect(creditsOf(result, 'textInput_cacheRead')?.lookupKey).toBe('[0.256, infinity]');
+ });
+
+ it('infers thinking mode from reasoning tokens when the caller does not pass it', () => {
+ const usage: ModelTokensUsage = {
+ outputReasoningTokens: 600_000,
+ outputTextTokens: 400_000,
+ totalInputTokens: 1000,
+ totalOutputTokens: 1_000_000,
+ };
+
+ const result = computeChatCost(qwenPlusPricing, usage);
+
+ expect(creditsOf(result, 'textOutput')).toMatchObject({
+ credits: 4_000_000,
+ lookupKey: '[0, 0.256]_[true]',
+ });
+ });
+
+ it('honors an explicit thinkingMode lookup param over the inferred one', () => {
+ const usage: ModelTokensUsage = {
+ outputTextTokens: 1_000_000,
+ totalInputTokens: 1000,
+ totalOutputTokens: 1_000_000,
+ };
+
+ const result = computeChatCost(qwenPlusPricing, usage, {
+ lookupParams: { thinkingMode: true },
+ });
+
+ expect(creditsOf(result, 'textOutput')?.lookupKey).toBe('[0, 0.256]_[true]');
+ });
+
+ it('resolves two-dimensional input/output ranges', () => {
+ const pricing = volcengineChatModels.find((model) => model.id === 'glm-4-7')?.pricing;
+ const shortReply: ModelTokensUsage = {
+ outputTextTokens: 100,
+ totalInputTokens: 10_000,
+ totalOutputTokens: 100,
+ };
+ const longReply: ModelTokensUsage = {
+ ...shortReply,
+ outputTextTokens: 300,
+ totalOutputTokens: 300,
+ };
+
+ expect(creditsOf(computeChatCost(pricing, shortReply), 'textInput')?.lookupKey).toBe(
+ '[0, 0.032]_[0, 0.0002]',
+ );
+ expect(creditsOf(computeChatCost(pricing, longReply), 'textInput')?.lookupKey).toBe(
+ '[0, 0.032]_[0.0002, infinity]',
+ );
+ });
+
+ // Every chat lookup param other than the caller-supplied `ttl` must be resolvable from usage,
+ // so a card using an unknown param name fails here instead of silently pricing at $0.
+ it('prices every model-bank chat lookup unit keyed on usage', () => {
+ const usage: ModelTokensUsage = {
+ inputCacheMissTokens: 10_000,
+ inputCachedTokens: 10_000,
+ outputTextTokens: 1000,
+ totalInputTokens: 20_000,
+ totalOutputTokens: 1000,
+ };
+
+ const failures = (LOBE_DEFAULT_MODEL_LIST as AIChatModelCard[])
+ .filter((model) => model.type === 'chat')
+ .flatMap((model) => {
+ const units = (model.pricing?.units ?? []).filter(
+ (unit): unit is LookupPricingUnit =>
+ unit.strategy === 'lookup' &&
+ unit.lookup.pricingParams.some((param) => param !== 'ttl'),
+ );
+ if (units.length === 0) return [];
+
+ const result = computeChatCost(model.pricing, usage);
+ return (result?.issues ?? [])
+ .filter((issue) => units.includes(issue.unit as LookupPricingUnit))
+ .map((issue) => `${model.providerId}/${model.id} ${issue.unit.name}: ${issue.reason}`);
+ });
+
+ expect(failures).toEqual([]);
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
index 548986318e2..b8c58c29348 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
@@ -132,6 +132,26 @@ const resolveTextPricedAudioTokens = (
context.hasDedicatedAudioInputUnit ? undefined : resolveInputAudioTokens(usage),
);
+// reasoning tokens cost within output tokens
+const resolveOutputTokens = (usage: ModelTokensUsage) => {
+ const { outputTextTokens, totalOutputTokens, outputReasoningTokens = 0 } = usage;
+ const reasoningTokens = outputReasoningTokens;
+
+ if (typeof outputTextTokens === 'number') {
+ return outputTextTokens + reasoningTokens;
+ }
+
+ if (typeof totalOutputTokens === 'number') {
+ return totalOutputTokens;
+ }
+
+ if (typeof usage.outputReasoningTokens === 'number') {
+ return usage.outputReasoningTokens;
+ }
+
+ return undefined;
+};
+
const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResolver>> = {
textInput: (usage, context) => {
const toolTokens = usage.inputToolTokens ?? 0;
@@ -210,25 +230,7 @@ const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResol
return usage.inputCachedTokens;
},
textInput_cacheWrite: (usage) => usage.inputWriteCacheTokens,
- // reasoning tokens cost within output tokens
- textOutput: (usage) => {
- const { outputTextTokens, totalOutputTokens, outputReasoningTokens = 0 } = usage;
- const reasoningTokens = outputReasoningTokens;
-
- if (typeof outputTextTokens === 'number') {
- return outputTextTokens + reasoningTokens;
- }
-
- if (typeof totalOutputTokens === 'number') {
- return totalOutputTokens;
- }
-
- if (typeof usage.outputReasoningTokens === 'number') {
- return usage.outputReasoningTokens;
- }
-
- return undefined;
- },
+ textOutput: resolveOutputTokens,
imageInput: resolveInputImageTokens,
imageInput_cacheRead: (usage) => usage.inputCachedImageTokens,
@@ -305,39 +307,100 @@ const computeTieredCredits = (
return { credits, segments };
};
+/**
+ * Lookup params a chat card can key on the request's own usage. Callers never pass these:
+ * the ranges are in million tokens (e.g. `[0.032, 0.128]`) and the thinking flag is
+ * `[true]`/`[false]`, so they are resolved here from the reported token counts.
+ */
+const resolveUsageLookupParam = (
+ param: string,
+ usage: ModelTokensUsage,
+): number | boolean | undefined => {
+ switch (param) {
+ // Providers such as Qwen pick the input tier from the whole prompt, cached part included.
+ case 'textInputRange': {
+ return usage.totalInputTokens ?? usage.inputTextTokens;
+ }
+ case 'textOutputRange': {
+ return resolveOutputTokens(usage);
+ }
+ // Thinking output is only billed at the thinking rate when the model actually reasoned.
+ case 'thinkingMode': {
+ return (usage.outputReasoningTokens ?? 0) > 0;
+ }
+ }
+};
+
+const RANGE_SEGMENT = /^\[\s*([\d.]+)\s*,\s*([\d.]+|infinity)\s*\]$/;
+const LITERAL_SEGMENT = /^\[([^,]*)\]$/;
+
+/**
+ * Matches one `_`-separated lookup key segment against a param value.
+ * Ranges are left-open and right-closed (`(lo, hi]`, with 0 included), matching vendor
+ * wording such as "32K < tokens ≤ 128K".
+ */
+const matchesKeySegment = (segment: string, value: string | number | boolean) => {
+ const range = RANGE_SEGMENT.exec(segment);
+ if (range) {
+ if (typeof value !== 'number') return false;
+ const millions = value / 1_000_000;
+ const lower = Number(range[1]);
+ const upper = range[2] === 'infinity' ? Number.POSITIVE_INFINITY : Number(range[2]);
+
+ return (millions > lower || (lower === 0 && millions === 0)) && millions <= upper;
+ }
+
+ const literal = LITERAL_SEGMENT.exec(segment);
+ if (literal) return literal[1] === String(value);
+
+ return segment === String(value);
+};
+
const resolveLookupKey = (
unit: LookupPricingUnit,
+ usage: ModelTokensUsage,
options: ComputeChatCostOptions | undefined,
): { key?: string; missingParams?: string[] } => {
if (!unit.lookup?.pricingParams?.length) return { key: undefined };
const missingParams: string[] = [];
- const params = unit.lookup.pricingParams.map((param) => {
+ const values = unit.lookup.pricingParams.map((param) => {
// Paths that never resolve a TTL (e.g. OpenAI-compatible providers falling back to an
// Anthropic card) still write to the cache, which the API does for its default 5 minutes.
const source =
options?.lookupParams?.[param] ??
- (param === 'ttl' && DEFAULT_CACHE_TTL in unit.lookup.prices ? DEFAULT_CACHE_TTL : undefined);
- if (source === undefined || source === null) {
- missingParams.push(param);
- return 'undefined';
- }
+ (param === 'ttl' && DEFAULT_CACHE_TTL in unit.lookup.prices
+ ? DEFAULT_CACHE_TTL
+ : resolveUsageLookupParam(param, usage));
+ if (source === undefined || source === null) missingParams.push(param);
- if (typeof source === 'boolean') return String(source);
- return String(source);
+ return source;
});
if (missingParams.length > 0) return { key: undefined, missingParams };
- return { key: params.join('_') };
+ const resolvedValues = values as Array<string | number | boolean>;
+ const exactKey = resolvedValues.map(String).join('_');
+ if (exactKey in unit.lookup.prices) return { key: exactKey };
+
+ const matchedKey = Object.keys(unit.lookup.prices).find((key) => {
+ const segments = key.split('_');
+ return (
+ segments.length === resolvedValues.length &&
+ segments.every((segment, index) => matchesKeySegment(segment, resolvedValues[index]))
+ );
+ });
+
+ return { key: matchedKey ?? exactKey };
};
const computeLookupCredits = (
unit: LookupPricingUnit,
quantity: number,
+ usage: ModelTokensUsage,
options: ComputeChatCostOptions | undefined,
): { credits: number; issues?: PricingComputationIssue; key?: string } => {
- const { key, missingParams } = resolveLookupKey(unit, options);
+ const { key, missingParams } = resolveLookupKey(unit, usage, options);
if (missingParams && missingParams.length > 0) {
return {
@@ -482,7 +545,7 @@ export const computeChatCost = (
credits: rawCredits,
key,
issues: lookupIssue,
- } = computeLookupCredits(lookupUnit, quantity, options);
+ } = computeLookupCredits(lookupUnit, quantity, usage, options);
if (lookupIssue) issues.push(lookupIssue);