This section describes Appery.io wrapper around openai.
More details are here.
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:
| Property | Value | Description |
|---|---|---|
| openaiApiKey | sk-proj-sFq........k8 | OpenAI 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);setDefaultConversation
setDefaultConversation(conversation): void
Parameters
- conversation - string with conversation ID or conversation object;
Set defaultConversation. defaultConversation is used in aioRequest and getConversationMessages methods for handling conversations if conversation is not specified.
getDefaultConversation
getDefaultConversation(): string|object
Get defaultConversation.
setDefaultPrompt
setDefaultPrompt(prompt): void
Parameters
- prompt - string with prompt ID or prompt object see reusable prompts
Set defaultPrompt. defaultPrompt is used in aioRequest method for handling prompts if prompt is not specified.
getDefaultPrompt
getDefaultPrompt(): object
Get defaultPrompt.
createConversation
createConversation(options?): ConversationObject
Create a conversation.
Parameters
- options - (optional). Available options are:
- items - array. Optional. Initial items to include in the conversation context. You may add up to 20 items at a time.
- metadata - object. Optional. Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long.
Returns
Returns a Conversation object.
getConversationMessages
getConversationMessages(options?): ConversationItemsList
List all items for a conversation with the given ID.
Parameters
- options - (optional). Available options are:
- conversationId - Optional. The ID of the conversation to list items for. If not specified defaultConversation is used.
- after - string. Optional. An item ID to list items after, used in pagination.
- limit - integer. Optional. A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.
- order - string. Optional. The order to return the input items in (**asc **or desc). Default is desc
Returns
Returns a list object containing Conversation items (see details).
aioRequest
aioRequest(prompt, options?): Promise
Make a request to the model based on the provided context.
Parameters
- prompt - the request to the model. String or Array of items (instructions and previous requests and answers)
- options - (optional). Available options are:
- model - string. Optional. Defaults to gpt-4o. The model to use for answer generation.
- prompt - string (prompt ID) or Prompt object. Optional. If it is not specified but defaultPrompt is provided, then defaultPrompt will be used.
- conversation - string (conversation ID) or Conversation object. Optional. The conversation that this response belongs to. Items from this conversation are prepended to input_items for this response request. Input items and output items from this response are automatically added to this conversation after this response completes. If it is not specified but defaultConversation is provided, then defaultConversation will be used.
- 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.
- stream - boolean. Optional. If true method will return Observable.
Returns
Promise with generated response or with Observable.
Example
let res = await this.$a.openai.aioRequest(
"What is ice cream made of?",
{format: [{name: "ingredient name", quantity: "gr, ml or pieces"}]}
)const chatObservable = await this.$a.openai.aioRequest(
"How can I make ice cream at home?",
{
prompt: {
"id": "pmpt_6914b0a47dd48196970fe646695f6af60c50d10123456789",
"version": "2"
},
stream: true
}
)
this.text = "";
chatObservable.subscribe({
next: (content: any) => {
// A new chunk of the response has been received.
this.text += content;
},
error: (e: any) => {
this.$a.showError(e);
},
complete: () => {
// Some actions to perform when the response is fully received.
}
});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 this.$a.openai.mathSolve("8x + 31 = 2")Deprecated methods
setDefaultAssistantId
Deprecated. The Assistant API is deprecated. Use Prompt and the setDefaultPrompt method instead.
setDefaultAssistantId(assistantId): void
Set defaultAssistantId. defaultAssistantId is used in methods for handling threads if assistantId is not specified.
getDefaultAssistantId
Deprecated. The Assistant API is deprecated. Use Prompt and the getDefaultPrompt method instead.
getDefaultAssistantId(): string
Get defaultAssistantId.
setDefaultThreadId
Deprecated. The Thread API is deprecated. Use Conversation and the setDefaultConversation method instead.
setDefaultThreadId(threadId): void
Set defaultThreadId. defaultThreadId is used in methods for handling threads if threadId is not specified.
getDefaultThreadId
Deprecated. The Thread API is deprecated. Use Conversation and the getDefaultConversation method instead.
getDefaultThreadId(): string
Get defaultThreadId.
createThread
Deprecated. The Thread API is deprecated. Use Conversation instead.
createThread(options?): Promise
Create conversation thread.
Parameters
- options - (optional). Available options are:
- messages - array. Optional. A list of messages to start the thread with.
- tool_resources - object or null. Optional. A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the code_interpreter tool requires a list of file IDs, while the file_search tool requires a list of vector store IDs.
- metadata - object. Optional. Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maximum of 512 characters long.
Returns
Promise with thread object.
Example
let thread = await this.$a.openai.createThread();createThreadMessage
Deprecated. The Thread API is deprecated. Use Conversation and the aioRequest method instead.
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
Deprecated. The Thread API is deprecated. Use the aioRequest method (with conversation, prompt and stream=true) instead.
runThread(options): Observable
Run particular thread.
Parameters
- options - (optional). Available options are:
- threadId - (optional). Thread Id. If not specified, the defaultThreadId will be used;
- assistantId - (optional). Assistant Id. If not specified, the defaultAssistantId will be used;
- model - (optional). string;
- instructions - (optional);
- additional_instructions - (optional);
- additional_messages - (optional). Adds additional messages to the thread before creating the run.
- tools - (optional);
- metadata - (optional);
- temperature - (optional) number. What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic;
- top_p - (optional);
- stream - (optional) boolean or null. If true, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a data: [DONE] message;
- max_prompt_tokens - (optional);
- max_completion_tokens - (optional);
- truncation_strategy - (optional);
- tool_choice - (optional);
- parallel_tool_calls - (optional);
- response_format - (optional) string or object. Specifies the format that the model must output. Compatible with GPT-4o, GPT-4 Turbo, and all GPT-3.5 Turbo models since gpt-3.5-turbo-1106. Setting to { "type": "json_schema", "json_schema": {...} } enables Structured Outputs which ensures the model will match your supplied JSON schema. Setting to { "type": "json_object" } enables JSON mode, which ensures the message the model generates is valid JSON.
If response_format is set to json_object, the response will return a JSON object instead of a string.
Returns
Observable object.
Example
const chatObservable = this.$a.openai.runThread({threadId: this.thread.id, assistantId: 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;
}
});runThreadPromise
Deprecated. The Thread API is deprecated. Use the aioRequest method (with conversation and prompt) instead.
runThreadPromise(options): Promise
The same as runThread, but it returns a Promise instead of an Observable.
Returns
Promise.
Example
const resp = await this.$a.openai.runThreadPromise();getThreadMessages
Deprecated. The Thread API is deprecated. Use Conversation and the getConversationMessages method instead.
getThreadMessages(options): Promise
Returns a list of messages for a given thread.
Parameters
- options - (optional). Available options are:
- threadId - (optional). Thread Id. If not specified, the defaultThreadId will be used;
- limit - (optional) integer. A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20;
- order - (optional) string. Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order;
- after - (optional) string. A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list;
- before - (optional) string. A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list;
- run_id - (optional) string. Filter messages by the run ID that generated them;
Returns
Promise.
Example
const messages = await this.$a.openai.getThreadMessages();