Zai class
The package exports one class: Zai. This class gives you access to the library’s methods.
To create a new Zai instance using your Botpress client:
const client = new Client ({ botId: 'YOUR_BOT_ID' , token: 'YOUR_TOKEN' })
const zai = new Zai ({ client })
Parameters
The ID of the user consuming the API. If not provided, requests will be made without user attribution.
The ID of the LLM you want to use. Available options:
best: The best available model
fast: The fastest available model
Custom model ID in format provider:model-name. For example: openai:gpt-4
enable
boolean
default: false
required
Enables active learning.
tableName
string
default: "ActiveLearningTable"
required
Name of the table to store active learning tasks in.
Namespace for organizing tasks and data.
Methods
Here’s a reference for all methods available with the Zai object.
All of the methods below return a Response object. If you just await the method’s result, it will return simplest form of the result. However, the Response object also has its own methods for accessing the result, event handling, and request control.
check()
Checks whether a condition is true or false for the given input.
const result = await zai . check ( input , condition , options )
Parameters
The input data to check the condition against.
The condition to check against the input.
examples
Array<Example>
default: "[]"
Examples to check the condition against. The input for the example.
Whether the condition is true for this example.
The reason for the decision.
The condition for this specific example.
Returns
Response
Response<CheckResult, boolean>
Whether the condition is true or not.
The explanation of the decision.
Extracts one or many elements from an arbitrary input using a schema.
const result = await zai . extract ( input , schema , options )
Parameters
The input data to extract elements from.
The Zod schema defining the structure of the data to extract.
Instructions to guide the user on how to extract the data.
The maximum number of tokens per chunk (100-100,000).
Whether to strictly follow the schema or not.
Returns
The extracted data matching the provided schema.
filter()
Filters elements of an array against a condition.
const result = await zai . filter ( input , condition , options )
Parameters
The array of elements to filter.
The condition to filter elements against.
The maximum number of tokens per item (1-100,000).
examples
Array<FilterExample>
default: "[]"
Examples to filter the condition against. The input for the example.
Whether this item should be filtered (kept).
The reason for the filtering decision.
Returns
The filtered array containing only elements that match the condition.
label()
Tags the provided input with a list of predefined labels.
const result = await zai . label ( input , labels , options )
Parameters
labels
Record<string, string>
required
A mapping of label keys to their descriptions/questions.
examples
Array<LabelExample>
default: "[]"
Examples to help make labeling decisions. The input for the example.
labels
Record<string, LabelResult>
required
The labels for this example. label
'ABSOLUTELY_NOT' | 'PROBABLY_NOT' | 'AMBIGUOUS' | 'PROBABLY_YES' | 'ABSOLUTELY_YES'
required
The confidence level for this label.
The explanation for this label decision.
Instructions to guide the labeling process.
The maximum number of tokens per chunk (100-100,000).
Returns
Response
Response<LabelResults, BooleanLabels>
For each label key provided: The explanation for this label decision.
Whether this label applies to the input.
The confidence level (0-1) for this decision.
rewrite()
Rewrites a string according to the provided prompt.
const result = await zai . rewrite ( original , prompt , options )
Parameters
The original text to rewrite.
The prompt describing how to rewrite the text.
examples
Array<RewriteExample>
default: "[]"
Examples to guide the rewriting. The input text for the example.
The expected output for the example.
Specific instructions for this example.
The maximum number of tokens to generate (10-16,000).
Returns
The rewritten text according to the prompt.
summarize()
Summarizes a text of any length to a summary of the desired length.
const result = await zai . summarize ( original , options )
Parameters
The original text to summarize.
What should the text be summarized to?
How to format the summary text.
The length of the summary in tokens (10-100,000).
How many times longer (than final length) are the intermediate summaries generated (1-10).
The maximum number of iterations to perform.
sliding
SlidingOptions
default: "{ window: 50000, overlap: 250 }"
Sliding window options. The window size for sliding window processing (10-100,000).
The overlap size between windows (0-100,000).
Returns
The summarized text according to the specified options.
text()
Generates a text of the desired length according to the prompt.
const result = await zai . text ( prompt , options )
Parameters
The prompt describing what text to generate.
The maximum number of tokens to generate (1-100,000).
Returns
The generated text according to the prompt.
sort()
Sorts array items based on natural language sorting criteria.
const result = await zai . sort ( input , instructions , options )
Parameters
The array of items to sort.
Natural language description of how to sort (e.g., “by priority”, “newest first”, “from least expensive to most expensive”).
The maximum number of tokens per item (1-100,000).
Returns
The sorted array according to the specified instructions.
rate()
Rates array items on a 1-5 scale based on single or multiple criteria.
const result = await zai . rate ( input , instructions , options )
Parameters
The array of items to rate.
instructions
string | Record<string, string>
required
Single criterion (string) or multiple criteria (object mapping criterion names to descriptions). Ratings scale: 1 = Very Bad, 2 = Bad, 3 = Average, 4 = Good, 5 = Very Good
The maximum number of tokens per item (1-100,000).
The maximum number of items to rate per chunk (1-100).
Returns
Response
Response<RatingResult[], SimplifiedRatingResult[]>
For single criterion (string instructions), returns array of numbers (total scores). For multiple criteria (object instructions), returns array of objects with scores per criterion and total. Score for this criterion (1-5).
Sum of all criterion scores.
group()
Groups array items into categories based on semantic similarity or criteria.
const result = await zai . group ( input , options )
Parameters
The array of items to group.
Instructions for how to group the items (e.g., “Group by type of customer issue”, “Categorize by technology”).
The maximum number of tokens per element (1-100,000).
The maximum number of tokens per chunk (100-100,000).
initialGroups
Array<InitialGroup>
default: "[]"
Predefined categories to use for grouping. Unique identifier for the group.
Display name for the group.
Optional initial elements in this group.
Returns
Response
Response<Group<T>[], Record<string, T[]>>
Simplified form: Object mapping group labels to arrays of items. Full form: Array of group objects with id, label, and elements. Unique identifier for the group.
Display name for the group.
Items that belong to this group.
answer()
Answers questions from documents with citations and intelligent handling of edge cases.
const result = await zai . answer ( documents , question , options )
Parameters
Array of documents to search (strings, objects, or any type).
examples
Array<AnswerExample>
default: "[]"
Examples to help guide answer generation.
Additional instructions for answer generation.
Maximum number of tokens per document chunk (250-100,000).
Maximum number of refinement iterations when merging chunked results (1-10).
Returns
The result can be one of five types: Show answer response attributes
Indicates this is a successful answer with citations.
Citations mapping answer text to source documents. Character offset where this citation appears in the answer.
The source document item.
The relevant text snippet from the document.
Show ambiguous response attributes
Indicates the question has multiple valid interpretations.
Explanation of what is ambiguous.
A follow-up question to clarify.
Possible answers for different interpretations (2-3 answers).
Show out of topic response attributes
Indicates the question is unrelated to the documents.
Why the question is considered out of topic.
Show invalid question response attributes
Indicates the question is invalid or malformed.
What makes this an invalid question.
Show missing knowledge response attributes
Indicates insufficient information to answer.
What knowledge is missing.
patch()
Patches files based on natural language instructions using the micropatch protocol.
const result = await zai . patch ( files , instructions , options )
Parameters
Array of files to patch. The file path (e.g., ‘src/components/Button.tsx’).
The file name (e.g., ‘Button.tsx’).
Natural language instructions describing what changes to make.
Maximum tokens per chunk when processing large files. If not specified, all files must fit in a single prompt.
Returns
Array of patched files with the same structure as input, plus: The micropatch operations that were applied.
with()
Creates a new Zai instance with modified configuration options.
const newZai = zai . with ( options )
Parameters
options
Partial<ZaiConfig>
required
Configuration options to override. Can include any of the ZaiConfig properties: client, userId, modelId, activeLearning, or namespace.
Returns
A new Zai instance with the updated configuration.
learn()
Creates a new Zai instance with active learning enabled for the specified task ID.
const learningZai = zai . learn ( taskId )
Parameters
The ID of the task for active learning. This will be used to organize and retrieve examples for improving future responses.
Returns
A new Zai instance with active learning enabled for the specified task.
Response methods
All Zai operations return a Response object that implements promise-like behavior while providing additional functionality for event handling and request control.
You can call any of the following methods on the Response object:
result()
Returns the complete result including output, usage statistics, and elapsed time.
const { output , usage , elapsed } = await response . result ()
Returns
The actual result of the operation.
Usage statistics for the operation. Request-related statistics. Total number of requests made.
Number of requests that resulted in errors.
Number of successful responses received.
Number of cached responses used.
Completion percentage of requests.
Cost-related statistics. Total cost for the operation.
Token usage statistics. Number of input tokens used.
Number of output tokens generated.
Total number of tokens processed.
Time elapsed in milliseconds for the operation.
on()
Registers an event listener for the specified event type.
response . on ( 'progress' , ( usage ) => {
console . log ( 'Request progress:' , usage )
})
Parameters
type
'progress' | 'complete' | 'error'
required
The event type to listen for:
progress: Emitted during request processing with usage statistics
complete: Emitted when the operation completes successfully
error: Emitted when an error occurs
listener
(event: EventData) => void
required
The callback function to execute when the event is emitted.
Returns
The same Response instance for method chaining.
off()
Removes an event listener for the specified event type.
const listener = ( usage ) => console . log ( usage )
response . on ( 'progress' , listener )
response . off ( 'progress' , listener )
Parameters
type
'progress' | 'complete' | 'error'
required
The event type to remove the listener from.
listener
(event: EventData) => void
required
The specific listener function to remove.
Returns
The same Response instance for method chaining.
once()
Registers an event listener that will be called only once.
response . once ( 'complete' , ( result ) => {
console . log ( 'Operation completed:' , result )
})
Parameters
type
'progress' | 'complete' | 'error'
required
The event type to listen for.
listener
(event: EventData) => void
required
The callback function to execute when the event is emitted.
Returns
The same Response instance for method chaining.
bindSignal()
Binds an AbortSignal to the response for cancellation control.
const controller = new AbortController ()
response . bindSignal ( controller . signal )
// Cancel the operation
controller . abort ( 'User cancelled' )
Parameters
The AbortSignal to bind to this response.
Returns
The same Response instance for method chaining.
abort()
Aborts the ongoing operation.
response . abort ( 'Operation cancelled by user' )
Parameters
Optional reason for the abortion.
Returns
then()
Attaches callbacks for the resolution and/or rejection of the response.
response
. then ( result => console . log ( 'Success:' , result ))
. catch ( error => console . error ( 'Error:' , error ))
Parameters
onfulfilled
(value: T) => TResult1 | PromiseLike<TResult1>
Callback to execute when the response resolves successfully.
onrejected
(reason: any) => TResult2 | PromiseLike<TResult2>
Callback to execute when the response rejects.
Returns
PromiseLike
PromiseLike<TResult1 | TResult2>
A promise-like object for further chaining.
catch()
Attaches a callback for handling rejection of the response.
response . catch ( error => {
console . error ( 'Operation failed:' , error )
})
Parameters
onrejected
(reason: any) => TResult | PromiseLike<TResult>
Callback to execute when the response rejects.
Returns
A promise-like object for further chaining.