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.

✨ feat: support Qwen Image 3 on fal and Grok Imagine Image 2.0 (#19996)

YuTengjingf44c713b8734
diff --git a/apps/server/src/services/generation/index.test.ts b/apps/server/src/services/generation/index.test.ts
index 4ce236048a8..4c604e0124d 100644
--- a/apps/server/src/services/generation/index.test.ts
+++ b/apps/server/src/services/generation/index.test.ts
@@ -216,12 +216,71 @@ describe('GenerationService', () => {
});
});
- it('should throw error when network request fails', async () => {
- mockSsrfSafeFetch.mockRejectedValueOnce(new Error('Network error'));
+ describe('transient failures', () => {
+ const okResponse = () => ({
+ ok: true,
+ status: 200,
+ headers: { get: vi.fn().mockReturnValue('image/jpeg') },
+ arrayBuffer: vi.fn().mockResolvedValue(Buffer.from('img').buffer),
+ });
- await expect(fetchImageFromUrl('https://example.com/image.jpg')).rejects.toThrow(
- 'Network error',
- );
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('should retry a reset connection and return the image', async () => {
+ mockSsrfSafeFetch
+ .mockRejectedValueOnce(
+ new Error('Fetch failed: Invalid response body while trying to fetch: aborted'),
+ )
+ .mockResolvedValueOnce(okResponse());
+
+ const promise = fetchImageFromUrl('https://example.com/image.jpg');
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toMatchObject({ mimeType: 'image/jpeg' });
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('should retry 5xx responses', async () => {
+ mockSsrfSafeFetch
+ .mockResolvedValueOnce({ ok: false, status: 503, statusText: 'Service Unavailable' })
+ .mockResolvedValueOnce(okResponse());
+
+ const promise = fetchImageFromUrl('https://example.com/image.jpg');
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toMatchObject({ mimeType: 'image/jpeg' });
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('should give up after all retries without reporting an abort', async () => {
+ mockSsrfSafeFetch.mockRejectedValue(new Error('Fetch failed: aborted'));
+
+ const promise = fetchImageFromUrl('https://example.com/image.jpg');
+ const assertion = expect(promise).rejects.toThrow(
+ 'Failed to fetch image from https://example.com/image.jpg after 3 attempts: network error',
+ );
+ await vi.runAllTimersAsync();
+
+ await assertion;
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(3);
+ });
+
+ it('should not retry SSRF blocks', async () => {
+ mockSsrfSafeFetch.mockRejectedValueOnce(
+ new Error('SSRF blocked: 10.0.0.1 is not allowed'),
+ );
+
+ await expect(fetchImageFromUrl('https://example.com/image.jpg')).rejects.toThrow(
+ 'SSRF blocked',
+ );
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(1);
+ });
});
});
diff --git a/apps/server/src/services/generation/index.ts b/apps/server/src/services/generation/index.ts
index 6153a3cfc5c..10276e0d37f 100644
--- a/apps/server/src/services/generation/index.ts
+++ b/apps/server/src/services/generation/index.ts
@@ -57,7 +57,7 @@ export async function fetchImageFromUrl(
// are read and returned, other responses leak status/statusText for blind probing.
// ssrfSafeFetch blocks private/link-local IPs at connect time and on every redirect hop.
// See GHSA-53h9-fmjf-frwr / #16536.
- const response = await ssrfSafeFetch(url, { headers: fetchHeaders });
+ const response = await fetchWithRetry(url, fetchHeaders);
if (!response.ok) {
throw new Error(
`Failed to fetch image from ${url}: ${response.status} ${response.statusText}`,
@@ -70,6 +70,51 @@ export async function fetchImageFromUrl(
}
}
+/**
+ * Delays before each retry of a remote image download. Providers such as xAI return a
+ * short-lived CDN URL after the generation is already billed upstream, so a single reset
+ * connection (ECONNRESET while reading the body) would otherwise discard a paid image.
+ */
+export const IMAGE_DOWNLOAD_RETRY_DELAYS_MS = [500, 1500];
+
+const isRetryableStatus = (status: number) => status === 408 || status === 429 || status >= 500;
+
+/**
+ * Download through ssrfSafeFetch, retrying transient failures: thrown network/body-read
+ * errors and 408/429/5xx responses. SSRF blocks and other 4xx responses are final.
+ */
+const fetchWithRetry = async (
+ url: string,
+ fetchHeaders?: Record<string, string>,
+): Promise<Response> => {
+ for (let attempt = 0; ; attempt++) {
+ const canRetry = attempt < IMAGE_DOWNLOAD_RETRY_DELAYS_MS.length;
+
+ try {
+ const response = await ssrfSafeFetch(url, { headers: fetchHeaders });
+ if (!canRetry || !isRetryableStatus(response.status)) return response;
+
+ log('Image download returned %d, retrying (attempt %d)', response.status, attempt + 1);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (message.startsWith('SSRF blocked')) throw error;
+
+ if (!canRetry) {
+ // Keep the transport detail in `cause` only: body-read failures surface as
+ // "...: aborted", which the async image task would misreport as TaskTimeout.
+ throw new Error(
+ `Failed to fetch image from ${url} after ${attempt + 1} attempts: network error`,
+ { cause: error },
+ );
+ }
+
+ log('Image download failed, retrying (attempt %d): %s', attempt + 1, message);
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, IMAGE_DOWNLOAD_RETRY_DELAYS_MS[attempt]));
+ }
+};
+
interface ImageForGeneration {
buffer: Buffer;
extension: string;
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
index 19a73f65ba1..fefff846399 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
@@ -342,4 +342,58 @@ describe('computeImageCost', () => {
expect(result?.totalCredits).toBe(0);
});
});
+
+ describe('per-image input fee', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'imageGeneration',
+ strategy: 'lookup',
+ unit: 'image',
+ lookup: {
+ pricingParams: ['resolution'],
+ prices: { '1k': 0.04, '2k': 0.08 },
+ },
+ },
+ { name: 'imageInput', rate: 0.01, strategy: 'fixed', unit: 'image' },
+ ],
+ };
+
+ it('adds the input fee for every reference image on each generated image', () => {
+ const result = computeImageCost(pricing, { imageUrls: ['a', 'b'], resolution: '1k' }, 2);
+
+ // (0.04 + 2 × 0.01) × 2 images
+ expect(result?.totalCost).toBeCloseTo(0.12);
+ expect(result?.breakdown).toMatchObject({ inputImageCount: 2, pricePerImage: 0.04 });
+ expect(result?.breakdown?.inputImageCost).toBeCloseTo(0.02);
+ });
+
+ it('counts a single imageUrl as one input image', () => {
+ const result = computeImageCost(pricing, { imageUrl: 'a', resolution: '2k' }, 1);
+
+ expect(result?.totalCost).toBeCloseTo(0.09);
+ });
+
+ it('charges no input fee for text-to-image', () => {
+ const result = computeImageCost(pricing, { imageUrls: [], resolution: '1k' }, 1);
+
+ expect(result?.totalCost).toBe(0.04);
+ expect(result?.breakdown?.inputImageCount).toBeUndefined();
+ });
+
+ it('ignores token-based imageInput units', () => {
+ const result = computeImageCost(
+ {
+ units: [
+ { name: 'imageGeneration', rate: 0.04, strategy: 'fixed', unit: 'image' },
+ { name: 'imageInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ { imageUrls: ['a'] },
+ 1,
+ );
+
+ expect(result?.totalCost).toBe(0.04);
+ });
+ });
});
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts
index 355a1f5b207..4ba2eebb5c5 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts
@@ -14,6 +14,10 @@ export interface ImageGenerationParams {
export interface ImageCostResult {
breakdown?: {
imageCount: number;
+ /** Number of reference images sent with each generation request */
+ inputImageCount?: number;
+ /** Input-image fee charged per generated image, in USD */
+ inputImageCost?: number;
lookupKey?: string;
pricePerImage: number; // Price per image in USD
};
@@ -21,6 +25,11 @@ export interface ImageCostResult {
totalCredits: number; // Total credits (USD * CREDITS_PER_DOLLAR)
}
+const countInputImages = (params: ImageGenerationParams): number => {
+ if (Array.isArray(params.imageUrls)) return params.imageUrls.filter(Boolean).length;
+ return params.imageUrl ? 1 : 0;
+};
+
/**
* Compute the cost for image generation based on pricing configuration
* @param pricing - The pricing configuration for the model
@@ -40,7 +49,7 @@ export const computeImageCost = (
return undefined;
}
- let pricePerImageInUSD = 0;
+ let pricePerImageInUSD: number;
let lookupKey: string | undefined;
switch (imageGenUnit.strategy) {
@@ -101,8 +110,21 @@ export const computeImageCost = (
}
}
+ // Some providers (e.g. xAI image edits) also bill every reference image sent with a
+ // request. Each generated image is its own upstream request carrying the same
+ // references, so the input fee is added once per generated image.
+ const inputImageCount = countInputImages(params);
+ const inputImageUnit = pricing.units.find(
+ (unit): unit is FixedPricingUnit =>
+ unit.name === 'imageInput' && unit.strategy === 'fixed' && unit.unit === 'image',
+ );
+ const inputImageCost = inputImageUnit ? inputImageUnit.rate * inputImageCount : 0;
+ if (inputImageCost > 0) {
+ log(`Input image fee: ${inputImageCount} images × $${inputImageUnit!.rate}`);
+ }
+
// Calculate total cost in USD first, then convert to credits
- const totalCost = pricePerImageInUSD * imageNum;
+ const totalCost = (pricePerImageInUSD + inputImageCost) * imageNum;
const totalCredits = Math.ceil(totalCost * CREDITS_PER_DOLLAR);
log(
@@ -112,6 +134,7 @@ export const computeImageCost = (
return {
breakdown: {
imageCount: imageNum,
+ ...(inputImageCost > 0 && { inputImageCost, inputImageCount }),
lookupKey,
pricePerImage: pricePerImageInUSD,
},
diff --git a/packages/model-runtime/src/providers/fal/index.test.ts b/packages/model-runtime/src/providers/fal/index.test.ts
index 764c1eb956d..b808519eccd 100644
--- a/packages/model-runtime/src/providers/fal/index.test.ts
+++ b/packages/model-runtime/src/providers/fal/index.test.ts
@@ -3,7 +3,7 @@ import { fal } from '@fal-ai/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateImagePayload } from '../../types';
-import { LobeFalAI } from './index';
+import { LobeFalAI, resolveFalImageSize } from './index';
// Mock the fal client
vi.mock('@fal-ai/client', () => ({
@@ -901,6 +901,71 @@ describe('LobeFalAI', () => {
});
});
+ describe('Qwen Image 3 (alibaba namespace)', () => {
+ beforeEach(() => {
+ mockFal.subscribe.mockResolvedValue({
+ requestId: 'test-request-id',
+ data: { images: [{ url: 'https://example.com/generated.jpg' }] },
+ } as any);
+ });
+
+ it('should keep the alibaba namespace and use text-to-image without imageUrls', async () => {
+ await instance.createImage({
+ model: 'alibaba/qwen-image-3',
+ params: { aspectRatio: '16:9', prompt: 'A poster', resolution: '1K' },
+ });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('alibaba/qwen-image-3/text-to-image', {
+ input: {
+ enable_safety_checker: false,
+ image_size: { height: 768, width: 1360 },
+ num_images: 1,
+ prompt: 'A poster',
+ },
+ });
+ });
+
+ it('should use the edit endpoint with imageUrls and a 2K image size', async () => {
+ await instance.createImage({
+ model: 'alibaba/qwen-image-3',
+ params: {
+ aspectRatio: '1:1',
+ imageUrls: ['https://example.com/input.png'],
+ prompt: 'Make it snow',
+ resolution: '2K',
+ },
+ });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('alibaba/qwen-image-3/edit', {
+ input: {
+ enable_safety_checker: false,
+ image_size: { height: 2048, width: 2048 },
+ image_urls: ['https://example.com/input.png'],
+ num_images: 1,
+ prompt: 'Make it snow',
+ },
+ });
+ });
+
+ it('should keep image sizes within the resolution pixel budget', () => {
+ for (const aspectRatio of ['1:1', '4:3', '3:4', '16:9', '9:16', '3:2', '2:3', '21:9']) {
+ for (const [resolution, edge] of [
+ ['1K', 1024],
+ ['2K', 2048],
+ ] as const) {
+ const size = resolveFalImageSize(aspectRatio, resolution)!;
+ expect(size.width % 16).toBe(0);
+ expect(size.height % 16).toBe(0);
+ expect(size.width * size.height).toBeLessThanOrEqual(edge * edge);
+ expect(Math.max(size.width, size.height)).toBeLessThanOrEqual(2048);
+ }
+ }
+ expect(resolveFalImageSize('16:9', '1K')).toEqual({ height: 768, width: 1360 });
+ expect(resolveFalImageSize('16:9', '2K')).toEqual({ height: 1152, width: 2048 });
+ expect(resolveFalImageSize('1:1', '4K')).toBeUndefined();
+ });
+ });
+
describe('Edge cases', () => {
it('should handle empty params object', async () => {
// Arrange
diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.ts
index e7e648a9375..360c44e3a59 100644
--- a/packages/model-runtime/src/providers/fal/index.ts
+++ b/packages/model-runtime/src/providers/fal/index.ts
@@ -16,6 +16,59 @@ const log = debug('lobe-image:fal');
type FluxDevOutput = Awaited<ReturnType<typeof fal.subscribe<'fal-ai/flux/dev'>>>['data'];
+/**
+ * fal hosts models under several namespaces (e.g. `alibaba/qwen-image-3`); only bare
+ * model ids without a known namespace get the default `fal-ai/` prefix.
+ */
+const FAL_NAMESPACES = ['fal-ai/', 'alibaba/'];
+
+/**
+ * Model families exposed as one card but served by separate fal endpoints: requests
+ * with reference images go to `/edit`, others to `/text-to-image`.
+ */
+const EDIT_OR_TEXT_TO_IMAGE_ENDPOINT_PREFIXES = [
+ 'fal-ai/bytedance/seedream/v',
+ 'fal-ai/hunyuan-image/v',
+ 'alibaba/qwen-image-3',
+];
+
+/**
+ * Long edge of a square image for each `resolution` preset. fal bills some models
+ * (e.g. Qwen Image 3) by output resolution tier, so the requested pixel count must
+ * stay within the tier the user picked.
+ */
+const RESOLUTION_BASE_EDGE: Record<string, number> = { '1K': 1024, '2K': 2048 };
+
+/**
+ * fal clamps each side to this length (a 2720x1536 request came back as 2048x1536),
+ * so wide 2K sizes must be scaled down to keep the requested aspect ratio.
+ */
+const MAX_IMAGE_SIDE = 2048;
+
+/**
+ * Convert `aspectRatio` + `resolution` presets into a fal `image_size` whose pixel
+ * count does not exceed the square of the preset edge and whose sides stay within
+ * `MAX_IMAGE_SIDE`, with both sides multiples of 16.
+ */
+export const resolveFalImageSize = (
+ aspectRatio: string | undefined,
+ resolution: string,
+): { height: number; width: number } | undefined => {
+ const baseEdge = RESOLUTION_BASE_EDGE[resolution];
+ if (!baseEdge) return;
+
+ const [ratioWidth, ratioHeight] = (aspectRatio ?? '1:1').split(':').map(Number);
+ if (!ratioWidth || !ratioHeight) return;
+
+ const scale = Math.min(
+ Math.sqrt((baseEdge * baseEdge) / (ratioWidth * ratioHeight)),
+ MAX_IMAGE_SIDE / Math.max(ratioWidth, ratioHeight),
+ );
+ const roundDown = (value: number) => Math.floor(value / 16) * 16;
+
+ return { height: roundDown(ratioHeight * scale), width: roundDown(ratioWidth * scale) };
+};
+
export class LobeFalAI implements LobeRuntimeAI {
private readonly modelIdMappingOptions: ModelIdMappingOptions;
@@ -60,6 +113,16 @@ export class LobeFalAI implements LobeRuntimeAI {
.map(([key, value]) => [paramsMap.get(key) ?? key, value]),
);
+ if (typeof userInput.resolution === 'string' && RESOLUTION_BASE_EDGE[userInput.resolution]) {
+ const imageSize = resolveFalImageSize(
+ userInput.aspectRatio as string | undefined,
+ userInput.resolution,
+ );
+ if (imageSize) userInput.image_size = imageSize;
+ delete userInput.aspectRatio;
+ delete userInput.resolution;
+ }
+
if ('width' in userInput && 'height' in userInput) {
if (userInput.size) {
throw new Error('width/height and size are not supported at the same time');
@@ -78,12 +141,11 @@ export class LobeFalAI implements LobeRuntimeAI {
defaultInput['acceleration'] = 'high';
}
- // Ensure model has fal-ai/ prefix
- let endpoint = requestModel.startsWith('fal-ai/') ? requestModel : `fal-ai/${requestModel}`;
+ let endpoint = FAL_NAMESPACES.some((namespace) => requestModel.startsWith(namespace))
+ ? requestModel
+ : `fal-ai/${requestModel}`;
const hasImageUrls = (params.imageUrls?.length ?? 0) > 0;
- if (
- ['fal-ai/bytedance/seedream/v', 'fal-ai/hunyuan-image/v'].some((m) => endpoint.startsWith(m))
- ) {
+ if (EDIT_OR_TEXT_TO_IMAGE_ENDPOINT_PREFIXES.some((m) => endpoint.startsWith(m))) {
endpoint += hasImageUrls ? '/edit' : '/text-to-image';
} else if (endpoint === 'fal-ai/nano-banana' && hasImageUrls) {
endpoint += '/edit';
diff --git a/packages/model-runtime/src/providers/xai/createImage.test.ts b/packages/model-runtime/src/providers/xai/createImage.test.ts
index 627d9fc1d3c..c5e3ffb3873 100644
--- a/packages/model-runtime/src/providers/xai/createImage.test.ts
+++ b/packages/model-runtime/src/providers/xai/createImage.test.ts
@@ -230,6 +230,33 @@ describe('createXAIImage', () => {
});
});
+ it('should pass quality and 1.5k resolution for grok-imagine-image-2.0', async () => {
+ global.fetch = vi.fn().mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ data: [{ url: 'https://xai-cdn.com/q.jpg', revised_prompt: '' }] }),
+ });
+
+ await createXAIImage(
+ {
+ model: 'grok-imagine-image-2.0',
+ params: { prompt: 'Test image', quality: 'low', resolution: '1.5k' },
+ },
+ mockOptions,
+ );
+
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://api.x.ai/v1/images/generations',
+ expect.objectContaining({
+ body: JSON.stringify({
+ model: 'grok-imagine-image-2.0',
+ prompt: 'Test image',
+ resolution: '1.5k',
+ quality: 'low',
+ }),
+ }),
+ );
+ });
+
it('should handle image editing mode with imageUrl', async () => {
const mockImageUrl = 'https://xai-cdn.com/images/generated/edited-image.jpg';
diff --git a/packages/model-runtime/src/providers/xai/createImage.ts b/packages/model-runtime/src/providers/xai/createImage.ts
index 6ed0fd28d7f..b24c3f2a77c 100644
--- a/packages/model-runtime/src/providers/xai/createImage.ts
+++ b/packages/model-runtime/src/providers/xai/createImage.ts
@@ -37,8 +37,11 @@ interface XAIImageRequest {
model: string;
n?: number;
prompt: string;
+ /**
+ * Only supported by `grok-imagine-image-2.0`; xAI defaults to `medium` when omitted.
+ */
quality?: 'low' | 'medium' | 'high';
- resolution?: '1k' | '2k';
+ resolution?: '1k' | '1.5k' | '2k';
response_format?: 'url' | 'b64_json';
size?: string;
style?: string;
@@ -84,6 +87,10 @@ export async function createXAIImage(
requestBody.resolution = params.resolution as XAIImageRequest['resolution'];
}
+ if (params.quality) {
+ requestBody.quality = params.quality as XAIImageRequest['quality'];
+ }
+
if (isImageEdit) {
if (hasImageUrl && params.imageUrl) {
requestBody.image = {