@tbox-dev-js/sdk 0.1.0 → 0.1.4

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 (2) hide show
  1. package/README.md +332 -101
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,222 +1,453 @@
1
- # @tbox/plugin-sdk
1
+ # @tbox-dev-js/sdk
2
2
 
3
- 百宝箱平台插件服务 JavaScript SDK,封装了插件工具执行、TTS/ASR、插件信息查询等核心能力。
3
+ 百宝箱(Tbox)平台 JavaScript SDK,提供知识库管理、插件工具执行、LLM 对话、会话管理、高德地图等一站式客户端能力。
4
+
5
+ **核心特性:**
6
+
7
+ - 🚀 **配置驱动** — 通过 `knowledge.json` 业务配置文件驱动多知识库操作,AI Coding 友好
8
+ - 🔐 **认证统一** — 全 SDK 共享一套 Token 配置,支持静态字符串或动态函数
9
+ - 📦 **双格式支持** — 同时提供 ESM(`import`)和 CommonJS(`require`)构建产物
10
+ - 🛡️ **类型安全** — 完整的 TypeScript 类型定义
11
+ - 🧩 **模块化** — 知识库、插件、LLM、会话、地图等模块独立可用
4
12
 
5
13
  调用域名:`https://o.tbox.cn`
6
14
 
15
+ ---
16
+
7
17
  ## 安装
8
18
 
9
19
  ```bash
10
- npm install @tbox/plugin-sdk
20
+ npm install @tbox-dev-js/sdk
11
21
  # 或
12
- yarn add @tbox/plugin-sdk
22
+ yarn add @tbox-dev-js/sdk
13
23
  # 或
14
- pnpm add @tbox/plugin-sdk
24
+ pnpm add @tbox-dev-js/sdk
15
25
  ```
16
26
 
27
+ ---
28
+
17
29
  ## 快速开始
18
30
 
31
+ ### 知识库管理(新架构 · 推荐)
32
+
19
33
  ```ts
20
- import { TboxPluginClient } from '@tbox/plugin-sdk';
34
+ import { KnowledgeClient } from '@tbox-dev-js/sdk';
21
35
 
22
- const client = new TboxPluginClient({
23
- apiKey: 'your-api-key', // 百宝箱应用 API Key
36
+ // 从配置文件加载(支持多知识库)
37
+ const client = new KnowledgeClient({
38
+ token: process.env.TBOX_API_KEY,
39
+ config: './config/knowledge.json',
24
40
  });
25
41
 
26
- // 按工具 ID 执行插件工具
27
- const result = await client.run('your-plugin-tool-id', {
42
+ // Scoped 模式:绑定到具体知识库后调用
43
+ const product = client.use('产品数据');
44
+ const results = await product.retrieve('消防安全措施有哪些?');
45
+ console.log(results.data);
46
+
47
+ // Direct 模式:名称作为第一个参数
48
+ const faqResults = await client.retrieve('FAQ', '如何重置密码?');
49
+ ```
50
+
51
+ ### 插件工具执行
52
+
53
+ ```ts
54
+ import { TboxPluginClient } from '@tbox-dev-js/sdk';
55
+
56
+ const client = new TboxPluginClient({ apiKey: 'your-api-key' });
57
+
58
+ const result = await client.run('tool-id-xxx', {
28
59
  inputs: { city: '杭州' },
29
60
  });
30
61
 
31
62
  if (result.success) {
32
63
  console.log(result.data?.output);
33
- } else {
34
- console.error(result.errorCode, result.errorMsg);
35
64
  }
36
65
  ```
37
66
 
38
- ## 初始化配置
67
+ ### LLM 对话
39
68
 
40
69
  ```ts
41
- const client = new TboxPluginClient({
42
- // 必填:API Key(百宝箱应用维度的 API Key)
43
- apiKey: 'your-api-key',
70
+ import { LlmClient } from '@tbox-dev-js/sdk';
44
71
 
45
- // 可选:自定义 base URL,默认 https://o.tbox.cn
46
- baseUrl: 'https://o.tbox.cn',
72
+ const client = new LlmClient({ apiKey: 'your-api-key' });
47
73
 
48
- // 可选:请求超时时间(毫秒)
49
- timeout: 10000,
50
- });
74
+ // 简化调用 — 自动处理流式输出,返回完整文本
75
+ const answer = await client.chat('kimi-k2.5', [
76
+ { role: 'user', content: '你好,请介绍一下你自己' },
77
+ ]);
78
+ console.log(answer);
51
79
  ```
