From db772d7df99e9b193ff7ae311b4feca41a5b8fc3 Mon Sep 17 00:00:00 2001 From: tbxark Date: Sun, 29 Sep 2024 11:39:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=94=AF=E6=8C=81workers=20ai=20base64?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=9B=BE=E7=89=87=20#293?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/agent/workersai.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) 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' }); + } +} +