JavaScript (Node.js) Quick Start Guide for v1-images-generations API
Last updated January 24, 2025
This article is a work in progress, or documents a feature that is not yet released to all users. This article is unlisted. Only those with the link can access it.
Table of Contents
The Heroku Managed Inference and Agent add-on is currently in pilot. The products offered as part of the pilot aren’t intended for production use and are considered as a Beta Service and are subject to the Beta Services terms at https://www.salesforce.com/company/legal/agreements.jsp.
The Stability AI Stable Image Ultra (stability-image-ultra
) model allows you to generate high-quality, detailed images from descriptive text prompts. This guide details how to access the v1-images-generations API using JavaScript.
Prerequisites
Before making requests, provision access to the model of your choice.
If it’s not already installed, install the Heroku CLI. Then install the Heroku AI plugin:
heroku plugins:install @heroku/plugin-ai
Attach the image model to an app of yours:
# If you don't have an app yet, you can create one with: heroku create $APP_NAME # specify the name you want for your app (or skip this step to use an existing app you have) # Create and attach one of our image models to your app, $APP_NAME: heroku ai:models:create -a $APP_NAME stability-image-ultra --as DIFFUSION
Install the necessary
axios
package:npm install axios
JavaScript Example Code
const axios = require('axios');
const fs = require('fs');
const { exec } = require('child_process');
// Assert that environment variables are set
const DIFFUSION_URL = process.env.DIFFUSION_URL;
const DIFFUSION_KEY = process.env.DIFFUSION_KEY;
const DIFFUSION_MODEL_ID = process.env.DIFFUSION_MODEL_ID;
if (!DIFFUSION_URL || !DIFFUSION_KEY || !DIFFUSION_MODEL_ID) {
console.error("Missing required environment variables.");
console.log("Set them up using the following commands:");
console.log("export DIFFUSION_URL=$(heroku config:get -a $APP_NAME DIFFUSION_URL)");
console.log("export DIFFUSION_KEY=$(heroku config:get -a $APP_NAME DIFFUSION_KEY)");
console.log("export DIFFUSION_MODEL_ID=$(heroku config:get -a $APP_NAME DIFFUSION_MODEL_ID)");
process.exit(1);
}
async function parseImageOutput(response, payload, filename = null) {
if (response.status === 200) {
if (payload.response_format === "base64") {
filename = filename || `${payload.prompt.slice(0, 20).replace(/ /g, "_").toLowerCase()}.png`;
fs.writeFileSync(filename, response.data.data[0].b64_json, 'base64');
console.log(`Image saved as ${filename}`);
// Automatically open the image after saving
openImage(filename);
} else {
console.log("Download the image from:", response.data.data[0].url);
}
} else {
console.log(`Request failed: ${response.status}, ${response.statusText}`);
}
}
function openImage(filename) {
const platform = process.platform;
let command;
if (platform === 'darwin') { // macOS
command = `open ${filename}`;
} else if (platform === 'win32') { // Windows
command = `start ${filename}`;
} else if (platform === 'linux') { // Linux
command = `xdg-open ${filename}`;
}
if (command) {
exec(command, (error) => {
if (error) {
console.error(`Failed to open image: ${error.message}`);
} else {
console.log(`Opened image: ${filename}`);
}
});
} else {
console.log("Automatic image opening is not supported on this platform.");
}
}
async function generateImage(payload, filename = null) {
try {
const response = await axios.post(`${DIFFUSION_URL}/v1/images/generations`, payload, {
headers: {
'Authorization': `Bearer ${DIFFUSION_KEY}`,
'Content-Type': 'application/json'
}
});
await parseImageOutput(response, payload, filename);
} catch (error) {
console.error("Error generating image:", error.message);
}
}
// Example payload
const payload = {
model: DIFFUSION_MODEL_ID,
prompt: "A surreal landscape with glowing mushrooms under a night sky.",
aspect_ratio: "16:9",
output_format: "png",
seed: 123,
negative_prompt: "crowded, noisy, chaotic"
};
// Generate image
generateImage(payload);