52
80
 
53
- ## API 文档
81
+ ---
82
+
83
+ ## 模块详解
54
84
 
55
- ### `client.run(pluginToolId, request)` 按工具 ID 执行插件
85
+ ### KnowledgeClient知识库管理
56
86
 
57
- **适用场景**:已知工具 ID,调用最直接、性能最好。
87
+ 配置驱动的多知识库客户端,支持语义检索、文档创建与更新。
88
+
89
+ #### 构造方式
58
90
 
59
91
  ```ts
60
- const res = await client.run('tool-id-xxx', {
61
- inputs: {
62
- query: '今天杭州天气',
92
+ import { KnowledgeClient, TboxAPI } from '@tbox-dev-js/sdk';
93
+
94
+ // 方式一:直接创建(CJS 环境)
95
+ const client = new KnowledgeClient({
96
+ token: process.env.TBOX_API_KEY,
97
+ config: './config/knowledge.json',
98
+ });
99
+
100
+ // 方式二:异步工厂(ESM 环境推荐)
101
+ const client = await KnowledgeClient.fromFile(
102
+ { token: process.env.TBOX_API_KEY },
103
+ './config/knowledge.json',
104
+ );
105
+
106
+ // 方式三:从已有 TboxAPI 实例创建(共享连接)
107
+ const tbox = new TboxAPI({ token: process.env.TBOX_API_KEY });
108
+ const client = KnowledgeClient.fromTboxAPI(tbox, './config/knowledge.json');
109
+
110
+ // 方式四:直接传配置对象(单知识库场景)
111
+ const client = new KnowledgeClient({
112
+ token: process.env.TBOX_API_KEY,
113
+ config: {
114
+ datasetId: 'your-dataset-id',
115
+ type: 'STRUCTURED',
116
+ topK: 5,
117
+ tableSchema: { name: '产品表', columns: [] },
63
118
  },
64
119
  });
65
- // res.data: PluginExecResult
66
120
  ```
67
121
 
68
- | 参数 | 类型 | 说明 |
69
- |------|------|------|
70
- | `pluginToolId` | `string` | 插件工具 ID |
71
- | `request.inputs` | `Record<string, unknown>` | 工具输入参数 |
122
+ #### API 方法
123
+
124
+ | 方法 | KnowledgeClient 签名 | KnowledgeScopedClient 签名 | 说明 |
125
+ |------|----------------------|---------------------------|------|
126
+ | `use` | `use(name)` | — | 获取绑定到指定知识库的 Scoped Client |
127
+ | `list` | `list(name?, pageNo?, pageSize?)` | — | 查询知识库列表(共享,不绑定具体知识库) |
128
+ | `retrieve` | `retrieve(name, query, options?)` | `retrieve(query, options?)` | 语义检索 |
129
+ | `create` | `create(name, file, options?)` | `create(file, options?)` | 上传文件创建知识库文档 |
130
+ | `update` | `update(name, file, options?)` | `update(file, options?)` | 更新知识库文档 |
131
+
132
+ #### knowledge.json 配置文件
133
+
134
+ ```json
135
+ {
136
+ "config": {
137
+ "type": "STRUCTURED",
138
+ "topK": 5,
139
+ "scoreThreshold": 0.5,
140
+ "updateMode": "UPSERT",
141
+ "pageSize": 10
142
+ },
143
+ "tools": ["list", "retrieve", "create", "update"],
144
+ "knowledges": {
145
+ "产品数据": {
146
+ "datasetId": "your-dataset-id",
147
+ "documentId": "",
148
+ "config": { "topK": 10, "scoreThreshold": 0.7 },
149
+ "tableSchema": {
150
+ "name": "产品表",
151
+ "columns": [
152
+ { "name": "id", "dataType": "STRING", "primaryKey": true },
153
+ { "name": "title", "dataType": "STRING" },
154
+ { "name": "price", "dataType": "FLOAT" }
155
+ ]
156
+ },
157
+ "indexColumns": ["id"]
158
+ },
159
+ "FAQ": {
160
+ "datasetId": "your-faq-dataset-id",
161
+ "documentId": "",
162
+ "tableSchema": { "name": "FAQ表", "columns": [] },
163
+ "indexColumns": []
164
+ }
165
+ }
166
+ }
167
+ ```
168
+
169
+ **Config 继承机制**:方法参数 > 知识库自身 config > 全局 config > 代码默认值
170
+
171
+ **Tools 运行时校验**:如果配置了 `tools` 字段,调用未声明的操作会抛出错误。
72
172
 
