@botpress/zai 1.0.0-beta.1 → 1.0.0-beta.3

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.
Files changed (47) hide show
  1. package/dist/src/env.d.ts +0 -36
  2. package/dist/src/zai.d.ts +6 -12
  3. package/dist/src/zai.js +2 -0
  4. package/dist/src/zai.js.map +1 -1
  5. package/dist/tsconfig.tsbuildinfo +1 -1
  6. package/dist/typings.d.ts +0 -6
  7. package/dist/typings.tsbuildinfo +1 -1
  8. package/package.json +18 -9
  9. package/tsconfig.json +1 -0
  10. package/dist/src/operations/check.test.js +0 -129
  11. package/dist/src/operations/extract.test.js +0 -163
  12. package/dist/src/operations/filter.test.js +0 -151
  13. package/dist/src/operations/label.test.js +0 -213
  14. package/dist/src/operations/rewrite.test.js +0 -96
  15. package/dist/src/operations/summarize.test.js +0 -22
  16. package/dist/src/operations/text.test.js +0 -51
  17. package/dist/src/operations/zai-learn.test.js +0 -71
  18. package/dist/src/operations/zai-retry.test.js +0 -50
  19. package/src/adapters/adapter.ts +0 -35
  20. package/src/adapters/botpress-table.ts +0 -213
  21. package/src/adapters/memory.ts +0 -13
  22. package/src/env.ts +0 -54
  23. package/src/index.ts +0 -11
  24. package/src/models.ts +0 -347
  25. package/src/operations/__tests/botpress_docs.txt +0 -26040
  26. package/src/operations/__tests/index.ts +0 -30
  27. package/src/operations/check.test.ts +0 -155
  28. package/src/operations/check.ts +0 -187
  29. package/src/operations/constants.ts +0 -2
  30. package/src/operations/errors.ts +0 -9
  31. package/src/operations/extract.test.ts +0 -209
  32. package/src/operations/extract.ts +0 -291
  33. package/src/operations/filter.test.ts +0 -182
  34. package/src/operations/filter.ts +0 -231
  35. package/src/operations/label.test.ts +0 -239
  36. package/src/operations/label.ts +0 -332
  37. package/src/operations/rewrite.test.ts +0 -114
  38. package/src/operations/rewrite.ts +0 -148
  39. package/src/operations/summarize.test.ts +0 -25
  40. package/src/operations/summarize.ts +0 -193
  41. package/src/operations/text.test.ts +0 -60
  42. package/src/operations/text.ts +0 -63
  43. package/src/operations/zai-learn.test.ts +0 -85
  44. package/src/operations/zai-retry.test.ts +0 -64
  45. package/src/scripts/update-models.ts +0 -74
  46. package/src/utils.ts +0 -61
  47. package/src/zai.ts +0 -179
