$a.openai

📘

This section describes Appery.io wrapper around openai

Initialization

The $a.openai helper initializes automatically if the OpenAI API key is specified in the Settings service property openaiApiKey. If the key is not provided, the OpenAI helper can be initialized using the init method.

Settings service

This is a common Settings file (Create New -> Service -> Settings (REST settings)). Available settings are:

PropertyValueDescription
openaiApiKeysk-proj-sFq........k8OpenAI API Key

init

init(apikey, Apperyio): void

Initialize the openai helper.

Parameters

  • apikey - OpenAI API Key;
  • Apperyio - Apperyio helper;

Example

this.$a.openai.init(myKey, this.$a);

aioRequest

aioRequest(prompt, options?): Promise

Make a request to the model based on the provided context.

Parameters

  • prompt - the request to the model;
  • options - (optional). Available options are:
    • model - string. Optional. Defaults to gpt-4o. The model to use for answer generation.
    • format - object, array or string with description. Optional. Description of the format in which the response should be received (e.g., Yes or No) or an example of the response (e.g., [{name: "ingredient name", quantity: "gr, ml or pieces"}]).
    • image - File object, file selected on device or string (base64-encoded file content). Optional.

Returns

Promise with generated response.

Example

let res = await this.$a.openai.aioRequest(
  "What is ice cream made of?", 
  {format: [{name: "ingredient name", quantity: "gr, ml or pieces"}]}
)

createThread

createThread(): Promise

Create conversation thread.

Returns

Promise with thread object.

Example

let thread = await this.$a.openai.createThread();

createThreadMessage

createThreadMessage(threadId, message): Promise

Create message for particular thread (used toghether with runThread method).

Returns

The method does not return a value.

Example

this.$a.openai.createThreadMessage(
    this.thread.id, {
        role: "user",
        content: "My question"
    }
);

runThread

runThread(threadId, assistantId): Promise

Run particular thread.

Returns

Observable object.

Example

const chatObservable = this.$a.openai.runThread(this.thread.id, this.$a.getConfig("assistantId"));
this.isWait = true;

chatObservable.subscribe({
    next: (content: any) => {
        this.messages[this.messages.length - 1].content += content;
        this.$a.scrollBottom(this, {
            duration: 0,
            timeout: 0
        });
    },
    error: (e: any) => {
        this.isWait = false;
        this.$a.showError(e);
    },
    complete: () => {
        this.isWait = false;
    }
});

getClient

getClient(): OpenAI

Get raw OpenAI Client.

Returns

OpenAI Client or undefined if openai helper was not initialized.

Example

let openai = this.$a.openai.getClient();

generateImage

generateImage(prompt, options?): Promise

Generate an image based on the provided prompt.

Parameters

  • prompt - the request or description based on which the image should be generated;
  • options - (optional). Available options are:
    • model - string. Optional. Defaults to dall-e-3. The model to use for image generation.
    • n - number. Optional. Defaults to 1. The number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is supported.
    • quality - string. Optional. Defaults to standard. The quality of the image that will be generated. hd creates images with finer details and greater consistency across the image. This param is only supported for dall-e-3.
    • response_format - string. Optional. Defaults to url. The format in which the generated images are returned. Must be one of url or b64_json. URLs are only valid for 60 minutes after the image has been generated.
    • size - string. Optional. Defaults to 1024x1024. The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models.
    • style - string. Optional. Defaults to vivid. The style of the generated images. Must be one of vivid or natural. 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. This param is only supported for dall-e-3.

Returns

Promise with generated image(s).

If response_format is url then returned value is:

Promise<{
  created: number;
  data: Array<{
    revised_prompt: string;
    url: string;
  }>
}>

If response_format is b64_json then returned value is:

Promise<{
  created: number;
  data: Array<{
    revised_prompt: string;
    b64_json: string;
  }>
}>

Example

let images = await this.$a.openai.generateImage("Green cat an a round table");

rewrite

rewrite(prompt, options): String

Rewrite passed prompt

Returns

Rewrited text.

Example

let rewritedText = await this.$a.openai.rewrite("Hello world", {polite: true, englishLevel: "B1"})

translate

translate(text, options): String

Translate text

Returns

Translated text.

Example

let translatedText = await this.$a.openai.translate("Hello world", {from: "English", to: "Spain"})

createFile

createFile(file, purpose): Promise

Upload a file that can be used across various endpoints.

Parameters

  • file - base64-encoded file content;
  • purpose - string;

Returns

A promise with information about the uploaded file, including its unique identifier, which can be used for further operations.

Fields of the returned response:

  • id - Unique identifier of the uploaded file.
  • object - Type of the object, in this case, "file".
  • bytes - Size of the file in bytes.
  • created_at - File creation time (in Unix timestamp format).
  • filename - Name of the file.
  • purpose - Purpose of the file upload, e.g., "fine-tune".

tts

tts(text, options?): Promise

Generates audio from the input text.

Parameters

  • text - The text to generate audio for. The maximum length is 4096 characters.;
  • options - (optional). Available options are:
    • model - string. Optional. One of the available TTS models: tts-1 or tts-1-hd. Default is tts-1.
    • voice - string. Optional. The voice to use when generating the audio. Supported voices are alloy, echo, fable, onyx, nova, and shimmer. Default is alloy.
    • response_format - string. Optional. The format to audio in. Supported formats are mp3, opus, aac, flac, wav, and pcm. Default is mp3.
    • speed - number. Optional. The speed of the generated audio. Select a value from 0.25 to 4.0. 1.0 is the default.

Returns

Promise with the audio file content..

Example

let audio = await this.$a.openai.tts("Hi Joe!");

mathSolve

mathSolve(prompt): Promise

Solve math expression

Parameters

Math expression

Returns

JSON object in the following format

{
  steps: [
    {
      explanation: 'We start with the given equation:',
      output: '8x + 31 = 2'
    },
    {
      explanation: 'Subtract 31 from both sides to isolate the term with x.',
      output: '8x = 2 - 31'
    },
    {
      explanation: 'Simplify the subtraction on the right-hand side:',
      output: '8x = -29'
    },
    {
      explanation: 'Divide both sides by 8 to solve for x:',
      output: 'x = -\\frac{29}{8}'
    }
  ],
  final_answer: 'x = -\\frac{29}{8}'
}

Example

let res = await test.mathSolve("8x + 31 = 2")