chatluna-plugin-kb 0.1.1 → 0.1.2
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/README.md +170 -11
- package/index.mjs +77 -1
- package/package.json +1 -1
- package/src/engine/bootstrap.mjs +2 -2
- package/src/webui/model-routes.mjs +5 -3
- package/src/webui/models.mjs +114 -21
- package/src/webui/server.mjs +83 -4
- package/web/client.css +136 -0
- package/web/client.js +514 -42
package/README.md
CHANGED
|
@@ -1,20 +1,179 @@
|
|
|
1
|
-
# chatluna-
|
|
1
|
+
# chatluna-kb
|
|
2
2
|
|
|
3
|
-
ChatLuna v2
|
|
3
|
+
ChatLuna v2 的知识库接入插件:通过 WeKnora REST API 提供检索与入库能力,并托管一个仅监听
|
|
4
|
+
`127.0.0.1` 的 weknora-lite 子进程。不依赖 MCP,所有能力以 3 个工具暴露。
|
|
4
5
|
|
|
5
|
-
##
|
|
6
|
+
## 功能
|
|
7
|
+
|
|
8
|
+
- 知识库检索:列库、列文档、混合/语义/关键词检索、按标题或分块读取。
|
|
9
|
+
- 内容入库:附件/本地文档、Markdown 文本、网页或文件直链。
|
|
10
|
+
- 文档维护:重新解析、删除(群聊禁止删除)。
|
|
11
|
+
- WebUI:引擎状态、启动/停止/重启、安装向导、权限分流规则编辑。
|
|
12
|
+
- 同源反代 `/kb-proxy/*`,可直接在 WebUI 内嵌 WeKnora 前端。
|
|
13
|
+
|
|
14
|
+
## 工具与权限
|
|
15
|
+
|
|
16
|
+
| 工具 | 默认加载 | effect | 能力 |
|
|
17
|
+
| --- | --- | --- | --- |
|
|
18
|
+
| `kb_read` | 常驻 | read | `list_kbs` / `list_docs` / `search` / `toc` / `read` |
|
|
19
|
+
| `kb_write` | 按需 | write | `ingest_file` / `ingest_text` / `ingest_url` |
|
|
20
|
+
| `kb_manage` | 按需 | write | `reparse` / `delete` |
|
|
21
|
+
|
|
22
|
+
兼容别名 `weknora_read` / `weknora_write` / `weknora_manage` 只做参数转发,权限规则与主工具完全一致。
|
|
23
|
+
|
|
24
|
+
权限按会话分流,规则字段:`match`(scene/platform/guildId/userId/minLevel)、`defaultKb`、
|
|
25
|
+
`readableKbs`、`writableKbs`、`manageableKbs`(`*` 表示全部)。规则存储在
|
|
26
|
+
`<dataDir>/rules.json`(唯一真源,0600);文件缺失或损坏时回退 `chatluna.yml` 的 `rules`。
|
|
27
|
+
工具每次调用都会把知识库名称/ID 归一到当前可见目录,越权直接抛出 `PermissionError`;
|
|
28
|
+
`list_kbs` 只返回白名单内可见的库。
|
|
29
|
+
|
|
30
|
+
## 双模式
|
|
31
|
+
|
|
32
|
+
- **managed-lite(默认)**:插件托管 `weknora-lite` 子进程,只监听 `127.0.0.1:<port>`(默认 18891)。
|
|
33
|
+
启动异步执行,失败只写入状态、不阻塞插件加载;崩溃带指数退避重启。
|
|
34
|
+
- **external**:连接已有 WeKnora 服务(`baseUrl`,默认 `http://127.0.0.1:8891`)。
|
|
35
|
+
不 spawn 任何进程,也不注册安装路由。`/kb-proxy` 与规则编辑仍可用。
|
|
36
|
+
- **systemd**:由独立 systemd 单元托管(`systemdUnit`,必须为 `*.service`)。插件只做
|
|
37
|
+
`systemctl`/`journalctl` 白名单调用与健康检查,绝不 spawn 或 start/stop 单元。
|
|
38
|
+
已显式配置 `mode: systemd` 的实例行为不变。
|
|
39
|
+
|
|
40
|
+
`mode` 的 schema 默认值是 `managed-lite`;已有配置里显式写出的 `mode` 永远优先。
|
|
41
|
+
|
|
42
|
+
managed-lite 需要引擎二进制已安装(见下方向导)。未安装时不会启动子进程,状态提示
|
|
43
|
+
“引擎未安装:请在知识库页面完成安装向导”。
|
|
44
|
+
|
|
45
|
+
## WebUI 安装(4 步)
|
|
46
|
+
|
|
47
|
+
1. **模式选择**:选择 managed-lite(托管)或 external(连接已有服务)。
|
|
48
|
+
2. **架构检测与安装包**:向导调用 `/kb-admin/install/status` 与 `detect`,展示平台/架构、
|
|
49
|
+
已安装版本与校验和,以及 `tesseract`/`pdftoppm`/`tessdata` 探测结果。可自动下载当前平台
|
|
50
|
+
的 latest 发布包(读 `release.json`,服务端校验 sha256 与 size 后解包)、手动填下载 URL,
|
|
51
|
+
或上传离线包。
|
|
52
|
+
3. **Embedding**:复用 ChatLuna 的 Embedding(`baseUrl` / `model` / API key),向导测试
|
|
53
|
+
`POST <baseUrl>/embeddings`(15 秒超时),返回维度与耗时;保存后写入
|
|
54
|
+
`<dataDir>/embedding.json`,重启生效。
|
|
55
|
+
4. **一键拉起**:安装完成后可直接启动引擎,首次启动自动完成 bootstrap(创建 API key、
|
|
56
|
+
默认知识库、Embedding 模型)并进入就绪状态。
|
|
57
|
+
|
|
58
|
+
### 发布清单自动下载
|
|
59
|
+
|
|
60
|
+
- 默认清单地址:
|
|
61
|
+
`https://github.com/yabo083/weknora-lite-kb/releases/latest/download/release.json`
|
|
62
|
+
- 配置项 `releaseManifestUrl` 可覆盖;`installMirrors` 接受带 `{url}` 占位符的镜像,
|
|
63
|
+
清单与安装包都会按“主地址 → 镜像”顺序回退。
|
|
64
|
+
- 清单形状:`{version, minPluginVersion, platforms: {"linux-amd64": {url, sha256, size}, ...}}`。
|
|
65
|
+
安装器按 `process.platform`/`arch` 映射到 `linux-amd64` / `linux-arm64`,条目缺失、
|
|
66
|
+
地址非 http(s)、sha256/size 非法或下载后不匹配都会明确报错,绝不跳过校验。
|
|
67
|
+
- 发布包内嵌 `tessdata/`(与二进制同级)会原样解出;安装器只要求
|
|
68
|
+
`weknora-lite`、`web/index.html`、`config/config.yaml`,额外目录不影响安装。
|
|
69
|
+
- `pluginVersion` 可选;配置后若低于清单 `minPluginVersion` 会拒绝自动安装。
|
|
70
|
+
|
|
71
|
+
### `kb.detect` 字段
|
|
72
|
+
|
|
73
|
+
只读探测,不安装、不启动;外部命令均有 2 秒超时,结果 60 秒缓存:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"platform": "linux",
|
|
78
|
+
"arch": "x64",
|
|
79
|
+
"platformKey": "linux-amd64",
|
|
80
|
+
"installed": true,
|
|
81
|
+
"installedVersion": "0.9.0",
|
|
82
|
+
"release": {"ok": true, "available": true, "version": "0.9.0", "url": "https://…"},
|
|
83
|
+
"tesseractFound": true,
|
|
84
|
+
"pdftoppmFound": true,
|
|
85
|
+
"tessdataDir": "<dataDir>/weknora-lite/tessdata",
|
|
86
|
+
"tessdataReady": true,
|
|
87
|
+
"ocr": {"ready": true, "engine": "tesseract", "tessdataDir": "…", "tesseractFound": true, "pdftoppmFound": true}
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
同一组平台/OCR 字段也会出现在 `kb.status` 快照中(`release` 只给清单 URL,不发网络请求)。
|
|
92
|
+
|
|
93
|
+
安装路由(需 WebUI 登录,见安全边界):
|
|
94
|
+
|
|
95
|
+
- `POST /kb-admin/install/upload`:原始 `tar.gz` 流上传,支持请求头 `x-sha256`(64 位十六进制)
|
|
96
|
+
与 `x-filename`;默认上限 512 MB,超限 413,空体 400,校验失败 409。
|
|
97
|
+
- `GET /kb-admin/install/status`:返回安装器状态;前端据此展示进度。
|
|
98
|
+
|
|
99
|
+
## 离线包上传
|
|
100
|
+
|
|
101
|
+
在向导第 2 步选择“上传离线包”,选择 `weknora-lite-kb-linux-amd64.tar.gz`。浏览器以流方式
|
|
102
|
+
直接上传,服务端按块计数、不整体驻留内存;可同时提供 sha256 由服务端强制校验。安装目标为
|
|
103
|
+
`<dataDir>/weknora-lite/`,包内根目录 `weknora-lite-kb/` 会被展开到该目录。
|
|
104
|
+
|
|
105
|
+
同一个包也可用 `kb.install.path` 从服务器本地绝对路径安装(自动下载失败/无外网时使用)。
|
|
106
|
+
包内 `tessdata/` 与二进制同级,安装后直接可用;额外目录(`migrations/` 等)会被保留。
|
|
107
|
+
|
|
108
|
+
## 目录布局
|
|
109
|
+
|
|
110
|
+
默认 `<dataDir>` 为 `/root/chatluna/data/chatluna-kb`:
|
|
6
111
|
|
|
7
112
|
```
|
|
8
|
-
|
|
113
|
+
<dataDir>/
|
|
114
|
+
├── weknora-lite/ # 安装产物(二进制、web/、config/)
|
|
115
|
+
│ └── weknora-lite
|
|
116
|
+
├── weknora.db # SQLite 主库
|
|
117
|
+
├── files/ # 本地文件存储
|
|
118
|
+
├── rules.json # 权限分流规则(0600)
|
|
119
|
+
├── embedding.json # 向导保存的 Embedding 配置(0600)
|
|
120
|
+
├── embedding.key # 向导填写的 Embedding API key(0600)
|
|
121
|
+
├── setup-token # Lite 初始化 token(0600)
|
|
122
|
+
├── jwt-secret # 会话签名密钥(0600)
|
|
123
|
+
└── system-aes-key # 系统加密密钥(0600)
|
|
9
124
|
```
|
|
10
125
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
126
|
+
所有凭据文件权限固定为 `0600`;配置里只出现文件路径,不出现密钥明文。
|
|
127
|
+
|
|
128
|
+
## 发布与安装(npm)
|
|
129
|
+
|
|
130
|
+
包名 `chatluna-plugin-kb`,`type: module`,入口 `index.mjs`,`files` 只包含
|
|
131
|
+
`index.mjs`、`src/**/*.mjs`、`web/**` 与 `README.md`(测试与部署产物不会进包)。
|
|
132
|
+
`@chatluna/*` 声明为 peerDependencies,由 ChatLuna 运行时提供;`engines.node >= 24`。
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
npm pack # 本地打包检查内容
|
|
136
|
+
npm publish # 发布(需要 npm 账号与包名权限)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
ChatLuna 侧把插件项 `name` 指向本包入口(`index.mjs`)即可;继续用 `file://` 路径加载
|
|
140
|
+
不受影响。`package.json` 的 `exports` 同时暴露 `web/client.js`,WebUI 静态资源按包根目录
|
|
141
|
+
解析。
|
|
142
|
+
|
|
143
|
+
配置里不出现任何密钥:setup token、JWT secret、AES key、API key 都只存在于
|
|
144
|
+
`<dataDir>` 下的 `0600` 文件或进程环境变量中。
|
|
145
|
+
|
|
146
|
+
## 从 weknora-kb / 外部全量迁移
|
|
147
|
+
|
|
148
|
+
1. **停旧服务**,备份旧数据目录(至少包含数据库、`files/`、凭据文件)。
|
|
149
|
+
2. 选择迁移方式:
|
|
150
|
+
- 继续使用已有服务:`mode: external`,把 `baseUrl` 指向它即可,无需搬迁数据。
|
|
151
|
+
- 切到托管:安装引擎后,将旧库文件复制到 `<dataDir>/weknora.db`,旧文件目录复制到
|
|
152
|
+
`<dataDir>/files/`;保留原 `setup-token`、`jwt-secret`、`system-aes-key`(若旧版本使用
|
|
153
|
+
相同机制),否则首次启动会生成新密钥,旧会话失效但不影响数据。
|
|
154
|
+
3. 若旧版使用不同的数据库驱动或存储后端,先在旧服务导出/重建知识库,再通过 `kb_write`
|
|
155
|
+
重新入库;不要直接混用不兼容的数据库文件。
|
|
156
|
+
4. 迁移后打开 WebUI 检查引擎状态,跑一次检索与一次入库验证读写链路。
|
|
157
|
+
|
|
158
|
+
## 故障排查
|
|
14
159
|
|
|
15
|
-
|
|
160
|
+
- **端口 18891 被占用**:托管模式拒绝启动且不会杀掉现有进程。用
|
|
161
|
+
`ss -ltnp | grep 18891` 找到占用者;是旧实例就停掉,或修改配置 `engine.port`。
|
|
162
|
+
- **sha256 校验失败**:确认安装包完整(与 `.sha256` 同目录比对
|
|
163
|
+
`sha256sum -c weknora-lite-kb-linux-amd64.tar.gz.sha256`)。重新下载而不是跳过校验。
|
|
164
|
+
- **Embedding 测试失败**:检查 `baseUrl` 是否能从本机访问、模型名是否存在、API key 文件是否
|
|
165
|
+
可读;错误信息已脱敏,不会回显 key。测试通过但启动后仍报错时,确认保存的是同一组配置,
|
|
166
|
+
并重启引擎使其生效。
|
|
167
|
+
- **引擎启动失败**:查看 WebUI 引擎页日志尾部(有界 50 行)与 `lastError`;常见原因是未安装、
|
|
168
|
+
端口占用、数据目录不可写。
|
|
169
|
+
- **安装后仍提示未安装**:确认二进制位于 `<dataDir>/weknora-lite/weknora-lite` 且可执行。
|
|
16
170
|
|
|
17
|
-
|
|
18
|
-
workflow manually. The workflow uses `npm publish --provenance --access public` with `id-token: write`.
|
|
171
|
+
## 安全边界
|
|
19
172
|
|
|
20
|
-
|
|
173
|
+
- weknora-lite 只绑定 `127.0.0.1`,不对外暴露端口。
|
|
174
|
+
- `/kb-proxy/*` 与 `/kb-admin/*` 都要求 ChatLuna WebUI 登录:`chatluna_session` cookie 或
|
|
175
|
+
有效 bearer access token;未登录请求在读取请求体之前就返回 401。
|
|
176
|
+
- 管理动作(启动/停止/重启/保存规则/安装)额外要求管理员权限等级。
|
|
177
|
+
- setup token、JWT secret、AES key、API key 只存在于 `0600` 文件或进程环境变量中,
|
|
178
|
+
不写入 `chatluna.yml`、不打印到日志、不出现在错误响应里。
|
|
179
|
+
- 上传流有字节上限,日志行有长度上限,规则条数与序列化大小均有上限。
|
package/index.mjs
CHANGED
|
@@ -1208,6 +1208,81 @@ export function apply(ctx, config) {
|
|
|
1208
1208
|
return list
|
|
1209
1209
|
}
|
|
1210
1210
|
|
|
1211
|
+
// 规则编辑器的候选目录:只读、脱敏、有上限。任何平台/引擎失败都降级为空数组,
|
|
1212
|
+
// 前端始终保留手动输入兜底,绝不能因为目录拉取失败而卡住规则编辑。
|
|
1213
|
+
async function readRuleOptions() {
|
|
1214
|
+
const limit = 200
|
|
1215
|
+
const bots = (() => {
|
|
1216
|
+
try {
|
|
1217
|
+
const satori = typeof ctx.get === 'function' ? ctx.get('satori') : undefined
|
|
1218
|
+
const list = satori?.bots ?? ctx.bots
|
|
1219
|
+
return list ? [...list].filter((bot) => bot?.hidden !== true).slice(0, 20) : []
|
|
1220
|
+
} catch {
|
|
1221
|
+
return []
|
|
1222
|
+
}
|
|
1223
|
+
})()
|
|
1224
|
+
const platformOf = (bot) =>
|
|
1225
|
+
String(bot?.platform ?? bot?.adapter?.platform ?? '').trim().slice(0, 80)
|
|
1226
|
+
const platforms = []
|
|
1227
|
+
const seenPlatforms = new Set()
|
|
1228
|
+
for (const bot of bots) {
|
|
1229
|
+
const platform = platformOf(bot)
|
|
1230
|
+
if (platform === '' || seenPlatforms.has(platform)) continue
|
|
1231
|
+
seenPlatforms.add(platform)
|
|
1232
|
+
platforms.push(platform)
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
const collect = async (method) => {
|
|
1236
|
+
const out = []
|
|
1237
|
+
const seen = new Set()
|
|
1238
|
+
for (const bot of bots) {
|
|
1239
|
+
if (typeof bot?.[method] !== 'function') continue
|
|
1240
|
+
let list
|
|
1241
|
+
try {
|
|
1242
|
+
const task = Promise.resolve()
|
|
1243
|
+
.then(() => bot[method]())
|
|
1244
|
+
.catch(() => [])
|
|
1245
|
+
list = await Promise.race([
|
|
1246
|
+
task,
|
|
1247
|
+
new Promise((resolve) => setTimeout(() => resolve([]), 1500))
|
|
1248
|
+
])
|
|
1249
|
+
} catch {
|
|
1250
|
+
continue
|
|
1251
|
+
}
|
|
1252
|
+
const rows = Array.isArray(list) ? list : Array.isArray(list?.data) ? list.data : []
|
|
1253
|
+
const platform = platformOf(bot)
|
|
1254
|
+
for (const item of rows.slice(0, limit)) {
|
|
1255
|
+
const id = String(item?.id ?? item?.guildId ?? item?.userId ?? '').trim()
|
|
1256
|
+
if (id === '') continue
|
|
1257
|
+
const key = `${platform}\u0000${id}`
|
|
1258
|
+
if (seen.has(key)) continue
|
|
1259
|
+
seen.add(key)
|
|
1260
|
+
const name = String(item?.name ?? item?.nick ?? item?.username ?? '').trim().slice(0, 120)
|
|
1261
|
+
out.push(name === '' ? { platform, id } : { platform, id, name })
|
|
1262
|
+
if (out.length >= limit) return out
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
return out
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
const [guilds, users] = await Promise.all([
|
|
1269
|
+
collect('getGuildList'),
|
|
1270
|
+
collect('getFriendList')
|
|
1271
|
+
])
|
|
1272
|
+
let kbs = []
|
|
1273
|
+
try {
|
|
1274
|
+
const list = await catalog()
|
|
1275
|
+
kbs = list.slice(0, limit).map((kb) => {
|
|
1276
|
+
const id = String(kb?.id ?? '').trim()
|
|
1277
|
+
const name = String(kb?.name ?? '').trim().slice(0, 120)
|
|
1278
|
+
return name === '' ? { id } : { id, name }
|
|
1279
|
+
}).filter((kb) => kb.id !== '')
|
|
1280
|
+
} catch {
|
|
1281
|
+
kbs = []
|
|
1282
|
+
}
|
|
1283
|
+
return { platforms, guilds, users, kbs }
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1211
1286
|
async function scopeFor(call) {
|
|
1212
1287
|
await waitReady()
|
|
1213
1288
|
const scope = await resolveScope(ctx, scopeConfig(), call)
|
|
@@ -1574,7 +1649,8 @@ export function apply(ctx, config) {
|
|
|
1574
1649
|
// 模型复制:列表已脱敏;导入返回 WeKnora 模型 id/维度,不含密钥。
|
|
1575
1650
|
listChatlunaModels,
|
|
1576
1651
|
importChatlunaModel,
|
|
1577
|
-
listWeKnoraModels
|
|
1652
|
+
listWeKnoraModels,
|
|
1653
|
+
ruleOptions: readRuleOptions
|
|
1578
1654
|
})
|
|
1579
1655
|
} catch (err) {
|
|
1580
1656
|
logError('webui', err)
|
package/package.json
CHANGED
package/src/engine/bootstrap.mjs
CHANGED
|
@@ -148,7 +148,7 @@ async function findEmbeddingModel(http, apiKey, name) {
|
|
|
148
148
|
listOf(res.json).find(
|
|
149
149
|
(model) =>
|
|
150
150
|
String(model?.name ?? '') === wanted &&
|
|
151
|
-
(model?.type === undefined || String(model.type) === 'embedding')
|
|
151
|
+
(model?.type === undefined || String(model.type).toLowerCase() === 'embedding')
|
|
152
152
|
) ?? null
|
|
153
153
|
)
|
|
154
154
|
} catch {
|
|
@@ -182,7 +182,7 @@ async function createEmbeddingModel(http, apiKey, embedding, embeddingKey, logge
|
|
|
182
182
|
if (!embedding?.baseUrl) throw new Error('embedding.baseUrl 未配置')
|
|
183
183
|
const body = {
|
|
184
184
|
name: embedding.model,
|
|
185
|
-
type: '
|
|
185
|
+
type: 'Embedding',
|
|
186
186
|
source: 'remote',
|
|
187
187
|
display_name: embedding.displayName ?? embedding.model,
|
|
188
188
|
description: embedding.description ?? 'ChatLuna 自动配置的 Embedding 模型',
|
|
@@ -28,7 +28,7 @@ const VALUE_DEPTH_MAX = 8
|
|
|
28
28
|
const VALUE_NODES_MAX = 2000
|
|
29
29
|
const VALUE_ARRAY_MAX = 200
|
|
30
30
|
|
|
31
|
-
const IMPORT_ROLES = new Set(['embedding', 'vlm'])
|
|
31
|
+
const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
|
|
32
32
|
const CONFLICT_CODES = new Set(['CONFLICT', 'ALREADY_EXISTS', 'DUPLICATE', 'MODEL_EXISTS', 'EXISTS'])
|
|
33
33
|
const VALIDATION_CODES = new Set([
|
|
34
34
|
'INVALID_ARGUMENT',
|
|
@@ -123,6 +123,8 @@ function sanitizeModelEntry(entry) {
|
|
|
123
123
|
if (isNonEmptyString(entry.modelId)) out.modelId = clip(entry.modelId, ID_MAX)
|
|
124
124
|
if (isNonEmptyString(entry.type)) out.type = clip(entry.type, CAPABILITY_MAX)
|
|
125
125
|
if (isNonEmptyString(entry.baseUrl)) out.baseUrl = clip(entry.baseUrl, URL_MAX)
|
|
126
|
+
if (entry.supportsVision === true) out.supportsVision = true
|
|
127
|
+
if (isNonEmptyString(entry.protocolHint)) out.protocolHint = clip(entry.protocolHint, CAPABILITY_MAX)
|
|
126
128
|
if (typeof entry.dimension === 'number' && Number.isSafeInteger(entry.dimension) && entry.dimension > 0) {
|
|
127
129
|
out.dimension = entry.dimension
|
|
128
130
|
}
|
|
@@ -288,7 +290,7 @@ function validateImport(body) {
|
|
|
288
290
|
throw new ModelRouteError('INVALID_ARGUMENT', '请求体必须是 JSON 对象')
|
|
289
291
|
}
|
|
290
292
|
if (typeof body.role !== 'string' || !IMPORT_ROLES.has(body.role)) {
|
|
291
|
-
throw new ModelRouteError('INVALID_ARGUMENT', 'role 必须是 embedding 或
|
|
293
|
+
throw new ModelRouteError('INVALID_ARGUMENT', 'role 必须是 embedding、chat、vlm 或 rerank')
|
|
292
294
|
}
|
|
293
295
|
return {
|
|
294
296
|
role: body.role,
|
|
@@ -320,7 +322,7 @@ function disposeOf(handle) {
|
|
|
320
322
|
* @param {string} [options.prefix='/kb-admin']
|
|
321
323
|
* @param {(ctx: object, req: object) => boolean | Promise<boolean>} options.authorize
|
|
322
324
|
* @param {() => unknown | Promise<unknown>} options.listModels
|
|
323
|
-
* @param {(input: { role: 'embedding' | 'vlm', providerId: string, modelId: string }) => unknown | Promise<unknown>} options.importModel
|
|
325
|
+
* @param {(input: { role: 'embedding' | 'chat' | 'vlm' | 'rerank', providerId: string, modelId: string }) => unknown | Promise<unknown>} options.importModel
|
|
324
326
|
* @param {() => unknown | Promise<unknown>} [options.listWeKnoraModels]
|
|
325
327
|
* @param {object} [options.logger]
|
|
326
328
|
* @returns {() => void} dispose
|
package/src/webui/models.mjs
CHANGED
|
@@ -21,7 +21,7 @@ const ROUTE_MODELS_MAX = 512
|
|
|
21
21
|
const MESSAGE_MAX = 200
|
|
22
22
|
const DEFAULT_TIMEOUT_MS = 15_000
|
|
23
23
|
|
|
24
|
-
const IMPORT_ROLES = new Set(['embedding', 'vlm'])
|
|
24
|
+
const IMPORT_ROLES = new Set(['embedding', 'chat', 'vlm', 'rerank'])
|
|
25
25
|
|
|
26
26
|
export class ModelBridgeError extends Error {
|
|
27
27
|
constructor(code, message) {
|
|
@@ -71,7 +71,7 @@ function validateImportInput(input) {
|
|
|
71
71
|
throw new ModelBridgeError('INVALID_ARGUMENT', '模型导入参数必须是对象')
|
|
72
72
|
}
|
|
73
73
|
if (typeof input.role !== 'string' || !IMPORT_ROLES.has(input.role)) {
|
|
74
|
-
throw new ModelBridgeError('INVALID_ARGUMENT', 'role 必须是 embedding 或
|
|
74
|
+
throw new ModelBridgeError('INVALID_ARGUMENT', 'role 必须是 embedding、chat、vlm 或 rerank')
|
|
75
75
|
}
|
|
76
76
|
const providerId = textOf(input.providerId, ID_MAX)
|
|
77
77
|
const modelId = textOf(input.modelId, ID_MAX)
|
|
@@ -105,17 +105,77 @@ function capabilitiesOf(model) {
|
|
|
105
105
|
return out
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
const VISION_CAPABILITIES = new Set(['vision', 'vlm'])
|
|
109
|
+
|
|
110
|
+
function normalizedCapabilities(capabilities) {
|
|
110
111
|
const list = Array.isArray(capabilities) ? capabilities : []
|
|
111
|
-
|
|
112
|
+
return list.map((item) => (typeof item === 'string' ? item.toLowerCase() : ''))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* ChatLuna 能力 → 复制角色。能力是叠加的,不能按「看到 vision 就是 VLM」一刀切:
|
|
117
|
+
* - embed* → embedding
|
|
118
|
+
* - rerank* → rerank
|
|
119
|
+
* - 只有 draw(或 image* 且无 chat)→ 生图模型,不进知识库清单
|
|
120
|
+
* - chat → 对话(KnowledgeQA);同时有 vision 时附带 supportsVision
|
|
121
|
+
* - 仅 vision/vlm 且无 chat/draw → 纯视觉(VLLM)
|
|
122
|
+
*/
|
|
123
|
+
export function modelTypeOf(capabilities) {
|
|
124
|
+
const lower = normalizedCapabilities(capabilities)
|
|
112
125
|
if (lower.some((item) => item.startsWith('embed'))) return 'embedding'
|
|
113
|
-
if (lower.some((item) => item
|
|
114
|
-
|
|
115
|
-
|
|
126
|
+
if (lower.some((item) => item.startsWith('rerank'))) return 'rerank'
|
|
127
|
+
const hasChat = lower.some((item) => item === 'chat' || item === 'knowledgeqa')
|
|
128
|
+
const hasDraw = lower.some((item) => item === 'draw' || item.startsWith('image'))
|
|
129
|
+
if (hasDraw && !hasChat) return null
|
|
130
|
+
if (hasChat) return 'chat'
|
|
131
|
+
if (lower.some((item) => VISION_CAPABILITIES.has(item))) return 'vlm'
|
|
116
132
|
return null
|
|
117
133
|
}
|
|
118
134
|
|
|
135
|
+
/** 一个模型允许导入的角色;带视觉的对话模型可二选一。 */
|
|
136
|
+
export function modelRolesOf(capabilities) {
|
|
137
|
+
const type = modelTypeOf(capabilities)
|
|
138
|
+
if (type === null) return []
|
|
139
|
+
const lower = normalizedCapabilities(capabilities)
|
|
140
|
+
if (type === 'chat' && lower.some((item) => VISION_CAPABILITIES.has(item))) {
|
|
141
|
+
return ['chat', 'vlm']
|
|
142
|
+
}
|
|
143
|
+
return [type]
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function modelSupportsVision(capabilities) {
|
|
147
|
+
const lower = normalizedCapabilities(capabilities)
|
|
148
|
+
return lower.some((item) => VISION_CAPABILITIES.has(item))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 复合路由把端点按协议拆分;按模型角色选择能用的 baseUrl。 */
|
|
152
|
+
export function routeBaseUrlOf(route, role = '') {
|
|
153
|
+
if (route === null || typeof route !== 'object') return ''
|
|
154
|
+
const candidates =
|
|
155
|
+
role === 'rerank'
|
|
156
|
+
? [route.rerank, route.baseURL, route.baseUrl, route.chat, route.responses]
|
|
157
|
+
: [route.baseURL, route.baseUrl, route.chat, route.responses]
|
|
158
|
+
for (const candidate of candidates) {
|
|
159
|
+
const value = textOf(candidate, URL_MAX)
|
|
160
|
+
if (value !== '') return value.replace(/\/+$/, '')
|
|
161
|
+
}
|
|
162
|
+
return ''
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function protocolHintOf(route, baseUrl) {
|
|
166
|
+
const pkg = textOf(route?.packageName, ID_MAX)
|
|
167
|
+
if (baseUrl === '') return undefined
|
|
168
|
+
if (pkg === '@ai-sdk/anthropic' && !/\/openai(?:\/|$)/i.test(baseUrl)) return 'anthropic'
|
|
169
|
+
if (
|
|
170
|
+
pkg === '@ai-sdk/google' &&
|
|
171
|
+
/generativelanguage\.googleapis\.com/i.test(baseUrl) &&
|
|
172
|
+
!/\/openai(?:\/|$)/i.test(baseUrl)
|
|
173
|
+
) {
|
|
174
|
+
return 'google'
|
|
175
|
+
}
|
|
176
|
+
return undefined
|
|
177
|
+
}
|
|
178
|
+
|
|
119
179
|
function dimensionOf(model) {
|
|
120
180
|
const raw = model?.embedding?.dimension ?? model?.dimension
|
|
121
181
|
const value = Number(raw)
|
|
@@ -149,7 +209,6 @@ export function collectChatlunaModels(entries) {
|
|
|
149
209
|
for (const route of routesOf(entry)) {
|
|
150
210
|
if (!isPlainObject(route)) continue
|
|
151
211
|
const routeId = textOf(route.id, ID_MAX)
|
|
152
|
-
const baseUrl = textOf(route.baseURL ?? route.baseUrl, URL_MAX)
|
|
153
212
|
for (const model of modelsOf(route)) {
|
|
154
213
|
if (!isPlainObject(model)) continue
|
|
155
214
|
const modelId = textOf(model.id, ID_MAX)
|
|
@@ -160,7 +219,10 @@ export function collectChatlunaModels(entries) {
|
|
|
160
219
|
const key = `${providerId}\u0000${routeId}\u0000${modelId}\u0000${type}`
|
|
161
220
|
if (seen.has(key)) continue
|
|
162
221
|
seen.add(key)
|
|
163
|
-
|
|
222
|
+
const baseUrl = routeBaseUrlOf(route, type)
|
|
223
|
+
const supportsVision = modelSupportsVision(capabilities)
|
|
224
|
+
const protocolHint = protocolHintOf(route, baseUrl)
|
|
225
|
+
const card = {
|
|
164
226
|
providerId,
|
|
165
227
|
providerLabel:
|
|
166
228
|
textOf(entry.label, LABEL_MAX) || textOf(route.displayName, LABEL_MAX) || providerId,
|
|
@@ -170,7 +232,10 @@ export function collectChatlunaModels(entries) {
|
|
|
170
232
|
baseUrl,
|
|
171
233
|
dimension: dimensionOf(model),
|
|
172
234
|
capabilities
|
|
173
|
-
}
|
|
235
|
+
}
|
|
236
|
+
if (supportsVision) card.supportsVision = true
|
|
237
|
+
if (protocolHint !== undefined) card.protocolHint = protocolHint
|
|
238
|
+
out.push(card)
|
|
174
239
|
if (out.length >= MODELS_MAX) return out
|
|
175
240
|
}
|
|
176
241
|
}
|
|
@@ -191,16 +256,17 @@ export function findChatlunaModel(entries, input) {
|
|
|
191
256
|
for (const model of modelsOf(route)) {
|
|
192
257
|
if (!isPlainObject(model) || textOf(model.id, ID_MAX) !== wanted.modelId) continue
|
|
193
258
|
const capabilities = capabilitiesOf(model)
|
|
194
|
-
|
|
195
|
-
if (type !== wanted.role) continue
|
|
259
|
+
if (!modelRolesOf(capabilities).includes(wanted.role)) continue
|
|
196
260
|
return {
|
|
197
261
|
input: wanted,
|
|
198
262
|
entry,
|
|
199
263
|
route,
|
|
200
264
|
model,
|
|
201
|
-
type,
|
|
202
|
-
baseUrl:
|
|
265
|
+
type: wanted.role,
|
|
266
|
+
baseUrl: routeBaseUrlOf(route, wanted.role),
|
|
203
267
|
dimension: dimensionOf(model),
|
|
268
|
+
supportsVision: modelSupportsVision(capabilities),
|
|
269
|
+
protocolHint: protocolHintOf(route, routeBaseUrlOf(route, wanted.role)),
|
|
204
270
|
displayName:
|
|
205
271
|
textOf(model.displayName, NAME_MAX) ||
|
|
206
272
|
textOf(model.name, NAME_MAX) ||
|
|
@@ -231,25 +297,49 @@ function sessionTokenOf(login) {
|
|
|
231
297
|
}
|
|
232
298
|
|
|
233
299
|
/** POST body 构造单独导出,测试可以断言明文 key 只出现在 parameters.api_key。 */
|
|
234
|
-
export function buildModelCreateBody({
|
|
300
|
+
export function buildModelCreateBody({
|
|
301
|
+
role,
|
|
302
|
+
baseUrl,
|
|
303
|
+
apiKey,
|
|
304
|
+
modelId,
|
|
305
|
+
displayName,
|
|
306
|
+
dimension,
|
|
307
|
+
supportsVision = false,
|
|
308
|
+
protocolHint = ''
|
|
309
|
+
}) {
|
|
235
310
|
const embedding = role === 'embedding'
|
|
311
|
+
const chat = role === 'chat'
|
|
312
|
+
const rerank = role === 'rerank'
|
|
313
|
+
const provider = rerank
|
|
314
|
+
? 'generic'
|
|
315
|
+
: protocolHint === 'anthropic'
|
|
316
|
+
? 'anthropic'
|
|
317
|
+
: protocolHint === 'google'
|
|
318
|
+
? 'gemini'
|
|
319
|
+
: 'openai'
|
|
236
320
|
const body = {
|
|
237
321
|
name: textOf(modelId, ID_MAX),
|
|
238
322
|
display_name: textOf(displayName, NAME_MAX) || textOf(modelId, ID_MAX),
|
|
239
|
-
type: embedding ? 'Embedding' : 'VLLM',
|
|
323
|
+
type: embedding ? 'Embedding' : chat ? 'KnowledgeQA' : rerank ? 'Rerank' : 'VLLM',
|
|
240
324
|
source: 'remote',
|
|
241
|
-
description: embedding
|
|
325
|
+
description: embedding
|
|
326
|
+
? '从 ChatLuna 复制的 Embedding 模型'
|
|
327
|
+
: chat
|
|
328
|
+
? '从 ChatLuna 复制的对话模型'
|
|
329
|
+
: rerank
|
|
330
|
+
? '从 ChatLuna 复制的 ReRank 模型'
|
|
331
|
+
: '从 ChatLuna 复制的视觉模型',
|
|
242
332
|
parameters: {
|
|
243
333
|
base_url: textOf(baseUrl, URL_MAX),
|
|
244
334
|
api_key: typeof apiKey === 'string' ? apiKey : '',
|
|
245
335
|
interface_type: 'openai',
|
|
246
|
-
provider
|
|
336
|
+
provider
|
|
247
337
|
}
|
|
248
338
|
}
|
|
249
339
|
if (embedding && Number.isSafeInteger(dimension) && dimension > 0) {
|
|
250
340
|
body.parameters.embedding_parameters = { dimension }
|
|
251
341
|
}
|
|
252
|
-
if (
|
|
342
|
+
if (supportsVision || role === 'vlm') body.parameters.supports_vision = true
|
|
253
343
|
return body
|
|
254
344
|
}
|
|
255
345
|
|
|
@@ -383,7 +473,9 @@ export function createModelBridge(options = {}) {
|
|
|
383
473
|
apiKey,
|
|
384
474
|
modelId: found.input.modelId,
|
|
385
475
|
displayName: found.displayName,
|
|
386
|
-
dimension: found.dimension
|
|
476
|
+
dimension: found.dimension,
|
|
477
|
+
supportsVision: found.supportsVision,
|
|
478
|
+
protocolHint: found.protocolHint
|
|
387
479
|
})
|
|
388
480
|
|
|
389
481
|
let response
|
|
@@ -419,6 +511,7 @@ export function createModelBridge(options = {}) {
|
|
|
419
511
|
? declaredDimension
|
|
420
512
|
: found.dimension
|
|
421
513
|
}
|
|
514
|
+
if (found.supportsVision === true) result.supportsVision = true
|
|
422
515
|
if (onChange !== null) {
|
|
423
516
|
try {
|
|
424
517
|
onChange()
|