v1-images-generations API の JavaScript (Node.js) クイックスタートガイド
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2025年01月24日(金)
Table of Contents
Heroku Managed Inference and Agent アドオンは現在パイロット段階です。パイロットの一環として提供される製品は本番環境での使用を目的としたものではなく、ベータサービスとみなされています。また、https://www.salesforce.com/company/legal/agreements.jsp のベータサービス条件が適用されます。
Stability AI Stable Image Ultra (stability-image-ultra
) モデルを使用すると、説明的なテキストプロンプトから高品質かつ精細な画像を生成できます。このガイドでは、JavaScript を使用して v1-images-generations API にアクセスする方法について説明します。
前提条件
リクエストを行う前に、選択したモデルへのアクセスをプロビジョニングします。
まだインストールされていない場合は、Heroku CLI をインストールします。次に、Heroku AI プラグインをインストールします。
heroku plugins:install @heroku/plugin-ai
画像モデルをアプリにアタッチします。
# 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
必要な
axios
パッケージをインストールします。npm install axios
JavaScript のサンプルコード
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);