OpenAI #Images: Generate

OpenAI #Images: Generate

translate OpenAI #Images: 生成

Creates an image given a PROMPT text by the “DALL-E 3 MODEL” via OpenAI API. By default a 1024×1024 image is generated, but 1024×1792 or 1792×1024 are also available. Note that the PROMPT text must be defined within 4000 characters.

Auto Step icon
Configs for this Auto Step
AuthzConfU1
U1: Select HTTP_Authz Setting (Secret API Key as “Fixed Value”) *
StrConfA1
A1: Set Request Message PROMPT *#{EL}
SelectConfB1
B1: Select FILE that stores Generated Image (update)
StrConfM
M: Set MODEL Name (default “dall-e-3”)#{EL}
StrConfU2
U2: Set OpenAI Organization ID (“org-xxxx”)#{EL}
StrConfU3
U3: Set End-User ID for Monitoring or Detecting (“user123456”)#{EL}
StrConfA3
A3: Set SIZE (“1024×1024”:default, “1792×1024” or “1024×1792”)#{EL}
StrConfA4
A4: Set Quality of Image (“hd”:default or “standard”)#{EL}
StrConfA5
A5: Set Style of Image (“vivid”:default or “natural”)#{EL}
SelectConfB2
B2: Select FILE that stores Generated Image (append)
StrConfC1
C1: To save-as, Set new File Name (new line delimited)#{EL}
Script (click to open)
// Script Example of Business Process Automation
// for 'engine type: 3' ("GraalJS standard mode")
// cf. 'engine type: 2' ("GraalJS Nashorn compatible mode") (renamed from "GraalJS" at 20230526)

//////// START "main()" /////////////////////////////////////////////////////////////////

main();
function main(){ 

////// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzSetting   = configs.get ( "AuthzConfU1" );             /// REQUIRED
  engine.log( " AutomatedTask Config: Authz Setting: " + strAuthzSetting );
const strOrgId          = configs.get ( "StrConfU2" );               // NotRequired
  engine.log( " AutomatedTask Config: OpenAI-Organization: " + strOrgId );
const strEndUserId      = configs.get ( "StrConfU3" ) !== "" ?       // NotRequired
                          configs.get ( "StrConfU3" ) :
                          "m" + processInstance.getProcessModelInfoId().toString(); // (default)
  engine.log( " AutomatedTask Config: End User IDs: " + strEndUserId );
const strModel          = configs.get ( "StrConfM" ) !== "" ?        // NotRequired
                          configs.get ( "StrConfM" ) : "dall-e-3";   // (default)
  engine.log( " AutomatedTask Config: OpenAI Model: " + strModel );

const strPrompt         = configs.get ( "StrConfA1" );               /// REQUIRED
  if( strPrompt       === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A1: Prompt} required \n" );
  }
const strSize           = configs.get ( "StrConfA3" ) !== "" ?       // NotRequired
                          configs.get ( "StrConfA3" ) : "1024x1024"; // (default)
const strQuality        = configs.get ( "StrConfA4" ) !== "" ?       // NotRequired
                          configs.get ( "StrConfA4" ) : "hd";        // (default)
const strStyle          = configs.get ( "StrConfA5" ) !== "" ?       // NotRequired
                          configs.get ( "StrConfA5" ) : "vivid";     // (default)

const filesPocketUpdate = configs.getObject( "SelectConfB1" ); // NotRequired
  let filesUpdate       = new java.util.ArrayList();
const filesPocketAppend = configs.getObject( "SelectConfB2" ); // NotRequired
  let filesAppend       = new java.util.ArrayList();
  if ( filesPocketAppend !== null ) {
    if ( engine.findData( filesPocketAppend ) !== null ) {
      filesAppend       = engine.findData( filesPocketAppend ); // java.util.ArrayList
      engine.log( " AutomatedTask FilesArray {B2}: " +
                  filesAppend.size() + " files" );
    }
  }
