Zai - AI操作简单
Zai是一个强大的LLM工具库,为常见的AI操作提供清洁,型号安全的API. 由Zod schemas和Botpress API所建,它使AI操作简单,直观,生产准备.
关键特性
- 简单 API - 用于共同AI任务的单行业务
- QQ 类型安全 - 在Zod schema验证下提供全部类型脚本支持
- 积极学习 - 从实例中学习并逐步改进
- 绩效 - 内置复机、缓存和错误处理
- QQ 无限文档 - 用自动块处理任意文档大小
- 使用跟踪 - 监测标志、费用和业绩
* 安装
npm install @botpress/zai @botpress/client @bpinternal/zui
QQ 快速启动
import { Client } from '@botpress/client'
import { Zai } from '@botpress/zai'
import { z } from '@bpinternal/zui'
// Initialize
const client = new Client({ botId: 'YOUR_BOT_ID', token: 'YOUR_TOKEN' })
const zai = new Zai({ client })
// Extract structured data
const person = await zai.extract(
'John Doe is 30 years old and lives in New York',
z.object({
name: z.string(),
age: z.number(),
location: z.string(),
})
)
// Result: { name: 'John Doe', age: 30, location: 'New York' }
// Check content
const isPositive = await zai.check('This product is amazing!', 'expresses positive sentiment')
// Result: true
// Generate text
const story = await zai.text('Write a short story about AI', { length: 200 })
// Summarize documents
const summary = await zai.summarize(longDocument, { length: 500 })
核心业务
1. 摘录 - 从文本中获取结构化数据
// Extract single object
const product = await zai.extract(
text,
z.object({
name: z.string(),
price: z.number(),
inStock: z.boolean(),
})
)
// Extract array of items
const products = await zai.extract(text, z.array(productSchema))
2. 检查 - 核查布尔条件
const result = await zai.check(email, 'is spam')
const { value, explanation } = await result.full()
3. 标签 - 应用多标签
const labels = await zai.label(review, {
positive: 'expresses positive sentiment',
technical: 'mentions technical details',
verified: 'from verified purchaser',
})
// Result: { positive: true, technical: false, verified: true }
4. 重写 - 变换文本
// Translate
const french = await zai.rewrite(text, 'translate to French')
// Change tone
const formal = await zai.rewrite('Hey! What's up?', 'make it professional')
5. 过滤器 - 有自然语言的过滤器阵列
const techCompanies = await zai.filter(companies, 'are technology companies')
const recentPosts = await zai.filter(posts, 'were published this week')
6. 组类 - 将物项分为类别
// Group items automatically
const grouped = await zai.group(tasks, {
instructions: 'Group by priority level',
})
// Result: { 'High Priority': [...], 'Medium Priority': [...], 'Low Priority': [...] }
// Group with initial categories
const categorized = await zai.group(emails, {
instructions: 'Group by topic',
initialGroups: [
{ id: 'work', label: 'Work' },
{ id: 'personal', label: 'Personal' },
],
})
// Group large datasets efficiently
const organized = await zai.group(largeArray, {
instructions: 'Group by date',
chunkLength: 8000, // Process in chunks for better performance
})
7. 比率 -- -- 1至5级分数项目
// Auto-generate criteria (returns total score)
const scores = await zai.rate(products, 'is it a good value product?')
// Result: [12, 8, 15] (total scores for each item)
// Get detailed ratings
const { output } = await zai.rate(products, 'is it a good value product?').result()
// Result: [
// { affordability: 4, quality: 5, features: 3, total: 12 },
// { affordability: 3, quality: 2, features: 3, total: 8 },
// ...
// ]
// Use fixed criteria
const ratings = await zai.rate(passwords, {
length: 'password length (12+ chars = very_good, 8-11 = good, 6-7 = average, 4-5 = bad, <4 = very_bad)',
complexity: 'character variety (all types = very_good, 3 types = good, 2 types = average, 1 type = bad)',
strength: 'overall password strength',
})
// Result: [
// { length: 5, complexity: 5, strength: 5, total: 15 },
// { length: 1, complexity: 1, strength: 1, total: 3 },
// ]
// Rate large datasets efficiently (parallelized)
const allRatings = await zai.rate(Array(500).fill(item), 'how complete is this?')
// Processes ~500 items in ~120ms with automatic chunking
8. 排序 - 有自然语言的顺序项目
// Sort by natural criteria
const sorted = await zai.sort(emails, 'sort by urgency')
// LLM determines criteria and orders items accordingly
// Sort with detailed results
const { output } = await zai.sort(tasks, 'sort by priority').result()
// output includes scoring breakdown for each item
// Complex multi-criteria sorting
const prioritized = await zai.sort(tickets, 'sort by customer importance and issue severity')
// Sort large datasets efficiently (parallelized with chunking)
const orderedItems = await zai.sort(Array(500).fill(item), 'sort by relevance')
9. 文本 - 生成内容
const blogPost = await zai.text('Write about the future of AI', {
length: 1000,
temperature: 0.7,
})
10. 总结 - 创建摘要
// Simple summary
const summary = await zai.summarize(article)
// With custom prompt
const technicalSummary = await zai.summarize(paper, {
length: 500,
prompt: 'Focus on technical implementation details',
})
积极学习
启用主动学习以随着时间的推移提高准确性 :
const zai = new Zai({
client,
activeLearning: {
enable: true,
tableName: 'ai_learning_data',
taskId: 'sentiment-analysis',
},
})
// Use with task ID for learning
const result = await zai.learn('sentiment-analysis').check(text, 'is positive')
QQ 配置
模式选择
// Use the best model (default)
const zai = new Zai({ client, model: 'best' })
// Use fast model for speed
const fastZai = new Zai({ client, model: 'fast' })
// Use specific model
const customZai = new Zai({ client, model: 'gpt-4-turbo' })
进展跟踪
const response = zai.summarize(veryLongDocument)
// Track progress
response.on('progress', (progress) => {
console.log(`${progress.percent}% complete`)
})
const summary = await response
使用量监测
const result = await zai.extract(text, schema)
const usage = await result.usage()
console.log({
tokens: usage.totalTokens,
cost: usage.totalCost,
latency: usage.totalLatency,
})
养恤金
- 生产准备 - 内置错误处理、重试和费率限制
- 类型安全 - 运行时间验证的全类型脚本支持
- 可缩放 - 用自动块处理大小的文档
- 成本效益 - 跟踪使用情况并优化积极学习
- 开发者友好 - 具有方法链和事件的清洁API
高级用途
链路操作
const processedData = await zai.with({ temperature: 0.3 }).learn('data-extraction').extract(document, complexSchema)
处理大型文档
// Automatically chunks and processes in parallel
const extractedData = await zai.extract(
hugeDocument, // 100k+ tokens
z.array(recordSchema),
{ chunkSize: 4000 }
)
自定义中止信号
const controller = new AbortController()
const response = zai.summarize(document, { signal: controller.signal })
// Cancel if needed
setTimeout(() => controller.abort(), 5000)
API 参考
蔡级
new Zai(options)- 用客户端和配置创建实例.with(config)- 创建合并配置的新实例.learn(taskId)- 允许积极学习特定任务
业务
.extract(content, schema, options?)- 提取结构化数据.check(content, condition, options?)- 验证布尔条件.label(content, criteria, options?)- 应用多个标签.rewrite(content, instruction, options?)- 变换文本.filter(items, condition, options?)- 过滤数组项目.group(items, options?)- 将物品分类.rate(items, instructions, options?)- 1至5级的收费项目.sort(items, instructions, options?)- 用自然语言订购物品.text(prompt, options?)- 生成文本.summarize(content, options?)- 创建摘要
反应方法
await response- 得到简单的结果await response.full()- 获得详细的元数据结果await response.usage()- 获得使用统计response.on('progress', handler)- 跟踪进展情况response.abort()- 取消运营
许可证
MIT - 详情见LICENSE文件