73
173
  ---
74
174
 
75
- ### `client.runByToolName(pluginId, toolName, request)` 按工具名称执行插件
175
+ ### TboxPluginClient插件工具执行
76
176
 
77
- **适用场景**:已知插件 ID 和工具名称,SDK 内部自动解析工具 ID。
177
+ 封装 `/openapi/v1/plugin` 下的全部接口。
78
178
 
79
179
  ```ts
80
- const res = await client.runByToolName('plugin-id', 'weather_search', {
81
- inputs: { city: '上海' },
180
+ import { TboxPluginClient } from '@tbox-dev-js/sdk';
181
+
182
+ const client = new TboxPluginClient({
183
+ apiKey: 'your-api-key',
184
+ baseUrl: 'https://o.tbox.cn', // 可选,默认值
185
+ timeout: 10000, // 可选,毫秒
82
186
  });
83
187
  ```
84
188
 
85
- | 参数 | 类型 | 说明 |
189
+ | 方法 | 说明 | 示例 |
86
190
  |------|------|------|
87
- | `pluginId` | `string` | 插件 ID |
88
- | `toolName` | `string` | 工具名称 |
89
- | `request.inputs` | `Record<string, unknown>` | 工具输入参数 |
191
+ | `run(toolId, request)` | 按工具 ID 执行插件 | `client.run('tool-id', { inputs: { city: '杭州' } })` |
192
+ | `getPluginInfo(pluginId)` | 查询插件信息及工具列表 | `client.getPluginInfo('plugin-id')` |
193
+ | `webSearch(request)` | 网络搜索(内置工具 ID) | `client.webSearch({ q: '上海天气' })` |
194
+ | `doTts(request)` | 文字转语音 | `client.doTts({ text: '你好' })` |
195
+ | `asrBase64(request)` | 语音转文字(Base64 输入) | `client.asrBase64({ audioBase64: '...' })` |
90
196
 
91
197
  ---
92
198
 
93
- ### `client.getPluginInfo(pluginId)`查询插件信息
199
+ ### LlmClientLLM 大模型对话
94
200
 
95
- 查询插件配置信息,包含插件下的工具列表及参数定义。
201
+ 提供 OpenAI 兼容的 Chat Completions 接口,支持流式和非流式输出。
96
202
 
97
203
  ```ts
98
- const res = await client.getPluginInfo('plugin-id');
99
- if (res.success) {
100
- const tools = res.data?.pluginToolList;
101
- tools?.forEach(tool => {
102
- console.log(tool.name, tool.description);
103
- });
204
+ import { LlmClient } from '@tbox-dev-js/sdk';
205
+
206
+ const client = new LlmClient({ apiKey: 'your-api-key' });
207
+ ```
208
+
209
+ #### 简化调用
210
+
211
+ ```ts
212
+ const answer = await client.chat('kimi-k2.5', [
213
+ { role: 'system', content: '你是一个有帮助的助手' },
214
+ { role: 'user', content: '你好' },
215
+ ], { temperature: 0.7, max_tokens: 2000 });
216
+
217
+ console.log(answer);
218
+ ```
219
+
220
+ #### 流式调用
221
+
222
+ ```ts
223
+ const stream = await client.chatCompletions({
224
+ model: 'kimi-k2.5',
225
+ messages: [{ role: 'user', content: '你好' }],
226
+ stream: true,
227
+ stream_options: { include_usage: true },
228
+ });
229
+
230
+ for await (const chunk of stream) {
231
+ const content = chunk.choices?.[0]?.delta?.content;
232
+ if (content) process.stdout.write(content);
233
+
234
+ if (chunk.usage) {
235
+ console.log(`\nToken 用量: ${chunk.usage.total_tokens}`);
236
+ }
104
237
  }
105
238
  ```
