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(image): backfill lookup-pricing params from model card defaults before charging (#21191)

Arvin Xuf3f03952408f
diff --git a/apps/server/src/routers/lambda/image/index.ts b/apps/server/src/routers/lambda/image/index.ts
index 84077cedcc8..84839614e25 100644
--- a/apps/server/src/routers/lambda/image/index.ts
+++ b/apps/server/src/routers/lambda/image/index.ts
@@ -29,7 +29,7 @@ import {
} from '@/types/asyncTask';
import { generateUniqueSeeds } from '@/utils/number';
-import { validateNoUrlsInConfig } from './utils';
+import { applyLookupPricingParamDefaults, validateNoUrlsInConfig } from './utils';
const log = debug('lobe-image:lambda');
@@ -192,6 +192,16 @@ export const imageRouter = router({
// Defensive check: ensure no full URLs enter the database
validateNoUrlsInConfig(configForDatabase, 'configForDatabase');
+ // Backfill lookup-pricing params (e.g. quality/resolution) from model
+ // card defaults so omitted optional parameters don't break cost
+ // computation before charging. Use the resolved model ID so business
+ // aliases without their own model-bank card still resolve pricing.
+ generationParams = await applyLookupPricingParamDefaults(
+ generationParams,
+ resolvedModelId,
+ provider,
+ );
+
const generationTopic = await generationTopicModel.findById(generationTopicId);
if (!generationTopic) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Invalid generation topic' });
diff --git a/apps/server/src/routers/lambda/image/utils.test.ts b/apps/server/src/routers/lambda/image/utils.test.ts
index 566b92d5151..884b2ba6f84 100644
--- a/apps/server/src/routers/lambda/image/utils.test.ts
+++ b/apps/server/src/routers/lambda/image/utils.test.ts
@@ -1,118 +1,259 @@
-import { describe, expect, it } from 'vitest';
-
-import { validateNoUrlsInConfig } from './utils';
-
-describe('imageRouter', () => {
- describe('validateNoUrlsInConfig utility', () => {
- describe('valid configurations', () => {
- it('should pass with normal keys', () => {
- const config = {
- imageUrl: 'images/photo.jpg',
- imageUrls: ['files/doc.pdf', 'assets/video.mp4'],
- prompt: 'Generate an image',
- };
-
- expect(() => validateNoUrlsInConfig(config)).not.toThrow();
- });
-
- it('should pass with empty strings', () => {
- const config = {
- imageUrl: '',
- imageUrls: [],
- prompt: 'Generate an image',
- };
-
- expect(() => validateNoUrlsInConfig(config)).not.toThrow();
- });
-
- it('should pass with null/undefined values', () => {
- const config = {
- imageUrl: null,
- imageUrls: undefined,
- prompt: 'Generate an image',
- };
-
- expect(() => validateNoUrlsInConfig(config)).not.toThrow();
- });
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { applyLookupPricingParamDefaults, validateNoUrlsInConfig } from './utils';
+
+const getModelPricingMock = vi.hoisted(() => vi.fn());
+const getModelParametersMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobechat/model-runtime', () => ({
+ getModelPricing: getModelPricingMock,
+ getModelParameters: getModelParametersMock,
+}));
+
+const lookupPricing = {
+ units: [
+ {
+ lookup: {
+ prices: {
+ low_1k: 0.04,
+ low_2k: 0.06,
+ medium_1k: 0.06,
+ medium_2k: 0.08,
+ },
+ pricingParams: ['quality', 'resolution'],
+ },
+ name: 'imageGeneration',
+ strategy: 'lookup',
+ unit: 'image',
+ },
+ ],
+};
+
+const modelParameters = {
+ aspectRatio: { default: 'auto', enum: ['auto', '1:1'] },
+ quality: { default: 'medium', enum: ['low', 'medium'] },
+ resolution: { default: '1k', enum: ['1k', '2k'] },
+};
+
+describe('applyLookupPricingParamDefaults', () => {
+ beforeEach(() => {
+ getModelPricingMock.mockClear();
+ getModelParametersMock.mockClear();
+ });
+
+ it('fills missing lookup params from model card defaults', async () => {
+ getModelPricingMock.mockResolvedValue(lookupPricing);
+ getModelParametersMock.mockResolvedValue(modelParameters);
+
+ const result = await applyLookupPricingParamDefaults(
+ { prompt: 'a red apple', resolution: '2k' },
+ 'grok-imagine-image-2.0',
+ 'lobehub',
+ );
+
+ expect(result).toEqual({
+ prompt: 'a red apple',
+ quality: 'medium',
+ resolution: '2k',
});
+ });
- describe('invalid configurations', () => {
- it('should throw for https URL in imageUrl', () => {
- const config = {
- imageUrl: 'https://s3.amazonaws.com/bucket/image.jpg',
- prompt: 'Generate an image',
- };
-
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'Invalid configuration: Found full URL instead of key at imageUrl',
- );
- });
-
- it('should throw for http URL in imageUrls array', () => {
- const config = {
- imageUrls: ['files/doc.pdf', 'http://example.com/image.jpg'],
- prompt: 'Generate an image',
- };
-
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'Invalid configuration: Found full URL instead of key at imageUrls[1]',
- );
- });
-
- it('should throw for nested URL in complex object', () => {
- const config = {
- settings: {
- imageConfig: {
- url: 'https://cdn.example.com/very-long-url-that-exceeds-100-characters-to-test-truncation-functionality.jpg',
- },
+ it('keeps explicit client params and only fills the absent ones', async () => {
+ getModelPricingMock.mockResolvedValue(lookupPricing);
+ getModelParametersMock.mockResolvedValue(modelParameters);
+
+ const result = await applyLookupPricingParamDefaults(
+ { prompt: 'a red apple', quality: 'low', resolution: '1k' },
+ 'grok-imagine-image-2.0',
+ 'lobehub',
+ );
+
+ expect(result).toEqual({ prompt: 'a red apple', quality: 'low', resolution: '1k' });
+ });
+
+ it('returns params untouched when pricing has no imageGeneration lookup unit', async () => {
+ getModelPricingMock.mockResolvedValue({
+ units: [{ name: 'imageGeneration', rate: 0.02, strategy: 'fixed', unit: 'image' }],
+ });
+
+ const params = { prompt: 'a red apple' };
+ const result = await applyLookupPricingParamDefaults(params, 'grok-imagine-image', 'lobehub');
+
+ expect(result).toBe(params);
+ expect(getModelParametersMock).not.toHaveBeenCalled();
+ });
+
+ it('returns params untouched when pricing is missing', async () => {
+ getModelPricingMock.mockResolvedValue(undefined);
+
+ const params = { prompt: 'a red apple' };
+ const result = await applyLookupPricingParamDefaults(params, 'unknown-model', 'lobehub');
+
+ expect(result).toBe(params);
+ });
+
+ it('returns params untouched when pricing lookup fails', async () => {
+ getModelPricingMock.mockRejectedValue(new Error('model config unavailable'));
+
+ const params = { prompt: 'a red apple' };
+ const result = await applyLookupPricingParamDefaults(params, 'grok-imagine-image-2.0', 'lobehub');
+
+ expect(result).toBe(params);
+ });
+
+ it('returns params untouched when model card has no parameters', async () => {
+ getModelPricingMock.mockResolvedValue(lookupPricing);
+ getModelParametersMock.mockResolvedValue(undefined);
+
+ const params = { prompt: 'a red apple' };
+ const result = await applyLookupPricingParamDefaults(params, 'grok-imagine-image-2.0', 'lobehub');
+
+ expect(result).toBe(params);
+ });
+
+ it('skips model-card defaults that are null and leaves the param absent', async () => {
+ getModelPricingMock.mockResolvedValue(lookupPricing);
+ getModelParametersMock.mockResolvedValue({
+ quality: { default: 'medium' },
+ resolution: { default: null },
+ });
+
+ const result = await applyLookupPricingParamDefaults(
+ { prompt: 'a red apple' },
+ 'grok-imagine-image-2.0',
+ 'lobehub',
+ );
+
+ expect(result).toEqual({ prompt: 'a red apple', quality: 'medium' });
+ });
+
+ it('treats null lookup params as missing and backfills defaults', async () => {
+ getModelPricingMock.mockResolvedValue(lookupPricing);
+ getModelParametersMock.mockResolvedValue(modelParameters);
+
+ const result = await applyLookupPricingParamDefaults(
+ { prompt: 'a red apple', quality: null, resolution: null },
+ 'grok-imagine-image-2.0',
+ 'lobehub',
+ );
+
+ expect(result).toEqual({
+ prompt: 'a red apple',
+ quality: 'medium',
+ resolution: '1k',
+ });
+ });
+});
+
+describe('validateNoUrlsInConfig utility', () => {
+ describe('valid configurations', () => {
+ it('should pass with normal keys', () => {
+ const config = {
+ imageUrl: 'images/photo.jpg',
+ imageUrls: ['files/doc.pdf', 'assets/video.mp4'],
+ prompt: 'Generate an image',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).not.toThrow();
+ });
+
+ it('should pass with empty strings', () => {
+ const config = {
+ imageUrl: '',
+ imageUrls: [],
+ prompt: 'Generate an image',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).not.toThrow();
+ });
+
+ it('should pass with null/undefined values', () => {
+ const config = {
+ imageUrl: null,
+ imageUrls: undefined,
+ prompt: 'Generate an image',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).not.toThrow();
+ });
+ });
+
+ describe('invalid configurations', () => {
+ it('should throw for https URL in imageUrl', () => {
+ const config = {
+ imageUrl: 'https://s3.amazonaws.com/bucket/image.jpg',
+ prompt: 'Generate an image',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'Invalid configuration: Found full URL instead of key at imageUrl',
+ );
+ });
+
+ it('should throw for http URL in imageUrls array', () => {
+ const config = {
+ imageUrls: ['files/doc.pdf', 'http://example.com/image.jpg'],
+ prompt: 'Generate an image',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'Invalid configuration: Found full URL instead of key at imageUrls[1]',
+ );
+ });
+
+ it('should throw for nested URL in complex object', () => {
+ const config = {
+ settings: {
+ imageConfig: {
+ url: 'https://cdn.example.com/very-long-url-that-exceeds-100-characters-to-test-truncation-functionality.jpg',
},
- };
-
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'Invalid configuration: Found full URL instead of key at settings.imageConfig.url',
- );
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'https://cdn.example.com/very-long-url-that-exceeds-100-characters-to-test-truncation-func',
- );
- });
-
- it('should throw for presigned URL with query parameters', () => {
- const config = {
- imageUrl:
- 'https://s3.amazonaws.com/bucket/file.jpg?X-Amz-Signature=abc&X-Amz-Expires=3600',
- };
-
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'All URLs must be converted to storage keys before database insertion',
- );
- });
+ },
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'Invalid configuration: Found full URL instead of key at settings.imageConfig.url',
+ );
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'https://cdn.example.com/very-long-url-that-exceeds-100-characters-to-test-truncation-func',
+ );
+ });
+
+ it('should throw for presigned URL with query parameters', () => {
+ const config = {
+ imageUrl:
+ 'https://s3.amazonaws.com/bucket/file.jpg?X-Amz-Signature=abc&X-Amz-Expires=3600',
+ };
+
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'All URLs must be converted to storage keys before database insertion',
+ );
});
+ });
- describe('edge cases', () => {
- it('should handle deeply nested structures', () => {
- const config = {
- level1: {
- level2: {
- level3: {
- level4: ['normal-key', 'https://bad-url.com'],
- },
+ describe('edge cases', () => {
+ it('should handle deeply nested structures', () => {
+ const config = {
+ level1: {
+ level2: {
+ level3: {
+ level4: ['normal-key', 'https://bad-url.com'],
},
},
- };
+ },
+ };
- expect(() => validateNoUrlsInConfig(config)).toThrow(
- 'Invalid configuration: Found full URL instead of key at level1.level2.level3.level4[1]',
- );
- });
+ expect(() => validateNoUrlsInConfig(config)).toThrow(
+ 'Invalid configuration: Found full URL instead of key at level1.level2.level3.level4[1]',
+ );
+ });
- it('should not throw for strings that contain but do not start with http', () => {
- const config = {
- imageUrl: 'some-prefix-https://example.com',
- description: 'This text contains http:// but is not a URL',
- };
+ it('should not throw for strings that contain but do not start with http', () => {
+ const config = {
+ imageUrl: 'some-prefix-https://example.com',
+ description: 'This text contains http:// but is not a URL',
+ };
- expect(() => validateNoUrlsInConfig(config)).not.toThrow();
- });
+ expect(() => validateNoUrlsInConfig(config)).not.toThrow();
});
});
});
diff --git a/apps/server/src/routers/lambda/image/utils.ts b/apps/server/src/routers/lambda/image/utils.ts
index 653d36f1209..b4ba6763828 100644
--- a/apps/server/src/routers/lambda/image/utils.ts
+++ b/apps/server/src/routers/lambda/image/utils.ts
@@ -1,3 +1,68 @@
+import { getModelParameters, getModelPricing } from '@lobechat/model-runtime';
+
+/**
+ * Fill model-card parameter defaults into `generationParams` for parameters
+ * required by lookup-based image pricing.
+ *
+ * Lookup pricing (e.g. `grok-imagine-image-2.0` priced by
+ * `pricingParams: ['quality', 'resolution']`) requires every lookup param to
+ * be present, otherwise `computeImageCost` returns `undefined` and the whole
+ * request is rejected with `Unable to compute cost for model`. Client callers
+ * may omit optional parameters, so before charging we backfill each missing
+ * lookup param from the model card's parameter defaults — the same values the
+ * upstream provider would apply anyway (xAI defaults to `medium`/`1k`).
+ *
+ * Non-lookup pricing and fully-absent model cards return the params untouched.
+ *
+ * Generic over the params object so required fields (e.g. `prompt`) survive
+ * the round trip for callers; `null` lookup values are treated as missing,
+ * matching `computeImageCost` which rejects both `null` and `undefined`.
+ */
+export const applyLookupPricingParamDefaults = async <T extends Record<string, unknown>>(
+ generationParams: T,
+ model: string,
+ provider: string,
+): Promise<T> => {
+ let pricingParams: string[] | undefined;
+
+ try {
+ const pricing = await getModelPricing(model, provider);
+ const lookupUnit = pricing?.units.find(
+ (unit) => unit.name === 'imageGeneration' && unit.strategy === 'lookup',
+ );
+ pricingParams =
+ lookupUnit && lookupUnit.strategy === 'lookup'
+ ? lookupUnit.lookup?.pricingParams
+ : undefined;
+ } catch {
+ // Pricing resolution is best-effort here: CostService will report a
+ // precise error afterwards if the pricing really is unusable.
+ return generationParams;
+ }
+
+ if (!pricingParams || pricingParams.length === 0) return generationParams;
+
+ const missingParams = pricingParams.filter(
+ (param) => generationParams[param] === undefined || generationParams[param] === null,
+ );
+ if (missingParams.length === 0) return generationParams;
+
+ const parameters = (await getModelParameters(model, provider)) as
+ | Record<string, { default?: unknown } | undefined>
+ | undefined;
+ if (!parameters) return generationParams;
+
+ const updates: Record<string, unknown> = {};
+ for (const param of missingParams) {
+ const fallback = parameters[param]?.default;
+ if (fallback !== undefined && fallback !== null) {
+ updates[param] = fallback;
+ }
+ }
+
+ return Object.keys(updates).length > 0 ? { ...generationParams, ...updates } : generationParams;
+};
+
/**
* Recursively validate that no full URLs are present in the config
* This is a defensive check to ensure only keys are stored in database