

OpenAI: Generate Image
This item generates an image using OpenAI’s model.
Basic Configs
- Step Name
- Note
Configs for this Auto Step
- conf_Auth
- C1: Authorization Setting in which Project API Key is set *
- conf_Model
- C2: Model *
- conf_Prompt
- C3: Prompt *#{EL}
- conf_Size
- C4: Image Size (auto if not selected)
- conf_Format
- C5: Image Format (PNG if not selected)
- conf_Quality
- C6: Image Quality (auto if not selected)
- conf_File
- C7: Data item to add the generated file *
- conf_FileName
- C8: File name to save as *#{EL}
Notes
- Project API Keys can be created here
- In [C2: Model], if you want to use a model that is not listed in the pull-down menu, select “Fixed Value” and enter the model name in the input field
- Model names should be written according to OpenAI documentation
- See the “Models” in the OpenAI Platform documentation
- Only those models which support image generation can be used
- Please refer to the details of each model’s details in the OpenAI documentation above
- Model names should be written according to OpenAI documentation
- Some options are only supported on certain models
- For more details, please refer to the OpenAI API Reference
See also
Script (click to open)
- An XML file that contains the code below is available to download
- openai-dalle-image-generate.xml (C) Questetra, Inc. (MIT License)
- If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step
function main() {
////// == 工程コンフィグ・ワークフローデータの参照 / Config & Data Retrieving ==
const auth = configs.getObject('conf_Auth'); /// REQUIRED
const model = retrieveModel();
const prompt = configs.get('conf_Prompt');
if (prompt === '') {
throw new Error('Prompt is empty.');
}
const size = retrieveSize();
const format = retrieveSelectItem('conf_Format');
const quality = retrieveSelectItem('conf_Quality');
const fileName = configs.get('conf_FileName');
if (fileName === '') {
throw new Error('File name is empty.');
}
////// == 演算 / Calculating ==
const newFile = generateImage(auth, model, prompt, size, format, quality, fileName);
saveFileData('conf_File', newFile);
}
/**
* config からモデル ID を読み出す
* モデル ID として不正な場合はエラー
* @return {String}
*/
const retrieveModel = () => {
const model = configs.get('conf_Model');
const reg = new RegExp('^[a-z0-9.-]+$');
if (!reg.test(model)) {
throw new Error('Model is invalid. It contains an invalid character.');
}
return model;
};
/**
* config からサイズを読み出す
* 形式: WIDTHxHEIGHT (例: 1024x1024)
* 指定なしの場合は undefined
* 形式が不正な場合はエラー
* 細かなバリデーションは API に任せ、ここではチェックしない
* @return {String}
*/
const retrieveSize = () => {
const size = retrieveSelectItem('conf_Size');
if (size === undefined) {
return undefined;
}
// 基本的な形式チェック: 数字x数字(1〜4桁)
const formatRegex = /^([1-9]\d{0,3})x([1-9]\d{0,3})$/;
if (!formatRegex.test(size)) {
throw new Error('Size is invalid. It must be WIDTHxHEIGHT.');
}
return size;
};
/**
* form-type="SELECT_ITEM" の設定値を取得する
* 空の場合、undefined を返す
* @param configName
* @returns {undefined|String}
*/
const retrieveSelectItem = (configName) => {
const value = configs.get(configName);
if (value === '') {
return undefined;
}
return value;
};
/**
* 画像生成
* @param auth
* @param model
* @param prompt
* @param size
* @param format
* @param quality
* @returns {String} answer1
*/
const generateImage = (auth, model, prompt, size, format, quality, fileName) => {
// https://platform.openai.com/docs/guides/safety-best-practices
// Sending end-user IDs in your requests can be a useful tool to help OpenAI monitor and detect abuse.
const user = `m${processInstance.getProcessModelInfoId().toString()}`;
/// prepare json
const requestJson = {
model,
prompt,
size,
output_format: format,
quality,
user,
n: 1,
};
const response = httpClient.begin().authSetting(auth)
.body(JSON.stringify(requestJson), 'application/json')
.post('https://api.openai.com/v1/images/generations');
const responseCode = response.getStatusCode();
const responseBody = response.getResponseAsString();
if (responseCode !== 200) {
engine.log(responseBody);
throw new Error(`Failed to request. status: ${responseCode}`);
}
const responseJson = JSON.parse(responseBody);
const usage = responseJson.usage;
engine.log(`Input Tokens: ${usage.input_tokens}`);
engine.log(`Output Tokens: ${usage.output_tokens}`);
engine.log(`Total Tokens: ${usage.total_tokens}`);
const image = base64.decodeFromStringToByteArray(responseJson.data[0].b64_json);
let contentType = "image/png";
if (format !== undefined) {
contentType = `image/${format}`;
}
return new com.questetra.bpms.core.event.scripttask.NewQfile(
fileName,
contentType,
image
);
};
/**
* データ項目への保存
* @param configName
* @param newFile
*/
const saveFileData = (configName, newFile) => {
const def = configs.getObject(configName);
if (def === null) {
return;
}
let files = engine.findData(def);
if (files === null) {
files = new java.util.ArrayList();
}
files.add(newFile);
engine.setData(def, files);
};