106
239
 
240
+ #### 非流式调用
241
+
242
+ ```ts
243
+ const response = await client.chatCompletions({
244
+ model: 'kimi-k2.5',
245
+ messages: [{ role: 'user', content: '你好' }],
246
+ stream: false,
247
+ });
248
+
249
+ console.log(response.choices?.[0]?.message?.content);
250
+ ```
251
+
107
252
  ---
108
253
 
109
- ### `client.submitToolOutput(request)`提交工具输出
254
+ ### TboxConversationClient会话管理
110
255
 
111
- Agent 调用工具后,将工具执行结果回传给平台。
256
+ 封装 `/openapi/v1/conversation` 下的全部接口。
112
257
 
113
258
  ```ts
114
- const res = await client.submitToolOutput({
115
- agent_id: 'app-id-xxx', // 百宝箱应用 ID
116
- tool_call_id: 'call-id-yyy', // 工具调用 ID
117
- output: { result: '晴天,25°C' },
118
- });
259
+ import { TboxConversationClient } from '@tbox-dev-js/sdk';
260
+
261
+ const client = new TboxConversationClient({ apiKey: 'your-api-key' });
119
262
  ```
120
263
 
264
+ | 方法 | 说明 | 示例 |
265
+ |------|------|------|
266
+ | `createConversation(request)` | 创建新会话 | `client.createConversation({ agentId: 'app-id', userId: 'user-id' })` |
267
+ | `listConversations(request)` | 查询会话列表(分页) | `client.listConversations({ agentId: 'app-id', pageNum: 1 })` |
268
+ | `listMessages(request)` | 查询消息列表(分页) | `client.listMessages({ conversationId: 'conv-id' })` |
269
+ | `saveMessage(request)` | 保存对话消息 | `client.saveMessage({ conversationId: 'conv-id', query: '...', answer: '...' })` |
270
+
121
271
  ---
122
272
 
123
- ### `client.doTts(request)`文字转语音
273
+ ### TboxAppClient应用服务
274
+
275
+ 封装 `/openapi/v1/app` 下的接口。
124
276
 
125
277
  ```ts
126
- const res = await client.doTts({
127
- text: '你好,欢迎使用百宝箱',
128
- voice: 'xiaoyun', // 可选,发音人
129
- speechRate: 0, // 可选,语速 -500~500
278
+ import { TboxAppClient } from '@tbox-dev-js/sdk';
279
+
280
+ const client = new TboxAppClient({ apiKey: 'your-api-key' });
281
+
282
+ // 生成免登录 sessionId
283
+ const result = await client.generateSession({
284
+ appId: 'your-app-id',
285
+ userId: 'user-123',
286
+ userInfo: [{ infoType: 'name', infoValue: '张三' }],
287
+ deviceInfo: { platform: 'IOS', appVersion: '1.0.0' },
130
288
  });
131
- if (res.success) {
132
- const audioBase64 = res.data?.audioBase64;
289
+
290
+ if (result.success) {
291
+ console.log('sessionId:', result.data?.sessionId);
133
292
  }
134
293
  ```
135
294
 
136
295
  ---
137
296
 
138
- ### `client.asrBase64(request)`语音转文字
297
+ ### AmapClient高德地图服务
139
298
 
140
- 输入 Base64 编码的音频数据,返回识别文本。
299
+ 通过百宝箱插件服务调用高德地图 API,支持天气查询、地理编码、路线规划等。
141
300
 
