Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Enhances image response handling for various providers
Implements provider-specific response formatting for image data.

Adds helper functions to identify image providers and format responses correctly based on the provider's requirements, ensuring proper handling of base64 image responses.

Improves the robustness of the image handling logic to adapt to different provider responses.
  • Loading branch information
unsync committed Jun 18, 2025
commit 09e3daa48d8bbeba5e404d1d7a227e45594bcab1
40 changes: 37 additions & 3 deletions src/handlers/retryHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import retry from 'async-retry';
import { MAX_RETRY_LIMIT_MS, POSSIBLE_RETRY_STATUS_HEADERS } from '../globals';
import {
MAX_RETRY_LIMIT_MS,
POSSIBLE_RETRY_STATUS_HEADERS,
SEGMIND,
WORKERS_AI,
} from '../globals';

async function fetchWithTimeout(
url: string,
Expand Down Expand Up @@ -103,8 +108,35 @@ export const retryRequest = async (

// custom code to handle image generation when the provider returns a image/ response
// Check if the response is an image and convert to base64 JSON
const getImageProvider = (url: string) => {
switch (new URL(url).host) {
case 'api.segmind.com':
return SEGMIND;
case 'api.cloudflare.com':
return WORKERS_AI;
default:
return undefined;
}
};
const formatResponse = (provider: string, base64Image: string) => {
switch (provider) {
case SEGMIND:
return {
image: base64Image,
};
case WORKERS_AI:
return {
result: {
image: base64Image,
},
};
default:
return {};
}
};
const contentType = response.headers.get('content-type');
if (contentType && contentType.startsWith('image/') && response.ok) {
const provider = getImageProvider(url);
if (provider && contentType?.startsWith('image/') && response.ok) {
const imageBuffer = await response.arrayBuffer();
// Simple ArrayBuffer to base64 conversion for environments like Cloudflare Workers
let binary = '';
Expand All @@ -114,7 +146,9 @@ export const retryRequest = async (
binary += String.fromCharCode(bytes[i]);
}
const base64Image = btoa(binary);
const jsonBody = JSON.stringify({ image: base64Image }); // Or format matching SegmindImageGenerateResponse if needed e.g. { data: [{b64_json: base64Image}], created: ... }
const jsonBody = JSON.stringify(
formatResponse(provider, base64Image)
); // Or format matching SegmindImageGenerateResponse if needed e.g. { data: [{b64_json: base64Image}], created: ... }
response = new Response(jsonBody, {
headers: {
// keep original headers
Expand Down