# @botpress/zai 中文文档

规范地址：https://npmcn.com/package/%40botpress/zai/

版本：3\.1\.3
npm 元数据更新时间：2026-11-05T00:47:52.700Z
中文译文更新时间：2026-11-08T12:24:02.143Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40botpress/zai
原文对照：https://npmcn.com/package/%40botpress/zai/?lang=original
项目主页：https://github.com/botpress/botpress#readme
源码仓库：https://github.com/botpress/botpress

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：276 kB，30 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：5 个
- peer 依赖：@bpinternal/zui ^2\.4\.1，@bpinternal/thicktoken ^3\.0\.0
- 首次发布：2024-12-12T00:55:51.452Z
- 最新版本发布：2026-11-05T00:47:52.383Z
- 近 30 天下载量：32337（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：124（近 12 个月 62 个）

## 中文简介

Zui AI(斋) - 在 Zui 和 Botpress API 上书写的 LLM 工具库

## 安装

```sh
npm install @botpress/zai
```

也可以使用：`pnpm add @botpress/zai`、`yarn add @botpress/zai`、`bun add @botpress/zai`

## README

# Zai - AI操作简单

Zai是一个强大的LLM工具库,为常见的AI操作提供清洁,型号安全的API. 由Zod schemas和Botpress API所建,它使AI操作简单,直观,生产准备.

## 关键特性

-   **简单 API** - 用于共同AI任务的单行业务
-   **QQ 类型安全** - 在Zod schema验证下提供全部类型脚本支持
-   **积极学习** - 从实例中学习并逐步改进
-   **绩效** - 内置复机、缓存和错误处理
-   **QQ 无限文档** - 用自动块处理任意文档大小
-   **使用跟踪** - 监测标志、费用和业绩

## \* 安装

```bash
npm install @botpress/zai @botpress/client @bpinternal/zui
```

## QQ 快速启动

```typescript
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\. 摘录 - 从文本中获取结构化数据

```typescript
// 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\. 检查 - 核查布尔条件

```typescript
const result = await zai.check(email, 'is spam')
const { value, explanation } = await result.full()
```

### 3\. 标签 - 应用多标签

```typescript
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\. 重写 - 变换文本

```typescript
// 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\. 过滤器 - 有自然语言的过滤器阵列

```typescript
const techCompanies = await zai.filter(companies, 'are technology companies')
const recentPosts = await zai.filter(posts, 'were published this week')
```

### 6\. 组类 - 将物项分为类别

```typescript
// 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级分数项目

```typescript
// 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\. 排序 - 有自然语言的顺序项目

```typescript
// 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\. 文本 - 生成内容

```typescript
const blogPost = await zai.text('Write about the future of AI', {
  length: 1000,
  temperature: 0.7,
})
```

### 10\. 总结 - 创建摘要

```typescript
// 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',
})
```

## 积极学习

启用主动学习以随着时间的推移提高准确性 :

```typescript
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 配置

### 模式选择

```typescript
// 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' })
```

### 进展跟踪

```typescript
const response = zai.summarize(veryLongDocument)

// Track progress
response.on('progress', (progress) => {
  console.log(`${progress.percent}% complete`)
})

const summary = await response
```

### 使用量监测

```typescript
const result = await zai.extract(text, schema)
const usage = await result.usage()

console.log({
  tokens: usage.totalTokens,
  cost: usage.totalCost,
  latency: usage.totalLatency,
})
```

## 养恤金

1.  **生产准备** - 内置错误处理、重试和费率限制
2.  **类型安全** - 运行时间验证的全类型脚本支持
3.  **可缩放** - 用自动块处理大小的文档
4.  **成本效益** - 跟踪使用情况并优化积极学习
5.  **开发者友好** - 具有方法链和事件的清洁API

## 高级用途

### 链路操作

```typescript
const processedData = await zai.with({ temperature: 0.3 }).learn('data-extraction').extract(document, complexSchema)
```

### 处理大型文档

```typescript
// Automatically chunks and processes in parallel
const extractedData = await zai.extract(
  hugeDocument, // 100k+ tokens
  z.array(recordSchema),
  { chunkSize: 4000 }
)
```

### 自定义中止信号

```typescript
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文件

## 常见问题

### @botpress/zai 是什么？

Zui AI\(斋\) - 在 Zui 和 Botpress API 上书写的 LLM 工具库

### 如何安装 @botpress/zai？

在项目目录运行 npm install @botpress/zai，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@bpinternal/zui（^2\.4\.1）、@bpinternal/thicktoken（^3\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @botpress/zai 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @botpress/zai 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @botpress/zai 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @botpress/zai 可以商用吗？

@botpress/zai 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @botpress/zai 的下载量有多少？

根据 npm 官方下载统计，@botpress/zai 在 2026/10/09 – 2026/11/07 这 30 天内被下载 32,337 次，日均约 1,078 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @botpress/zai 还在维护吗？

最新版本 3\.1\.3 发布于 2026/11/05（3 天前）；至今共发布 124 个版本，其中过去 12 个月发布了 62 个；首次发布于 2024/12/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