142
301
  ```ts
143
- const res = await client.asrBase64({
144
- audioBase64: '<base64-encoded-audio>',
145
- format: 'mp3', // 可选,音频格式
146
- sampleRate: 16000, // 可选,采样率
302
+ import { AmapClient } from '@tbox-dev-js/sdk';
303
+
304
+ const client = new AmapClient({ apiKey: 'your-api-key' });
305
+ ```
306
+
307
+ | 方法 | 说明 |
308
+ |------|------|
309
+ | `weather(request)` | 天气查询 |
310
+ | `geocode(request)` | 地址转经纬度 |
311
+ | `regeocode(request)` | 经纬度转地址 |
312
+ | `ipLocation(request)` | IP 定位 |
313
+ | `peripheralSearch(request)` | 周边搜索 |
314
+ | `poiSearch(request)` | POI 关键字搜索 |
315
+ | `walkingRoute(request)` | 步行路线规划 |
316
+ | `cyclingRoute(request)` | 骑行路线规划 |
317
+ | `drivingRoute(request)` | 驾车路线规划 |
318
+ | `ebikeRoute(request)` | 电动车路线规划 |
319
+ | `transitRoute(request)` | 公交路线规划 |
320
+ | `district(request)` | 行政区域查询 |
321
+ | `convert(request)` | 坐标转换 |
322
+
323
+ ---
324
+
325
+ ### TboxAPI — 底层资源访问(高级用户)
326
+
327
+ 直接访问底层 API 资源,适合需要精细控制的场景。
328
+
329
+ ```ts
330
+ import { TboxAPI } from '@tbox-dev-js/sdk';
331
+
332
+ const tbox = new TboxAPI({
333
+ token: process.env.TBOX_API_KEY,
334
+ baseURL: 'https://o.tbox.cn',
335
+ timeout: 10000,
336
+ debug: true,
147
337
  });
148
- if (res.success) {
149
- console.log(res.data?.text);
150
- }
338
+
339
+ // 知识库 API
340
+ await tbox.knowledge.list({ name: '搜索关键词' });
341
+ await tbox.knowledge.retrieve({ datasetId: '...', query: '查询文本', topK: 5 });
342
+ await tbox.knowledge.documents.create({ file, type: 'STRUCTURED', tableSchema });
343
+ await tbox.knowledge.documents.update({ documentId: '...', file, type: 'STRUCTURED' });
344
+
345
+ // Schema Registry — 获取 API 的 JSON Schema 描述
346
+ const schema = tbox.schemas.get('knowledge');
347
+ console.log(schema?.operations);
151
348
  ```
152
349
 
153
350
  ---
154
351
 
155
352
  ## 统一响应格式
156
353
 
157
- 所有方法均返回 `Promise<SdkResponse<T>>`:
354
+ 旧架构客户端(`TboxPluginClient`、`TboxConversationClient`、`TboxAppClient`、`AmapClient`)的所有方法均返回 `SdkResponse<T>`:
158
355
 
159
356
  ```ts
160
357
  interface SdkResponse<T> {
161
- success: boolean; // 是否成功
162
- data?: T; // 响应数据(成功时)
163
- errorCode?: string; // 错误码(失败时)
164
- errorMsg?: string; // 错误信息(失败时)
358
+ success: boolean;
359
+ data?: T;
360
+ errorCode?: string;
361
+ errorMsg?: string;
165
362
  }
166
363
  ```
167
364
 
168
- ## 错误处理
365
+ 新架构客户端(`TboxAPI`、`KnowledgeClient`)直接返回业务数据,错误通过异常抛出:
169
366
 
170
367
  ```ts
171
- const res = await client.run('tool-id', { inputs: {} });
172
-
173
- if (!res.success) {
174
- switch (res.errorCode) {
175
- case 'NETWORK_ERROR':
176
- console.error('网络请求失败:', res.errorMsg);
177
- break;
178
- case 'HTTP_401':
179
- console.error('API Key 无效或已过期');
180
- break;
181
- default:
182
- console.error(`调用失败 [${res.errorCode}]:`, res.errorMsg);
368
+ import { APIError, AuthenticationError, NetworkError } from '@tbox-dev-js/sdk';
369
+
370
+ try {
371
+ const results = await client.retrieve('产品数据', '查询文本');
372
+ } catch (error) {
373
+ if (error instanceof AuthenticationError) {
374
+ console.error('Token 无效或已过期');
375
+ } else if (error instanceof NetworkError) {
376
+ console.error('网络请求失败');
377
+ } else if (error instanceof APIError) {
378
+ console.error(`API 错误 [${error.status}]:`, error.message);
183
379
  }
184
380
  }
185
381
  ```
