🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import createDebug from 'debug';
import type { RuntimeImageGenParamsValue } from 'model-bank';
import type OpenAI from 'openai';
import type {
CreateImageMethodOptions,
CreateImagePayload,
CreateImageResponse,
} from '../../types/image';
import { getModelPricing } from '../../utils/getModelPricing';
import { cleanObject } from '../../utils/object';
import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
import { convertImageUrlToFile } from '../contextBuilders/openai';
import { convertOpenAIImageUsage } from '../usageConverters/openai';
import { applyImageOutputParams, resolveImageOutputMimeType } from './imageOutputParams';
const log = createDebug('lobe-image:openai-compatible');
interface CreateOpenAICompatibleImageOptions {
pricingContext?: CreateImageMethodOptions['pricingContext'];
pricingModel?: string;
requestModel?: string;
routingModel?: string;
}
/**
* Generate images using traditional OpenAI images API (DALL-E, etc.)
*/
async function generateByImageMode(
client: OpenAI,
payload: CreateImagePayload,
provider: string,
imageOptions?: CreateOpenAICompatibleImageOptions,
): Promise<CreateImageResponse> {
const { model, params } = payload;
const requestModel = imageOptions?.requestModel ?? model;
const routingModel = imageOptions?.routingModel ?? model;
log('Creating image with model: %s and params: %O', requestModel, params);
// Both fields map to the API's single `image` input. Reject a payload carrying both instead of
// letting one silently overwrite the other while the generation is still billed.
if (params.imageUrl && params.imageUrls?.length) {
throw new Error('Pass reference images in either imageUrl or imageUrls, not both.');
}
// Map parameter names, mapping imageUrls to image
const paramsMap = new Map<RuntimeImageGenParamsValue, string>([
['imageUrls', 'image'],
['imageUrl', 'image'],
]);
const userInput: Record<string, any> = Object.fromEntries(
Object.entries(params).map(([key, value]) => [
paramsMap.get(key as RuntimeImageGenParamsValue) ?? key,
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);
// Validate output controls before downloading reference images: GIF + edit fails anyway.
applyImageOutputParams(userInput, { isImageEdit });
// If there are imageUrls parameters, convert them to File objects
if (isImageEdit) {
try {
// Convert all image URLs to File objects
const imageFiles = await Promise.all(
userInput.image.map((url: string) => convertImageUrlToFile(url)),
);
// 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) {
throw new Error(`Failed to convert image URLs to File objects: ${error}`, { cause: error });
}
} else {
delete userInput.image;
}
if (userInput.size === 'auto') {
delete userInput.size;
}
// gpt-image-2 dropped input_fidelity ("output is already high fidelity by default").
// https://developers.openai.com/cookbook/examples/multimodal/image-gen-models-prompting-guide
// Match the gpt-image-1 family (including dated snapshots like
// `gpt-image-1-2025-04-15` and the `.5` variant), but exclude the mini tier.
const isGptImage1Family = /^gpt-image-1(?:$|[-.])/.test(routingModel);
const supportsInputFidelity = isImageEdit && isGptImage1Family && !routingModel.includes('mini');
// Leave `n` to the API default (1): each generation is its own request, and
// strict-schema OpenAI-compatible gateways reject properties the model does not declare.
const defaultInput = {
...(routingModel.includes('dall-e') ? { response_format: 'b64_json' } : {}),
// https://platform.openai.com/docs/api-reference/images/createEdit#images_createedit-input_fidelity
...(supportsInputFidelity ? { input_fidelity: 'high' } : {}),
};
const options = cleanObject({
model: requestModel,
...defaultInput,
...userInput,
});
log('options: %O', options);
// Determine if it's an image editing operation
const img = isImageEdit
? await client.images.edit(options as any)
: await client.images.generate(options as any);
// Check the integrity of response data
if (!img || !img.data || !Array.isArray(img.data) || img.data.length === 0) {
throw new Error('Invalid image response: missing or empty data array');
}
const imageData = img.data[0];
if (!imageData) {
throw new Error('Invalid image response: first data item is null or undefined');
}
let imageUrl: string;
// Handle base64 format response
if (imageData.b64_json) {
// GIF/JPEG/WebP outputs must keep their real MIME type: storage derives the file extension
// and served Content-Type from it, so a GIF labelled PNG would no longer animate.
const mimeType = resolveImageOutputMimeType(
(img as { output_format?: string }).output_format,
userInput.output_format,
);
// Convert base64 string to complete data URL
imageUrl = `data:${mimeType};base64,${imageData.b64_json}`;
log('Successfully converted base64 to data URL, length: %d', imageUrl.length);
}
// Handle URL format response
else if (imageData.url) {
imageUrl = imageData.url;
log('Using direct image URL: %s', imageUrl);
}
// If neither format exists, throw error
else {
throw new Error('Invalid image response: missing both b64_json and url fields');
}
return {
imageUrl,
...(img.usage
? {
modelUsage: convertOpenAIImageUsage(
img.usage,
await getModelPricing(
imageOptions?.pricingModel ?? routingModel,
provider,
imageOptions?.pricingContext,
),
),
}
: {}),
};
}
/**
* Process image URL for chat model input
*/
async function processImageUrlForChat(imageUrl: string): Promise<string> {
const { type, base64, mimeType } = parseDataUri(imageUrl);
if (type === 'base64') {
if (!base64) {
throw new TypeError("Image URL doesn't contain base64 data");
}
return `data:${mimeType || 'image/png'};base64,${base64}`;
} else if (type === 'url') {
// For URL type, convert to base64 first
const { base64: urlBase64, mimeType: urlMimeType } = await referenceImageUrlToBase64(imageUrl);
return `data:${urlMimeType};base64,${urlBase64}`;
} else {
throw new TypeError(`Currently we don't support image url: ${imageUrl}`);
}
}
/**
* Generate images using chat completion API (OpenRouter Gemini, etc.)
*/
async function generateByChatModel(
client: OpenAI,
payload: CreateImagePayload,
requestModel?: string,
): Promise<CreateImageResponse> {
const { model, params } = payload;
const actualModel = (requestModel ?? model).replace(':image', ''); // Remove :image suffix
log('Creating image via chat API with model: %s and params: %O', actualModel, params);
// Build message content array
const content: Array<any> = [
{
text: params.prompt,
type: 'text',
},
];
// `:image` model cards declare only `imageUrls` (CHAT_MODEL_IMAGE_GENERATION_PARAMS). Reject
// `imageUrl` so the caller resends in the declared field instead of generating without it.
if (params.imageUrl) {
throw new Error('Chat image models take reference images in imageUrls, not imageUrl.');
}
const referenceUrls = params.imageUrls ?? [];
// Download references concurrently; Promise.all keeps their order for the message content.
const processedImageUrls = await Promise.all(
referenceUrls.map(async (imageUrl) => {
log('Processing image URL for editing mode: %s', imageUrl);
try {
return await processImageUrlForChat(imageUrl);
} catch (error) {
throw new Error(`Failed to process image URL: ${error}`, { cause: error });
}
}),
);
for (const url of processedImageUrls) {
content.push({ image_url: { url }, type: 'image_url' });
}
// Call chat completion API
const response = await client.chat.completions.create({
messages: [
{
content,
role: 'user',
},
],
model: actualModel,
stream: false,
});
log('Chat API response: %O', response);
// Extract image from response
const message = response.choices[0]?.message;
if (!message) {
throw new Error('No message in chat completion response');
}
// Check if response has images in the expected format
if ((message as any).images && Array.isArray((message as any).images)) {
const { images } = message as any;
if (images.length > 0) {
const image = images[0];
if (image.image_url?.url) {
log('Successfully extracted image from chat response');
return { imageUrl: image.image_url.url };
}
}
}
// If no images found, throw error
throw new Error('No image generated in chat completion response');
}
/**
* Create image using OpenAI Compatible API
*/
export async function createOpenAICompatibleImage(
client: OpenAI,
payload: CreateImagePayload,
provider: string,
options?: CreateOpenAICompatibleImageOptions,
): Promise<CreateImageResponse> {
const { model } = payload;
const routingModel = options?.routingModel ?? model;
// Check if it's a chat model for image generation (via :image suffix)
if (routingModel.endsWith(':image')) {
return await generateByChatModel(client, payload, options?.requestModel);
}
// Default to traditional images API
return await generateByImageMode(client, payload, provider, options);
}