Skip to content

Commit

Permalink
fix: 支持workers ai base64格式图片 #293
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Sep 29, 2024
1 parent b7869b1 commit db772d7
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/agent/workersai.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<Blob> {
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' });
}
}

0 comments on commit db772d7

Please sign in to comment.