const strFileNames      = configs.get( "StrConfC1" );           // NotRequired
const arrFileNames      = strFileNames === "" ?
                          [] : strFileNames.split( '\n' );



////// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Retrieved via Expression Language in Config Retrieving)



////// == Calculating / 演算 ==

//// OpenAI API > Documentation > API REFERENCE > IMAGES
//// https://platform.openai.com/docs/api-reference/images/create

/// prepare json
let strJson = {};
    strJson.prompt          = strPrompt;
    strJson.model           = strModel;
    strJson.size            = strSize;
    strJson.response_format = "url";
    strJson.user            = strEndUserId;
    strJson.quality         = strQuality;
    strJson.style           = strStyle;

/// prepare request1
let request1Uri = "https://api.openai.com/v1/images/generations";
let request1 = httpClient.begin(); // HttpRequestWrapper
    request1 = request1.authSetting( strAuthzSetting ); // with "Authorization: Bearer XX"
    if ( strOrgId !== "" ){
      request1 = request1.header( "OpenAI-Organization", strOrgId );
    }
    request1 = request1.body( JSON.stringify( strJson ), "application/json" );

/// try request1
const response1     = request1.post( request1Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest1 Start: " + request1Uri );
const response1Code = response1.getStatusCode() + ""; // JavaNum to string
const response1Body = response1.getResponseAsString();
engine.log( " AutomatedTask ApiResponse1 Status: " + response1Code );
if( response1Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response1Code + "\n" + response1Body + "\n" );
}

/// parse response1
/* engine.log( response1Body ); // debug
{
  "created": 1682927558,
  "data": [
    {
      "revised_prompt": "A Japanese woman with ...",
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-sWMNK..."
    }
  ]
}
*/
const response1Obj = JSON.parse( response1Body );
engine.log( " AutomatedTask OpenAI #created: " + response1Obj.created );

for ( let i = 0; i < response1Obj.data.length; i++ ) {

  /// prepare request2
  let request2Uri = response1Obj.data[i].url;
  let request2 = httpClient.begin(); // HttpRequestWrapper

  /// try request2i
  const response2     = request2.get( request2Uri ); // HttpResponseWrapper
  engine.log( " AutomatedTask ApiRequest2 Start: " + request2Uri );
  const response2Code = response2.getStatusCode() + ""; // JavaNum to string
  engine.log( " AutomatedTask ApiResponse2 Status: " + response2Code );
  if( response2Code !== "200"){
    throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                      response2Code + "\n" + response2.getResponseAsString() + "\n" );
  }

  /// save file
  let strName = arrFileNames[i] ?? "";
  if ( strName === "" ) {
    strName = processInstance.getProcessInstanceId().toString() +
            "-" + i + ".png";
  }
  const qfileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
    strName, response2.getContentType(), response2.getResponse()
  );
  // NewQfile ( stringFileName, stringContentType, ByteArray )

  filesUpdate.add( qfileTmp );
  filesAppend.add( qfileTmp );

}



////// == Data Updating / ワークフローデータへの代入 ==

if( filesPocketUpdate !== null ){
  engine.setData( filesPocketUpdate, filesUpdate );
}
if( filesPocketAppend !== null ){
  engine.setData( filesPocketAppend, filesAppend );
}

} //////// END "main()" /////////////////////////////////////////////////////////////////


