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: qwen image inside new api (#9587)

YuTengjing08ea8561f989
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
index f23c7d67f75..8161b198cf4 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
@@ -1,3 +1,4 @@
+import { cleanObject } from '@lobechat/utils/object';
import createDebug from 'debug';
import { RuntimeImageGenParamsValue } from 'model-bank';
import OpenAI from 'openai';
@@ -34,24 +35,25 @@ async function generateByImageMode(
value,
]),
);
+ // unify image input to array
+ if (typeof userInput.image === 'string' && userInput.image.trim() !== '') {
+ userInput.image = [userInput.image];
+ }
// https://platform.openai.com/docs/api-reference/images/createEdit
const isImageEdit = Array.isArray(userInput.image) && userInput.image.length > 0;
+ log('isImageEdit: %O, userInput.image: %O', isImageEdit, userInput.image);
// If there are imageUrls parameters, convert them to File objects
if (isImageEdit) {
- log('Converting imageUrls to File objects: %O', userInput.image);
try {
// Convert all image URLs to File objects
const imageFiles = await Promise.all(
userInput.image.map((url: string) => convertImageUrlToFile(url)),
);
- log('Successfully converted %d images to File objects', imageFiles.length);
-
// According to official docs, if there are multiple images, pass an array; if only one, pass a single File
userInput.image = imageFiles.length === 1 ? imageFiles[0] : imageFiles;
} catch (error) {
- log('Error converting imageUrls to File objects: %O', error);
throw new Error(`Failed to convert image URLs to File objects: ${error}`);
}
} else {
@@ -68,11 +70,11 @@ async function generateByImageMode(
...(isImageEdit ? { input_fidelity: 'high' } : {}),
};
- const options = {
+ const options = cleanObject({
model,
...defaultInput,
...userInput,
- };
+ });
log('options: %O', options);
@@ -83,13 +85,11 @@ async function generateByImageMode(
// Check the integrity of response data
if (!img || !img.data || !Array.isArray(img.data) || img.data.length === 0) {
- log('Invalid image response: missing data array');
throw new Error('Invalid image response: missing or empty data array');
}
const imageData = img.data[0];
if (!imageData) {
- log('Invalid image response: first data item is null/undefined');
throw new Error('Invalid image response: first data item is null or undefined');
}
@@ -111,12 +111,9 @@ async function generateByImageMode(
}
// If neither format exists, throw error
else {
- log('Invalid image response: missing both b64_json and url fields');
throw new Error('Invalid image response: missing both b64_json and url fields');
}
- log('provider: %s', provider);
-
return {
imageUrl,
...(img.usage
@@ -180,7 +177,6 @@ async function generateByChatModel(
});
log('Successfully processed image URL for chat input');
} catch (error) {
- log('Error processing image URL: %O', error);
throw new Error(`Failed to process image URL: ${error}`);
}
}
@@ -218,7 +214,6 @@ async function generateByChatModel(
}
// If no images found, throw error
- log('No images found in chat completion response');
throw new Error('No image generated in chat completion response');
}
@@ -228,21 +223,15 @@ async function generateByChatModel(
export async function createOpenAICompatibleImage(
client: OpenAI,
payload: CreateImagePayload,
- provider: string, // eslint-disable-line @typescript-eslint/no-unused-vars
+ provider: string,
): Promise<CreateImageResponse> {
- try {
- const { model } = payload;
-
- // Check if it's a chat model for image generation (via :image suffix)
- if (model.endsWith(':image')) {
- return await generateByChatModel(client, payload);
- }
+ const { model } = payload;
- // Default to traditional images API
- return await generateByImageMode(client, payload, provider);
- } catch (error) {
- const err = error as Error;
- log('Error in createImage: %O', err);
- throw err;
+ // Check if it's a chat model for image generation (via :image suffix)
+ if (model.endsWith(':image')) {
+ return await generateByChatModel(client, payload);
}
+
+ // Default to traditional images API
+ return await generateByImageMode(client, payload, provider);
}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 07bd232a048..cac5d621d1d 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -296,6 +296,8 @@ describe('LobeOpenAICompatibleFactory', () => {
});
it('should transform non-streaming response to stream correctly', async () => {
+ vi.useFakeTimers();
+
const mockResponse = {
id: 'a',
object: 'chat.completion',
@@ -319,13 +321,18 @@ describe('LobeOpenAICompatibleFactory', () => {
mockResponse as any,
);
- const result = await instance.chat({
+ const chatPromise = instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
model: 'mistralai/mistral-7b-instruct:free',
temperature: 0,
stream: false,
});
+ // Advance time to simulate processing delay
+ vi.advanceTimersByTime(10);
+
+ const result = await chatPromise;
+
const decoder = new TextDecoder();
const reader = result.body!.getReader();
const stream: string[] = [];
@@ -345,16 +352,20 @@ describe('LobeOpenAICompatibleFactory', () => {
'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
'id: output_speed\n',
'event: speed\n',
- expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*}\n\n$/), // tps ttft 测试结果不一样
+ expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*}\n\n$/), // tps ttft should be calculated with elapsed time
'id: a\n',
'event: stop\n',
'data: "stop"\n\n',
]);
expect((await reader.read()).done).toBe(true);
+
+ vi.useRealTimers();
});
it('should transform non-streaming response to stream correctly with reasoning content', async () => {
+ vi.useFakeTimers();
+
const mockResponse = {
id: 'a',
object: 'chat.completion',
@@ -382,13 +393,18 @@ describe('LobeOpenAICompatibleFactory', () => {
mockResponse as any,
);
- const result = await instance.chat({
+ const chatPromise = instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
model: 'deepseek/deepseek-reasoner',
temperature: 0,
stream: false,
});
+ // Advance time to simulate processing delay
+ vi.advanceTimersByTime(10);
+
+ const result = await chatPromise;
+
const decoder = new TextDecoder();
const reader = result.body!.getReader();
const stream: string[] = [];
@@ -411,13 +427,15 @@ describe('LobeOpenAICompatibleFactory', () => {
'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
'id: output_speed\n',
'event: speed\n',
- expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*}\n\n$/), // tps ttft 测试结果不一样
+ expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*}\n\n$/), // tps ttft should be calculated with elapsed time
'id: a\n',
'event: stop\n',
'data: "stop"\n\n',
]);
expect((await reader.read()).done).toBe(true);
+
+ vi.useRealTimers();
});
});
@@ -974,7 +992,11 @@ describe('LobeOpenAICompatibleFactory', () => {
.spyOn(inst['client'].responses, 'create')
.mockResolvedValue({ tee: () => [prod, debug] } as any);
- await inst.chat({ messages: [{ content: 'hi', role: 'user' }], model: 'any-model', temperature: 0 });
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'any-model',
+ temperature: 0,
+ });
expect(mockResponsesCreate).toHaveBeenCalled();
});
@@ -990,20 +1012,38 @@ describe('LobeOpenAICompatibleFactory', () => {
const inst = new LobeMockProviderUseResponseModels({ apiKey: 'test' });
const spy = vi.spyOn(inst['client'].responses, 'create');
// Prevent hanging by mocking normal chat completion stream
- vi.spyOn(inst['client'].chat.completions, 'create').mockResolvedValue(new ReadableStream() as any);
+ vi.spyOn(inst['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
// First invocation: model contains the string
- spy.mockResolvedValueOnce({ tee: () => [new ReadableStream(), new ReadableStream()] } as any);
- await inst.chat({ messages: [{ content: 'hi', role: 'user' }], model: 'prefix-special-model-suffix', temperature: 0 });
+ spy.mockResolvedValueOnce({
+ tee: () => [new ReadableStream(), new ReadableStream()],
+ } as any);
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'prefix-special-model-suffix',
+ temperature: 0,
+ });
expect(spy).toHaveBeenCalledTimes(1);
// Second invocation: model matches the RegExp
- spy.mockResolvedValueOnce({ tee: () => [new ReadableStream(), new ReadableStream()] } as any);
- await inst.chat({ messages: [{ content: 'hi', role: 'user' }], model: 'special-xyz', temperature: 0 });
+ spy.mockResolvedValueOnce({
+ tee: () => [new ReadableStream(), new ReadableStream()],
+ } as any);
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'special-xyz',
+ temperature: 0,
+ });
expect(spy).toHaveBeenCalledTimes(2);
// Third invocation: model does not match any useResponseModels patterns
- await inst.chat({ messages: [{ content: 'hi', role: 'user' }], model: 'unrelated-model', temperature: 0 });
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'unrelated-model',
+ temperature: 0,
+ });
expect(spy).toHaveBeenCalledTimes(2); // Ensure no additional calls were made
});
});
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index 3d32e7d442e..f29c76b70a5 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -384,7 +384,6 @@ export const createTokenSpeedCalculator = (
}: { enableStreaming?: boolean; inputStartAt?: number; streamStack?: StreamContext } = {},
) => {
let outputStartAt: number | undefined;
- let outputThinking: boolean | undefined;
const process = (chunk: StreamProtocolChunk) => {
let result = [chunk];
@@ -393,24 +392,12 @@ export const createTokenSpeedCalculator = (
outputStartAt = Date.now();
}
- /**
- * 部分 provider 在正式输出 reasoning 前,可能会先输出 content 为空字符串的 chunk,
- * 其中 reasoning 可能为 null,会导致判断是否输出思考内容错误,所以过滤掉 null 或者空字符串。
- * 也可能是某些特殊 token,所以不修改 outputStartAt 的逻辑。
- */
- if (
- outputThinking === undefined &&
- (chunk.type === 'text' || chunk.type === 'reasoning') &&
- typeof chunk.data === 'string' &&
- chunk.data.length > 0
- ) {
- outputThinking = chunk.type === 'reasoning';
- }
// if the chunk is the stop chunk, set as output finish
if (inputStartAt && outputStartAt && chunk.type === 'usage') {
// TPS should always include all generated tokens (including reasoning tokens)
// because it measures generation speed, not just visible content
- const outputTokens = chunk.data?.totalOutputTokens ?? 0;
+ const usage = chunk.data as ModelUsage;
+ const outputTokens = usage?.totalOutputTokens ?? 0;
const now = Date.now();
const elapsed = now - (enableStreaming ? outputStartAt : inputStartAt);
const duration = now - outputStartAt;
diff --git a/packages/model-runtime/src/providers/newapi/index.test.ts b/packages/model-runtime/src/providers/newapi/index.test.ts
index 71e45e77af2..c334a72e358 100644
--- a/packages/model-runtime/src/providers/newapi/index.test.ts
+++ b/packages/model-runtime/src/providers/newapi/index.test.ts
@@ -563,7 +563,22 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
if (inputPrice !== undefined) {
const outputPrice = inputPrice * (pricing.completion_ratio || 1);
- enhancedModel.pricing = { input: inputPrice, output: outputPrice };
+ enhancedModel.pricing = {
+ units: [
+ {
+ name: 'textInput',
+ unit: 'millionTokens',
+ strategy: 'fixed',
+ rate: inputPrice,
+ },
+ {
+ name: 'textOutput',
+ unit: 'millionTokens',
+ strategy: 'fixed',
+ rate: outputPrice,
+ },
+ ],
+ };
}
}
@@ -582,8 +597,18 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
// Verify pricing results
- expect(enrichedModels[0].pricing).toEqual({ input: 40, output: 120 }); // model_price * 2, input * completion_ratio
- expect(enrichedModels[1].pricing).toEqual({ input: 10, output: 10 }); // model_ratio * 2, input * 1 (default)
+ expect(enrichedModels[0].pricing).toEqual({
+ units: [
+ { name: 'textInput', unit: 'millionTokens', strategy: 'fixed', rate: 40 },
+ { name: 'textOutput', unit: 'millionTokens', strategy: 'fixed', rate: 120 },
+ ],
+ }); // model_price * 2, input * completion_ratio
+ expect(enrichedModels[1].pricing).toEqual({
+ units: [
+ { name: 'textInput', unit: 'millionTokens', strategy: 'fixed', rate: 10 },
+ { name: 'textOutput', unit: 'millionTokens', strategy: 'fixed', rate: 10 },
+ ],
+ }); // model_ratio * 2, input * 1 (default)
expect(enrichedModels[2].pricing).toBeUndefined(); // quota_type = 1, skipped
// Verify provider detection
diff --git a/packages/model-runtime/src/providers/newapi/index.ts b/packages/model-runtime/src/providers/newapi/index.ts
index d01f7bc1edb..e0410559fe8 100644
--- a/packages/model-runtime/src/providers/newapi/index.ts
+++ b/packages/model-runtime/src/providers/newapi/index.ts
@@ -20,41 +20,21 @@ export interface NewAPIPricing {
model_name: string;
model_price?: number;
model_ratio?: number;
- quota_type: number; // 0: 按量计费, 1: 按次计费
+ /** 0: Pay-per-token, 1: Pay-per-call */
+ quota_type: number;
supported_endpoint_types?: string[];
}
const handlePayload = (payload: ChatStreamPayload) => {
- // 处理 OpenAI responses API 模式
+ // Handle OpenAI responses API mode
if (
responsesAPIModels.has(payload.model) ||
payload.model.includes('gpt-') ||
/^o\d/.test(payload.model)
) {
- return { ...payload, apiMode: 'responses' } as any;
+ return { ...payload, apiMode: 'responses' };
}
- return payload as any;
-};
-
-// 根据 owned_by 字段判断提供商(基于 NewAPI 的 channel name)
-const getProviderFromOwnedBy = (ownedBy: string): string => {
- const normalizedOwnedBy = ownedBy.toLowerCase();
-
- if (normalizedOwnedBy.includes('claude') || normalizedOwnedBy.includes('anthropic')) {
- return 'anthropic';
- }
- if (normalizedOwnedBy.includes('google') || normalizedOwnedBy.includes('gemini')) {
- return 'google';
- }
- if (normalizedOwnedBy.includes('xai') || normalizedOwnedBy.includes('grok')) {
- return 'xai';
- }
- if (normalizedOwnedBy.includes('ali') || normalizedOwnedBy.includes('qwen')) {
- return 'qwen';
- }
-
- // 默认为 openai
- return 'openai';
+ return payload;
};
export const LobeNewAPIAI = createRouterRuntime({
@@ -66,16 +46,16 @@ export const LobeNewAPIAI = createRouterRuntime({
},
id: ModelProvider.NewAPI,
models: async ({ client: openAIClient }) => {
- // 获取基础 URL(移除末尾的 API 版本路径如 /v1、/v1beta 等)
+ // Get base URL (remove trailing API version paths like /v1, /v1beta, etc.)
const baseURL = openAIClient.baseURL.replace(/\/v\d+[a-z]*\/?$/, '');
const modelsPage = (await openAIClient.models.list()) as any;
const modelList: NewAPIModelCard[] = modelsPage.data || [];
- // 尝试获取 pricing 信息以补充模型详细信息
+ // Try to get pricing information to enrich model details
let pricingMap: Map<string, NewAPIPricing> = new Map();
try {
- // 使用保存的 baseURL
+ // Use saved baseURL
const pricingResponse = await fetch(`${baseURL}/api/pricing`, {
headers: {
Authorization: `Bearer ${openAIClient.apiKey}`,
@@ -99,22 +79,22 @@ export const LobeNewAPIAI = createRouterRuntime({
const enrichedModelList = modelList.map((model) => {
let enhancedModel: any = { ...model };
- // 1. 添加 pricing 信息
+ // add pricing info
const pricing = pricingMap.get(model.id);
if (pricing) {
- // NewAPI 的价格计算逻辑:
- // - quota_type: 0 表示按量计费(按 token),1 表示按次计费
- // - model_ratio: 相对于基础价格的倍率(基础价格 = $0.002/1K tokens)
- // - model_price: 直接指定的价格(优先使用)
- // - completion_ratio: 输出价格相对于输入价格的倍率
+ // NewAPI pricing calculation logic:
+ // - quota_type: 0 means pay-per-token, 1 means pay-per-call
+ // - model_ratio: multiplier relative to base price (base price = $0.002/1K tokens)
+ // - model_price: directly specified price (takes priority)
+ // - completion_ratio: output price multiplier relative to input price
//
- // LobeChat 需要的格式:美元/百万 token
+ // LobeChat required format: USD per million tokens
let inputPrice: number | undefined;
let outputPrice: number | undefined;
if (pricing.quota_type === 0) {
- // 按量计费
+ // Pay-per-token
if (pricing.model_price && pricing.model_price > 0) {
// model_price is a direct price value; need to confirm its unit.
// Assumption: model_price is the price per 1,000 tokens (i.e., $/1K tokens).
@@ -124,62 +104,38 @@ export const LobeNewAPIAI = createRouterRuntime({
inputPrice = pricing.model_price * 2;
} else if (pricing.model_ratio) {
// model_ratio × $0.002/1K = model_ratio × $2/1M
- inputPrice = pricing.model_ratio * 2; // 转换为 $/1M tokens
+ inputPrice = pricing.model_ratio * 2; // Convert to $/1M tokens
}
if (inputPrice !== undefined) {
- // 计算输出价格
+ // Calculate output price
outputPrice = inputPrice * (pricing.completion_ratio || 1);
enhancedModel.pricing = {
- input: inputPrice,
- output: outputPrice,
+ units: [
+ {
+ name: 'textInput',
+ rate: inputPrice,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ {
+ name: 'textOutput',
+ rate: outputPrice,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
};
}
}
- // quota_type === 1 按次计费暂不支持
- }
-
- // 2. 根据优先级处理 provider 信息并缓存路由
- let detectedProvider = 'openai'; // 默认
-
- // 优先级1:使用 supported_endpoint_types
- if (model.supported_endpoint_types && model.supported_endpoint_types.length > 0) {
- if (model.supported_endpoint_types.includes('anthropic')) {
- detectedProvider = 'anthropic';
- } else if (model.supported_endpoint_types.includes('gemini')) {
- detectedProvider = 'google';
- } else if (model.supported_endpoint_types.includes('xai')) {
- detectedProvider = 'xai';
- } else if (model.supported_endpoint_types.includes('qwen')) {
- detectedProvider = 'qwen';
- }
- }
- // 优先级2:使用 owned_by 字段
- else if (model.owned_by) {
- detectedProvider = getProviderFromOwnedBy(model.owned_by);
- }
- // 优先级3:基于模型名称检测
- else {
- detectedProvider = detectModelProvider(model.id);
+ // quota_type === 1 pay-per-call is not currently supported
}
- // 将检测到的 provider 信息附加到模型上
- enhancedModel._detectedProvider = detectedProvider;
-
return enhancedModel;
});
- // 使用 processMultiProviderModelList 处理模型能力
- const processedModels = await processMultiProviderModelList(enrichedModelList, 'newapi');
-
- // 清理临时字段
- return processedModels.map((model: any) => {
- if (model._detectedProvider) {
- delete model._detectedProvider;
- }
- return model;
- });
+ return processMultiProviderModelList(enrichedModelList, 'newapi');
},
routers: (options) => {
const userBaseURL = options.baseURL?.replace(/\/v\d+[a-z]*\/?$/, '') || '';
@@ -215,16 +171,6 @@ export const LobeNewAPIAI = createRouterRuntime({
baseURL: urlJoin(userBaseURL, '/v1'),
},
},
- {
- apiType: 'qwen',
- models: LOBE_DEFAULT_MODEL_LIST.map((m) => m.id).filter(
- (id) => detectModelProvider(id) === 'qwen',
- ),
- options: {
- ...options,
- baseURL: urlJoin(userBaseURL, '/v1'),
- },
- },
{
apiType: 'openai',
options: {
diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.ts
index 30172110302..d1d433956b1 100644
--- a/packages/model-runtime/src/types/index.ts
+++ b/packages/model-runtime/src/types/index.ts
@@ -8,4 +8,3 @@ export * from './textToImage';
export * from './toolsCalling';
export * from './tts';
export * from './type';
-export * from './usage';
diff --git a/packages/model-runtime/src/types/usage.ts b/packages/model-runtime/src/types/usage.ts
deleted file mode 100644
index 99f360e2169..00000000000
--- a/packages/model-runtime/src/types/usage.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-export interface ModelTokensUsage {
- acceptedPredictionTokens?: number;
- inputAudioTokens?: number;
- inputCacheMissTokens?: number;
- inputCachedTokens?: number;
- /**
- * currently only pplx has citation_tokens
- */
- inputCitationTokens?: number;
- /**
- * user prompt image
- */
- inputImageTokens?: number;
- /**
- * user prompt input
- */
- inputTextTokens?: number;
- inputWriteCacheTokens?: number;
- outputAudioTokens?: number;
- outputImageTokens?: number;
- outputReasoningTokens?: number;
- outputTextTokens?: number;
- rejectedPredictionTokens?: number;
- totalInputTokens?: number;
- totalOutputTokens?: number;
- totalTokens?: number;
-}
diff --git a/packages/types/src/message/base.ts b/packages/types/src/message/base.ts
index a430117b3f8..3d5115ea650 100644
--- a/packages/types/src/message/base.ts
+++ b/packages/types/src/message/base.ts
@@ -61,6 +61,7 @@ export interface ModelTokensUsage {
rejectedPredictionTokens?: number;
// Total tokens
+ // TODO: make all following fields required
totalInputTokens?: number;
totalOutputTokens?: number;
totalTokens?: number;
diff --git a/packages/utils/package.json b/packages/utils/package.json
index ea5b7ad32ef..ccc8f2dfa29 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -5,7 +5,8 @@
"exports": {
".": "./src/index.ts",
"./server": "./src/server/index.ts",
- "./client": "./src/client/index.ts"
+ "./client": "./src/client/index.ts",
+ "./object": "./src/object.ts"
},
"scripts": {
"test": "vitest",