mm_llm 1.3.0 → 1.3.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/index.js +5 -30
- package/lib/admin.js +22 -0
- package/lib/llm.js +228 -639
- package/lib/llm_execute.js +216 -0
- package/lib/llm_message.js +224 -0
- package/lib/manager.js +1 -1
- package/lib/memory.js +1 -1
- package/lib/sqlite.js +9 -475
- package/lib/sqlite_config.js +197 -0
- package/lib/sqlite_quota.js +123 -0
- package/lib/sqlite_session.js +189 -0
- package/package.json +3 -3
- package/tool/llm/index.js +487 -5
- package/tool/llm/tool.json +135 -3
- package/tool/llm_admin/index.js +36 -0
- package/tool/llm_admin/tool.json +11 -0
- package/lib/llm_tool_logic.js +0 -231
- package/lib/tools/index.js +0 -16
- package/lib/tools/llm/index.js +0 -7
package/lib/llm.js
CHANGED
|
@@ -1,639 +1,228 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const { AsyncLocalStorage } = require('async_hooks');
|
|
4
|
-
const { OpenAI } = require('openai');
|
|
5
|
-
const { Drive } = require('mm_machine');
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
//
|
|
73
|
-
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
*
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
*
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
*
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
*
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
*
|
|
179
|
-
* @param {
|
|
180
|
-
* @
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
*
|
|
196
|
-
* @returns {
|
|
197
|
-
*/
|
|
198
|
-
|
|
199
|
-
this
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
if (!authed) {
|
|
230
|
-
throw new Error(`[LLM] 用户 ${ctx.user_id} 无权调用智能体 ${params.agent_id}`);
|
|
231
|
-
}
|
|
232
|
-
const allowed = await this.checkQuota(ctx.user_id, params.agent_id);
|
|
233
|
-
if (!allowed) {
|
|
234
|
-
throw new Error(`[LLM] 用户 ${ctx.user_id} 调用智能体 ${params.agent_id} 被拒绝`);
|
|
235
|
-
}
|
|
236
|
-
if (params.content) {
|
|
237
|
-
this.getStore().addMessage(ctx.user_id, params.agent_id, params.session_id, {
|
|
238
|
-
role: 'user',
|
|
239
|
-
content: params.content
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
const response = await this.send(ctx.user_id, params.agent_id, params.session_id);
|
|
243
|
-
this._saveResponse(ctx.user_id, params.agent_id, params.session_id, response);
|
|
244
|
-
return response;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* 发送消息
|
|
249
|
-
*
|
|
250
|
-
* 依次装配消息上下文、工具定义与调用选项,交由 post 完成调用。
|
|
251
|
-
* @param {Number} user_id 用户ID
|
|
252
|
-
* @param {Number} agent_id 智能体ID
|
|
253
|
-
* @param {Number} session_id 会话ID
|
|
254
|
-
* @returns {Promise<Object>} 助手消息;stream 为真时返回流对象
|
|
255
|
-
*/
|
|
256
|
-
async send(user_id, agent_id, session_id) {
|
|
257
|
-
const messages = await this.getMessages(user_id, agent_id, session_id);
|
|
258
|
-
const tools = this.getTools(agent_id);
|
|
259
|
-
const options = this.getOptions(user_id, agent_id);
|
|
260
|
-
return this.post(messages, tools, options);
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// ---------- 准入控制(默认实现,可覆写) ----------
|
|
264
|
-
/**
|
|
265
|
-
* 调用前鉴权
|
|
266
|
-
*
|
|
267
|
-
* 默认按智能体配置判定:智能体的 users 存在时,仅列表内的用户可调用,
|
|
268
|
-
* 空数组表示谁都不能用;users 缺省时由 config.auth_default 决定,
|
|
269
|
-
* 'allow' 放行、'deny' 拒绝。
|
|
270
|
-
* 子类可覆写以实现角色、黑名单等其它鉴权:返回假值即拒绝本次调用,
|
|
271
|
-
* main 会抛出异常,不发送请求也不写入消息;需要自定义拒绝原因时,
|
|
272
|
-
* 可直接在覆写实现中抛出异常。
|
|
273
|
-
* @param {Number} user_id 用户ID
|
|
274
|
-
* @param {Number} agent_id 智能体ID
|
|
275
|
-
* @returns {Promise<Boolean>} 是否允许调用
|
|
276
|
-
*/
|
|
277
|
-
async checkAuth(user_id, agent_id) {
|
|
278
|
-
const agent = this.getStore().getAgent(agent_id);
|
|
279
|
-
return this._canUseAgent(agent, user_id);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* 调用前准入判定
|
|
284
|
-
*
|
|
285
|
-
* 默认按用户配额判定:从存储读取该用户的剩余配额,大于 0 才放行;
|
|
286
|
-
* 未设置配额(返回 undefined)视为无配额,一并拒绝。
|
|
287
|
-
* 子类可覆写以实现权限、限流等其它控制:返回假值即拒绝本次调用,
|
|
288
|
-
* main 会抛出异常,不发送请求也不写入消息;需要自定义拒绝原因时,
|
|
289
|
-
* 可直接在覆写实现中抛出异常。配额扣减等结算动作由二次开发者自行处理。
|
|
290
|
-
* @param {Number} user_id 用户ID
|
|
291
|
-
* @param {Number} agent_id 智能体ID
|
|
292
|
-
* @returns {Promise<Boolean>} 是否允许调用
|
|
293
|
-
*/
|
|
294
|
-
async checkQuota(user_id, agent_id) {
|
|
295
|
-
const quota = this.getStore().getQuota(user_id);
|
|
296
|
-
return typeof quota === 'number' && quota > 0;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// ---------- 数据装配(默认实现,可覆写或替换 store) ----------
|
|
300
|
-
/**
|
|
301
|
-
* 获取系统提示
|
|
302
|
-
*
|
|
303
|
-
* 由两段拼成:基础提示 + 用户信息段。
|
|
304
|
-
* 基础提示优先取 (user_id, agent_id) 级提示词,其次智能体配置,最后实例配置。
|
|
305
|
-
* 任一段为空则忽略,都为空时返回空串表示不添加系统消息。
|
|
306
|
-
* @param {Number} user_id 用户ID
|
|
307
|
-
* @param {Number} agent_id 智能体ID
|
|
308
|
-
* @param {Number} session_id 会话ID
|
|
309
|
-
* @returns {String} 系统提示
|
|
310
|
-
*/
|
|
311
|
-
getSystemPrompt(user_id, agent_id, session_id) {
|
|
312
|
-
const base_prompt = this.getBasePrompt(user_id, agent_id);
|
|
313
|
-
const user_prompt = this._buildUserPrompt(user_id);
|
|
314
|
-
return this._joinPrompts([base_prompt, user_prompt]);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* 获取基础提示词
|
|
319
|
-
*
|
|
320
|
-
* 优先取该用户对该智能体的提示词(由 setOptions 设置),
|
|
321
|
-
* 存在时即代替智能体自身的系统提示词;否则依次回落到智能体配置、实例配置。
|
|
322
|
-
* @param {Number} user_id 用户ID
|
|
323
|
-
* @param {Number} agent_id 智能体ID
|
|
324
|
-
* @returns {String} 基础提示词,均未配置时返回空串
|
|
325
|
-
*/
|
|
326
|
-
getBasePrompt(user_id, agent_id) {
|
|
327
|
-
const options = this.getStore().getOptions(user_id, agent_id);
|
|
328
|
-
if (options.system_prompt) return options.system_prompt;
|
|
329
|
-
const agent = this.getStore().getAgent(agent_id);
|
|
330
|
-
return agent.system_prompt || this.config.system_prompt || '';
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* 获取历史消息
|
|
335
|
-
*
|
|
336
|
-
* 默认从存储中按 (user_id, agent_id, session_id) 三元组读取;替换存储即改从 SQLite 等处读取。
|
|
337
|
-
* @param {Number} user_id 用户ID
|
|
338
|
-
* @param {Number} agent_id 智能体ID
|
|
339
|
-
* @param {Number} session_id 会话ID
|
|
340
|
-
* @returns {Promise<Array>} 历史消息数组,元素形如 { role, content }
|
|
341
|
-
*/
|
|
342
|
-
async getHistory(user_id, agent_id, session_id) {
|
|
343
|
-
return this.getStore().getMessages(user_id, agent_id, session_id);
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* 获取消息上下文
|
|
348
|
-
*
|
|
349
|
-
* 会话首次调用时把系统提示固化为一条 system 消息写入存储(置于最前),
|
|
350
|
-
* 之后每轮直接从历史读取,不再重新拼装,使历史前缀保持稳定以命中缓存。
|
|
351
|
-
* 若历史中已有 system 消息,或本就无需系统提示,则原样返回历史。
|
|
352
|
-
* @param {Number} user_id 用户ID
|
|
353
|
-
* @param {Number} agent_id 智能体ID
|
|
354
|
-
* @param {Number} session_id 会话ID
|
|
355
|
-
* @returns {Promise<Array>} 消息上下文数组
|
|
356
|
-
*/
|
|
357
|
-
async getMessages(user_id, agent_id, session_id) {
|
|
358
|
-
const history = await this.getHistory(user_id, agent_id, session_id);
|
|
359
|
-
if (this._hasSystemMessage(history)) return history;
|
|
360
|
-
|
|
361
|
-
const system_message = this._buildSystemMessage(user_id, agent_id, session_id);
|
|
362
|
-
if (!system_message) return history;
|
|
363
|
-
|
|
364
|
-
const messages = [system_message].concat(history);
|
|
365
|
-
this.getStore().setMessages(user_id, agent_id, session_id, messages);
|
|
366
|
-
return messages;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* 获取选项
|
|
371
|
-
*
|
|
372
|
-
* 合并优先级由低到高:实例默认配置 < 该用户对该智能体的选项 < 本次调用选项。
|
|
373
|
-
* 选项按 (user_id, agent_id) 成对存放,故同一用户对不同智能体可有不同选项;
|
|
374
|
-
* 本次调用选项取自异步上下文,故同一实例并发多用户时互不影响。
|
|
375
|
-
* @param {Number} user_id 用户ID
|
|
376
|
-
* @param {Number} agent_id 智能体ID
|
|
377
|
-
* @returns {Object} 选项对象,含 api_key / base_url / model / temperature / stream 等
|
|
378
|
-
*/
|
|
379
|
-
getOptions(user_id, agent_id) {
|
|
380
|
-
const defaults = this._pickOptions(this.config);
|
|
381
|
-
const options = this.getStore().getOptions(user_id, agent_id);
|
|
382
|
-
const call_options = CALL_OPTIONS_STORAGE.getStore() || {};
|
|
383
|
-
return Object.assign({}, defaults, options, call_options);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/**
|
|
387
|
-
* 获取工具定义
|
|
388
|
-
*
|
|
389
|
-
* 默认取智能体配置中的工具名集合(agent.tools),逐个到存储读取工具定义
|
|
390
|
-
* (即提交给模型的函数声明)后拼成数组;引用的工具名未在存储中定义时抛出异常。
|
|
391
|
-
* 工具的执行函数由实例上的工具注册表提供,见 setTool。
|
|
392
|
-
* @param {Number} agent_id 智能体ID
|
|
393
|
-
* @returns {Array} 工具函数数组,元素为模型的函数定义结构
|
|
394
|
-
*/
|
|
395
|
-
getTools(agent_id) {
|
|
396
|
-
const agent = this.getStore().getAgent(agent_id);
|
|
397
|
-
const tool_names = agent.tools || [];
|
|
398
|
-
return tool_names.map((tool_name) => this._getToolSchema(tool_name));
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// ---------- 执行(默认实现,可覆写) ----------
|
|
402
|
-
/**
|
|
403
|
-
* 使用工具函数
|
|
404
|
-
*
|
|
405
|
-
* 默认从实例上的工具注册表按名称查找执行函数。
|
|
406
|
-
* @param {String} tool_name 工具函数名称
|
|
407
|
-
* @param {Object} params 工具函数参数
|
|
408
|
-
* @returns {Promise<*>} 工具函数执行结果
|
|
409
|
-
*/
|
|
410
|
-
async useTool(tool_name, params) {
|
|
411
|
-
const handler = this.getTool(tool_name);
|
|
412
|
-
if (typeof handler !== 'function') {
|
|
413
|
-
throw new Error(`[LLM] 未找到工具 ${tool_name} 的实现`);
|
|
414
|
-
}
|
|
415
|
-
return handler(params);
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
/**
|
|
419
|
-
* 发送消息
|
|
420
|
-
*
|
|
421
|
-
* 默认走 OpenAI 兼容接口,并在模型请求工具时执行工具、回填结果后继续对话,
|
|
422
|
-
* 直到模型不再请求工具或达到 config.max_rounds 上限。
|
|
423
|
-
* @param {Array} messages 消息上下文数组
|
|
424
|
-
* @param {Array} tools 工具函数数组
|
|
425
|
-
* @param {Object} options 选项对象
|
|
426
|
-
* @returns {Promise<Object>} 助手消息;stream 为真时返回流对象
|
|
427
|
-
*/
|
|
428
|
-
async post(messages, tools, options) {
|
|
429
|
-
const client = this._getClient(options);
|
|
430
|
-
let round = 0;
|
|
431
|
-
for (;;) {
|
|
432
|
-
const request = this._buildRequest(messages, tools, options);
|
|
433
|
-
const response = await client.chat.completions.create(request);
|
|
434
|
-
if (options.stream) return response;
|
|
435
|
-
|
|
436
|
-
const message = response.choices[0].message;
|
|
437
|
-
const tool_calls = message.tool_calls || [];
|
|
438
|
-
if (tool_calls.length === 0 || round >= this.config.max_rounds) {
|
|
439
|
-
return message;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
await this._appendToolMessages(messages, message, tool_calls);
|
|
443
|
-
round += 1;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// ---------- 私有方法 ----------
|
|
448
|
-
/**
|
|
449
|
-
* 判断用户能否调用指定智能体(私有方法)
|
|
450
|
-
*
|
|
451
|
-
* 以 users 字段是否存在区分「已限定」与「未限定」:存在时仅列表内用户可通过,
|
|
452
|
-
* 空数组即谁都不能用;缺省时回落到 config.auth_default。
|
|
453
|
-
* @param {Object} agent 智能体配置
|
|
454
|
-
* @param {Number} user_id 用户ID
|
|
455
|
-
* @returns {Boolean} 是否允许调用
|
|
456
|
-
*/
|
|
457
|
-
_canUseAgent(agent, user_id) {
|
|
458
|
-
if (agent.users === undefined) return this.config.auth_default !== 'deny';
|
|
459
|
-
return agent.users.includes(user_id);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/**
|
|
463
|
-
* 从存储读取用户信息并组装成提示段(私有方法)
|
|
464
|
-
* @param {Number} user_id 用户ID
|
|
465
|
-
* @returns {String} 用户信息提示段,无用户信息时返回空串
|
|
466
|
-
*/
|
|
467
|
-
_buildUserPrompt(user_id) {
|
|
468
|
-
const user = this.getStore().getUser(user_id);
|
|
469
|
-
const lines = [];
|
|
470
|
-
if (user.name) lines.push(`用户称呼:${user.name}`);
|
|
471
|
-
if (user.profile) lines.push(`用户偏好:${user.profile}`);
|
|
472
|
-
return lines.join('\n');
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
/**
|
|
476
|
-
* 拼接非空提示段(私有方法)
|
|
477
|
-
* @param {Array} sections 提示段数组,空值会被忽略
|
|
478
|
-
* @returns {String} 拼接结果,各段以空行分隔
|
|
479
|
-
*/
|
|
480
|
-
_joinPrompts(sections) {
|
|
481
|
-
const valid = [];
|
|
482
|
-
for (const section of sections) {
|
|
483
|
-
if (section) valid.push(section);
|
|
484
|
-
}
|
|
485
|
-
return valid.join('\n\n');
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/**
|
|
489
|
-
* 组装系统消息(私有方法)
|
|
490
|
-
* @param {Number} user_id 用户ID
|
|
491
|
-
* @param {Number} agent_id 智能体ID
|
|
492
|
-
* @param {Number} session_id 会话ID
|
|
493
|
-
* @returns {Object|null} 系统消息,提示为空时返回 null
|
|
494
|
-
*/
|
|
495
|
-
_buildSystemMessage(user_id, agent_id, session_id) {
|
|
496
|
-
const system_prompt = this.getSystemPrompt(user_id, agent_id, session_id);
|
|
497
|
-
if (!system_prompt) return null;
|
|
498
|
-
return { role: 'system', content: system_prompt };
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* 判断消息列表中是否已有 system 消息(私有方法)
|
|
503
|
-
* @param {Array} messages 消息数组
|
|
504
|
-
* @returns {Boolean} 是否已含 system 消息
|
|
505
|
-
*/
|
|
506
|
-
_hasSystemMessage(messages) {
|
|
507
|
-
for (const message of messages) {
|
|
508
|
-
if (message.role === 'system') return true;
|
|
509
|
-
}
|
|
510
|
-
return false;
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
/**
|
|
514
|
-
* 按工具名读取工具定义(私有方法)
|
|
515
|
-
* @param {String} tool_name 工具函数名称
|
|
516
|
-
* @returns {Object} 工具定义
|
|
517
|
-
*/
|
|
518
|
-
_getToolSchema(tool_name) {
|
|
519
|
-
const schema = this.getStore().getToolSchema(tool_name);
|
|
520
|
-
if (!schema) {
|
|
521
|
-
throw new Error(`[LLM] 智能体引用的工具 ${tool_name} 未在存储中定义`);
|
|
522
|
-
}
|
|
523
|
-
return schema;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
/**
|
|
527
|
-
* 从配置中挑选模型调用相关字段(私有方法)
|
|
528
|
-
* @param {Object} source 配置来源
|
|
529
|
-
* @returns {Object} 选项对象
|
|
530
|
-
*/
|
|
531
|
-
_pickOptions(source) {
|
|
532
|
-
const keys = ['api_key', 'base_url', 'model', 'temperature', 'max_tokens', 'stream'];
|
|
533
|
-
const options = {};
|
|
534
|
-
for (const key of keys) {
|
|
535
|
-
if (source[key] !== undefined) options[key] = source[key];
|
|
536
|
-
}
|
|
537
|
-
return options;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
/**
|
|
541
|
-
* 组装请求参数(私有方法)
|
|
542
|
-
* @param {Array} messages 消息上下文数组
|
|
543
|
-
* @param {Array} tools 工具函数数组
|
|
544
|
-
* @param {Object} options 选项对象
|
|
545
|
-
* @returns {Object} 请求参数
|
|
546
|
-
*/
|
|
547
|
-
_buildRequest(messages, tools, options) {
|
|
548
|
-
const request = {
|
|
549
|
-
model: options.model,
|
|
550
|
-
messages,
|
|
551
|
-
temperature: options.temperature,
|
|
552
|
-
max_tokens: options.max_tokens,
|
|
553
|
-
stream: options.stream
|
|
554
|
-
};
|
|
555
|
-
if (tools && tools.length > 0) request.tools = tools;
|
|
556
|
-
return request;
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/**
|
|
560
|
-
* 获取 OpenAI 客户端(私有方法,按 api_key 与 base_url 缓存)
|
|
561
|
-
* @param {Object} options 选项对象
|
|
562
|
-
* @returns {Object} OpenAI 客户端
|
|
563
|
-
*/
|
|
564
|
-
_getClient(options) {
|
|
565
|
-
if (!options.api_key) {
|
|
566
|
-
throw new Error('[LLM] 缺少 api_key,请通过实例配置、用户配置或智能体配置提供');
|
|
567
|
-
}
|
|
568
|
-
const client_key = `${options.api_key}@${options.base_url}`;
|
|
569
|
-
if (this.#client && this.#client_key === client_key) {
|
|
570
|
-
return this.#client;
|
|
571
|
-
}
|
|
572
|
-
this.#client = new OpenAI({ apiKey: options.api_key, baseURL: options.base_url });
|
|
573
|
-
this.#client_key = client_key;
|
|
574
|
-
return this.#client;
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
/**
|
|
578
|
-
* 把助手消息与工具执行结果追加到上下文(私有方法)
|
|
579
|
-
* @param {Array} messages 消息上下文数组
|
|
580
|
-
* @param {Object} message 助手消息
|
|
581
|
-
* @param {Array} tool_calls 工具调用数组
|
|
582
|
-
*/
|
|
583
|
-
async _appendToolMessages(messages, message, tool_calls) {
|
|
584
|
-
messages.push({
|
|
585
|
-
role: 'assistant',
|
|
586
|
-
content: message.content || '',
|
|
587
|
-
tool_calls
|
|
588
|
-
});
|
|
589
|
-
for (const tool_call of tool_calls) {
|
|
590
|
-
const params = this._parseToolParams(tool_call);
|
|
591
|
-
const result = await this.useTool(tool_call.function.name, params);
|
|
592
|
-
messages.push({
|
|
593
|
-
role: 'tool',
|
|
594
|
-
tool_call_id: tool_call.id,
|
|
595
|
-
content: this._stringifyResult(result)
|
|
596
|
-
});
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
/**
|
|
601
|
-
* 解析工具调用参数(私有方法)
|
|
602
|
-
* @param {Object} tool_call 工具调用对象
|
|
603
|
-
* @returns {Object} 参数对象,解析失败时为空对象
|
|
604
|
-
*/
|
|
605
|
-
_parseToolParams(tool_call) {
|
|
606
|
-
try {
|
|
607
|
-
return JSON.parse(tool_call.function.arguments || '{}');
|
|
608
|
-
} catch (error) {
|
|
609
|
-
return {};
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/**
|
|
614
|
-
* 序列化工具执行结果(私有方法)
|
|
615
|
-
* @param {*} result 工具执行结果
|
|
616
|
-
* @returns {String} 字符串结果
|
|
617
|
-
*/
|
|
618
|
-
_stringifyResult(result) {
|
|
619
|
-
if (typeof result === 'string') return result;
|
|
620
|
-
return JSON.stringify(result === undefined ? null : result);
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
/**
|
|
624
|
-
* 把助手回复写回存储(私有方法,流式响应时跳过)
|
|
625
|
-
* @param {Number} user_id 用户ID
|
|
626
|
-
* @param {Number} agent_id 智能体ID
|
|
627
|
-
* @param {Number} session_id 会话ID
|
|
628
|
-
* @param {Object} response 助手消息或流对象
|
|
629
|
-
*/
|
|
630
|
-
_saveResponse(user_id, agent_id, session_id, response) {
|
|
631
|
-
if (!session_id || !response || !response.role) return;
|
|
632
|
-
this.getStore().addMessage(user_id, agent_id, session_id, {
|
|
633
|
-
role: response.role,
|
|
634
|
-
content: response.content || ''
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
module.exports = { LLM };
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { AsyncLocalStorage } = require('async_hooks');
|
|
4
|
+
const { OpenAI } = require('openai/index.js');
|
|
5
|
+
const { Drive } = require('mm_machine');
|
|
6
|
+
const llm_message = require('./llm_message');
|
|
7
|
+
const llm_execute = require('./llm_execute');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 大模型调用类
|
|
11
|
+
*
|
|
12
|
+
* 直接实例化即可使用:默认从内存存储(Memory)读取会话消息、智能体与用户配置,
|
|
13
|
+
* 经 OpenAI 兼容接口完成对话,并把助手回复写回存储。
|
|
14
|
+
*
|
|
15
|
+
* 用法:
|
|
16
|
+
* const llm = new LLM({ name: 'gpt', api_key: 'sk-xxx' });
|
|
17
|
+
* llm.setTool('get_time', () => ({ time: '12:00' }));
|
|
18
|
+
* llm.getStore().setToolSchema('get_time', { type: 'function', function: { name: 'get_time' } });
|
|
19
|
+
* llm.getStore().setAgent(1, { system_prompt: '你是助手', tools: ['get_time'], users: [9] });
|
|
20
|
+
* const message = await llm.main({ user_id: 9 }, { agent_id: 1, session_id: 100, content: '你好' });
|
|
21
|
+
*
|
|
22
|
+
* 可替换点:
|
|
23
|
+
* 1. 注入存储:new LLM({ store }),传入实现同一契约的存储(如 SQLite 存储),
|
|
24
|
+
* 消息、选项、系统提示、工具即改由该存储提供;
|
|
25
|
+
* 2. 覆写方法:子类覆写 getHistory / getOptions / getSystemPrompt / getTools /
|
|
26
|
+
* useTool / post / checkAuth / checkQuota,即可自定义任意一步的数据来源与行为。
|
|
27
|
+
*
|
|
28
|
+
* 消息分区:
|
|
29
|
+
* 存储按 (user_id, agent_id, session_id) 三元组分区,因此不同用户或不同智能体
|
|
30
|
+
* 复用同一 session_id 也不会串台。
|
|
31
|
+
*
|
|
32
|
+
* 鉴权:
|
|
33
|
+
* 调用前按智能体配置中的 users(允许调用的用户ID数组)判定:
|
|
34
|
+
* users 存在时不在此列的用户一律拒绝,空数组表示谁都不能用;
|
|
35
|
+
* users 缺省时由 config.auth_default 决定,'allow' 放行(默认)、'deny' 拒绝。
|
|
36
|
+
*
|
|
37
|
+
* 存储契约(store):
|
|
38
|
+
* getMessages(user_id, agent_id, session_id) -> Array
|
|
39
|
+
* setMessages(user_id, agent_id, session_id, messages) -> store
|
|
40
|
+
* addMessage(user_id, agent_id, session_id, message) -> store
|
|
41
|
+
* delSession(user_id, agent_id, session_id) -> Boolean
|
|
42
|
+
* getAgent(agent_id) -> { system_prompt, tools, users }
|
|
43
|
+
* getToolSchema(tool_name) -> Object
|
|
44
|
+
* setToolSchema(tool_name, schema) -> store
|
|
45
|
+
* getUser(user_id) -> { name, profile }
|
|
46
|
+
* getOptions(user_id, agent_id) -> Object
|
|
47
|
+
* getQuota(user_id) -> Number(未设置时返回 undefined,视为无配额)
|
|
48
|
+
*
|
|
49
|
+
* mm_machine 集成:
|
|
50
|
+
* 继承 Drive,可由 LLMManager 以 llm.json 配置文件登记为托管实例;
|
|
51
|
+
* 配置声明 main 指向脚本时,脚本的 func_name 函数会覆写内置 main
|
|
52
|
+
* (脚本不存在时按 lib/script.tpl.js 模板生成);缺省 main 为空,
|
|
53
|
+
* 不加载脚本,保持内置对话逻辑。
|
|
54
|
+
*/
|
|
55
|
+
class LLM extends Drive {
|
|
56
|
+
/**
|
|
57
|
+
* 本次调用选项的异步上下文存储
|
|
58
|
+
*
|
|
59
|
+
* 用 AsyncLocalStorage 而非实例字段承载调用选项,
|
|
60
|
+
* 使同一 LLM 实例并发处理多个用户时互不干扰。
|
|
61
|
+
* @type {AsyncLocalStorage}
|
|
62
|
+
*/
|
|
63
|
+
static #call_options_storage = new AsyncLocalStorage();
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 默认配置
|
|
67
|
+
*/
|
|
68
|
+
static config = {
|
|
69
|
+
name: '',
|
|
70
|
+
title: '',
|
|
71
|
+
description: '',
|
|
72
|
+
// 主脚本文件,缺省为空表示不加载脚本、保持内置对话逻辑
|
|
73
|
+
main: '',
|
|
74
|
+
// 脚本回调函数名
|
|
75
|
+
func_name: 'main',
|
|
76
|
+
// 作用域
|
|
77
|
+
scope: 'os',
|
|
78
|
+
// 状态 0未启用 1启用
|
|
79
|
+
state: 1,
|
|
80
|
+
// 排序
|
|
81
|
+
sort: 10,
|
|
82
|
+
api_key: '',
|
|
83
|
+
base_url: 'https://api.openai.com/v1',
|
|
84
|
+
model: 'gpt-4o',
|
|
85
|
+
temperature: 0.7,
|
|
86
|
+
max_tokens: 8192,
|
|
87
|
+
stream: false,
|
|
88
|
+
system_prompt: '',
|
|
89
|
+
max_rounds: 8,
|
|
90
|
+
auth_default: 'allow',
|
|
91
|
+
store: null
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 工具注册表,工具名 -> 执行函数(私有)
|
|
96
|
+
*/
|
|
97
|
+
#handlers = new Map();
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 缓存的 OpenAI 客户端(私有)
|
|
101
|
+
*/
|
|
102
|
+
#client = null;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 客户端缓存键(私有)
|
|
106
|
+
*/
|
|
107
|
+
#client_key = '';
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 构造函数
|
|
111
|
+
* @param {Object} config 配置,字段同 LLM.config,name 必填
|
|
112
|
+
* @param {Object} parent 父级管理器(可选)
|
|
113
|
+
*/
|
|
114
|
+
constructor(config = {}, parent) {
|
|
115
|
+
if (!config.name) {
|
|
116
|
+
throw new TypeError('[LLM] 配置缺少 name,实例名称必填');
|
|
117
|
+
}
|
|
118
|
+
super({ ...LLM.config, ...config }, parent);
|
|
119
|
+
this.setStore(this.config.store);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------- 工具注册表 ----------
|
|
123
|
+
/**
|
|
124
|
+
* 注册工具实现
|
|
125
|
+
*
|
|
126
|
+
* 工具的执行函数注册在实例上;工具定义(提交给模型的函数声明)存于存储,
|
|
127
|
+
* 见存储的 setToolSchema,两者按同名关联。
|
|
128
|
+
* @param {String} tool_name 工具函数名称
|
|
129
|
+
* @param {Function} handler 工具执行函数,签名为 (params) => result
|
|
130
|
+
* @returns {LLM} 当前实例
|
|
131
|
+
*/
|
|
132
|
+
setTool(tool_name, handler) {
|
|
133
|
+
this.#handlers.set(tool_name, handler);
|
|
134
|
+
return this;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 获取工具实现
|
|
139
|
+
* @param {String} tool_name 工具函数名称
|
|
140
|
+
* @returns {Function|undefined} 工具执行函数
|
|
141
|
+
*/
|
|
142
|
+
getTool(tool_name) {
|
|
143
|
+
return this.#handlers.get(tool_name);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 删除工具实现
|
|
148
|
+
* @param {String} tool_name 工具函数名称
|
|
149
|
+
* @returns {Boolean} 是否删除了已注册的工具
|
|
150
|
+
*/
|
|
151
|
+
delTool(tool_name) {
|
|
152
|
+
return this.#handlers.delete(tool_name);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 列出已注册的工具名
|
|
157
|
+
* @returns {Array} 工具函数名称数组
|
|
158
|
+
*/
|
|
159
|
+
listTools() {
|
|
160
|
+
return Array.from(this.#handlers.keys());
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 清空工具注册表
|
|
165
|
+
* @returns {LLM} 当前实例
|
|
166
|
+
*/
|
|
167
|
+
clearTools() {
|
|
168
|
+
this.#handlers.clear();
|
|
169
|
+
return this;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---------- 对外入口 ----------
|
|
173
|
+
/**
|
|
174
|
+
* 执行一次对话(对外入口)
|
|
175
|
+
*
|
|
176
|
+
* 记录本次调用选项,把用户输入写入存储,委托 send 完成调用,
|
|
177
|
+
* 再把助手回复写回存储。
|
|
178
|
+
* @param {Object} ctx 调用上下文,含 user_id
|
|
179
|
+
* @param {Object} params 调用参数,含 agent_id / session_id / content
|
|
180
|
+
* @param {Object} options 本次调用选项,优先级高于用户与智能体配置
|
|
181
|
+
* @returns {Promise<Object>} 助手消息;stream 为真时返回流对象
|
|
182
|
+
*/
|
|
183
|
+
async main(ctx = {}, params = {}, options = {}) {
|
|
184
|
+
return LLM.#call_options_storage.run(options, () => this._converse(params, ctx, options));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---------- 调用选项 ----------
|
|
188
|
+
/**
|
|
189
|
+
* 获取选项
|
|
190
|
+
*
|
|
191
|
+
* 合并优先级由低到高:实例默认配置 < 该用户对该智能体的选项 < 本次调用选项。
|
|
192
|
+
* 选项按 (user_id, agent_id) 成对存放,故同一用户对不同智能体可有不同选项;
|
|
193
|
+
* 本次调用选项取自异步上下文,故同一实例并发多用户时互不影响。
|
|
194
|
+
* @param {Number} user_id 用户ID
|
|
195
|
+
* @param {Number} agent_id 智能体ID
|
|
196
|
+
* @returns {Object} 选项对象,含 api_key / base_url / model / temperature / stream 等
|
|
197
|
+
*/
|
|
198
|
+
getOptions(user_id, agent_id) {
|
|
199
|
+
let defaults = this._pickOptions(this.config);
|
|
200
|
+
let options = this.getStore().getOptions(user_id, agent_id);
|
|
201
|
+
let call_options = LLM.#call_options_storage.getStore() || {};
|
|
202
|
+
return Object.assign({}, defaults, options, call_options);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 获取 OpenAI 客户端(私有方法,按 api_key 与 base_url 缓存)
|
|
207
|
+
* @param {Object} options 选项对象
|
|
208
|
+
* @returns {Object} OpenAI 客户端
|
|
209
|
+
*/
|
|
210
|
+
_getClient(options) {
|
|
211
|
+
if (!options.api_key) {
|
|
212
|
+
throw new Error('[LLM] 缺少 api_key,请通过实例配置、用户配置或智能体配置提供');
|
|
213
|
+
}
|
|
214
|
+
let client_key = `${options.api_key}@${options.base_url}`;
|
|
215
|
+
if (this.#client && this.#client_key === client_key) {
|
|
216
|
+
return this.#client;
|
|
217
|
+
}
|
|
218
|
+
this.#client = new OpenAI({ apiKey: options.api_key, baseURL: options.base_url });
|
|
219
|
+
this.#client_key = client_key;
|
|
220
|
+
return this.#client;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 分区装配:消息装配、对话执行
|
|
225
|
+
llm_message.install(LLM);
|
|
226
|
+
llm_execute.install(LLM);
|
|
227
|
+
|
|
228
|
+
module.exports = LLM;
|