aiwrapper
Version:
A Universal AI Wrapper for JavaScript & TypeScript
172 lines (171 loc) • 6.78 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { LangMessages } from "../lang/messages.js";
import { httpRequestWithRetry as fetch } from "../http-request.js";
class OpenAIImg {
constructor(options) {
__publicField(this, "_apiKey");
__publicField(this, "_model");
__publicField(this, "_baseURL");
this._apiKey = options.apiKey;
this._model = options.model || "gpt-image-1";
this._baseURL = options.baseURL || "https://api.openai.com/v1";
}
async generate(prompt, options) {
var _a;
const messages = new LangMessages();
messages.addUserMessage(`Generate image: ${prompt}`);
const result = messages;
const body = __spreadValues(__spreadValues({
model: this._model,
prompt,
n: 1
}, (options == null ? void 0 : options.size) ? { size: options.size } : {}), (options == null ? void 0 : options.quality) ? { quality: options.quality } : {});
const response = await fetch(`${this._baseURL}/images/generations`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this._apiKey}`
},
body: JSON.stringify(body)
});
const json = await response.json();
const dataItem = (_a = json == null ? void 0 : json.data) == null ? void 0 : _a[0];
if (!dataItem) throw new Error("No image data");
result.finished = true;
return result;
}
async edit(params) {
var _a;
const messages = new LangMessages();
messages.addUserMessage(`Edit image: ${params.prompt}`);
const result = messages;
const form = await this.buildImageEditForm(__spreadValues({ model: this._model }, params));
const response = await fetch(`${this._baseURL}/images/edits`, {
method: "POST",
headers: { Authorization: `Bearer ${this._apiKey}` },
body: form
});
const json = await response.json();
const dataItem = (_a = json == null ? void 0 : json.data) == null ? void 0 : _a[0];
if (!dataItem) throw new Error("No image data");
result.finished = true;
return result;
}
async vary(params) {
var _a;
const messages = new LangMessages();
messages.addUserMessage("Vary image");
const result = messages;
const form = await this.buildImageVariationForm(__spreadValues({ model: this._model }, params));
const response = await fetch(`${this._baseURL}/images/variations`, {
method: "POST",
headers: { Authorization: `Bearer ${this._apiKey}` },
body: form
});
const json = await response.json();
const dataItem = (_a = json == null ? void 0 : json.data) == null ? void 0 : _a[0];
if (!dataItem) throw new Error("No image data");
result.finished = true;
return result;
}
// Helpers
async buildImageEditForm(args) {
const form = new FormData();
form.append("model", args.model);
form.append("prompt", args.prompt);
const img = await this.imageInputToBlob(args.image);
form.append("image", img, this.blobFilename(img.type));
if (args.mask) {
const mask = await this.imageInputToBlob(args.mask);
if (mask.type !== "image/png") throw new Error("Mask must be PNG with transparency");
form.append("mask", mask, this.blobFilename(mask.type));
}
if (args.size) form.append("size", args.size);
if (args.n) form.append("n", String(args.n));
if (args.quality) form.append("quality", args.quality);
return form;
}
async buildImageVariationForm(args) {
const form = new FormData();
form.append("model", args.model);
const img = await this.imageInputToBlob(args.image);
form.append("image", img, this.blobFilename(img.type));
if (args.size) form.append("size", args.size);
if (args.n) form.append("n", String(args.n));
if (args.quality) form.append("quality", args.quality);
return form;
}
async imageInputToBlob(image) {
var _a, _b;
const kind = image.kind;
if (kind === "url") {
const url = image.url;
const res = await fetch(url, { method: "GET" });
const arrayBuffer = await res.arrayBuffer();
const contentType = ((_b = (_a = res.headers) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "content-type")) || this.guessMimeFromUrl(url) || "image/png";
return new Blob([arrayBuffer], { type: contentType });
}
if (kind === "base64") {
const base64 = image.base64;
const mimeType = image.mimeType || "image/png";
const buf = Buffer.from(base64, "base64");
const arrayBuffer = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
return new Blob([arrayBuffer], { type: mimeType });
}
if (kind === "bytes") {
const bytes = image.bytes;
const mimeType = image.mimeType || "application/octet-stream";
const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
const arrayBuffer = arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);
return new Blob([arrayBuffer], { type: mimeType });
}
if (kind === "blob") {
const blob = image.blob;
const mimeType = image.mimeType || blob.type || "application/octet-stream";
return mimeType && mimeType !== blob.type ? new Blob([await blob.arrayBuffer()], { type: mimeType }) : blob;
}
throw new Error("Unknown LangImageInput kind");
}
blobFilename(mime) {
switch (mime) {
case "image/png":
return "image.png";
case "image/jpeg":
return "image.jpg";
case "image/webp":
return "image.webp";
case "image/gif":
return "image.gif";
default:
return "image.bin";
}
}
guessMimeFromUrl(url) {
const lower = url.toLowerCase();
if (lower.endsWith(".png")) return "image/png";
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
if (lower.endsWith(".webp")) return "image/webp";
if (lower.endsWith(".gif")) return "image/gif";
return void 0;
}
}
export {
OpenAIImg
};
//# sourceMappingURL=openai-img.js.map