/*
Notes:
- This [Automated Step] obtains the Image via OpenAI API (Chat endpoint).
    - Num of images: Only n=1 is supported in this [Automated Step]. (asof 202311 Dalle3 version)
    - To generate by "DALL-E 2", use the older version.
    - https://support.questetra.com/addons/openai-images-generate-2023/
- If place this [Automated Atep] in the workflow diagram, communication will occur every time a process arrives.
    - Request from the Questetra BPM Suite server to the OpenAI server.
    - Analyzes the response from the OpenAI server and stores the necessary information.
- [HTTP Authz Settings] is required for workflow apps that include this [Automated Step].
    - An API key is required to use OpenAI API. Please obtain an API key in advance.
        - https://platform.openai.com/api-keys
    - Set 'Secret API Key' as communication token. [HTTP Authz Settings] > [Token Fixed Value]

APPENDIX
- Image Quality
    - "hd" or "standard" can be set.
    - "hd" creates images with finer details and greater consistency across the image.
- Image style
    - "vivid" or "natural" can be set.
    - "vivid" causes the MODEL to lean towards generating hyper-real and dramatic images. 
    - "natural" causes the MODEL to produce more natural, less hyper-real looking images.
- Timeout errors often occur.
    - A script error has occurred. `java.util.concurrent.TimeoutException`

Notes-ja:
- この[自動工程]は、OpenAI API (Chat エンドポイント)を通じて、生成画像を取得します。
    - この[自動工程](Dalle3版)で生成できる枚数は1枚です。(2023年11月現在)
    - "DALL-E 2" で生成させたい場合は、旧版をご利用ください。
    - https://support.questetra.com/ja/addons/openai-images-generate-2023/
- この[自動工程]をワークフロー図に配置すれば、案件到達の度に通信が発生します。
    - Questetra BPM Suite サーバから OpenAI サーバに対してリクエストします。
    - OpenAI サーバからのレスポンスを解析し、必要情報を格納します。
- この[自動工程]を含むワークフローアプリには、[HTTP 認証設定]が必要です。
    - OpenAI API の利用には API key が必要です。あらかじめ API Key を取得しておいてください。
        - https://platform.openai.com/api-keys
    - 'Secret API Key' を通信トークンとしてセットします。[HTTP 認証設定]>[トークン直接指定]

APPENDIX-ja
- 画像クオリティ
    - "hd" と "standard" のいずれかが設定可能です。
    - "hd" を指定することで、画像全体に渡り、より詳細で、より一貫性の高い画像が生成されます。 
- 画像スタイル
    - "vivid" と "natural" のいずれかが設定可能です。
    - "vivid" (鮮やか) を設定すると、リアルすぎる画像/ドラマチックな画像が生成される傾向になります。
    - "natural" を設定すると、自然な画像/リアルすぎない画像が生成される傾向になります。
- タイムアウトエラーが起きる場合があります。
    - スクリプトエラーが発生しました。 `java.util.concurrent.TimeoutException`

*/

Download

warning Freely modifiable JavaScript (ECMAScript) code. No warranty of any kind.
(Installing Addon Auto-Steps are available only on the Professional edition.)

Notes

  • This [Automated Step] obtains the Image via OpenAI API (Chat endpoint).
  • If place this [Automated Atep] in the workflow diagram, communication will occur every time a process arrives.
    • Request from the Questetra BPM Suite server to the OpenAI server.
    • Analyzes the response from the OpenAI server and stores the necessary information.
  • [HTTP Authz Settings] is required for workflow apps that include this [Automated Step].
    • An API key is required to use OpenAI API. Please obtain an API key in advance.
    • Set ‘Secret API Key’ as the communication token. [HTTP Authz Settings] > [Token Fixed Value]

Capture

Creates an image given a PROMPT text by the "DALL-E 3 MODEL" via OpenAI API. By default a 1024x1024 image is generated, but 1024x1792 or 1792x1024 are also available. Note that PROMPT must be defined within 4000 characters.

Appendix

  • Image Quality
    • “hd” or “standard” can be set.
    • “hd” creates images with finer details and greater consistency across the image.
  • Image style
    • “vivid” or “natural” can be set.
    • “vivid” causes the MODEL to lean towards generating hyper-real and dramatic images.
    • “natural” causes the MODEL to produce more natural, less hyper-real looking images.
  • Timeout errors often occur.
    • A script error has occurred. java.util.concurrent.TimeoutException

See Also

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d