186
382
 
187
- ## 兼容环境
383
+ ---
384
+
385
+ ## 环境要求
188
386
 
189
- - **Node.js** >= 18(原生支持 `fetch`)
387
+ - **Node.js** >= 16.0.0
190
388
  - **浏览器**:支持 `fetch` API 的现代浏览器
191
389
  - **模块格式**:ESM(`import`)+ CJS(`require`)双格式
192
390
 
391
+ ---
392
+
193
393
  ## 项目结构
194
394
 
195
395
  ```
196
396
  tbox-js/
197
397
  ├── src/
198
- │ ├── types.ts # TypeScript 类型定义
199
- │ ├── http.ts # 底层 HTTP 封装
200
- │ ├── plugin.ts # TboxPluginClient 核心类
201
- └── index.ts # 统一导出入口
202
- ├── dist/ # 构建产物(npm 发布内容)
203
- │ ├── index.js # CJS 格式
204
- │ ├── index.esm.js # ESM 格式
205
- │ └── index.d.ts # TypeScript 类型声明
398
+ │ ├── core.ts # APIClient 核心基类(认证、请求、错误处理)
399
+ │ ├── tbox-api.ts # SDK 入口类(挂载子模块 + SchemaRegistry)
400
+ │ ├── knowledge-client.ts # 配置驱动的多知识库客户端
401
+ ├── resources/knowledge/ # Knowledge 资源模块
402
+ │ │ ├── index.ts # list、retrieve
403
+ ├── documents.ts # create、update(FormData 上传)
404
+ ├── types.ts # 类型定义
405
+ └── schema.ts # JSON Schema 定义
406
+ │ ├── schema.ts # ResourceSchema 类型体系 + SchemaRegistry
407
+ │ ├── plugin.ts # 插件工具执行客户端
408
+ │ ├── conversation.ts # 会话管理客户端
409
+ │ ├── app.ts # 应用服务客户端
410
+ │ ├── amap.ts # 高德地图客户端
411
+ │ ├── llm.ts # LLM 大模型对话客户端
412
+ │ ├── http.ts # 旧架构 HTTP 封装
413
+ │ ├── error.ts # 错误类层级
414
+ │ ├── resource.ts # APIResource 基类
415
+ │ ├── constant.ts # 常量定义
416
+ │ ├── types.ts # 旧架构类型定义
417
+ │ └── index.ts # 统一导出入口
418
+ ├── config/
419
+ │ └── knowledge.json # 知识库业务配置文件
420
+ ├── docs/
421
+ │ └── knowledge-client.md # KnowledgeClient 设计文档
422
+ ├── scripts/
423
+ │ └── publish.sh # npm 发布脚本
424
+ ├── dist/ # 构建产物
425
+ │ ├── index.cjs # CJS 格式
426
+ │ ├── index.esm.js # ESM 格式
427
+ │ └── index.d.ts # TypeScript 类型声明
206
428
  ├── package.json
207
429
  ├── tsconfig.json
208
430
  └── rollup.config.js
209
431
  ```
210
432
 
433
+ ---
434
+
211
435
  ## 开发构建
212
436
 
213
437
  ```bash
214
438
  # 安装依赖
215
439
  npm install
216
440
 
441
+ # 类型检查
442
+ npm run typecheck
443
+
217
444
  # 构建产物
218
445
  npm run build
219
446
 
220
- # 类型检查
221
- npm run typecheck
447
+ # 清理构建产物
448
+ npm run clean
222
449
  ```
450
+
451
+ ## 许可证
452
+
453
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox-dev-js/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.4",
4
4
  "description": "百宝箱平台 JavaScript SDK — 知识库、插件、会话等服务的统一客户端",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",