@botpress/zai 2.4.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -76,8 +76,118 @@ export type SimplifiedRatingResult<T extends RatingInstructions> = T extends str
76
76
  declare module '@botpress/zai' {
77
77
  interface Zai {
78
78
  /**
79
- * Rates an array of items based on provided instructions.
80
- * Returns a number (1-5) if instructions is a string, or a Record<string, number> if instructions is a Record.
79
+ * Rates array items on a 1-5 scale based on single or multiple criteria.
80
+ *
81
+ * This operation evaluates each item and assigns numeric ratings (1-5) where:
82
+ * - 1 = Very Bad, 2 = Bad, 3 = Average, 4 = Good, 5 = Very Good
83
+ *
84
+ * Supports both simple single-criterion rating (string instructions) and
85
+ * multi-criteria rating (object with criterion → description mapping).
86
+ *
87
+ * @param input - Array of items to rate
88
+ * @param instructions - Single criterion (string) or multiple criteria (object)
89
+ * @param options - Configuration for chunking and tokens per item
90
+ * @returns Response with ratings array (simplified to numbers for single criterion)
91
+ *
92
+ * @example Single criterion rating
93
+ * ```typescript
94
+ * const reviews = [
95
+ * "Amazing product! Best purchase ever!",
96
+ * "It's okay, nothing special",
97
+ * "Terrible quality, broke immediately"
98
+ * ]
99
+ *
100
+ * const ratings = await zai.rate(reviews, 'Rate the sentiment')
101
+ * // Result: [5, 3, 1] (simplified to numbers)
102
+ *
103
+ * // Get full details
104
+ * const { output } = await zai.rate(reviews, 'Rate the sentiment').result()
105
+ * // output[0]: { sentiment: 5, total: 5 }
106
+ * ```
107
+ *
108
+ * @example Multi-criteria rating
109
+ * ```typescript
110
+ * const essays = [
111
+ * "... student essay text ...",
112
+ * "... another essay ...",
113
+ * ]
114
+ *
115
+ * const ratings = await zai.rate(essays, {
116
+ * grammar: 'Rate the grammar and spelling',
117
+ * clarity: 'Rate how clear and well-organized the writing is',
118
+ * argumentation: 'Rate the strength of arguments and evidence'
119
+ * })
120
+ *
121
+ * // Result: [
122
+ * // { grammar: 4, clarity: 5, argumentation: 3, total: 12 },
123
+ * // { grammar: 3, clarity: 4, argumentation: 4, total: 11 }
124
+ * // ]
125
+ * ```
126
+ *
127
+ * @example Rating customer support conversations
128
+ * ```typescript
129
+ * const conversations = [
130
+ * { agent: 'John', messages: [...], duration: 300 },
131
+ * { agent: 'Jane', messages: [...], duration: 180 }
132
+ * ]
133
+ *
134
+ * const ratings = await zai.rate(conversations, {
135
+ * professionalism: 'How professional was the agent?',
136
+ * helpfulness: 'How helpful was the agent in solving the issue?',
137
+ * efficiency: 'How efficiently was the conversation handled?'
138
+ * })
139
+ *
140
+ * // Calculate average scores
141
+ * const avgProfessionalism = ratings.reduce((sum, r) => sum + r.professionalism, 0) / ratings.length
142
+ * ```
143
+ *
144
+ * @example Rating code quality
145
+ * ```typescript
146
+ * const codeSamples = [
147
+ * "function foo() { return x + y }",
148
+ * "const calculateTotal = (items) => items.reduce((sum, item) => sum + item.price, 0)",
149
+ * ]
150
+ *
151
+ * const quality = await zai.rate(codeSamples, {
152
+ * readability: 'How readable and clear is the code?',
153
+ * best_practices: 'Does it follow coding best practices?',
154
+ * documentation: 'Is the code well-documented?'
155
+ * })
156
+ * ```
157
+ *
158
+ * @example Product review rating
159
+ * ```typescript
160
+ * const products = [
161
+ * { name: 'Laptop', reviews: [...], avgStars: 4.2 },
162
+ * { name: 'Mouse', reviews: [...], avgStars: 3.8 }
163
+ * ]
164
+ *
165
+ * const ratings = await zai.rate(
166
+ * products,
167
+ * 'Rate overall product quality based on reviews and rating',
168
+ * {
169
+ * tokensPerItem: 500, // Allow more tokens for detailed reviews
170
+ * maxItemsPerChunk: 20 // Process 20 products per chunk
171
+ * }
172
+ * )
173
+ * ```
174
+ *
175
+ * @example Finding highest-rated items
176
+ * ```typescript
177
+ * const ratings = await zai.rate(items, {
178
+ * quality: 'Product quality',
179
+ * value: 'Value for money',
180
+ * design: 'Design and aesthetics'
181
+ * })
182
+ *
183
+ * // Sort by total score
184
+ * const sorted = items
185
+ * .map((item, idx) => ({ item, rating: ratings[idx] }))
186
+ * .sort((a, b) => b.rating.total - a.rating.total)
187
+ *
188
+ * console.log('Top rated:', sorted[0].item)
189
+ * console.log('Score breakdown:', sorted[0].rating)
190
+ * ```
81
191
  */
82
192
  rate<T, I extends RatingInstructions>(
83
193
  input: Array<T>,
@@ -33,7 +33,90 @@ const Options = z.object({
33
33
 
34
34
  declare module '@botpress/zai' {
35
35
  interface Zai {
36
- /** Rewrites a string according to match the prompt */
36
+ /**
37
+ * Rewrites text according to specific instructions while preserving the core meaning.
38
+ *
39
+ * This operation transforms text based on natural language instructions. Perfect for
40
+ * tone adjustment, format conversion, translation, simplification, and style changes.
41
+ *
42
+ * @param original - The text to rewrite
43
+ * @param prompt - Instructions describing how to transform the text
44
+ * @param options - Configuration for examples and length constraints
45
+ * @returns Response promise resolving to the rewritten text
46
+ *
47
+ * @example Change tone
48
+ * ```typescript
49
+ * const original = "Your request has been denied due to insufficient funds."
50
+ * const friendly = await zai.rewrite(
51
+ * original,
52
+ * 'Make this sound more friendly and empathetic'
53
+ * )
54
+ * // Result: "We appreciate your interest, but unfortunately we're unable to proceed..."
55
+ * ```
56
+ *
57
+ * @example Simplify technical content
58
+ * ```typescript
59
+ * const technical = "The API implements RESTful architecture with OAuth 2.0 authentication..."
60
+ * const simple = await zai.rewrite(
61
+ * technical,
62
+ * 'Explain this in simple terms for non-technical users'
63
+ * )
64
+ * ```
65
+ *
66
+ * @example Professional email conversion
67
+ * ```typescript
68
+ * const casual = "Hey, can you send me that report? Thanks!"
69
+ * const professional = await zai.rewrite(
70
+ * casual,
71
+ * 'Rewrite this as a formal business email'
72
+ * )
73
+ * // Result: "Dear colleague, I would appreciate it if you could share the report..."
74
+ * ```
75
+ *
76
+ * @example Format conversion
77
+ * ```typescript
78
+ * const paragraph = "First do this. Then do that. Finally do this other thing."
79
+ * const bullets = await zai.rewrite(
80
+ * paragraph,
81
+ * 'Convert this to a bulleted list'
82
+ * )
83
+ * // Result:
84
+ * // - First do this
85
+ * // - Then do that
86
+ * // - Finally do this other thing
87
+ * ```
88
+ *
89
+ * @example With examples for consistent style
90
+ * ```typescript
91
+ * const result = await zai.rewrite(
92
+ * original,
93
+ * 'Rewrite in our brand voice',
94
+ * {
95
+ * examples: [
96
+ * {
97
+ * input: 'We offer many products.',
98
+ * output: 'Discover our curated collection of innovative solutions.'
99
+ * },
100
+ * {
101
+ * input: 'Contact us for help.',
102
+ * output: "We're here to support your success. Let's connect!"
103
+ * }
104
+ * ],
105
+ * length: 200 // Limit output length
106
+ * }
107
+ * )
108
+ * ```
109
+ *
110
+ * @example Translation-like transformation
111
+ * ```typescript
112
+ * const code = "if (user.isActive && user.hasPermission) { allowAccess() }"
113
+ * const pseudocode = await zai.rewrite(
114
+ * code,
115
+ * 'Convert this code to natural language pseudocode'
116
+ * )
117
+ * // Result: "If the user is active AND has permission, then allow access"
118
+ * ```
119
+ */
37
120
  rewrite(original: string, prompt: string, options?: Options): Response<string>
38
121
  }
39
122
  }
@@ -35,17 +35,119 @@ type SortingCriteria = Record<
35
35
  declare module '@botpress/zai' {
36
36
  interface Zai {
37
37
  /**
38
- * Sorts an array of items based on provided instructions.
39
- * Returns the sorted array directly when awaited.
40
- * Use .result() to get detailed scoring information including why each item got its position.
38
+ * Sorts array items based on natural language sorting criteria.
41
39
  *
42
- * @example
43
- * // Simple usage
44
- * const sorted = await zai.sort(items, 'from least expensive to most expensive')
40
+ * This operation intelligently orders items according to your instructions, understanding
41
+ * complex sorting logic like priority, quality, chronology, or any custom criteria.
42
+ * Perfect for ranking, organizing, and prioritizing lists based on subjective or
43
+ * multi-faceted criteria.
45
44
  *
46
- * @example
47
- * // Get detailed results
48
- * const { output: sorted, usage } = await zai.sort(items, 'by priority').result()
45
+ * @param input - Array of items to sort
46
+ * @param instructions - Natural language description of how to sort (e.g., "by priority", "newest first")
47
+ * @param options - Configuration for tokens per item
48
+ * @returns Response resolving to the sorted array
49
+ *
50
+ * @example Sort by price
51
+ * ```typescript
52
+ * const products = [
53
+ * { name: 'Laptop', price: 999 },
54
+ * { name: 'Mouse', price: 29 },
55
+ * { name: 'Keyboard', price: 79 }
56
+ * ]
57
+ *
58
+ * const sorted = await zai.sort(products, 'from least expensive to most expensive')
59
+ * // Result: [Mouse ($29), Keyboard ($79), Laptop ($999)]
60
+ * ```
61
+ *
62
+ * @example Sort by priority/urgency
63
+ * ```typescript
64
+ * const tasks = [
65
+ * "Update documentation",
66
+ * "Fix critical security bug",
67
+ * "Add new feature",
68
+ * "System is down - all users affected"
69
+ * ]
70
+ *
71
+ * const prioritized = await zai.sort(tasks, 'by urgency and impact, most urgent first')
72
+ * // Result: ["System is down...", "Fix critical security bug", "Add new feature", "Update documentation"]
73
+ * ```
74
+ *
75
+ * @example Sort by quality/rating
76
+ * ```typescript
77
+ * const reviews = [
78
+ * "Product is okay",
79
+ * "Absolutely amazing! Best purchase ever!",
80
+ * "Terrible, broke immediately",
81
+ * "Good quality for the price"
82
+ * ]
83
+ *
84
+ * const sorted = await zai.sort(reviews, 'by sentiment, most positive first')
85
+ * // Result: [amazing review, good review, okay review, terrible review]
86
+ * ```
87
+ *
88
+ * @example Sort by complexity
89
+ * ```typescript
90
+ * const problems = [
91
+ * "Fix typo in README",
92
+ * "Redesign entire authentication system",
93
+ * "Update a dependency version",
94
+ * "Implement new microservice architecture"
95
+ * ]
96
+ *
97
+ * const sorted = await zai.sort(problems, 'by complexity, simplest first')
98
+ * ```
99
+ *
100
+ * @example Sort by relevance to query
101
+ * ```typescript
102
+ * const documents = [
103
+ * "Article about cats",
104
+ * "Article about dogs and their training",
105
+ * "Article about dog breeds",
106
+ * "Article about fish"
107
+ * ]
108
+ *
109
+ * const sorted = await zai.sort(
110
+ * documents,
111
+ * 'by relevance to "dog training", most relevant first'
112
+ * )
113
+ * // Result: [dogs and training, dog breeds, cats, fish]
114
+ * ```
115
+ *
116
+ * @example Sort candidates by fit
117
+ * ```typescript
118
+ * const candidates = [
119
+ * { name: 'Alice', experience: 5, skills: ['React', 'Node'] },
120
+ * { name: 'Bob', experience: 10, skills: ['Python', 'ML'] },
121
+ * { name: 'Charlie', experience: 3, skills: ['React', 'TypeScript'] }
122
+ * ]
123
+ *
124
+ * const sorted = await zai.sort(
125
+ * candidates,
126
+ * 'by fit for a senior React developer position, best fit first'
127
+ * )
128
+ * ```
129
+ *
130
+ * @example Sort chronologically
131
+ * ```typescript
132
+ * const events = [
133
+ * "Started the project last month",
134
+ * "Will launch next week",
135
+ * "Met with client yesterday",
136
+ * "Planning meeting tomorrow"
137
+ * ]
138
+ *
139
+ * const chronological = await zai.sort(events, 'in chronological order')
140
+ * // Understands relative time expressions
141
+ * ```
142
+ *
143
+ * @example With token limit per item
144
+ * ```typescript
145
+ * const sorted = await zai.sort(
146
+ * longDocuments,
147
+ * 'by relevance to climate change research',
148
+ * { tokensPerItem: 500 } // Allow 500 tokens per document
149
+ * )
150
+ * ```
49
151
  */
50
152
  sort<T>(input: Array<T>, instructions: string, options?: Options): Response<Array<T>, Array<T>>
51
153
  }
@@ -58,7 +58,80 @@ const Options = z.object({
58
58
 
59
59
  declare module '@botpress/zai' {
60
60
  interface Zai {
61
- /** Summarizes a text of any length to a summary of the desired length */
61
+ /**
62
+ * Summarizes text of any length to a target length using intelligent chunking strategies.
63
+ *
64
+ * This operation can handle documents from a few paragraphs to entire books. It uses
65
+ * two strategies based on document size:
66
+ * - **Sliding window**: For moderate documents, processes overlapping chunks iteratively
67
+ * - **Merge sort**: For very large documents, recursively summarizes and merges
68
+ *
69
+ * @param original - The text to summarize
70
+ * @param options - Configuration for length, focus, format, and chunking strategy
71
+ * @returns Response promise resolving to the summary text
72
+ *
73
+ * @example Basic summarization
74
+ * ```typescript
75
+ * const article = "Long article text here..."
76
+ * const summary = await zai.summarize(article, {
77
+ * length: 100 // Target 100 tokens (~75 words)
78
+ * })
79
+ * ```
80
+ *
81
+ * @example Custom focus and format
82
+ * ```typescript
83
+ * const meetingNotes = "... detailed meeting transcript ..."
84
+ * const summary = await zai.summarize(meetingNotes, {
85
+ * length: 200,
86
+ * prompt: 'Key decisions, action items, and next steps',
87
+ * format: 'Bullet points with clear sections for Decisions, Actions, and Next Steps'
88
+ * })
89
+ * ```
90
+ *
91
+ * @example Summarizing very large documents
92
+ * ```typescript
93
+ * const book = await readFile('large-book.txt', 'utf-8') // 100k+ tokens
94
+ * const summary = await zai.summarize(book, {
95
+ * length: 500,
96
+ * intermediateFactor: 4, // Intermediate summaries can be 4x target length
97
+ * prompt: 'Main themes, key events, and character development'
98
+ * })
99
+ * // Automatically uses merge-sort strategy for efficiency
100
+ * ```
101
+ *
102
+ * @example Technical documentation summary
103
+ * ```typescript
104
+ * const docs = "... API documentation ..."
105
+ * const summary = await zai.summarize(docs, {
106
+ * length: 300,
107
+ * prompt: 'Core API endpoints, authentication methods, and rate limits',
108
+ * format: 'Structured markdown with code examples where relevant'
109
+ * })
110
+ * ```
111
+ *
112
+ * @example Adjusting chunking strategy
113
+ * ```typescript
114
+ * const summary = await zai.summarize(document, {
115
+ * length: 150,
116
+ * sliding: {
117
+ * window: 30000, // Process 30k tokens at a time
118
+ * overlap: 500 // 500 token overlap between windows
119
+ * }
120
+ * })
121
+ * ```
122
+ *
123
+ * @example Progress tracking for long documents
124
+ * ```typescript
125
+ * const response = zai.summarize(veryLongDocument, { length: 400 })
126
+ *
127
+ * response.on('progress', (usage) => {
128
+ * console.log(`Progress: ${Math.round(usage.requests.percentage * 100)}%`)
129
+ * console.log(`Tokens used: ${usage.tokens.total}`)
130
+ * })
131
+ *
132
+ * const summary = await response
133
+ * ```
134
+ */
62
135
  summarize(original: string, options?: Options): Response<string>
63
136
  }
64
137
  }
@@ -19,7 +19,56 @@ const Options = z.object({
19
19
 
20
20
  declare module '@botpress/zai' {
21
21
  interface Zai {
22
- /** Generates a text of the desired length according to the prompt */
22
+ /**
23
+ * Generates text content based on a natural language prompt.
24
+ *
25
+ * This operation creates original text content using LLMs with optional length constraints.
26
+ * Perfect for generating descriptions, emails, articles, creative content, and more.
27
+ *
28
+ * @param prompt - Natural language description of what text to generate
29
+ * @param options - Optional configuration for text length
30
+ * @returns Response promise resolving to the generated text
31
+ *
32
+ * @example Product description
33
+ * ```typescript
34
+ * const description = await zai.text(
35
+ * 'Write a compelling product description for eco-friendly bamboo toothbrushes'
36
+ * )
37
+ * ```
38
+ *
39
+ * @example With length constraint
40
+ * ```typescript
41
+ * const tagline = await zai.text(
42
+ * 'Create a catchy tagline for a fitness app',
43
+ * { length: 10 } // ~10 tokens (7-8 words)
44
+ * )
45
+ * ```
46
+ *
47
+ * @example Email generation
48
+ * ```typescript
49
+ * const email = await zai.text(`
50
+ * Write a professional email to a customer explaining
51
+ * that their order will be delayed by 2 days due to weather.
52
+ * Apologize and offer a 10% discount on their next purchase.
53
+ * `, { length: 150 })
54
+ * ```
55
+ *
56
+ * @example Blog post
57
+ * ```typescript
58
+ * const blogPost = await zai.text(`
59
+ * Write an informative blog post about the benefits of meditation
60
+ * for software developers. Include practical tips and scientific research.
61
+ * `, { length: 500 })
62
+ * ```
63
+ *
64
+ * @example Social media content
65
+ * ```typescript
66
+ * const tweet = await zai.text(
67
+ * 'Write an engaging tweet announcing our new AI-powered chatbot feature',
68
+ * { length: 30 } // Twitter-friendly length
69
+ * )
70
+ * ```
71
+ */
23
72
  text(prompt: string, options?: Options): Response<string>
24
73
  }
25
74
  }