diff --git a/src/agent/workersai.ts b/src/agent/workersai.ts index b098e979..680ad26e 100644 --- a/src/agent/workersai.ts +++ b/src/agent/workersai.ts @@ -1,7 +1,7 @@ import type { AgentUserConfig } from '../config/env'; -import type { ChatAgent, ChatStreamTextHandler, HistoryItem, ImageAgent, LLMChatParams } from './types'; import type { SseChatCompatibleOptions } from './request'; -import { requestChatCompletions } from './request'; +import type { ChatAgent, ChatStreamTextHandler, HistoryItem, ImageAgent, LLMChatParams } from './types'; +import { isJsonResponse, requestChatCompletions } from './request'; class WorkerBase { readonly name = 'workers'; @@ -83,6 +83,26 @@ export class WorkersImage extends WorkerBase implements ImageAgent { throw new Error('Cloudflare account ID or token is not set'); } const raw = await this.run(context.WORKERS_IMAGE_MODEL, { prompt }, id, token); + if (isJsonResponse(raw)) { + const { result } = await raw.json(); + const image = result?.image; + if (typeof image !== 'string') { + throw new TypeError('Invalid image response'); + } + return base64StringToBlob(image); + } return await raw.blob(); }; } + +async function base64StringToBlob(base64String: string): Promise { + try { + const { Buffer } = await import('node:buffer'); + const buffer = Buffer.from(base64String, 'base64'); + return new Blob([buffer], { type: 'image/png' }); + } catch { + const uint8Array = Uint8Array.from(atob(base64String), c => c.charCodeAt(0)); + return new Blob([uint8Array], { type: 'image/png' }); + } +} +