fix(ai): classify malformed image provider replies and options (#4725)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Filip KujundžićandClaude Fable 5.2 authored and GitHub committed 2026-11-21 15:52:14 -07:00
1 parent 2f43d618ae
commit b0df774be7
14 files changed
+99 -56

No files matched your search

@@ -18,7 +18,7 @@
*/
import { describe, expect, it } from 'vitest';
import { imageDataUri } from './imageOutput.js';
import { imageDataUri, imageEntryUrl } from './imageOutput.js';
describe('imageDataUri', () => {
it.each([
@@ -51,3 +51,29 @@ describe('imageDataUri', () => {
);
});
});
describe('imageEntryUrl', () => {
it('prefers the URL and falls back to the base64 payload', () => {
expect(imageEntryUrl({ url: 'https://x.test/a.png' })).toBe(
'https://x.test/a.png',
);
expect(imageEntryUrl({ b64_json: 'AAAA' }, 'image/jpeg')).toBe(
'data:image/jpeg;base64,AAAA',
);
});
it('finds nothing in an entry that holds neither as text', () => {
for (const entry of [
undefined,
null,
'x',
{},
{ url: '' },
{ url: { href: 'https://x.test' } },
{ b64_json: 5 },
{ b64_json: { data: 'AAAA' } },
]) {
expect(imageEntryUrl(entry)).toBeUndefined();
}
});
});
@@ -22,6 +22,21 @@ import { SVG_SNIFF_WINDOW, sniffImageMime } from '../../../../util/appIcon.js';
// Base64 chars needed to recover SVG_SNIFF_WINDOW decoded bytes.
const SNIFF_BASE64_CHARS = Math.ceil((SVG_SNIFF_WINDOW * 4) / 3);
/** The URL of an OpenAI-style image entry, or its base64 as a data URI. */
export const imageEntryUrl = (
entry: unknown,
fallbackMime?: string,
): string | undefined => {
const { url, b64_json: base64 } = (entry ?? {}) as {
url?: unknown;
b64_json?: unknown;
};
if (typeof url === 'string' && url) return url;
return typeof base64 === 'string' && base64
? imageDataUri(base64, fallbackMime)
: undefined;
};
/** Label generated bytes with the existing content-based MIME detector. */
export function imageDataUri(
base64: string,
@@ -130,6 +130,7 @@ describe('BytePlusImageProvider construction', () => {
makeProvider();
expect(openAICtor).toHaveBeenCalledWith({
apiKey: 'test-key',
fetch: expect.any(Function),
baseURL: 'https://ark.ap-southeast.bytepluses.com/api/v3',
});
});
@@ -140,6 +141,7 @@ describe('BytePlusImageProvider construction', () => {
});
expect(openAICtor).toHaveBeenCalledWith({
apiKey: 'test-key',
fetch: expect.any(Function),
baseURL: 'https://ark.eu-west.bytepluses.com/api/v3',
});
});
@@ -636,7 +638,7 @@ describe('BytePlusImageProvider.generate response handling', () => {
generateMock.mockResolvedValueOnce({ data: [{}] });
await expect(
withTestActor(() => makeProvider().generate({ prompt: 'hi' })),
).rejects.toThrow(/Failed to extract image URL/);
).rejects.toThrow(/unexpected response/);
expect(batchIncrementUsagesSpy).not.toHaveBeenCalled();
});
});
@@ -19,7 +19,9 @@
import { assertImagePrompt } from '../../../interfaces/image/imageValidation.js';
import { OpenAI } from 'openai';
import { imageDataUri } from '../../../interfaces/image/imageOutput.js';
import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js';
import { imageEntryUrl } from '../../../interfaces/image/imageOutput.js';
import { malformedUpstreamResponse } from '../../../../util/upstreamErrors.js';
import { closestAspectRatio } from '../../../interfaces/image/imageDimensions.js';
import type { ImageSize } from '../../../interfaces/image/types.js';
import { Context } from '../../../../../core/context.js';
@@ -90,6 +92,7 @@ export class BytePlusImageProvider implements IImageProvider {
this.#meteringService = meteringService;
this.#client = new OpenAI({
apiKey: config.apiKey,
fetch: jsonCheckedFetch,
baseURL:
config.apiBaseUrl ??
'https://ark.ap-southeast.bytepluses.com/api/v3',
@@ -200,30 +203,24 @@ export class BytePlusImageProvider implements IImageProvider {
OpenAI['images']['generate']
>[0])) as ArkImageResponse;
const first = response.data?.[0];
const first = response?.data?.[0];
if (first?.error) {
throw new HttpError(
400,
first.error.message ?? 'Image generation failed',
typeof first.error.message === 'string'
? first.error.message
: 'Image generation failed',
{
legacyCode: 'upstream_failed',
fields: { provider: 'byteplus' },
},
);
}
const url =
first?.url ||
(first?.b64_json
? imageDataUri(
first.b64_json,
`image/${first.output_format ?? 'jpeg'}`,
)
: undefined);
if (!url) {
throw new Error(
'Failed to extract image URL from BytePlus response',
);
}
const url = imageEntryUrl(
first,
`image/${typeof first?.output_format === 'string' ? first.output_format : 'jpeg'}`,
);
if (!url) throw malformedUpstreamResponse('byteplus', 'BytePlus');
const usageEntries = [
{
@@ -24,6 +24,7 @@ import type { AiMeteringService } from '../../../../../util/aiCostFactor.js';
import { klingImageInput, klingRequest } from '../kling.js';
import {
CONTENT_FILTER_PATTERN,
malformedUpstreamResponse,
sanitizeUpstreamMessage,
} from '../../../../util/upstreamErrors.js';
import { JobHold, pollUntilSettled } from '../../../shared/polling.js';
@@ -221,8 +222,8 @@ export class KlingImageProvider implements IImageProvider {
throw this.#taskFailure(task.task_status_msg);
}
const url = task.task_result?.images?.[0]?.url;
if (!url) {
throw new Error('Kling response did not include an image URL');
if (typeof url !== 'string' || !url) {
throw malformedUpstreamResponse('kling', 'Kling');
}
return url;
} finally {
@@ -236,8 +237,7 @@ export class KlingImageProvider implements IImageProvider {
*/
#taskFailure(message: string | undefined): HttpError {
const detail =
sanitizeUpstreamMessage(message ?? '') ||
'Kling image generation failed';
sanitizeUpstreamMessage(message) || 'Kling image generation failed';
const fields = { provider: 'kling' };
if (CONTENT_FILTER_PATTERN.test(detail)) {
return new HttpError(400, detail, {
@@ -158,12 +158,12 @@ export async function klingRequest<T>(
if (!response.ok || (code !== undefined && code !== 0)) {
throw klingError(
code,
envelope.message ||
(typeof envelope.message === 'string' && envelope.message) ||
`Kling request failed (status ${response.status})`,
response.status,
);
}
if (envelope.data === undefined) {
if (!envelope.data || typeof envelope.data !== 'object') {
throw klingError(undefined, 'Kling response had no data', 502);
}
return envelope.data;
@@ -143,7 +143,10 @@ describe('OpenAiImageProvider construction', () => {
it('constructs the OpenAI SDK with the configured api key', () => {
makeProvider();
expect(openAICtor).toHaveBeenCalledTimes(1);
expect(openAICtor).toHaveBeenCalledWith({ apiKey: 'test-key' });
expect(openAICtor).toHaveBeenCalledWith({
apiKey: 'test-key',
fetch: expect.any(Function),
});
});
});
@@ -19,7 +19,8 @@
import { assertImagePrompt } from '../../../interfaces/image/imageValidation.js';
import { closestAspectRatio } from '../../../interfaces/image/imageDimensions.js';
import { imageDataUri } from '../../../interfaces/image/imageOutput.js';
import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js';
import { imageEntryUrl } from '../../../interfaces/image/imageOutput.js';
import openai, { OpenAI, toFile } from 'openai';
import {
ImageEditParamsNonStreaming,
@@ -101,6 +102,7 @@ export class OpenAiImageProvider implements IImageProvider {
this.#meteringService = meteringService;
this.#openai = new openai.OpenAI({
apiKey: config.apiKey,
fetch: jsonCheckedFetch,
});
}
@@ -299,11 +301,7 @@ export class OpenAiImageProvider implements IImageProvider {
);
}
const url =
result.data?.[0]?.url ||
(result.data?.[0]?.b64_json
? imageDataUri(result.data[0].b64_json)
: null);
const url = imageEntryUrl(result?.data?.[0]);
if (!url) {
throw new HttpError(
@@ -320,7 +318,7 @@ export class OpenAiImageProvider implements IImageProvider {
}
#extractUsage(result: ImagesResponse): OpenAIImageUsage {
const usage = (result.usage ?? {}) as ImagesResponse.Usage &
const usage = (result?.usage ?? {}) as ImagesResponse.Usage &
Record<string, unknown>;
const inputTokens = this.#toSafeCount(usage.input_tokens);
const outputTokens = this.#toSafeCount(usage.output_tokens);
@@ -31,6 +31,7 @@ import sharp from 'sharp';
import type { Actor } from '../../../../../core/actor.js';
import { Context } from '../../../../../core/context.js';
import { HttpError } from '../../../../../core/http/HttpError.js';
import { convertsToText } from '../../../shared/scalarOptions.js';
import { insufficientCreditsError } from '../../../../../services/metering/enforcement.js';
import {
type CreditHold,
@@ -462,7 +463,7 @@ export class ReplicateImageGenerationProvider implements IImageProvider {
) {
if (signal?.aborted) throw aborted();
throw new Error(
`Prediction failed: ${prediction.error || prediction.status}`,
`Prediction failed: ${typeof prediction.error === 'string' && prediction.error ? prediction.error : prediction.status}`,
);
}
output = prediction.output;
@@ -944,7 +945,8 @@ export class ReplicateImageGenerationProvider implements IImageProvider {
const url = this.#extractUrl(object[key]);
if (url) return url;
}
const value = String(output);
// A file output prints as its URL.
const value = convertsToText(output) ? String(output) : '';
if (/^https?:\/\//.test(value)) return value;
}
return undefined;
@@ -18,6 +18,7 @@
*/
import { HttpError } from '../../../../../core/http/HttpError.js';
import { convertsToText } from '../../../shared/scalarOptions.js';
import {
closestAspectRatio,
expandAspectRatio,
@@ -174,6 +175,8 @@ export function buildCatalogInput(
if (tierKey) input[tierKey] = params.quality;
}
if (params.output_megapixels != null) {
if (!convertsToText(params.output_megapixels))
throw badRequest('`output_megapixels` is not a usable value');
const key = schema.output_megapixels
? 'output_megapixels'
: schema.megapixels
@@ -110,7 +110,10 @@ describe('TogetherImageProvider construction', () => {
it('constructs the Together SDK with the configured api key', () => {
makeProvider();
expect(togetherCtor).toHaveBeenCalledTimes(1);
expect(togetherCtor).toHaveBeenCalledWith({ apiKey: 'test-key' });
expect(togetherCtor).toHaveBeenCalledWith({
apiKey: 'test-key',
fetch: expect.any(Function),
});
});
it('throws when no apiKey is supplied', () => {
@@ -22,7 +22,8 @@ import {
closestAspectRatio,
expandAspectRatio,
} from '../../../interfaces/image/imageDimensions.js';
import { imageDataUri } from '../../../interfaces/image/imageOutput.js';
import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js';
import { imageEntryUrl } from '../../../interfaces/image/imageOutput.js';
import { Together } from 'together-ai';
import { Context } from '../../../../../core/context.js';
import type { AiMeteringService } from '../../../../../util/aiCostFactor.js';
@@ -77,7 +78,10 @@ export class TogetherImageProvider implements IImageProvider {
throw new Error('Together AI image generation requires an API key');
}
this.#meteringService = meteringService;
this.#client = new Together({ apiKey: config.apiKey });
this.#client = new Together({
apiKey: config.apiKey,
fetch: jsonCheckedFetch,
});
}
models(): TogetherImageModel[] {
@@ -287,13 +291,7 @@ export class TogetherImageProvider implements IImageProvider {
);
}
const first = response.data[0] as {
url?: string;
b64_json?: string;
};
const url =
first.url ||
(first.b64_json ? imageDataUri(first.b64_json) : undefined);
const url = imageEntryUrl(response?.data?.[0]);
if (!url) {
throw new HttpError(
@@ -135,6 +135,7 @@ describe('XAIImageProvider construction', () => {
expect(openAICtor).toHaveBeenCalledTimes(1);
expect(openAICtor).toHaveBeenCalledWith({
apiKey: 'test-key',
fetch: expect.any(Function),
baseURL: 'https://api.x.ai/v1',
});
});
@@ -485,7 +486,7 @@ describe('XAIImageProvider.generate success path', () => {
prompt: 'a small red dot',
}),
),
).rejects.toThrow(/Failed to extract image URL/);
).rejects.toThrow(/unexpected response/);
// Failure path must NOT meter usage.
expect(batchIncrementUsagesSpy).not.toHaveBeenCalled();
@@ -18,7 +18,9 @@
*/
import { assertImagePrompt } from '../../../interfaces/image/imageValidation.js';
import { imageDataUri } from '../../../interfaces/image/imageOutput.js';
import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js';
import { imageEntryUrl } from '../../../interfaces/image/imageOutput.js';
import { malformedUpstreamResponse } from '../../../../util/upstreamErrors.js';
import { OpenAI } from 'openai';
import { formatAspectRatio } from '../../../interfaces/image/imageDimensions.js';
import { Context } from '../../../../../core/context.js';
@@ -64,6 +66,7 @@ export class XAIImageProvider implements IImageProvider {
this.#meteringService = meteringService;
this.#client = new OpenAI({
apiKey: config.apiKey,
fetch: jsonCheckedFetch,
baseURL: 'https://api.x.ai/v1',
});
this.#catalog = cachedRemoteCatalog({
@@ -184,16 +187,8 @@ export class XAIImageProvider implements IImageProvider {
OpenAI['images']['generate']
>[0])) as XaiImageResponse);
const first = response.data?.[0];
const url =
first?.url ||
(first?.b64_json ? imageDataUri(first.b64_json) : undefined);
if (!url) {
throw new Error(
'Failed to extract image URL from xAI response',
);
}
const url = imageEntryUrl(response?.data?.[0]);
if (!url) throw malformedUpstreamResponse('xai', 'xAI');
const usageEntries = [
{