@botpress/adk 1.19.0-beta.9 → 2.0.0-alpha.1
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.
- package/dist/agent-init/agent-project-generator.d.ts +5 -1
- package/dist/agent-init/agent-project-generator.d.ts.map +1 -1
- package/dist/agent-project/agent-project.d.ts +3 -3
- package/dist/agent-project/agent-project.d.ts.map +1 -1
- package/dist/agent-project/agent-resolver.d.ts.map +1 -1
- package/dist/agent-project/config-writer.d.ts +1 -1
- package/dist/agent-project/dependency-state-to-dependencies.d.ts +11 -0
- package/dist/agent-project/dependency-state-to-dependencies.d.ts.map +1 -0
- package/dist/agent-project/types.d.ts +9 -4
- package/dist/agent-project/types.d.ts.map +1 -1
- package/dist/agent0/capabilities/commands/adk-build.md +6 -5
- package/dist/agent0/capabilities/commands/adk-debug.md +1 -1
- package/dist/agent0/capabilities/commands/adk-dev-console.md +1 -1
- package/dist/agent0/capabilities/commands/adk-document.md +10 -2
- package/dist/agent0/capabilities/commands/adk-eval.md +1 -1
- package/dist/agent0/capabilities/commands/adk-explain.md +2 -2
- package/dist/agent0/capabilities/commands/adk-init.md +2 -2
- package/dist/agent0/capabilities/commands/adk-ship.md +1 -1
- package/dist/agent0/capabilities/commands/adk-test.md +3 -3
- package/dist/agent0/capabilities/commands/adk-validate.md +3 -3
- package/dist/agent0/capabilities/skills/adk/SKILL.md +21 -21
- package/dist/agent0/capabilities/skills/adk/references/actions.md +245 -239
- package/dist/agent0/capabilities/skills/adk/references/advanced-patterns.md +185 -218
- package/dist/agent0/capabilities/skills/adk/references/agent-config.md +74 -71
- package/dist/agent0/capabilities/skills/adk/references/assets.md +45 -48
- package/dist/agent0/capabilities/skills/adk/references/autonomous-execution.md +40 -46
- package/dist/agent0/capabilities/skills/adk/references/cli.md +17 -7
- package/dist/agent0/capabilities/skills/adk/references/context-api.md +98 -94
- package/dist/agent0/capabilities/skills/adk/references/conversation-lifecycle.md +65 -62
- package/dist/agent0/capabilities/skills/adk/references/conversations.md +395 -385
- package/dist/agent0/capabilities/skills/adk/references/custom-components.md +1 -1
- package/dist/agent0/capabilities/skills/adk/references/desk.md +236 -234
- package/dist/agent0/capabilities/skills/adk/references/explain-config.md +54 -37
- package/dist/agent0/capabilities/skills/adk/references/files.md +301 -306
- package/dist/agent0/capabilities/skills/adk/references/integration-actions.md +211 -214
- package/dist/agent0/capabilities/skills/adk/references/integrations.md +33 -31
- package/dist/agent0/capabilities/skills/adk/references/interfaces.md +13 -12
- package/dist/agent0/capabilities/skills/adk/references/knowledge-bases.md +98 -111
- package/dist/agent0/capabilities/skills/adk/references/mcp-server.md +6 -0
- package/dist/agent0/capabilities/skills/adk/references/messages.md +280 -256
- package/dist/agent0/capabilities/skills/adk/references/model-configuration.md +52 -49
- package/dist/agent0/capabilities/skills/adk/references/patterns-mistakes.md +102 -101
- package/dist/agent0/capabilities/skills/adk/references/plugins.md +15 -15
- package/dist/agent0/capabilities/skills/adk/references/tables.md +204 -210
- package/dist/agent0/capabilities/skills/adk/references/tags.md +141 -143
- package/dist/agent0/capabilities/skills/adk/references/tools.md +191 -199
- package/dist/agent0/capabilities/skills/adk/references/triggers.md +331 -336
- package/dist/agent0/capabilities/skills/adk/references/workflow-steps.md +132 -96
- package/dist/agent0/capabilities/skills/adk/references/workflows.md +479 -464
- package/dist/agent0/capabilities/skills/adk/references/zai-agent-reference.md +127 -129
- package/dist/agent0/capabilities/skills/adk/references/zai-complete-guide.md +255 -276
- package/dist/agent0/capabilities/skills/adk-debugger/SKILL.md +21 -17
- package/dist/agent0/capabilities/skills/adk-debugger/references/common-failures.md +25 -25
- package/dist/agent0/capabilities/skills/adk-debugger/references/conversation-analysis.md +49 -41
- package/dist/agent0/capabilities/skills/adk-debugger/references/debug-workflow.md +20 -14
- package/dist/agent0/capabilities/skills/adk-debugger/references/llm-debugging.md +13 -13
- package/dist/agent0/capabilities/skills/adk-debugger/references/trace-summarization.md +18 -18
- package/dist/agent0/capabilities/skills/adk-debugger/references/traces-and-logs.md +67 -67
- package/dist/agent0/capabilities/skills/adk-dev-console/SKILL.md +36 -36
- package/dist/agent0/capabilities/skills/adk-dev-console/references/agent-steps.md +14 -6
- package/dist/agent0/capabilities/skills/adk-dev-console/references/multi-agent-dashboard.md +13 -13
- package/dist/agent0/capabilities/skills/adk-dev-console/references/pages.md +18 -0
- package/dist/agent0/capabilities/skills/adk-docs/SKILL.md +13 -13
- package/dist/agent0/capabilities/skills/adk-docs/references/doc-standards.md +15 -0
- package/dist/agent0/capabilities/skills/adk-evals/SKILL.md +29 -23
- package/dist/agent0/capabilities/skills/adk-evals/references/eval-format.md +31 -23
- package/dist/agent0/capabilities/skills/adk-evals/references/test-patterns.md +25 -36
- package/dist/agent0/capabilities/skills/adk-evals/references/testing-workflow.md +6 -4
- package/dist/agent0/index.js +41 -19
- package/dist/agent0/index.js.map +7 -7
- package/dist/agent0/runtime/client.d.ts +2 -0
- package/dist/agent0/runtime/client.d.ts.map +1 -1
- package/dist/agent0/runtime/engine.d.ts +2 -1
- package/dist/agent0/runtime/engine.d.ts.map +1 -1
- package/dist/agent0/runtime/process.d.ts +1 -0
- package/dist/agent0/runtime/process.d.ts.map +1 -1
- package/dist/assets/manager.d.ts +3 -0
- package/dist/assets/manager.d.ts.map +1 -1
- package/dist/auth/credentials.d.ts +1 -1
- package/dist/bot-generator/generator.d.ts +22 -0
- package/dist/bot-generator/generator.d.ts.map +1 -1
- package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
- package/dist/commands/base-command.d.ts +1 -0
- package/dist/commands/base-command.d.ts.map +1 -1
- package/dist/commands/bp-dev-command.d.ts +1 -1
- package/dist/commands/bp-dev-command.d.ts.map +1 -1
- package/dist/commands/bp-dev-stderr.d.ts +9 -0
- package/dist/commands/bp-dev-stderr.d.ts.map +1 -1
- package/dist/commands/index.d.ts +1 -0
- package/dist/commands/index.d.ts.map +1 -1
- package/dist/dependencies/catalog/catalog-service.d.ts +53 -0
- package/dist/dependencies/catalog/catalog-service.d.ts.map +1 -0
- package/dist/dependencies/catalog/client-factory.d.ts +33 -0
- package/dist/dependencies/catalog/client-factory.d.ts.map +1 -0
- package/dist/dependencies/catalog/integration-source.d.ts +34 -0
- package/dist/dependencies/catalog/integration-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/interface-source.d.ts +23 -0
- package/dist/dependencies/catalog/interface-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/plugin-source.d.ts +49 -0
- package/dist/dependencies/catalog/plugin-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/resolution-cache.d.ts +76 -0
- package/dist/dependencies/catalog/resolution-cache.d.ts.map +1 -0
- package/dist/dependencies/dependency-manager.d.ts +31 -16
- package/dist/dependencies/dependency-manager.d.ts.map +1 -1
- package/dist/dependencies/errors.d.ts +2 -2
- package/dist/dependencies/errors.d.ts.map +1 -1
- package/dist/dependencies/index.d.ts +5 -4
- package/dist/dependencies/index.d.ts.map +1 -1
- package/dist/dependencies/index.js +2089 -1670
- package/dist/dependencies/index.js.map +37 -30
- package/dist/dependencies/legacy-lock-file.d.ts +15 -0
- package/dist/dependencies/legacy-lock-file.d.ts.map +1 -0
- package/dist/dependencies/migration.d.ts +19 -0
- package/dist/dependencies/migration.d.ts.map +1 -1
- package/dist/dependencies/resolvers/integration-resolver.d.ts +4 -3
- package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -1
- package/dist/dependencies/resolvers/plugin-resolver.d.ts +4 -4
- package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -1
- package/dist/dependencies/snapshot-store.d.ts +59 -0
- package/dist/dependencies/snapshot-store.d.ts.map +1 -0
- package/dist/dependencies/status-resolver.d.ts +36 -0
- package/dist/dependencies/status-resolver.d.ts.map +1 -0
- package/dist/dependencies/status.d.ts +214 -0
- package/dist/dependencies/status.d.ts.map +1 -0
- package/dist/dependencies/types.d.ts +380 -29
- package/dist/dependencies/types.d.ts.map +1 -1
- package/dist/file-watcher/watcher.d.ts +21 -5
- package/dist/file-watcher/watcher.d.ts.map +1 -1
- package/dist/generators/action-types.d.ts.map +1 -1
- package/dist/generators/client-wrapper.d.ts.map +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3134 -2226
- package/dist/index.js.map +55 -48
- package/dist/integrations/config-utils.d.ts +11 -7
- package/dist/integrations/config-utils.d.ts.map +1 -1
- package/dist/integrations/hub-cache.d.ts +0 -58
- package/dist/integrations/hub-cache.d.ts.map +1 -1
- package/dist/integrations/index.d.ts +1 -3
- package/dist/integrations/index.d.ts.map +1 -1
- package/dist/integrations/manager.d.ts +19 -53
- package/dist/integrations/manager.d.ts.map +1 -1
- package/dist/interfaces/enhanced-cache.d.ts +7 -7
- package/dist/interfaces/enhanced-cache.d.ts.map +1 -1
- package/dist/interfaces/manager.d.ts +11 -17
- package/dist/interfaces/manager.d.ts.map +1 -1
- package/dist/knowledge/manager.d.ts +3 -0
- package/dist/knowledge/manager.d.ts.map +1 -1
- package/dist/plugins/index.d.ts +0 -1
- package/dist/plugins/index.d.ts.map +1 -1
- package/dist/plugins/manager.d.ts +16 -48
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/preflight/checker.d.ts +6 -1
- package/dist/preflight/checker.d.ts.map +1 -1
- package/dist/preflight/dependency-gate.d.ts +37 -0
- package/dist/preflight/dependency-gate.d.ts.map +1 -0
- package/dist/preflight/index.d.ts +2 -1
- package/dist/preflight/index.d.ts.map +1 -1
- package/dist/preflight/types.d.ts +18 -0
- package/dist/preflight/types.d.ts.map +1 -1
- package/dist/runner/script-runner.d.ts.map +1 -1
- package/dist/tables/table-manager.d.ts +3 -0
- package/dist/tables/table-manager.d.ts.map +1 -1
- package/dist/templates/README.md +23 -13
- package/dist/templates/blank/agent.config.ts +3 -3
- package/dist/templates/blank/src/triggers/index.ts +1 -1
- package/dist/templates/botpress-desk/evals/index.eval.ts +1 -1
- package/dist/templates/botpress-desk/src/triggers/index.ts +1 -1
- package/dist/templates/crm-enrichment/README.md +3 -3
- package/dist/templates/crm-enrichment/agent.config.ts +2 -2
- package/dist/templates/crm-enrichment/src/conversations/index.ts +1 -1
- package/dist/templates/hello-world/agent.config.ts +3 -3
- package/dist/templates/hello-world/src/triggers/index.ts +1 -1
- package/dist/templates/knowledge-assistant/src/triggers/index.ts +1 -1
- package/dist/templates/template.config.json +3 -3
- package/dist/utils/ids.d.ts +10 -0
- package/dist/utils/ids.d.ts.map +1 -1
- package/dist/workspace/workspace-cache.d.ts +2 -1
- package/dist/workspace/workspace-cache.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/agent-project/lock-to-dependencies.d.ts +0 -11
- package/dist/agent-project/lock-to-dependencies.d.ts.map +0 -1
- package/dist/dependencies/lock-file.d.ts +0 -15
- package/dist/dependencies/lock-file.d.ts.map +0 -1
- package/dist/integrations/enhanced-cache.d.ts +0 -53
- package/dist/integrations/enhanced-cache.d.ts.map +0 -1
- package/dist/plugins/enhanced-cache.d.ts +0 -53
- package/dist/plugins/enhanced-cache.d.ts.map +0 -1
- package/dist/templates/blank/package.json +0 -17
- package/dist/templates/blank/tsconfig.json +0 -25
- package/dist/templates/botpress-desk/package.json +0 -17
- package/dist/templates/crm-enrichment/package.json +0 -18
- package/dist/templates/crm-enrichment/tsconfig.json +0 -25
- package/dist/templates/hello-world/package.json +0 -18
- package/dist/templates/hello-world/tsconfig.json +0 -25
- package/dist/templates/knowledge-assistant/package.json +0 -18
- package/dist/templates/knowledge-assistant/tsconfig.json +0 -25
- package/dist/templates/slack-triage/package.json +0 -18
- package/dist/templates/slack-triage/tsconfig.json +0 -25
|
@@ -15,18 +15,18 @@ npm install @botpress/zai @botpress/client @bpinternal/zui
|
|
|
15
15
|
#### Basic Setup
|
|
16
16
|
|
|
17
17
|
```typescript
|
|
18
|
-
import { Client } from
|
|
19
|
-
import { Zai } from
|
|
20
|
-
import { z } from
|
|
18
|
+
import { Client } from '@botpress/client'
|
|
19
|
+
import { Zai } from '@botpress/zai'
|
|
20
|
+
import { z } from '@bpinternal/zui'
|
|
21
21
|
|
|
22
22
|
// Initialize Botpress client
|
|
23
23
|
const client = new Client({
|
|
24
|
-
botId:
|
|
25
|
-
token:
|
|
26
|
-
})
|
|
24
|
+
botId: 'YOUR_BOT_ID',
|
|
25
|
+
token: 'YOUR_TOKEN',
|
|
26
|
+
})
|
|
27
27
|
|
|
28
28
|
// Create ZAI instance
|
|
29
|
-
const zai = new Zai({ client })
|
|
29
|
+
const zai = new Zai({ client })
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
#### Configuration Options
|
|
@@ -34,16 +34,16 @@ const zai = new Zai({ client });
|
|
|
34
34
|
```typescript
|
|
35
35
|
const zai = new Zai({
|
|
36
36
|
client, // Required: Botpress client or Cognitive instance
|
|
37
|
-
modelId:
|
|
38
|
-
userId:
|
|
39
|
-
namespace:
|
|
37
|
+
modelId: 'best', // Model selection: 'best' | 'fast' | specific model ID
|
|
38
|
+
userId: 'user-123', // Optional: Track usage per user
|
|
39
|
+
namespace: 'my-app', // Default: 'zai'
|
|
40
40
|
activeLearning: {
|
|
41
41
|
// Enable learning from examples
|
|
42
42
|
enable: true,
|
|
43
|
-
tableName:
|
|
44
|
-
taskId:
|
|
43
|
+
tableName: 'AILearningTable',
|
|
44
|
+
taskId: 'sentiment-analysis',
|
|
45
45
|
},
|
|
46
|
-
})
|
|
46
|
+
})
|
|
47
47
|
```
|
|
48
48
|
|
|
49
49
|
### 2. Core Operations
|
|
@@ -56,13 +56,13 @@ Extract structured data from any input using Zod schemas. Located in `/packages/
|
|
|
56
56
|
|
|
57
57
|
```typescript
|
|
58
58
|
const person = await zai.extract(
|
|
59
|
-
|
|
59
|
+
'John Doe is 30 years old and lives in New York',
|
|
60
60
|
z.object({
|
|
61
61
|
name: z.string(),
|
|
62
62
|
age: z.number(),
|
|
63
63
|
location: z.string(),
|
|
64
|
-
})
|
|
65
|
-
)
|
|
64
|
+
})
|
|
65
|
+
)
|
|
66
66
|
// Result: { name: 'John Doe', age: 30, location: 'New York' }
|
|
67
67
|
```
|
|
68
68
|
|
|
@@ -76,19 +76,19 @@ const products = await zai.extract(
|
|
|
76
76
|
name: z.string(),
|
|
77
77
|
price: z.number(),
|
|
78
78
|
inStock: z.boolean(),
|
|
79
|
-
})
|
|
80
|
-
)
|
|
81
|
-
)
|
|
79
|
+
})
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
82
|
```
|
|
83
83
|
|
|
84
84
|
**Advanced Options:**
|
|
85
85
|
|
|
86
86
|
```typescript
|
|
87
87
|
const data = await zai.extract(input, schema, {
|
|
88
|
-
instructions:
|
|
88
|
+
instructions: 'Focus on technical specifications', // Guide extraction
|
|
89
89
|
chunkLength: 8000, // Max tokens per chunk (default: 16000)
|
|
90
90
|
strict: false, // Allow partial matches
|
|
91
|
-
})
|
|
91
|
+
})
|
|
92
92
|
```
|
|
93
93
|
|
|
94
94
|
**Large Document Handling:**
|
|
@@ -105,15 +105,15 @@ Verify conditions with natural language. Located in `/packages/zai/src/operation
|
|
|
105
105
|
**Simple Check:**
|
|
106
106
|
|
|
107
107
|
```typescript
|
|
108
|
-
const isSpam = await zai.check(
|
|
108
|
+
const isSpam = await zai.check('Win FREE iPhone!!!', 'is spam')
|
|
109
109
|
// Result: true
|
|
110
110
|
```
|
|
111
111
|
|
|
112
112
|
**Detailed Results:**
|
|
113
113
|
|
|
114
114
|
```typescript
|
|
115
|
-
const result = await zai.check(email,
|
|
116
|
-
const { value, explanation } = await result.full()
|
|
115
|
+
const result = await zai.check(email, 'contains personal information')
|
|
116
|
+
const { value, explanation } = await result.full()
|
|
117
117
|
// value: true
|
|
118
118
|
// explanation: "The email contains names, addresses, and phone numbers"
|
|
119
119
|
```
|
|
@@ -121,12 +121,12 @@ const { value, explanation } = await result.full();
|
|
|
121
121
|
**With Examples:**
|
|
122
122
|
|
|
123
123
|
```typescript
|
|
124
|
-
const isValid = await zai.check(code,
|
|
124
|
+
const isValid = await zai.check(code, 'is valid JavaScript', {
|
|
125
125
|
examples: [
|
|
126
|
-
{ input:
|
|
127
|
-
{ input:
|
|
126
|
+
{ input: 'const x = 1', check: true, reason: 'Valid const declaration' },
|
|
127
|
+
{ input: 'const = 1', check: false, reason: 'Missing variable name' },
|
|
128
128
|
],
|
|
129
|
-
})
|
|
129
|
+
})
|
|
130
130
|
```
|
|
131
131
|
|
|
132
132
|
#### 2.3 Label - Multi-Label Classification
|
|
@@ -135,19 +135,19 @@ Apply multiple labels simultaneously. Located in `/packages/zai/src/operations/l
|
|
|
135
135
|
|
|
136
136
|
```typescript
|
|
137
137
|
const labels = await zai.label(customerReview, {
|
|
138
|
-
positive:
|
|
139
|
-
technical:
|
|
140
|
-
verified:
|
|
141
|
-
urgent:
|
|
142
|
-
})
|
|
138
|
+
positive: 'expresses positive sentiment',
|
|
139
|
+
technical: 'mentions technical specifications',
|
|
140
|
+
verified: 'from a verified purchaser',
|
|
141
|
+
urgent: 'requires immediate attention',
|
|
142
|
+
})
|
|
143
143
|
// Result: { positive: true, technical: true, verified: false, urgent: false }
|
|
144
144
|
```
|
|
145
145
|
|
|
146
146
|
Each label gets its own explanation:
|
|
147
147
|
|
|
148
148
|
```typescript
|
|
149
|
-
const result = await zai.label(text, criteria)
|
|
150
|
-
const detailed = await result.full()
|
|
149
|
+
const result = await zai.label(text, criteria)
|
|
150
|
+
const detailed = await result.full()
|
|
151
151
|
// detailed.positive = { value: true, explanation: "User says 'excellent product'" }
|
|
152
152
|
```
|
|
153
153
|
|
|
@@ -158,16 +158,13 @@ Transform text according to instructions. Located in `/packages/zai/src/operatio
|
|
|
158
158
|
**Translation:**
|
|
159
159
|
|
|
160
160
|
```typescript
|
|
161
|
-
const french = await zai.rewrite(englishText,
|
|
161
|
+
const french = await zai.rewrite(englishText, 'translate to French')
|
|
162
162
|
```
|
|
163
163
|
|
|
164
164
|
**Tone Adjustment:**
|
|
165
165
|
|
|
166
166
|
```typescript
|
|
167
|
-
const professional = await zai.rewrite(
|
|
168
|
-
"hey whats up? need that report asap!!",
|
|
169
|
-
"make it professional and polite",
|
|
170
|
-
);
|
|
167
|
+
const professional = await zai.rewrite('hey whats up? need that report asap!!', 'make it professional and polite')
|
|
171
168
|
// "Good morning, I hope this message finds you well.
|
|
172
169
|
// Could you please provide the report at your earliest convenience?"
|
|
173
170
|
```
|
|
@@ -175,8 +172,8 @@ const professional = await zai.rewrite(
|
|
|
175
172
|
**Format Conversion:**
|
|
176
173
|
|
|
177
174
|
```typescript
|
|
178
|
-
const markdown = await zai.rewrite(htmlContent,
|
|
179
|
-
const json = await zai.rewrite(csvData,
|
|
175
|
+
const markdown = await zai.rewrite(htmlContent, 'convert to Markdown format')
|
|
176
|
+
const json = await zai.rewrite(csvData, 'convert to JSON array')
|
|
180
177
|
```
|
|
181
178
|
|
|
182
179
|
#### 2.5 Filter - Array Filtering
|
|
@@ -185,15 +182,12 @@ Filter arrays using natural language conditions. Located in `/packages/zai/src/o
|
|
|
185
182
|
|
|
186
183
|
```typescript
|
|
187
184
|
const companies = [
|
|
188
|
-
{ name:
|
|
189
|
-
{ name:
|
|
190
|
-
{ name:
|
|
191
|
-
]
|
|
192
|
-
|
|
193
|
-
const techGiants = await zai.filter(
|
|
194
|
-
companies,
|
|
195
|
-
"are technology companies with revenue over 200 billion",
|
|
196
|
-
);
|
|
185
|
+
{ name: 'Apple', industry: 'Tech', revenue: 365 },
|
|
186
|
+
{ name: 'Ford', industry: 'Auto', revenue: 156 },
|
|
187
|
+
{ name: 'Google', industry: 'Tech', revenue: 282 },
|
|
188
|
+
]
|
|
189
|
+
|
|
190
|
+
const techGiants = await zai.filter(companies, 'are technology companies with revenue over 200 billion')
|
|
197
191
|
// Result: [Apple, Google]
|
|
198
192
|
```
|
|
199
193
|
|
|
@@ -207,8 +201,8 @@ const eligibleUsers = await zai.filter(
|
|
|
207
201
|
- Account created more than 30 days ago
|
|
208
202
|
- No recent violations
|
|
209
203
|
- Located in North America
|
|
210
|
-
|
|
211
|
-
)
|
|
204
|
+
`
|
|
205
|
+
)
|
|
212
206
|
```
|
|
213
207
|
|
|
214
208
|
#### 2.6 Text - Content Generation
|
|
@@ -216,11 +210,11 @@ const eligibleUsers = await zai.filter(
|
|
|
216
210
|
Generate text from prompts. Located in `/packages/zai/src/operations/text.ts`.
|
|
217
211
|
|
|
218
212
|
```typescript
|
|
219
|
-
const blogPost = await zai.text(
|
|
213
|
+
const blogPost = await zai.text('Write about the future of AI in healthcare', {
|
|
220
214
|
length: 1000, // Target length in tokens
|
|
221
215
|
temperature: 0.7, // Creativity (0-1)
|
|
222
|
-
stopSequences: [
|
|
223
|
-
})
|
|
216
|
+
stopSequences: ['---'], // Optional stop markers
|
|
217
|
+
})
|
|
224
218
|
```
|
|
225
219
|
|
|
226
220
|
**Structured Generation:**
|
|
@@ -232,7 +226,7 @@ const outline = await zai.text(`
|
|
|
232
226
|
- Level: Beginner
|
|
233
227
|
- Duration: 8 weeks
|
|
234
228
|
- Format: Online
|
|
235
|
-
`)
|
|
229
|
+
`)
|
|
236
230
|
```
|
|
237
231
|
|
|
238
232
|
#### 2.7 Summarize - Document Summarization
|
|
@@ -242,7 +236,7 @@ Create intelligent summaries. Located in `/packages/zai/src/operations/summarize
|
|
|
242
236
|
**Basic Summary:**
|
|
243
237
|
|
|
244
238
|
```typescript
|
|
245
|
-
const summary = await zai.summarize(longArticle)
|
|
239
|
+
const summary = await zai.summarize(longArticle)
|
|
246
240
|
```
|
|
247
241
|
|
|
248
242
|
**Custom Summaries:**
|
|
@@ -250,9 +244,9 @@ const summary = await zai.summarize(longArticle);
|
|
|
250
244
|
```typescript
|
|
251
245
|
const technicalSummary = await zai.summarize(researchPaper, {
|
|
252
246
|
length: 500, // Max tokens
|
|
253
|
-
prompt:
|
|
247
|
+
prompt: 'Focus on methodology and results',
|
|
254
248
|
bulletPoints: true, // Format as bullet points
|
|
255
|
-
})
|
|
249
|
+
})
|
|
256
250
|
```
|
|
257
251
|
|
|
258
252
|
**Handling Large Documents:**
|
|
@@ -261,8 +255,8 @@ const technicalSummary = await zai.summarize(researchPaper, {
|
|
|
261
255
|
// ZAI automatically handles documents of any size
|
|
262
256
|
const bookSummary = await zai.summarize(entireBook, {
|
|
263
257
|
length: 2000,
|
|
264
|
-
prompt:
|
|
265
|
-
})
|
|
258
|
+
prompt: 'Summarize each chapter separately, then provide overall themes',
|
|
259
|
+
})
|
|
266
260
|
```
|
|
267
261
|
|
|
268
262
|
#### 2.8 Answer - Question Answering with Citations
|
|
@@ -273,15 +267,15 @@ Answer questions from documents with citations and intelligent edge case handlin
|
|
|
273
267
|
|
|
274
268
|
```typescript
|
|
275
269
|
const documents = [
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
]
|
|
280
|
-
|
|
281
|
-
const result = await zai.answer(documents,
|
|
282
|
-
if (result.type ===
|
|
283
|
-
console.log(result.answer)
|
|
284
|
-
console.log(result.citations)
|
|
270
|
+
'Botpress was founded in 2016.',
|
|
271
|
+
'The company is based in Quebec, Canada.',
|
|
272
|
+
'Botpress provides an AI agent platform.',
|
|
273
|
+
]
|
|
274
|
+
|
|
275
|
+
const result = await zai.answer(documents, 'When was Botpress founded?')
|
|
276
|
+
if (result.type === 'answer') {
|
|
277
|
+
console.log(result.answer) // "Botpress was founded in 2016."
|
|
278
|
+
console.log(result.citations) // Citations with source references
|
|
285
279
|
}
|
|
286
280
|
```
|
|
287
281
|
|
|
@@ -290,36 +284,36 @@ if (result.type === "answer") {
|
|
|
290
284
|
The answer operation returns different types based on the situation:
|
|
291
285
|
|
|
292
286
|
```typescript
|
|
293
|
-
const result = await zai.answer(documents, question)
|
|
287
|
+
const result = await zai.answer(documents, question)
|
|
294
288
|
|
|
295
289
|
switch (result.type) {
|
|
296
|
-
case
|
|
290
|
+
case 'answer':
|
|
297
291
|
// Has answer with citations
|
|
298
|
-
console.log(result.answer)
|
|
299
|
-
console.log(result.citations)
|
|
300
|
-
break
|
|
292
|
+
console.log(result.answer)
|
|
293
|
+
console.log(result.citations) // [{ offset, item, snippet }]
|
|
294
|
+
break
|
|
301
295
|
|
|
302
|
-
case
|
|
296
|
+
case 'ambiguous':
|
|
303
297
|
// Multiple interpretations exist
|
|
304
|
-
console.log(result.ambiguity)
|
|
305
|
-
console.log(result.follow_up)
|
|
306
|
-
console.log(result.answers)
|
|
307
|
-
break
|
|
298
|
+
console.log(result.ambiguity) // Why it's ambiguous
|
|
299
|
+
console.log(result.follow_up) // Clarifying question
|
|
300
|
+
console.log(result.answers) // Possible answers
|
|
301
|
+
break
|
|
308
302
|
|
|
309
|
-
case
|
|
303
|
+
case 'out_of_topic':
|
|
310
304
|
// Question unrelated to documents
|
|
311
|
-
console.log(result.reason)
|
|
312
|
-
break
|
|
305
|
+
console.log(result.reason)
|
|
306
|
+
break
|
|
313
307
|
|
|
314
|
-
case
|
|
308
|
+
case 'invalid_question':
|
|
315
309
|
// Malformed or unclear question
|
|
316
|
-
console.log(result.reason)
|
|
317
|
-
break
|
|
310
|
+
console.log(result.reason)
|
|
311
|
+
break
|
|
318
312
|
|
|
319
|
-
case
|
|
313
|
+
case 'missing_knowledge':
|
|
320
314
|
// Insufficient information to answer
|
|
321
|
-
console.log(result.reason)
|
|
322
|
-
break
|
|
315
|
+
console.log(result.reason)
|
|
316
|
+
break
|
|
323
317
|
}
|
|
324
318
|
```
|
|
325
319
|
|
|
@@ -336,12 +330,12 @@ const result = await zai.answer(documents, "What is the pricing?", {
|
|
|
336
330
|
**Tracking Citations:**
|
|
337
331
|
|
|
338
332
|
```typescript
|
|
339
|
-
if (result.type ===
|
|
333
|
+
if (result.type === 'answer') {
|
|
340
334
|
result.citations.forEach((citation) => {
|
|
341
|
-
console.log(`At position ${citation.offset}:`)
|
|
342
|
-
console.log(` Cited: "${citation.snippet}"`)
|
|
343
|
-
console.log(` From document:`, citation.item)
|
|
344
|
-
})
|
|
335
|
+
console.log(`At position ${citation.offset}:`)
|
|
336
|
+
console.log(` Cited: "${citation.snippet}"`)
|
|
337
|
+
console.log(` From document:`, citation.item)
|
|
338
|
+
})
|
|
345
339
|
}
|
|
346
340
|
```
|
|
347
341
|
|
|
@@ -354,8 +348,8 @@ Rate array items on a 1-5 scale based on criteria. Located in `/packages/zai/src
|
|
|
354
348
|
```typescript
|
|
355
349
|
const emails = [
|
|
356
350
|
/* array of emails */
|
|
357
|
-
]
|
|
358
|
-
const urgencyScores = await zai.rate(emails,
|
|
351
|
+
]
|
|
352
|
+
const urgencyScores = await zai.rate(emails, 'urgency level')
|
|
359
353
|
// Result: [4, 2, 5, 1, 3] // Numbers 1-5
|
|
360
354
|
```
|
|
361
355
|
|
|
@@ -364,12 +358,12 @@ const urgencyScores = await zai.rate(emails, "urgency level");
|
|
|
364
358
|
```typescript
|
|
365
359
|
const products = [
|
|
366
360
|
/* array of products */
|
|
367
|
-
]
|
|
361
|
+
]
|
|
368
362
|
const ratings = await zai.rate(products, {
|
|
369
|
-
quality:
|
|
370
|
-
value:
|
|
371
|
-
design:
|
|
372
|
-
})
|
|
363
|
+
quality: 'product build quality',
|
|
364
|
+
value: 'price to performance ratio',
|
|
365
|
+
design: 'aesthetic appeal',
|
|
366
|
+
})
|
|
373
367
|
// Result: [
|
|
374
368
|
// { quality: 5, value: 4, design: 5, total: 14 },
|
|
375
369
|
// { quality: 3, value: 5, design: 4, total: 12 },
|
|
@@ -383,7 +377,7 @@ const ratings = await zai.rate(products, {
|
|
|
383
377
|
const rated = await zai.rate(items, instructions, {
|
|
384
378
|
tokensPerItem: 250, // Max tokens per item
|
|
385
379
|
maxItemsPerChunk: 50, // Items per batch
|
|
386
|
-
})
|
|
380
|
+
})
|
|
387
381
|
```
|
|
388
382
|
|
|
389
383
|
#### 2.10 Sort - Natural Language Sorting
|
|
@@ -393,17 +387,14 @@ Sort arrays based on natural language instructions. Located in `/packages/zai/sr
|
|
|
393
387
|
**Basic Sorting:**
|
|
394
388
|
|
|
395
389
|
```typescript
|
|
396
|
-
const sorted = await zai.sort(tickets,
|
|
397
|
-
const byPrice = await zai.sort(products,
|
|
390
|
+
const sorted = await zai.sort(tickets, 'from least urgent to most urgent')
|
|
391
|
+
const byPrice = await zai.sort(products, 'by price, cheapest first')
|
|
398
392
|
```
|
|
399
393
|
|
|
400
394
|
**Priority-Based Sorting:**
|
|
401
395
|
|
|
402
396
|
```typescript
|
|
403
|
-
const prioritized = await zai.sort(
|
|
404
|
-
emails,
|
|
405
|
-
"prioritize: open old items highest",
|
|
406
|
-
);
|
|
397
|
+
const prioritized = await zai.sort(emails, 'prioritize: open old items highest')
|
|
407
398
|
// First item = highest priority, last = lowest priority
|
|
408
399
|
```
|
|
409
400
|
|
|
@@ -417,8 +408,8 @@ const sorted = await zai.sort(
|
|
|
417
408
|
1. Completeness (complete applications first)
|
|
418
409
|
2. Submission date (newer first)
|
|
419
410
|
3. Applicant experience (more experienced first)
|
|
420
|
-
|
|
421
|
-
)
|
|
411
|
+
`
|
|
412
|
+
)
|
|
422
413
|
```
|
|
423
414
|
|
|
424
415
|
**With Options:**
|
|
@@ -426,7 +417,7 @@ const sorted = await zai.sort(
|
|
|
426
417
|
```typescript
|
|
427
418
|
const sorted = await zai.sort(items, instructions, {
|
|
428
419
|
tokensPerItem: 250, // Max tokens per item
|
|
429
|
-
})
|
|
420
|
+
})
|
|
430
421
|
```
|
|
431
422
|
|
|
432
423
|
#### 2.11 Group - Array Grouping
|
|
@@ -437,8 +428,8 @@ Group array elements based on natural language criteria. Located in `/packages/z
|
|
|
437
428
|
|
|
438
429
|
```typescript
|
|
439
430
|
const groups = await zai.group(tickets, {
|
|
440
|
-
instructions:
|
|
441
|
-
})
|
|
431
|
+
instructions: 'group by issue type and priority',
|
|
432
|
+
})
|
|
442
433
|
// Result: [
|
|
443
434
|
// { id: 'bugs', label: 'Bug Reports', elements: [...] },
|
|
444
435
|
// { id: 'features', label: 'Feature Requests', elements: [...] },
|
|
@@ -450,26 +441,26 @@ const groups = await zai.group(tickets, {
|
|
|
450
441
|
|
|
451
442
|
```typescript
|
|
452
443
|
const groups = await zai.group(emails, {
|
|
453
|
-
instructions:
|
|
444
|
+
instructions: 'categorize emails',
|
|
454
445
|
initialGroups: [
|
|
455
|
-
{ id:
|
|
456
|
-
{ id:
|
|
457
|
-
{ id:
|
|
446
|
+
{ id: 'urgent', label: 'Urgent' },
|
|
447
|
+
{ id: 'spam', label: 'Spam' },
|
|
448
|
+
{ id: 'normal', label: 'Normal' },
|
|
458
449
|
],
|
|
459
|
-
})
|
|
450
|
+
})
|
|
460
451
|
```
|
|
461
452
|
|
|
462
453
|
**Access Results:**
|
|
463
454
|
|
|
464
455
|
```typescript
|
|
465
456
|
// As groups array
|
|
466
|
-
const groups = await zai.group(items, options)
|
|
457
|
+
const groups = await zai.group(items, options)
|
|
467
458
|
for (const group of groups) {
|
|
468
|
-
console.log(`${group.label}: ${group.elements.length} items`)
|
|
459
|
+
console.log(`${group.label}: ${group.elements.length} items`)
|
|
469
460
|
}
|
|
470
461
|
|
|
471
462
|
// As dictionary (using .result())
|
|
472
|
-
const { output } = await zai.group(items, options).result()
|
|
463
|
+
const { output } = await zai.group(items, options).result()
|
|
473
464
|
// output is Record<string, T[]>
|
|
474
465
|
```
|
|
475
466
|
|
|
@@ -493,13 +484,13 @@ Patch code files using natural language instructions with efficient micropatch p
|
|
|
493
484
|
```typescript
|
|
494
485
|
const files = [
|
|
495
486
|
{
|
|
496
|
-
path:
|
|
497
|
-
name:
|
|
487
|
+
path: 'src/hello.ts',
|
|
488
|
+
name: 'hello.ts',
|
|
498
489
|
content: 'console.log("Hello World")',
|
|
499
490
|
},
|
|
500
|
-
]
|
|
491
|
+
]
|
|
501
492
|
|
|
502
|
-
const patched = await zai.patch(files, 'change message to "Hi World"')
|
|
493
|
+
const patched = await zai.patch(files, 'change message to "Hi World"')
|
|
503
494
|
// Result: [{
|
|
504
495
|
// path: 'src/hello.ts',
|
|
505
496
|
// name: 'hello.ts',
|
|
@@ -512,40 +503,37 @@ const patched = await zai.patch(files, 'change message to "Hi World"');
|
|
|
512
503
|
|
|
513
504
|
```typescript
|
|
514
505
|
const files = [
|
|
515
|
-
{ path:
|
|
516
|
-
{ path:
|
|
517
|
-
]
|
|
506
|
+
{ path: 'package.json', name: 'package.json', content: '...' },
|
|
507
|
+
{ path: 'config.json', name: 'config.json', content: '...' },
|
|
508
|
+
]
|
|
518
509
|
|
|
519
|
-
const patched = await zai.patch(
|
|
520
|
-
files,
|
|
521
|
-
"update version to 2.0.0 in all config files",
|
|
522
|
-
);
|
|
510
|
+
const patched = await zai.patch(files, 'update version to 2.0.0 in all config files')
|
|
523
511
|
```
|
|
524
512
|
|
|
525
513
|
**Common Use Cases:**
|
|
526
514
|
|
|
527
515
|
```typescript
|
|
528
516
|
// Add documentation
|
|
529
|
-
await zai.patch(files,
|
|
517
|
+
await zai.patch(files, 'add JSDoc comments to all exported functions')
|
|
530
518
|
|
|
531
519
|
// Remove code
|
|
532
|
-
await zai.patch(files,
|
|
520
|
+
await zai.patch(files, 'remove all debug code')
|
|
533
521
|
|
|
534
522
|
// Refactoring
|
|
535
|
-
await zai.patch(files,
|
|
523
|
+
await zai.patch(files, 'convert to async/await and add error handling')
|
|
536
524
|
|
|
537
525
|
// Type annotations
|
|
538
|
-
await zai.patch(files,
|
|
526
|
+
await zai.patch(files, 'add TypeScript types to all function parameters')
|
|
539
527
|
```
|
|
540
528
|
|
|
541
529
|
**Inspect Applied Patches:**
|
|
542
530
|
|
|
543
531
|
```typescript
|
|
544
|
-
const patched = await zai.patch(files, instructions)
|
|
532
|
+
const patched = await zai.patch(files, instructions)
|
|
545
533
|
for (const file of patched) {
|
|
546
534
|
if (file.patch) {
|
|
547
|
-
console.log(`Patches for ${file.path}:`)
|
|
548
|
-
console.log(file.patch)
|
|
535
|
+
console.log(`Patches for ${file.path}:`)
|
|
536
|
+
console.log(file.patch) // Micropatch operations
|
|
549
537
|
}
|
|
550
538
|
}
|
|
551
539
|
```
|
|
@@ -555,7 +543,7 @@ for (const file of patched) {
|
|
|
555
543
|
```typescript
|
|
556
544
|
const patched = await zai.patch(files, instructions, {
|
|
557
545
|
maxTokensPerChunk: 16000, // Max tokens per processing chunk
|
|
558
|
-
})
|
|
546
|
+
})
|
|
559
547
|
```
|
|
560
548
|
|
|
561
549
|
### 3. Advanced Features
|
|
@@ -567,14 +555,12 @@ Enable learning from examples to improve accuracy over time. Implementation in `
|
|
|
567
555
|
**How It Works:**
|
|
568
556
|
|
|
569
557
|
1. **Example Storage**: When enabled, ZAI stores successful operations as examples with:
|
|
570
|
-
|
|
571
558
|
- A unique hash key based on input, instructions, task type, and task ID
|
|
572
559
|
- The input and output data
|
|
573
560
|
- Metadata (tokens, cost, latency, model used)
|
|
574
561
|
- A status field (`'pending'` by default)
|
|
575
562
|
|
|
576
563
|
2. **Example Retrieval**: On subsequent operations, ZAI:
|
|
577
|
-
|
|
578
564
|
- Generates the same hash key for identical inputs
|
|
579
565
|
- Checks for exact matches (returns immediately if found - no LLM call!)
|
|
580
566
|
- Searches for similar examples using Botpress Tables API (first 1024 chars)
|
|
@@ -585,12 +571,12 @@ Enable learning from examples to improve accuracy over time. Implementation in `
|
|
|
585
571
|
```typescript
|
|
586
572
|
const Key = fastHash(
|
|
587
573
|
JSON.stringify({
|
|
588
|
-
taskType:
|
|
589
|
-
taskId:
|
|
574
|
+
taskType: 'zai.extract',
|
|
575
|
+
taskId: 'product-extraction',
|
|
590
576
|
input: inputAsString,
|
|
591
|
-
instructions:
|
|
592
|
-
})
|
|
593
|
-
)
|
|
577
|
+
instructions: 'Extract product details',
|
|
578
|
+
})
|
|
579
|
+
)
|
|
594
580
|
```
|
|
595
581
|
|
|
596
582
|
**Configuration:**
|
|
@@ -601,14 +587,14 @@ const zai = new Zai({
|
|
|
601
587
|
client,
|
|
602
588
|
activeLearning: {
|
|
603
589
|
enable: true,
|
|
604
|
-
tableName:
|
|
605
|
-
taskId:
|
|
590
|
+
tableName: 'MyLearningTable', // Must end with "Table"
|
|
591
|
+
taskId: 'my-task', // Namespaced as 'zai/my-task'
|
|
606
592
|
},
|
|
607
|
-
})
|
|
593
|
+
})
|
|
608
594
|
|
|
609
595
|
// Enable for specific task using .learn()
|
|
610
|
-
const sentimentZai = zai.learn(
|
|
611
|
-
const result = await sentimentZai.check(text,
|
|
596
|
+
const sentimentZai = zai.learn('sentiment-analysis')
|
|
597
|
+
const result = await sentimentZai.check(text, 'is positive')
|
|
612
598
|
```
|
|
613
599
|
|
|
614
600
|
**Important Notes:**
|
|
@@ -624,7 +610,7 @@ Creates a new ZAI instance with active learning enabled for a specific task:
|
|
|
624
610
|
|
|
625
611
|
```typescript
|
|
626
612
|
// Enable for specific task
|
|
627
|
-
const sentimentZai = zai.learn(
|
|
613
|
+
const sentimentZai = zai.learn('sentiment-analysis')
|
|
628
614
|
|
|
629
615
|
// What actually happens:
|
|
630
616
|
// 1. Enables active learning with the given taskId
|
|
@@ -667,12 +653,12 @@ const sentimentZai = zai.learn("sentiment-analysis");
|
|
|
667
653
|
|
|
668
654
|
```typescript
|
|
669
655
|
// Isolate learning contexts
|
|
670
|
-
const productSpamZai = zai.learn(
|
|
671
|
-
const commentSpamZai = zai.learn(
|
|
656
|
+
const productSpamZai = zai.learn('spam-detection-products')
|
|
657
|
+
const commentSpamZai = zai.learn('spam-detection-comments')
|
|
672
658
|
|
|
673
659
|
// Each maintains separate example sets
|
|
674
|
-
const isProductSpam = await productSpamZai.check(productDesc,
|
|
675
|
-
const isCommentSpam = await commentSpamZai.check(userComment,
|
|
660
|
+
const isProductSpam = await productSpamZai.check(productDesc, 'is spam')
|
|
661
|
+
const isCommentSpam = await commentSpamZai.check(userComment, 'is spam')
|
|
676
662
|
```
|
|
677
663
|
|
|
678
664
|
#### 3.2 Progress Tracking
|
|
@@ -680,36 +666,36 @@ const isCommentSpam = await commentSpamZai.check(userComment, "is spam");
|
|
|
680
666
|
Monitor long-running operations. Implementation in `/packages/zai/src/response.ts`.
|
|
681
667
|
|
|
682
668
|
```typescript
|
|
683
|
-
const response = zai.summarize(veryLongDocument)
|
|
669
|
+
const response = zai.summarize(veryLongDocument)
|
|
684
670
|
|
|
685
671
|
// Track progress
|
|
686
|
-
response.on(
|
|
687
|
-
console.log(`Processing: ${progress.percent}% complete`)
|
|
688
|
-
console.log(`Chunks: ${progress.completed}/${progress.total}`)
|
|
689
|
-
})
|
|
672
|
+
response.on('progress', (progress) => {
|
|
673
|
+
console.log(`Processing: ${progress.percent}% complete`)
|
|
674
|
+
console.log(`Chunks: ${progress.completed}/${progress.total}`)
|
|
675
|
+
})
|
|
690
676
|
|
|
691
|
-
const summary = await response
|
|
677
|
+
const summary = await response
|
|
692
678
|
```
|
|
693
679
|
|
|
694
680
|
**Additional Event Methods:**
|
|
695
681
|
|
|
696
682
|
```typescript
|
|
697
683
|
// One-time event listener
|
|
698
|
-
response.once(
|
|
699
|
-
console.log(
|
|
700
|
-
})
|
|
684
|
+
response.once('complete', (result) => {
|
|
685
|
+
console.log('Operation finished:', result)
|
|
686
|
+
})
|
|
701
687
|
|
|
702
688
|
// Remove event listener
|
|
703
|
-
const handler = (progress) => console.log(progress)
|
|
704
|
-
response.on(
|
|
705
|
-
response.off(
|
|
689
|
+
const handler = (progress) => console.log(progress)
|
|
690
|
+
response.on('progress', handler)
|
|
691
|
+
response.off('progress', handler)
|
|
706
692
|
|
|
707
693
|
// Connect AbortSignal for external cancellation control
|
|
708
|
-
const controller = new AbortController()
|
|
709
|
-
response.bindSignal(controller.signal)
|
|
694
|
+
const controller = new AbortController()
|
|
695
|
+
response.bindSignal(controller.signal)
|
|
710
696
|
|
|
711
697
|
// Cancel from external controller
|
|
712
|
-
setTimeout(() => controller.abort(), 5000)
|
|
698
|
+
setTimeout(() => controller.abort(), 5000)
|
|
713
699
|
```
|
|
714
700
|
|
|
715
701
|
#### 3.3 Usage Monitoring
|
|
@@ -717,8 +703,8 @@ setTimeout(() => controller.abort(), 5000);
|
|
|
717
703
|
Track tokens, costs, and performance. Implementation in `/packages/zai/src/context.ts:175-196`.
|
|
718
704
|
|
|
719
705
|
```typescript
|
|
720
|
-
const result = await zai.extract(text, schema)
|
|
721
|
-
const usage = await result.usage()
|
|
706
|
+
const result = await zai.extract(text, schema)
|
|
707
|
+
const usage = await result.usage()
|
|
722
708
|
|
|
723
709
|
console.log({
|
|
724
710
|
tokens: {
|
|
@@ -734,7 +720,7 @@ console.log({
|
|
|
734
720
|
requests: usage.requests.requests,
|
|
735
721
|
cached: usage.requests.cached,
|
|
736
722
|
latency: usage.elapsedTime, // Milliseconds
|
|
737
|
-
})
|
|
723
|
+
})
|
|
738
724
|
```
|
|
739
725
|
|
|
740
726
|
#### 3.4 Method Chaining
|
|
@@ -743,15 +729,12 @@ Create specialized instances with different configurations:
|
|
|
743
729
|
|
|
744
730
|
```typescript
|
|
745
731
|
// Create temperature variant
|
|
746
|
-
const creativeZai = zai.with({ temperature: 0.9 })
|
|
732
|
+
const creativeZai = zai.with({ temperature: 0.9 })
|
|
747
733
|
|
|
748
734
|
// Chain multiple configurations
|
|
749
|
-
const preciseExtractor = zai
|
|
750
|
-
.with({ modelId: "gpt-4-turbo" })
|
|
751
|
-
.with({ temperature: 0.1 })
|
|
752
|
-
.learn("invoice-extraction");
|
|
735
|
+
const preciseExtractor = zai.with({ modelId: 'gpt-4-turbo' }).with({ temperature: 0.1 }).learn('invoice-extraction')
|
|
753
736
|
|
|
754
|
-
const invoice = await preciseExtractor.extract(document, invoiceSchema)
|
|
737
|
+
const invoice = await preciseExtractor.extract(document, invoiceSchema)
|
|
755
738
|
```
|
|
756
739
|
|
|
757
740
|
#### 3.5 Abort Operations
|
|
@@ -759,16 +742,16 @@ const invoice = await preciseExtractor.extract(document, invoiceSchema);
|
|
|
759
742
|
Cancel long-running operations:
|
|
760
743
|
|
|
761
744
|
```typescript
|
|
762
|
-
const response = zai.summarize(massiveDocument)
|
|
745
|
+
const response = zai.summarize(massiveDocument)
|
|
763
746
|
|
|
764
747
|
// Abort after 5 seconds
|
|
765
|
-
setTimeout(() => response.abort(), 5000)
|
|
748
|
+
setTimeout(() => response.abort(), 5000)
|
|
766
749
|
|
|
767
750
|
try {
|
|
768
|
-
const summary = await response
|
|
751
|
+
const summary = await response
|
|
769
752
|
} catch (error) {
|
|
770
|
-
if (error.name ===
|
|
771
|
-
console.log(
|
|
753
|
+
if (error.name === 'AbortError') {
|
|
754
|
+
console.log('Operation cancelled')
|
|
772
755
|
}
|
|
773
756
|
}
|
|
774
757
|
```
|
|
@@ -779,17 +762,17 @@ try {
|
|
|
779
762
|
|
|
780
763
|
```typescript
|
|
781
764
|
try {
|
|
782
|
-
const result = await zai.extract(text, schema)
|
|
765
|
+
const result = await zai.extract(text, schema)
|
|
783
766
|
} catch (error) {
|
|
784
767
|
if (error instanceof JsonParsingError) {
|
|
785
768
|
// Schema validation failed
|
|
786
|
-
console.error(
|
|
787
|
-
} else if (error.name ===
|
|
769
|
+
console.error('Invalid JSON:', error.message)
|
|
770
|
+
} else if (error.name === 'AbortError') {
|
|
788
771
|
// Operation was cancelled
|
|
789
|
-
console.log(
|
|
790
|
-
} else if (error.code ===
|
|
772
|
+
console.log('Operation aborted')
|
|
773
|
+
} else if (error.code === 'RATE_LIMIT') {
|
|
791
774
|
// API rate limit hit
|
|
792
|
-
await delay(error.retryAfter)
|
|
775
|
+
await delay(error.retryAfter)
|
|
793
776
|
}
|
|
794
777
|
}
|
|
795
778
|
```
|
|
@@ -800,10 +783,10 @@ ZAI includes built-in retry logic with exponential backoff. You can also wrap ZA
|
|
|
800
783
|
|
|
801
784
|
```typescript
|
|
802
785
|
// Example from /packages/llmz/examples/utils/zai.ts:3-33
|
|
803
|
-
import { withRetry } from
|
|
786
|
+
import { withRetry } from './utils/zai'
|
|
804
787
|
|
|
805
|
-
const reliableZai = withRetry(zai)
|
|
806
|
-
const result = await reliableZai.extract(text, schema)
|
|
788
|
+
const reliableZai = withRetry(zai)
|
|
789
|
+
const result = await reliableZai.extract(text, schema) // Retries up to 10 times
|
|
807
790
|
```
|
|
808
791
|
|
|
809
792
|
### 5. Integration Patterns
|
|
@@ -812,19 +795,19 @@ const result = await reliableZai.extract(text, schema); // Retries up to 10 time
|
|
|
812
795
|
|
|
813
796
|
```typescript
|
|
814
797
|
// In Botpress action or hook
|
|
815
|
-
import { Zai } from
|
|
798
|
+
import { Zai } from '@botpress/zai'
|
|
816
799
|
|
|
817
800
|
export const analyzeSentiment = async ({ client, input }) => {
|
|
818
|
-
const zai = new Zai({ client })
|
|
801
|
+
const zai = new Zai({ client })
|
|
819
802
|
|
|
820
803
|
const sentiment = await zai.label(input.message, {
|
|
821
|
-
positive:
|
|
822
|
-
negative:
|
|
823
|
-
neutral:
|
|
824
|
-
})
|
|
804
|
+
positive: 'expresses positive sentiment',
|
|
805
|
+
negative: 'expresses negative sentiment',
|
|
806
|
+
neutral: 'is neutral in tone',
|
|
807
|
+
})
|
|
825
808
|
|
|
826
|
-
return { sentiment }
|
|
827
|
-
}
|
|
809
|
+
return { sentiment }
|
|
810
|
+
}
|
|
828
811
|
```
|
|
829
812
|
|
|
830
813
|
#### 5.2 With LLMz Framework
|
|
@@ -832,31 +815,31 @@ export const analyzeSentiment = async ({ client, input }) => {
|
|
|
832
815
|
Example from `/packages/llmz/examples/07_chat_guardrails/index.ts:33-46`:
|
|
833
816
|
|
|
834
817
|
```typescript
|
|
835
|
-
import { execute, ThinkSignal } from
|
|
836
|
-
import { Zai } from
|
|
818
|
+
import { execute, ThinkSignal } from 'llmz'
|
|
819
|
+
import { Zai } from '@botpress/zai'
|
|
837
820
|
|
|
838
|
-
const zai = new Zai({ client })
|
|
821
|
+
const zai = new Zai({ client })
|
|
839
822
|
|
|
840
823
|
// Use ZAI for content moderation
|
|
841
824
|
const guardrails = {
|
|
842
|
-
violence:
|
|
843
|
-
hate:
|
|
844
|
-
pii:
|
|
845
|
-
}
|
|
825
|
+
violence: 'is free of violence',
|
|
826
|
+
hate: 'is free of hate speech',
|
|
827
|
+
pii: 'does not contain personal data',
|
|
828
|
+
}
|
|
846
829
|
|
|
847
830
|
await execute({
|
|
848
831
|
async onBeforeExecution(iteration) {
|
|
849
|
-
const checks = await zai.label(iteration.code, guardrails)
|
|
832
|
+
const checks = await zai.label(iteration.code, guardrails)
|
|
850
833
|
|
|
851
834
|
const violations = Object.entries(checks)
|
|
852
835
|
.filter(([_, result]) => !result.value)
|
|
853
|
-
.map(([rule, result]) => `${rule}: ${result.explanation}`)
|
|
836
|
+
.map(([rule, result]) => `${rule}: ${result.explanation}`)
|
|
854
837
|
|
|
855
838
|
if (violations.length > 0) {
|
|
856
|
-
throw new ThinkSignal(`Fix violations: ${violations.join(
|
|
839
|
+
throw new ThinkSignal(`Fix violations: ${violations.join(', ')}`)
|
|
857
840
|
}
|
|
858
841
|
},
|
|
859
|
-
})
|
|
842
|
+
})
|
|
860
843
|
```
|
|
861
844
|
|
|
862
845
|
#### 5.3 Batch Processing
|
|
@@ -867,7 +850,7 @@ async function processBatch(documents: string[]) {
|
|
|
867
850
|
const results = await Promise.all(
|
|
868
851
|
documents.map(async (doc, i) => {
|
|
869
852
|
// Stagger requests to avoid rate limits
|
|
870
|
-
await delay(i * 100)
|
|
853
|
+
await delay(i * 100)
|
|
871
854
|
|
|
872
855
|
return zai.extract(
|
|
873
856
|
doc,
|
|
@@ -875,12 +858,12 @@ async function processBatch(documents: string[]) {
|
|
|
875
858
|
title: z.string(),
|
|
876
859
|
category: z.string(),
|
|
877
860
|
summary: z.string(),
|
|
878
|
-
})
|
|
879
|
-
)
|
|
880
|
-
})
|
|
881
|
-
)
|
|
861
|
+
})
|
|
862
|
+
)
|
|
863
|
+
})
|
|
864
|
+
)
|
|
882
865
|
|
|
883
|
-
return results
|
|
866
|
+
return results
|
|
884
867
|
}
|
|
885
868
|
```
|
|
886
869
|
|
|
@@ -941,15 +924,15 @@ packages/zai/
|
|
|
941
924
|
|
|
942
925
|
```typescript
|
|
943
926
|
export class Zai {
|
|
944
|
-
protected client: Cognitive
|
|
945
|
-
protected Model: ModelId
|
|
946
|
-
protected namespace: string
|
|
947
|
-
protected adapter: Adapter
|
|
948
|
-
protected activeLearning: ActiveLearning
|
|
949
|
-
|
|
950
|
-
constructor(config: ZaiConfig)
|
|
951
|
-
with(options: Partial<ZaiConfig>): Zai
|
|
952
|
-
learn(taskId: string): Zai
|
|
927
|
+
protected client: Cognitive // LLM client
|
|
928
|
+
protected Model: ModelId // Selected model
|
|
929
|
+
protected namespace: string // Operation namespace
|
|
930
|
+
protected adapter: Adapter // Storage adapter
|
|
931
|
+
protected activeLearning: ActiveLearning
|
|
932
|
+
|
|
933
|
+
constructor(config: ZaiConfig)
|
|
934
|
+
with(options: Partial<ZaiConfig>): Zai
|
|
935
|
+
learn(taskId: string): Zai
|
|
953
936
|
}
|
|
954
937
|
```
|
|
955
938
|
|
|
@@ -957,12 +940,12 @@ export class Zai {
|
|
|
957
940
|
|
|
958
941
|
```typescript
|
|
959
942
|
export class ZaiContext {
|
|
960
|
-
private _client: Cognitive
|
|
961
|
-
public controller: AbortController
|
|
943
|
+
private _client: Cognitive
|
|
944
|
+
public controller: AbortController
|
|
962
945
|
|
|
963
|
-
async generateContent<Out>(props): Promise<{ meta; output; text; extracted }
|
|
964
|
-
get usage(): Usage
|
|
965
|
-
on<K>(type: K, listener: Function): this
|
|
946
|
+
async generateContent<Out>(props): Promise<{ meta; output; text; extracted }>
|
|
947
|
+
get usage(): Usage
|
|
948
|
+
on<K>(type: K, listener: Function): this
|
|
966
949
|
}
|
|
967
950
|
```
|
|
968
951
|
|
|
@@ -988,8 +971,8 @@ systemPrompt: `
|
|
|
988
971
|
Extract the following information from the input:
|
|
989
972
|
${schemaTypescript}
|
|
990
973
|
====
|
|
991
|
-
${instructions.map((x) => `• ${x}`).join(
|
|
992
|
-
`.trim()
|
|
974
|
+
${instructions.map((x) => `• ${x}`).join('\n')}
|
|
975
|
+
`.trim()
|
|
993
976
|
```
|
|
994
977
|
|
|
995
978
|
Operations include:
|
|
@@ -1005,16 +988,14 @@ For large documents (`/packages/zai/src/operations/extract.ts:112-149`):
|
|
|
1005
988
|
```typescript
|
|
1006
989
|
if (tokenizer.count(inputAsString) > options.chunkLength) {
|
|
1007
990
|
// 1. Split into chunks
|
|
1008
|
-
const tokens = tokenizer.split(inputAsString)
|
|
1009
|
-
const chunks = chunk(tokens, options.chunkLength)
|
|
991
|
+
const tokens = tokenizer.split(inputAsString)
|
|
992
|
+
const chunks = chunk(tokens, options.chunkLength)
|
|
1010
993
|
|
|
1011
994
|
// 2. Process in parallel
|
|
1012
|
-
const all = await Promise.allSettled(
|
|
1013
|
-
chunks.map((chunk) => extract(chunk, schema, options, ctx)),
|
|
1014
|
-
);
|
|
995
|
+
const all = await Promise.allSettled(chunks.map((chunk) => extract(chunk, schema, options, ctx)))
|
|
1015
996
|
|
|
1016
997
|
// 3. Merge results recursively
|
|
1017
|
-
return extract(mergePrompt, originalSchema, options, ctx)
|
|
998
|
+
return extract(mergePrompt, originalSchema, options, ctx)
|
|
1018
999
|
}
|
|
1019
1000
|
```
|
|
1020
1001
|
|
|
@@ -1026,8 +1007,8 @@ if (tokenizer.count(inputAsString) > options.chunkLength) {
|
|
|
1026
1007
|
|
|
1027
1008
|
```typescript
|
|
1028
1009
|
export interface Adapter {
|
|
1029
|
-
saveExample(example: Example): Promise<void
|
|
1030
|
-
getExamples<I, O>(params: GetExamplesParams): Promise<Example<I, O>[]
|
|
1010
|
+
saveExample(example: Example): Promise<void>
|
|
1011
|
+
getExamples<I, O>(params: GetExamplesParams): Promise<Example<I, O>[]>
|
|
1031
1012
|
}
|
|
1032
1013
|
```
|
|
1033
1014
|
|
|
@@ -1066,8 +1047,8 @@ if (taskId && ctx.adapter && !ctx.controller.signal.aborted) {
|
|
|
1066
1047
|
input: inputAsString,
|
|
1067
1048
|
output: final,
|
|
1068
1049
|
metadata: { cost, latency, model, tokens },
|
|
1069
|
-
status:
|
|
1070
|
-
})
|
|
1050
|
+
status: 'pending', // Default - requires approval
|
|
1051
|
+
})
|
|
1071
1052
|
}
|
|
1072
1053
|
```
|
|
1073
1054
|
|
|
@@ -1081,9 +1062,9 @@ const { rows } = await this._client.findTableRows({
|
|
|
1081
1062
|
filter: {
|
|
1082
1063
|
taskType,
|
|
1083
1064
|
taskId,
|
|
1084
|
-
status:
|
|
1065
|
+
status: 'approved', // Only approved examples used!
|
|
1085
1066
|
},
|
|
1086
|
-
})
|
|
1067
|
+
})
|
|
1087
1068
|
```
|
|
1088
1069
|
|
|
1089
1070
|
#### 3.3 Example Matching
|
|
@@ -1162,16 +1143,16 @@ For extract operations (`/packages/zai/src/operations/extract.ts:323-339`):
|
|
|
1162
1143
|
|
|
1163
1144
|
```typescript
|
|
1164
1145
|
try {
|
|
1165
|
-
const json = x.slice(0, x.indexOf(END)).trim()
|
|
1166
|
-
const repairedJson = jsonrepair(json)
|
|
1167
|
-
const parsedJson = JSON5.parse(repairedJson)
|
|
1168
|
-
const safe = schema.safeParse(parsedJson)
|
|
1169
|
-
|
|
1170
|
-
if (safe.success) return safe.data
|
|
1171
|
-
if (options.strict) throw new JsonParsingError(x, safe.error)
|
|
1172
|
-
return parsedJson
|
|
1146
|
+
const json = x.slice(0, x.indexOf(END)).trim()
|
|
1147
|
+
const repairedJson = jsonrepair(json) // Fix common JSON errors
|
|
1148
|
+
const parsedJson = JSON5.parse(repairedJson) // Flexible parsing
|
|
1149
|
+
const safe = schema.safeParse(parsedJson) // Validate
|
|
1150
|
+
|
|
1151
|
+
if (safe.success) return safe.data
|
|
1152
|
+
if (options.strict) throw new JsonParsingError(x, safe.error)
|
|
1153
|
+
return parsedJson // Non-strict mode
|
|
1173
1154
|
} catch (error) {
|
|
1174
|
-
throw new JsonParsingError(x, error)
|
|
1155
|
+
throw new JsonParsingError(x, error)
|
|
1175
1156
|
}
|
|
1176
1157
|
```
|
|
1177
1158
|
|
|
@@ -1183,12 +1164,12 @@ Models configured at initialization (`/packages/zai/src/zai.ts:50-68`):
|
|
|
1183
1164
|
|
|
1184
1165
|
```typescript
|
|
1185
1166
|
modelId: z.custom<ModelId | string>((value) => {
|
|
1186
|
-
if (typeof value !==
|
|
1187
|
-
if (value !==
|
|
1188
|
-
return false
|
|
1167
|
+
if (typeof value !== 'string') return false
|
|
1168
|
+
if (value !== 'best' && value !== 'fast' && !value.includes(':')) {
|
|
1169
|
+
return false
|
|
1189
1170
|
}
|
|
1190
|
-
return true
|
|
1191
|
-
}).default(
|
|
1171
|
+
return true
|
|
1172
|
+
}).default('best')
|
|
1192
1173
|
```
|
|
1193
1174
|
|
|
1194
1175
|
Options:
|
|
@@ -1227,7 +1208,7 @@ Used for:
|
|
|
1227
1208
|
```typescript
|
|
1228
1209
|
const result = await zai.extract(hugeDocument, schema, {
|
|
1229
1210
|
chunkLength: 4000, // Smaller chunks
|
|
1230
|
-
})
|
|
1211
|
+
})
|
|
1231
1212
|
```
|
|
1232
1213
|
|
|
1233
1214
|
#### 2. Schema Validation Failures
|
|
@@ -1238,8 +1219,8 @@ const result = await zai.extract(hugeDocument, schema, {
|
|
|
1238
1219
|
```typescript
|
|
1239
1220
|
const result = await zai.extract(input, schema, {
|
|
1240
1221
|
strict: false, // Allow partial matches
|
|
1241
|
-
instructions:
|
|
1242
|
-
})
|
|
1222
|
+
instructions: 'If age is missing, use -1',
|
|
1223
|
+
})
|
|
1243
1224
|
```
|
|
1244
1225
|
|
|
1245
1226
|
#### 3. Rate Limiting
|
|
@@ -1250,8 +1231,8 @@ const result = await zai.extract(input, schema, {
|
|
|
1250
1231
|
```typescript
|
|
1251
1232
|
// Stagger requests
|
|
1252
1233
|
for (const [i, doc] of documents.entries()) {
|
|
1253
|
-
await delay(i * 200)
|
|
1254
|
-
await zai.summarize(doc)
|
|
1234
|
+
await delay(i * 200) // 200ms between requests
|
|
1235
|
+
await zai.summarize(doc)
|
|
1255
1236
|
}
|
|
1256
1237
|
```
|
|
1257
1238
|
|
|
@@ -1262,11 +1243,9 @@ for (const [i, doc] of documents.entries()) {
|
|
|
1262
1243
|
|
|
1263
1244
|
```typescript
|
|
1264
1245
|
// Split manually before processing
|
|
1265
|
-
const chunks = splitIntoChunks(document, 10000)
|
|
1266
|
-
const summaries = await Promise.all(
|
|
1267
|
-
|
|
1268
|
-
);
|
|
1269
|
-
const final = await zai.summarize(summaries.join("\n"));
|
|
1246
|
+
const chunks = splitIntoChunks(document, 10000)
|
|
1247
|
+
const summaries = await Promise.all(chunks.map((chunk) => zai.summarize(chunk)))
|
|
1248
|
+
const final = await zai.summarize(summaries.join('\n'))
|
|
1270
1249
|
```
|
|
1271
1250
|
|
|
1272
1251
|
### Performance Tuning
|
|
@@ -1292,10 +1271,10 @@ const zai = new Zai({
|
|
|
1292
1271
|
client,
|
|
1293
1272
|
activeLearning: {
|
|
1294
1273
|
enable: true,
|
|
1295
|
-
tableName:
|
|
1296
|
-
taskId:
|
|
1274
|
+
tableName: 'ProductExtractionTable',
|
|
1275
|
+
taskId: 'product-catalog',
|
|
1297
1276
|
},
|
|
1298
|
-
})
|
|
1277
|
+
})
|
|
1299
1278
|
```
|
|
1300
1279
|
|
|
1301
1280
|
Benefits:
|