type Openai = {
api_key: string;
organization_id: string;
};
type Base64 = string;
/**
* Create image variation
* Creates a variation of a given image.
*/
export async function main(
auth: Openai,
body: {
image: {
base64: Base64;
type:
| "image/png"
| "image/jpeg"
| "image/gif"
| "application/pdf"
| "appication/json"
| "text/csv"
| "text/plain"
| "audio/mpeg"
| "audio/wav"
| "video/mp4";
name: string;
};
model?: string | "dall-e-2";
n?: number;
response_format?: "url" | "b64_json";
size?: "256x256" | "512x512" | "1024x1024";
user?: string;
[k: string]: unknown;
}
) {
const url = new URL(`https://api.openai.com/v1/images/variations`);
const formData = new FormData();
for (const [k, v] of Object.entries(body)) {
if (v !== undefined && v !== "") {
if (["image"].includes(k)) {
const { base64, type, name } = v as {
base64: Base64;
type: string;
name: string;
};
formData.append(
k,
new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
type,
}),
name
);
} else {
formData.append(k, String(v));
}
}
}
const response = await fetch(url, {
method: "POST",
headers: {
"OpenAI-Organization": auth.organization_id,
Authorization: "Bearer " + auth.api_key,
},
body: formData,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`${response.status} ${text}`);
}
return await response.json();
}
Submitted by hugo697 392 days ago