@@ -1,74 +0,0 @@
1
- import '../env.ts'
2
-
3
- import { Client } from '@botpress/client'
4
- import { llm } from '@botpress/shared/interfaces'
5
- import dotenv from 'dotenv'
6
- import _ from 'lodash'
7
- import fs from 'node:fs'
8
- import path from 'node:path'
9
-
10
- const envLocal = [
11
- path.resolve('.', '.env.local'),
12
- path.resolve('../', '.env.local'),
13
- path.resolve('../..', '.env.local'),
14
- path.resolve('../../..', '.env.local')
15
- ].find(fs.existsSync)
16
-
17
- if (envLocal) {
18
- dotenv.config({ path: envLocal })
19
- }
20
-
21
- const LLM_LIST_MODELS = 'listLanguageModels' satisfies keyof typeof llm.definition.actions
22
-
23
- const client = new Client({
24
- apiUrl: process.env.VITE_CLOUD_API_ENDPOINT,
25
- botId: process.env.VITE_BOT_ID,
26
- token: process.env.VITE_CLOUD_PAT
27
- })
28
-
29
- const { bot } = await client.getBot({
30
- id: process.env.VITE_BOT_ID!
31
- })
32
-
33
- type Model = llm.Model & {
34
- integration: string
35
- }
36
-
37
- const models: Model[] = []
38
-
39
- for (const integrationId in bot.integrations) {
40
- const botIntegration = bot.integrations[integrationId]
41
- if (botIntegration.public && botIntegration.enabled && botIntegration.status === 'registered') {
42
- try {
43
- const { integration } = await client.getPublicIntegrationById({
44
- id: botIntegration.id
45
- })
46
-
47
- const canListModels = Object.keys(integration.actions).includes(LLM_LIST_MODELS)
48
- if (!canListModels) {
49
- continue
50
- }
51
-
52
- const { output } = await client.callAction({
53
- type: `${integration.name}:${LLM_LIST_MODELS}`,
54
- input: {}
55
- })
56
-
57
- if (_.isArray(output?.models)) {
58
- for (const model of output.models) {
59
- models.push({
60
- ...model,
61
- id: `${integration.name}__${model.id}`,
62
- integration: integration.name
63
- })
64
- }
65
- }
66
- } catch (err) {
67
- console.error('Error fetching integration:', err.message)
68
- }
69
- }
70
- }
71
-
72
- const content = JSON.stringify(_.orderBy(models, ['integration', 'name']), null, 2)
73
-
74
- fs.writeFileSync('./src/models.ts', `export const Models = ${content} as const`, 'utf-8')
package/src/utils.ts DELETED
@@ -1,61 +0,0 @@
1
- import { Client } from '@botpress/client'
2
- import { z } from '@bpinternal/zui'
3
-
4
- export const stringify = (input: unknown, beautify = true) => {
5
- return typeof input === 'string' && !!input.length
6
- ? input
7
- : input
8
- ? JSON.stringify(input, beautify ? null : undefined, beautify ? 2 : undefined)
9
- : '<input is null, false, undefined or empty>'
10
- }
11
-
12
- export const BotpressClient = z.custom<Client>(
13
- (value) =>
14
- typeof value === 'object' && value !== null && 'callAction' in value && typeof value.callAction === 'function',
15
- {
16
- message: 'Invalid Botpress Client. Make sure to pass an instance of @botpress/client'
17
- }
18
- )
19
-
20
- export function fastHash(str: string): string {
21
- let hash = 0
22
- for (let i = 0; i < str.length; i++) {
23
- hash = (hash << 5) - hash + str.charCodeAt(i)
24
- hash |= 0 // Convert to 32bit integer
25
- }
26
- return (hash >>> 0).toString(16) // Convert to unsigned and then to hex
27
- }
28
-
29
- export const takeUntilTokens = <T>(arr: T[], tokens: number, count: (el: T) => number) => {
30
- const result: T[] = []
31
- let total = 0
32
-
33
- for (const value of arr) {
34
- const valueTokens = count(value)
35
- if (total + valueTokens > tokens) {
36
- break
37
- }
38
- total += valueTokens
39
- result.push(value)
40
- }
41
-
42
- return result
43
- }
44
-
45
- export type GenerationMetadata = z.input<typeof GenerationMetadata>
46
- export const GenerationMetadata = z.object({
47
- model: z.string(),
48
- cost: z
49
- .object({
50
- input: z.number(),
51
- output: z.number()
52
- })
53
- .describe('Cost in $USD'),
54
- latency: z.number().describe('Latency in milliseconds'),
55
- tokens: z
56
- .object({
57
- input: z.number(),
58
- output: z.number()
59
- })
60
- .describe('Number of tokens used')
61
- })
package/src/zai.ts DELETED
@@ -1,179 +0,0 @@
1
- import { Client } from '@botpress/client'
2
- import { llm } from '@botpress/shared/interfaces'
3
- import { type TextTokenizer, getWasmTokenizer } from '@botpress/wasm'
4
- import { z } from '@bpinternal/zui'
5
-
6
- import { Adapter } from './adapters/adapter'
7
- import { TableAdapter } from './adapters/botpress-table'
8
- import { MemoryAdapter } from './adapters/memory'
9
- import { Models } from './models'
10
- import { BotpressClient, GenerationMetadata } from './utils'
11
-
12
- type ModelId = (typeof Models)[number]['id']
13
-
14
- type ActiveLearning = z.input<typeof ActiveLearning>
15
- const ActiveLearning = z.object({
16
- enable: z.boolean().describe('Whether to enable active learning').default(false),
17
- tableName: z
18
- .string()
19
- .regex(
20
- /^[A-Za-z0-9_/-]{1,100}Table$/,
21
- 'Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes'
22
- )
23
- .describe('The name of the table to store active learning tasks')
24
- .default('ActiveLearningTable'),
25
- taskId: z
26
- .string()
27
- .regex(
28
- /^[A-Za-z0-9_/-]{1,100}$/,
29
- 'Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes'
30
- )
31
- .describe('The ID of the task')
32
- .default('default')
33
- })
34
-
35
- type ZaiConfig = z.input<typeof ZaiConfig>
36
- const ZaiConfig = z.object({
37
- client: BotpressClient,
38
- userId: z.string().describe('The ID of the user consuming the API').optional(),
39
- retry: z.object({ maxRetries: z.number().min(0).max(100) }).default({ maxRetries: 3 }),
40
- modelId: z
41
- .custom<ModelId>(
42
- (value) => {
43
- if (typeof value !== 'string' || !value.includes('__')) {
44
- return false
45
- }
46
-
47
- return true
48
- },
49
- {
50
- message: 'Invalid model ID'
51
- }
52
- )
53
- .describe('The ID of the model you want to use')
54
- .default('openai__gpt-4o-mini-2024-07-18' satisfies ModelId),
55
- activeLearning: ActiveLearning.default({ enable: false }),
56
- namespace: z
57
- .string()
58
- .regex(
59
- /^[A-Za-z0-9_/-]{1,100}$/,
60
- 'Namespace must be alphanumeric and contain only letters, numbers, underscores, hyphens and slashes'
61
- )
62
- .default('zai')
63
- })
64
-
65
- export class Zai {
66
- protected static tokenizer: TextTokenizer = null!
67
- protected client: Client
68
-
69
- private originalConfig: ZaiConfig
70
-
71
- private userId: string | undefined
72
- private integration: string
73
- private model: string
74
- private retry: { maxRetries: number }
75
-
76
- protected Model: (typeof Models)[number]
77
- protected namespace: string
78
- protected adapter: Adapter
79
- protected activeLearning: ActiveLearning
80
-
81
- constructor(config: ZaiConfig) {
82
- this.originalConfig = config
83
- const parsed = ZaiConfig.parse(config)
84
-
85
- this.client = parsed.client
86
- const [integration, modelId] = parsed.modelId.split('__')
87
- this.integration = integration
88
- this.model = modelId
89
- this.namespace = parsed.namespace
90
- this.userId = parsed.userId
91
- this.retry = parsed.retry as typeof this.retry
92
- this.Model = Models.find((m) => m.id === parsed.modelId)!
93
- this.activeLearning = parsed.activeLearning
94
-
95
- this.adapter = parsed.activeLearning?.enable
96
- ? new TableAdapter({ client: this.client, tableName: parsed.activeLearning.tableName })
97
- : new MemoryAdapter([])
98
- }
99
-
100
- protected async callModel(
101
- props: Partial<llm.GenerateContentInput>
102
- ): Promise<llm.GenerateContentOutput & { metadata: GenerationMetadata }> {
103
- let retries = this.retry.maxRetries
104
- while (retries-- >= 0) {
105
- try {
106
- return await this._callModel(props)
107
- } catch (e) {
108
- if (retries >= 0) {
109
- await new Promise((resolve) => setTimeout(resolve, 1000))
110
- } else {
111
- throw new Error('Failed to call model after multiple retries', e)
112
- }
113
- }
114
- }
115
-
116
- throw new Error('Failed to call model after multiple retries')
117
- }
118
-
119
- private async _callModel(
120
- props: Partial<llm.GenerateContentInput>
121
- ): Promise<llm.GenerateContentOutput & { metadata: GenerationMetadata }> {
122
- let retries = this.retry.maxRetries
123
- do {
124
- const start = Date.now()
125
- const input: llm.GenerateContentInput = {
126
- messages: [],
127
- temperature: 0.0,
128
- topP: 1,
129
- model: { id: this.model },
130
- userId: this.userId,
131
- ...props
132
- }
133
-
134
- const { output } = (await this.client.callAction({
135
- type: `${this.integration}:generateContent`,
136
- input
137
- })) as unknown as { output: llm.GenerateContentOutput }
138
-
139
- const latency = Date.now() - start
140
-
141
- return {
142
- ...output,
143
- metadata: {
144
- model: this.model,
145
- latency,
146
- cost: { input: output.usage.inputCost, output: output.usage.outputCost },
147
- tokens: { input: output.usage.inputTokens, output: output.usage.outputTokens }
148
- }
149
- }
150
- } while (--retries > 0)
151
- }
152
-
153
- protected async getTokenizer() {
154
- Zai.tokenizer ??= await getWasmTokenizer()
155
- return Zai.tokenizer
156
- }
157
-
158
- protected get taskId() {
159
- if (!this.activeLearning.enable) {
160
- return undefined
161
- }
162
-
163
- return `${this.namespace}/${this.activeLearning.taskId}`.replace(/\/+/g, '/')
164
- }
165
-
166
- public with(options: Partial<ZaiConfig>): Zai {
167
- return new Zai({
168
- ...this.originalConfig,
169
- ...options
170
- })
171
- }
172
-
173
- public learn(taskId: string) {
174
- return new Zai({
175
- ...this.originalConfig,
176
- activeLearning: { ...this.activeLearning, taskId, enable: true }
177
- })
178
- }
179
- }