import { ImageGenerateParams } from "openai/resources"; import { VisionInterface } from "../../interfaces/Vision"; import OpenAI from "openai"; import { ImageParams, ImageResult, VideoParams, VideoResult } from "../../types/vision/vision"; import { VisionResultStream } from "../../utils/stream"; export class VisonOpenAIService implements VisionInterface { host: string; apiKey: string; openai: OpenAI; constructor(options?: { host?: string, apiKey?: string }) { this.host = options?.host || "https://api.openai.com/v1" this.apiKey = options?.apiKey || "" if (!this.apiKey) { throw new Error("apiKey is required") } this.openai = new OpenAI({ baseURL: this.host, apiKey: this.apiKey }) } async image(params: ImageGenerateParams & ImageParams): Promise> { const stream = new VisionResultStream() const timer = setInterval(() => { stream.write({ status: "processing", created_at: Date.now() } as ImageResult) }, 1000) this.openai.images.generate(params).then(result => { clearInterval(timer) stream.write( { status: "completed", created_at: Date.now(), data: result.data ? result.data.map(item => { return { format: item.url ? "url" : "b64_json", url: item.url || undefined, b64_json: item.b64_json || undefined } }) : [] } as ImageResult ) }).catch(err => { clearInterval(timer) stream.write({ status: "failed", created_at: Date.now(), message: err.message || err } as ImageResult) stream.end() }) return stream } video(params: VideoParams): Promise> { throw new Error("Method not implemented."); } }