my-ai-chat-framework 1.0.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.
@@ -0,0 +1,1381 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const axios = require("axios");
4
+ class MessageFormatter {
5
+ /**
6
+ * 将消息转换为标准格式(过滤掉自定义元数据)
7
+ */
8
+ static toStandardFormat(message) {
9
+ const { role, content } = message;
10
+ const standardMessage = { role, content };
11
+ if (message.reasoning_content) {
12
+ standardMessage.reasoning_content = message.reasoning_content;
13
+ }
14
+ if (message.tool_calls) {
15
+ standardMessage.tool_calls = message.tool_calls;
16
+ }
17
+ if (message.tool_call_id) {
18
+ standardMessage.tool_call_id = message.tool_call_id;
19
+ }
20
+ return standardMessage;
21
+ }
22
+ /**
23
+ * 批量转换消息为标准格式
24
+ */
25
+ static batchToStandardFormat(messages) {
26
+ return messages.map((msg) => this.toStandardFormat(msg));
27
+ }
28
+ /**
29
+ * 从Messages实例获取格式化后的消息数组
30
+ */
31
+ static formatMessages(messagesInstance, baseRounds, cycleRounds) {
32
+ const systems = messagesInstance.getEnabledSystemPrompts();
33
+ const hintSystem = {
34
+ role: "system",
35
+ content: `你的名字||标题是:${messagesInstance.getName() || "未知"}`
36
+ };
37
+ systems.unshift(hintSystem);
38
+ const recentMessages = messagesInstance.getRecentMessages(baseRounds, cycleRounds);
39
+ return [...systems, ...recentMessages];
40
+ }
41
+ /**
42
+ * 构造工具参数
43
+ */
44
+ static constructParameters(array) {
45
+ let paramsArray = [];
46
+ if (Array.isArray(array)) {
47
+ paramsArray = array;
48
+ } else if (typeof array === "object" && array !== null) {
49
+ paramsArray = [array];
50
+ } else {
51
+ throw new Error("[系统提示异常] 检测到无效的参数格式");
52
+ }
53
+ const parameters = {};
54
+ for (let i = 0; i < paramsArray.length; i++) {
55
+ const param = paramsArray[i];
56
+ if (!param?.name?.trim()) {
57
+ throw new Error(`[系统提示异常] 检测到空参数名称 位置: 第 ${i + 1} 个参数`);
58
+ }
59
+ if (!param?.type?.trim()) {
60
+ throw new Error(`[系统提示异常] 检测到空参数类型 位置: 参数 "${param.name}"`);
61
+ }
62
+ if (!param?.description?.trim()) {
63
+ throw new Error(`[系统提示异常] 检测到空参数描述 位置: 参数 "${param.name}"`);
64
+ }
65
+ parameters[param.name] = {
66
+ type: param.type,
67
+ description: param.description
68
+ };
69
+ }
70
+ return {
71
+ type: "object",
72
+ properties: parameters,
73
+ required: Object.keys(parameters)
74
+ };
75
+ }
76
+ /**
77
+ * 构造工具定义
78
+ */
79
+ static constructTool({ name, description, parameters }) {
80
+ if (!name?.trim()) {
81
+ throw new Error("[系统提示异常] 检测到空工具名称");
82
+ }
83
+ if (!description?.trim()) {
84
+ throw new Error("[系统提示异常] 检测到空工具描述");
85
+ }
86
+ let processedParameters;
87
+ try {
88
+ processedParameters = this.constructParameters(parameters);
89
+ } catch (error) {
90
+ throw new Error(`[系统提示异常] 工具参数验证失败 工具名称: ${name} 错误详情: ${error.message}`);
91
+ }
92
+ return {
93
+ type: "function",
94
+ function: {
95
+ name,
96
+ description,
97
+ parameters: processedParameters
98
+ }
99
+ };
100
+ }
101
+ }
102
+ class Messages {
103
+ constructor() {
104
+ this.messages = [];
105
+ this.systemPrompts = [];
106
+ this.tools = [];
107
+ this.metadata = {
108
+ name: "",
109
+ createdAt: /* @__PURE__ */ new Date(),
110
+ lastModified: /* @__PURE__ */ new Date()
111
+ };
112
+ }
113
+ // ========== 核心消息方法 ==========
114
+ /**
115
+ * 添加消息(通用方法)
116
+ * @param {string} role - 角色:user/assistant/system/tool
117
+ * @param {string} content - 消息内容
118
+ * @param {object} metadata - 额外元数据
119
+ * @returns {number} 新消息的索引
120
+ */
121
+ addMessage(role, content, metadata = {}) {
122
+ const validRoles = ["user", "assistant", "system", "tool"];
123
+ if (!validRoles.includes(role)) {
124
+ throw new Error(`无效的角色: ${role},有效值: ${validRoles.join(", ")}`);
125
+ }
126
+ if (role === "tool") {
127
+ if (!metadata.tool_call_id) {
128
+ throw new Error("tool消息必须包含tool_call_id");
129
+ }
130
+ } else {
131
+ if (typeof content !== "string") {
132
+ throw new Error("消息内容必须是字符串");
133
+ }
134
+ if (content === void 0 || content === null) {
135
+ throw new Error("消息内容不能为undefined或null");
136
+ }
137
+ }
138
+ const message = {
139
+ role,
140
+ content: content ? content.trim() : "",
141
+ // 允许空字符串
142
+ timestamp: /* @__PURE__ */ new Date()
143
+ };
144
+ if (metadata && typeof metadata === "object") {
145
+ for (const [key, value] of Object.entries(metadata)) {
146
+ if (value !== void 0 && value !== null) {
147
+ message[key] = value;
148
+ }
149
+ }
150
+ }
151
+ return this.messages.push(message) - 1;
152
+ }
153
+ /**
154
+ * 添加用户消息(便捷方法)
155
+ */
156
+ addUserMessage(content, metadata = {}) {
157
+ return this.addMessage("user", content, metadata);
158
+ }
159
+ /**
160
+ * 添加助手消息(便捷方法)
161
+ */
162
+ addAssistantMessage(content, metadata = {}) {
163
+ return this.addMessage("assistant", content, metadata);
164
+ }
165
+ /**
166
+ * 添加系统消息(便捷方法)
167
+ */
168
+ addSystemMessage(content, metadata = {}) {
169
+ return this.addMessage("system", content, metadata);
170
+ }
171
+ /**
172
+ * 添加工具消息(便捷方法)
173
+ */
174
+ addToolMessage(content, toolCallId, metadata = {}) {
175
+ if (!toolCallId || typeof toolCallId !== "string") {
176
+ throw new Error("tool_call_id不能为空");
177
+ }
178
+ return this.addMessage("tool", content, {
179
+ tool_call_id: toolCallId,
180
+ ...metadata
181
+ });
182
+ }
183
+ /**
184
+ * 批量添加消息
185
+ */
186
+ addMessages(messagesArray) {
187
+ if (!Array.isArray(messagesArray)) {
188
+ throw new Error("参数必须是数组");
189
+ }
190
+ const indices = [];
191
+ for (const msg of messagesArray) {
192
+ if (!msg.role || !msg.content) {
193
+ throw new Error("消息必须包含role和content属性");
194
+ }
195
+ const { role, content, ...metadata } = msg;
196
+ const index2 = this.addMessage(role, content, metadata);
197
+ indices.push(index2);
198
+ }
199
+ return indices;
200
+ }
201
+ // ========== 消息查询 ==========
202
+ /**
203
+ * 获取所有消息
204
+ */
205
+ getMessages() {
206
+ return [...this.messages];
207
+ }
208
+ /**
209
+ * 按角色获取消息
210
+ */
211
+ getMessagesByRole(role) {
212
+ const validRoles = ["user", "assistant", "system", "tool"];
213
+ if (!validRoles.includes(role)) {
214
+ throw new Error(`无效的角色: ${role}`);
215
+ }
216
+ return this.messages.filter((msg) => msg.role === role);
217
+ }
218
+ /**
219
+ * 获取最后一条消息
220
+ */
221
+ getLastMessage() {
222
+ return this.messages.length > 0 ? { ...this.messages[this.messages.length - 1] } : null;
223
+ }
224
+ /**
225
+ * 获取最后一条用户消息
226
+ */
227
+ getLastUserMessage() {
228
+ for (let i = this.messages.length - 1; i >= 0; i--) {
229
+ if (this.messages[i].role === "user") {
230
+ return { ...this.messages[i] };
231
+ }
232
+ }
233
+ return null;
234
+ }
235
+ /**
236
+ * 获取最后一条助手消息
237
+ */
238
+ getLastAssistantMessage() {
239
+ for (let i = this.messages.length - 1; i >= 0; i--) {
240
+ if (this.messages[i].role === "assistant") {
241
+ return { ...this.messages[i] };
242
+ }
243
+ }
244
+ return null;
245
+ }
246
+ /**
247
+ * 获取消息数量
248
+ */
249
+ getMessageCount() {
250
+ return this.messages.length;
251
+ }
252
+ // ========== 消息修改 ==========
253
+ /**
254
+ * 更新消息内容
255
+ */
256
+ updateMessage(index2, content) {
257
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
258
+ throw new Error(`无效的消息索引: ${index2}`);
259
+ }
260
+ if (typeof content !== "string" || !content.trim()) {
261
+ throw new Error("消息内容不能为空");
262
+ }
263
+ this.messages[index2].content = content.trim();
264
+ this.messages[index2].lastModified = /* @__PURE__ */ new Date();
265
+ return this;
266
+ }
267
+ /**
268
+ * 更新最后一条消息
269
+ */
270
+ updateLastMessage(content) {
271
+ if (this.messages.length === 0) {
272
+ throw new Error("没有消息可以修改");
273
+ }
274
+ return this.updateMessage(this.messages.length - 1, content);
275
+ }
276
+ /**
277
+ * 设置消息字段
278
+ */
279
+ setMessageField(index2, field, value) {
280
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
281
+ throw new Error(`无效的消息索引: ${index2}`);
282
+ }
283
+ this.messages[index2][field] = value;
284
+ this.messages[index2].lastModified = /* @__PURE__ */ new Date();
285
+ return this;
286
+ }
287
+ // ========== 消息删除 ==========
288
+ /**
289
+ * 删除消息
290
+ */
291
+ removeMessage(index2) {
292
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
293
+ throw new Error(`无效的消息索引: ${index2}`);
294
+ }
295
+ return this.messages.splice(index2, 1)[0];
296
+ }
297
+ /**
298
+ * 删除最后一条消息
299
+ */
300
+ removeLastMessage() {
301
+ if (this.messages.length === 0) {
302
+ throw new Error("没有消息可以删除");
303
+ }
304
+ return this.removeMessage(this.messages.length - 1);
305
+ }
306
+ /**
307
+ * 撤回到上一条助手消息
308
+ */
309
+ undoToAssistant() {
310
+ if (this.messages.length === 0) {
311
+ return [];
312
+ }
313
+ let lastAssistantIndex = -1;
314
+ for (let i = this.messages.length - 1; i >= 0; i--) {
315
+ if (this.messages[i].role === "assistant") {
316
+ lastAssistantIndex = i;
317
+ break;
318
+ }
319
+ }
320
+ if (lastAssistantIndex >= 0) {
321
+ return this.messages.splice(lastAssistantIndex + 1);
322
+ } else {
323
+ const removed = [...this.messages];
324
+ this.messages = [];
325
+ return removed;
326
+ }
327
+ }
328
+ /**
329
+ * 是否可以撤回
330
+ */
331
+ canUndo() {
332
+ return this.messages.some((msg) => msg.role === "assistant");
333
+ }
334
+ /**
335
+ * 清空所有消息
336
+ */
337
+ clearMessages() {
338
+ const removed = [...this.messages];
339
+ this.messages = [];
340
+ this.metadata.lastModified = /* @__PURE__ */ new Date();
341
+ return removed;
342
+ }
343
+ // ========== 系统提示管理 ==========
344
+ /**
345
+ * 添加系统提示
346
+ */
347
+ addSystemPrompt(content, enabled = true) {
348
+ if (typeof content !== "string" || !content.trim()) {
349
+ throw new Error("系统提示内容不能为空");
350
+ }
351
+ const prompt = {
352
+ role: "system",
353
+ content: content.trim(),
354
+ enabled: Boolean(enabled),
355
+ createdAt: /* @__PURE__ */ new Date()
356
+ };
357
+ return this.systemPrompts.push(prompt) - 1;
358
+ }
359
+ /**
360
+ * 获取启用的系统提示
361
+ */
362
+ getEnabledSystemPrompts() {
363
+ return this.systemPrompts.filter((prompt) => prompt.enabled).map((prompt) => ({ role: prompt.role, content: prompt.content }));
364
+ }
365
+ /**
366
+ * 切换系统提示状态
367
+ */
368
+ toggleSystemPrompt(index2) {
369
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
370
+ throw new Error(`无效的系统提示索引: ${index2}`);
371
+ }
372
+ this.systemPrompts[index2].enabled = !this.systemPrompts[index2].enabled;
373
+ return this;
374
+ }
375
+ /**
376
+ * 更新系统提示内容
377
+ */
378
+ updateSystemPrompt(index2, content) {
379
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
380
+ throw new Error(`无效的系统提示索引: ${index2}`);
381
+ }
382
+ if (typeof content !== "string" || !content.trim()) {
383
+ throw new Error("系统提示内容不能为空");
384
+ }
385
+ this.systemPrompts[index2].content = content.trim();
386
+ this.systemPrompts[index2].lastModified = /* @__PURE__ */ new Date();
387
+ return this;
388
+ }
389
+ /**
390
+ * 删除系统提示
391
+ */
392
+ removeSystemPrompt(index2) {
393
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
394
+ throw new Error(`无效的系统提示索引: ${index2}`);
395
+ }
396
+ return this.systemPrompts.splice(index2, 1)[0];
397
+ }
398
+ // ========== 工具管理 ==========
399
+ /**
400
+ * 添加工具
401
+ */
402
+ addTool(toolDefinition) {
403
+ if (typeof toolDefinition === "object" && toolDefinition !== null) {
404
+ if (!toolDefinition.type || toolDefinition.type !== "function") {
405
+ throw new Error(`无效的工具类型,期望: 'function',实际: '${toolDefinition.type || "undefined"}'`);
406
+ }
407
+ if (!toolDefinition.function?.name?.trim()) {
408
+ throw new Error("工具名称不能为空");
409
+ }
410
+ return this.tools.push(toolDefinition) - 1;
411
+ }
412
+ if (toolDefinition.name && toolDefinition.description && toolDefinition.parameters) {
413
+ const constructedTool = MessageFormatter.constructTool(toolDefinition);
414
+ return this.tools.push(constructedTool) - 1;
415
+ }
416
+ throw new Error("无效的工具格式");
417
+ }
418
+ /**
419
+ * 从定义添加工具
420
+ */
421
+ addToolFromDefinition(name, description, parameters) {
422
+ const tool = MessageFormatter.constructTool({ name, description, parameters });
423
+ return this.tools.push(tool) - 1;
424
+ }
425
+ /**
426
+ * 获取所有工具
427
+ */
428
+ getTools() {
429
+ return [...this.tools];
430
+ }
431
+ /**
432
+ * 删除工具
433
+ */
434
+ removeTool(index2) {
435
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.tools.length) {
436
+ throw new Error(`无效的工具索引: ${index2}`);
437
+ }
438
+ return this.tools.splice(index2, 1)[0];
439
+ }
440
+ /**
441
+ * 清空所有工具
442
+ */
443
+ clearTools() {
444
+ const removed = [...this.tools];
445
+ this.tools = [];
446
+ return removed;
447
+ }
448
+ // ========== 元数据管理 ==========
449
+ setName(name) {
450
+ if (typeof name !== "string" || !name.trim()) {
451
+ throw new Error("名称不能为空");
452
+ }
453
+ this.metadata.name = name.trim();
454
+ this.metadata.lastModified = /* @__PURE__ */ new Date();
455
+ return this;
456
+ }
457
+ getName() {
458
+ return this.metadata.name;
459
+ }
460
+ // ========== 兼容性方法 ==========
461
+ /**
462
+ * 获取最近的消息(兼容旧方法)
463
+ */
464
+ getRecentMessages(baseRounds, cycleRounds) {
465
+ const messages = this.messages.map((item) => {
466
+ return MessageFormatter.toStandardFormat(item);
467
+ });
468
+ const msgTotal = messages.length;
469
+ const totalRounds = msgTotal / 2;
470
+ if (!baseRounds || isNaN(baseRounds) || baseRounds <= 0) {
471
+ return messages;
472
+ }
473
+ const maxCycleRoundMultiple = cycleRounds > 0 ? Math.floor(totalRounds / cycleRounds) * cycleRounds : 0;
474
+ const actualRounds = baseRounds + (totalRounds - maxCycleRoundMultiple);
475
+ const actualMsgCount = actualRounds * 2;
476
+ const n = Math.max(msgTotal - actualMsgCount, 0);
477
+ return messages.slice(n);
478
+ }
479
+ /**
480
+ * 获取所有格式化消息(兼容旧方法)
481
+ */
482
+ getMessagesFormatted(baseRounds, cycleRounds) {
483
+ const systems = this.getEnabledSystemPrompts();
484
+ const hintSystem = {
485
+ role: "system",
486
+ content: `你的名字||标题是:${this.metadata.name || "未知"}`
487
+ };
488
+ systems.unshift(hintSystem);
489
+ const recentMessages = this.getRecentMessages(baseRounds, cycleRounds);
490
+ return [...systems, ...recentMessages];
491
+ }
492
+ // ========== 导入导出 ==========
493
+ export() {
494
+ return {
495
+ __format_version: 2,
496
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
497
+ metadata: { ...this.metadata },
498
+ payload: {
499
+ messages: JSON.parse(JSON.stringify(this.messages)),
500
+ systemPrompts: JSON.parse(JSON.stringify(this.systemPrompts)),
501
+ tools: JSON.parse(JSON.stringify(this.tools))
502
+ }
503
+ };
504
+ }
505
+ import(data) {
506
+ const obj = typeof data === "string" ? JSON.parse(data) : data;
507
+ const parsed = Messages.parseCompatible(obj);
508
+ this.messages = parsed.messages || [];
509
+ this.systemPrompts = parsed.systemPrompts || [];
510
+ this.tools = parsed.tools || [];
511
+ this.metadata = parsed.metadata || {
512
+ name: "",
513
+ createdAt: /* @__PURE__ */ new Date(),
514
+ lastModified: /* @__PURE__ */ new Date()
515
+ };
516
+ this.metadata.lastModified = /* @__PURE__ */ new Date();
517
+ return this;
518
+ }
519
+ static parseCompatible(obj) {
520
+ if (obj?.__format_version === 2 && obj.payload) {
521
+ return {
522
+ messages: obj.payload.messages || [],
523
+ systemPrompts: obj.payload.systemPrompts || [],
524
+ tools: obj.payload.tools || [],
525
+ metadata: obj.metadata || {
526
+ name: "",
527
+ createdAt: /* @__PURE__ */ new Date(),
528
+ lastModified: /* @__PURE__ */ new Date()
529
+ }
530
+ };
531
+ }
532
+ if (obj?.__format_version === 1 && obj.payload) {
533
+ return {
534
+ messages: obj.payload.messages || [],
535
+ systemPrompts: obj.payload.systems || [],
536
+ tools: obj.payload.tools || [],
537
+ metadata: {
538
+ name: obj.payload.hintData?.name || "",
539
+ createdAt: /* @__PURE__ */ new Date(),
540
+ lastModified: /* @__PURE__ */ new Date()
541
+ }
542
+ };
543
+ }
544
+ if (obj?.messages && Array.isArray(obj.messages)) {
545
+ return {
546
+ messages: obj.messages || [],
547
+ systemPrompts: obj.systems || [],
548
+ tools: obj.tools || [],
549
+ metadata: {
550
+ name: obj.hintData?.name || "",
551
+ createdAt: /* @__PURE__ */ new Date(),
552
+ lastModified: /* @__PURE__ */ new Date()
553
+ }
554
+ };
555
+ }
556
+ throw new Error("无法识别的聊天数据格式");
557
+ }
558
+ }
559
+ class EventEmitter {
560
+ constructor() {
561
+ this.events = {};
562
+ }
563
+ /**
564
+ * 监听事件
565
+ * @param {string} eventName - 要注册的事件名称
566
+ * @param {Function} callback - 事件触发时执行的回调函数
567
+ */
568
+ //实现一个监听事件的方法
569
+ on(eventName, callback) {
570
+ if (!this.events[eventName]) {
571
+ this.events[eventName] = [];
572
+ }
573
+ this.events[eventName].push(callback);
574
+ return () => this.off(eventName, callback);
575
+ }
576
+ /**
577
+ * 触发事件
578
+ * @param {string} eventName --要触发的事件名称
579
+ * @param {any} data --传递给回调函数的数据
580
+ */
581
+ emit(eventName, data) {
582
+ const callbacks = this.events[eventName];
583
+ if (!callbacks) return;
584
+ const callbakesCopy = callbacks.slice();
585
+ for (let i = 0; i < callbakesCopy.length; i++) {
586
+ try {
587
+ callbakesCopy[i](data);
588
+ } catch (error) {
589
+ console.error(`事件 ${eventName} 的回调函数执行出错:`, error);
590
+ }
591
+ }
592
+ }
593
+ /**
594
+ * 取消监听事件
595
+ * @param {string} eventName --要取消的事件名称
596
+ * @param {Function} callback --要移除的回调函数
597
+ */
598
+ off(eventName, callback) {
599
+ const callbacks = this.events[eventName];
600
+ if (!callbacks) return;
601
+ this.events[eventName] = callbacks.filter((item) => item !== callback);
602
+ if (this.events[eventName].length === 0) {
603
+ delete this.events[eventName];
604
+ }
605
+ }
606
+ /**
607
+ * 只监听一次事件(触发后自动取消)
608
+ * @param {string} eventName - 事件名称
609
+ * @param {Function} callback - 回调函数
610
+ */
611
+ once(evenName, callback) {
612
+ const onceCallback = (data) => {
613
+ this.off(evenName, onceCallback);
614
+ callback(data);
615
+ };
616
+ this.on(evenName, onceCallback);
617
+ return () => this.off(evenName, onceCallback);
618
+ }
619
+ /**
620
+ * 移除某个事件的所有监听器
621
+ * @param {string} eventName - 事件名称
622
+ */
623
+ removeAllListeners(eventName) {
624
+ if (eventName) {
625
+ delete this.events[eventName];
626
+ } else {
627
+ this.events = {};
628
+ }
629
+ }
630
+ /**
631
+ * 获取某个事件的所有监听器数量
632
+ * @param {string} eventName - 事件名称
633
+ * @returns {number} 监听器数量
634
+ */
635
+ listenerCount(eventName) {
636
+ const callbacks = this.events[eventName];
637
+ return callbacks ? callbacks.length : 0;
638
+ }
639
+ }
640
+ class ToolManager extends EventEmitter {
641
+ constructor() {
642
+ super();
643
+ this.tools = /* @__PURE__ */ new Map();
644
+ }
645
+ /**
646
+ * 注册工具
647
+ * @param {string} name - 工具名称
648
+ * @param {object} toolDefinition - 工具定义(包含描述和参数信息)
649
+ * @param {Function} executor - 工具执行函数,接受参数对象并返回结果
650
+ */
651
+ registerTool(name, toolDefinition, executor) {
652
+ if (this.tools.has(name)) {
653
+ throw new Error(`[系统提示异常] 工具 "${name}" 已经注册过了`);
654
+ }
655
+ this.tools.set(name, {
656
+ definition: toolDefinition,
657
+ executor
658
+ });
659
+ this.emit("tool-registered", { name, definition: toolDefinition });
660
+ return this;
661
+ }
662
+ /**
663
+ * 执行工具调用
664
+ * @param {object} toolCall - 工具调用信息,包含工具名称和参数
665
+ * @returns {Promise<any>} - 工具执行结果
666
+ */
667
+ async executeToolCall(toolCall) {
668
+ const { id, function: func } = toolCall;
669
+ const { name, arguments: argsStr } = func;
670
+ if (!this.tools.has(name)) {
671
+ throw new Error(`未找到工具: ${name}`);
672
+ }
673
+ const tool = this.tools.get(name);
674
+ try {
675
+ const args = JSON.parse(argsStr);
676
+ this.emit("tool-execute-start", { name, args });
677
+ const result = await tool.executor(args);
678
+ this.emit("tool-execute-success", { name, args, result });
679
+ return {
680
+ tool_call_id: id,
681
+ // 必须包含tool_call_id
682
+ name,
683
+ result: JSON.stringify(result),
684
+ success: true
685
+ };
686
+ } catch (error) {
687
+ this.emit("tool-execute-error", { name, error });
688
+ return {
689
+ tool_call_id: id,
690
+ name,
691
+ error: error.message,
692
+ success: false
693
+ };
694
+ }
695
+ }
696
+ /**
697
+ * 获取所有工具定义(用于发送给AI)
698
+ */
699
+ getToolDefinitions() {
700
+ const definitions = [];
701
+ for (const [name, tool] of this.tools) {
702
+ definitions.push(tool.definition);
703
+ }
704
+ return definitions;
705
+ }
706
+ /**
707
+ * 检查是否有工具
708
+ */
709
+ hasTools() {
710
+ return this.tools.size > 0;
711
+ }
712
+ /**
713
+ * 批量执行工具调用
714
+ * @param {Array} toolCalls - 工具调用数组
715
+ * @returns {Promise<Array>} - 所有工具的执行结果
716
+ */
717
+ async executeToolCalls(toolCalls) {
718
+ if (!Array.isArray(toolCalls)) {
719
+ throw new Error("toolCalls必须是数组");
720
+ }
721
+ const results = [];
722
+ const promises = toolCalls.map(async (toolCall) => {
723
+ try {
724
+ const result = await this.executeToolCall(toolCall);
725
+ return result;
726
+ } catch (error) {
727
+ return {
728
+ tool_call_id: toolCall.id,
729
+ name: toolCall.function.name,
730
+ error: error.message,
731
+ success: false
732
+ };
733
+ }
734
+ });
735
+ const settledResults = await Promise.allSettled(promises);
736
+ for (const settled of settledResults) {
737
+ if (settled.status === "fulfilled") {
738
+ results.push(settled.value);
739
+ } else {
740
+ results.push({
741
+ error: settled.reason.message,
742
+ success: false
743
+ });
744
+ }
745
+ }
746
+ return results;
747
+ }
748
+ /**
749
+ * 串行执行工具调用(如果需要顺序执行)
750
+ */
751
+ async executeToolCallsSequentially(toolCalls) {
752
+ const results = [];
753
+ for (const toolCall of toolCalls) {
754
+ try {
755
+ const result = await this.executeToolCall(toolCall);
756
+ results.push(result);
757
+ } catch (error) {
758
+ results.push({
759
+ tool_call_id: toolCall.id,
760
+ name: toolCall.function.name,
761
+ error: error.message,
762
+ success: false
763
+ });
764
+ }
765
+ }
766
+ return results;
767
+ }
768
+ }
769
+ class RequestBuilder {
770
+ constructor(model, messagesInstance, config = {}) {
771
+ this.model = model;
772
+ this.messages = messagesInstance;
773
+ this.config = {
774
+ // temperature: 0.7,
775
+ // max_tokens: 2000,
776
+ // stream: false, // 默认关闭流式传输
777
+ ...config
778
+ };
779
+ this.toolManager = null;
780
+ }
781
+ /**
782
+ * 设置ToolManager引用
783
+ */
784
+ setToolManager(toolManager) {
785
+ this.toolManager = toolManager;
786
+ return this;
787
+ }
788
+ /**
789
+ * 构建OpenAI兼容格式的请求体
790
+ */
791
+ buildOpenAIFormat(baseRounds, cycleRounds) {
792
+ const formattedMessages = MessageFormatter.formatMessages(
793
+ this.messages,
794
+ baseRounds,
795
+ cycleRounds
796
+ );
797
+ const request = {
798
+ model: this.model,
799
+ messages: formattedMessages,
800
+ ...this.config
801
+ };
802
+ let tools = [];
803
+ if (this.toolManager && this.toolManager.hasTools()) {
804
+ tools = this.toolManager.getToolDefinitions();
805
+ } else {
806
+ tools = this.messages.getTools();
807
+ }
808
+ if (tools && tools.length > 0) {
809
+ request.tools = tools;
810
+ request.tool_choice = "auto";
811
+ }
812
+ return request;
813
+ }
814
+ /**
815
+ * 构建请求体并返回JSON字符串
816
+ */
817
+ toJSON(baseRounds, cycleRounds) {
818
+ const request = this.buildOpenAIFormat(baseRounds, cycleRounds);
819
+ return JSON.stringify(request);
820
+ }
821
+ /**
822
+ * 构建请求体并返回对象
823
+ */
824
+ toObject(baseRounds, cycleRounds) {
825
+ return this.buildOpenAIFormat(baseRounds, cycleRounds);
826
+ }
827
+ /**
828
+ * 设置配置项
829
+ */
830
+ setConfig(key, value) {
831
+ this.config[key] = value;
832
+ return this;
833
+ }
834
+ /**
835
+ * 批量设置配置项
836
+ */
837
+ setConfigs(configs) {
838
+ Object.assign(this.config, configs);
839
+ return this;
840
+ }
841
+ }
842
+ class ApiClient extends EventEmitter {
843
+ constructor(apiKey, apiUrl = "https://api.deepseek.com/v1/chat/completions") {
844
+ super();
845
+ this.apiKey = apiKey;
846
+ this.url = apiUrl;
847
+ this.isGenerating = false;
848
+ this.cancelTokenSource = null;
849
+ this.axiosInstance = axios.create({
850
+ baseURL: apiUrl,
851
+ headers: {
852
+ "Authorization": `Bearer ${apiKey}`,
853
+ "Content-Type": "application/json"
854
+ },
855
+ timeout: 3e4
856
+ // 30秒超时
857
+ });
858
+ }
859
+ setApiKey(apiKey) {
860
+ if (!apiKey || typeof apiKey !== "string") {
861
+ throw new Error("无效的API Key");
862
+ }
863
+ this.apiKey = apiKey;
864
+ this.axiosInstance.defaults.headers["Authorization"] = `Bearer ${apiKey}`;
865
+ }
866
+ setApiUrl(apiUrl) {
867
+ if (!apiUrl || typeof apiUrl !== "string") {
868
+ throw new Error("无效的API URL");
869
+ }
870
+ this.url = apiUrl;
871
+ this.axiosInstance.defaults.baseURL = apiUrl;
872
+ }
873
+ async send(body) {
874
+ this.isGenerating = true;
875
+ this.cancelTokenSource = axios.CancelToken.source();
876
+ try {
877
+ this.emit("request-start", { body });
878
+ const requestBody = this._buildRequestBody(body);
879
+ const response = await this.axiosInstance.post("", requestBody, {
880
+ cancelToken: this.cancelTokenSource.token
881
+ });
882
+ this.emit("request-success", { response: response.data });
883
+ return response.data;
884
+ } catch (error) {
885
+ if (axios.isCancel(error)) {
886
+ const cancelError = new Error("请求被中断");
887
+ cancelError.name = "CancelError";
888
+ this.emit("request-cancel", { error: cancelError });
889
+ throw cancelError;
890
+ }
891
+ this.emit("request-error", { error });
892
+ throw this._handleAxiosError(error);
893
+ } finally {
894
+ this.isGenerating = false;
895
+ this.cancelTokenSource = null;
896
+ }
897
+ }
898
+ async strSend(body, onProgress = () => {
899
+ }, onDone = () => {
900
+ }) {
901
+ this.isGenerating = true;
902
+ this.cancelTokenSource = axios.CancelToken.source();
903
+ try {
904
+ this.emit("stream-start", { body });
905
+ const requestBody = this._buildRequestBody(body);
906
+ const response = await fetch(this.url, {
907
+ method: "POST",
908
+ headers: {
909
+ "Content-Type": "application/json",
910
+ "Authorization": `Bearer ${this.apiKey}`,
911
+ "Accept": "text/event-stream"
912
+ },
913
+ body: requestBody,
914
+ signal: this.cancelTokenSource.token ? new AbortController().signal : void 0
915
+ });
916
+ if (!response.ok) {
917
+ throw new Error(`HTTP错误: ${response.status}`);
918
+ }
919
+ const reader = response.body.getReader();
920
+ const decoder = new TextDecoder();
921
+ let buffer = "";
922
+ const message = {
923
+ content: "",
924
+ reasoning_content: "",
925
+ tool_calls: []
926
+ // 新增:收集工具调用
927
+ };
928
+ while (true) {
929
+ const { done, value } = await reader.read();
930
+ if (done) break;
931
+ buffer += decoder.decode(value, { stream: true });
932
+ let lines = buffer.split(/(\r?\n){2,}/);
933
+ buffer = lines.pop() || "";
934
+ for (let rawChunk of lines) {
935
+ const cleanChunk = rawChunk.trim().replace(/^data: /, "");
936
+ if (!cleanChunk) continue;
937
+ if (cleanChunk === "[DONE]") {
938
+ this.emit("stream-done", { message });
939
+ onDone({ ...message });
940
+ return;
941
+ }
942
+ try {
943
+ const obj = JSON.parse(cleanChunk);
944
+ console.log("🔍 收到流式chunk:", obj);
945
+ if (obj.choices?.[0]?.delta?.content) {
946
+ message.content += obj.choices[0].delta.content;
947
+ }
948
+ if (obj.choices?.[0]?.delta?.reasoning_content) {
949
+ message.reasoning_content += obj.choices[0].delta.reasoning_content;
950
+ }
951
+ if (obj.choices?.[0]?.delta?.tool_calls) {
952
+ const deltaToolCalls = obj.choices[0].delta.tool_calls;
953
+ deltaToolCalls.forEach((toolCall) => {
954
+ const index2 = toolCall.index || 0;
955
+ if (!message.tool_calls) message.tool_calls = [];
956
+ if (!message.tool_calls[index2]) {
957
+ message.tool_calls[index2] = {
958
+ id: "",
959
+ type: "function",
960
+ function: { name: "", arguments: "" }
961
+ };
962
+ }
963
+ if (toolCall.id) message.tool_calls[index2].id = toolCall.id;
964
+ if (toolCall.type) message.tool_calls[index2].type = toolCall.type;
965
+ if (toolCall.function?.name) {
966
+ message.tool_calls[index2].function.name += toolCall.function.name;
967
+ }
968
+ if (toolCall.function?.arguments) {
969
+ message.tool_calls[index2].function.arguments += toolCall.function.arguments;
970
+ }
971
+ });
972
+ }
973
+ this.emit("stream-chunk", { chunk: obj, message });
974
+ onProgress({ ...message });
975
+ } catch (e) {
976
+ console.error("🔍 解析chunk错误:", e, "原始数据:", cleanChunk);
977
+ }
978
+ }
979
+ if (!this.isGenerating) {
980
+ break;
981
+ }
982
+ }
983
+ this.emit("stream-done", { message });
984
+ onDone({ ...message });
985
+ } catch (error) {
986
+ if (error.name === "AbortError" || axios.isCancel(error)) {
987
+ const cancelError = new Error("请求被中断");
988
+ cancelError.name = "CancelError";
989
+ this.emit("stream-cancel", { error: cancelError });
990
+ throw cancelError;
991
+ }
992
+ this.emit("stream-error", { error });
993
+ throw error;
994
+ } finally {
995
+ this.isGenerating = false;
996
+ this.cancelTokenSource = null;
997
+ }
998
+ }
999
+ interrupt() {
1000
+ if (this.isGenerating && this.cancelTokenSource) {
1001
+ this.cancelTokenSource.cancel("用户中断请求");
1002
+ this.isGenerating = false;
1003
+ }
1004
+ }
1005
+ _buildRequestBody(body) {
1006
+ if (typeof body?.toJSON === "function") {
1007
+ return body.toJSON();
1008
+ } else if (typeof body === "object" && body !== null) {
1009
+ return JSON.stringify(body);
1010
+ } else if (typeof body === "string") {
1011
+ try {
1012
+ JSON.parse(body);
1013
+ return body;
1014
+ } catch {
1015
+ throw new Error("字符串不是有效的JSON格式");
1016
+ }
1017
+ } else {
1018
+ throw new Error("无效的请求体类型,应传入对象或JSON字符串");
1019
+ }
1020
+ }
1021
+ _handleAxiosError(error) {
1022
+ if (error.response) {
1023
+ const status = error.response.status;
1024
+ const data = error.response.data;
1025
+ let message = `API错误 ${status}`;
1026
+ if (data?.error?.message) {
1027
+ message += `: ${data.error.message}`;
1028
+ }
1029
+ return new Error(message);
1030
+ } else if (error.request) {
1031
+ return new Error("网络错误:无法连接到API服务器");
1032
+ } else {
1033
+ return error;
1034
+ }
1035
+ }
1036
+ static parseCompatible(obj) {
1037
+ if (obj?.__format_version === 1 && obj.payload) {
1038
+ return {
1039
+ messages: obj.payload.messages || [],
1040
+ systems: obj.payload.systems || [],
1041
+ hintData: obj.payload.hintData || {
1042
+ name: "",
1043
+ toolState: {
1044
+ currentTime: "同步失败",
1045
+ currentTime_TS: 0
1046
+ }
1047
+ },
1048
+ tools: obj.payload.tools || []
1049
+ };
1050
+ }
1051
+ if (obj?.messages && Array.isArray(obj.messages)) {
1052
+ return {
1053
+ messages: obj.messages || [],
1054
+ systems: obj.systems || [],
1055
+ hintData: obj.hintData || {
1056
+ name: "",
1057
+ toolState: {
1058
+ currentTime: "同步失败",
1059
+ currentTime_TS: 0
1060
+ }
1061
+ },
1062
+ tools: obj.tools || []
1063
+ };
1064
+ }
1065
+ throw new Error("无法识别的聊天数据格式");
1066
+ }
1067
+ }
1068
+ class ChatService extends EventEmitter {
1069
+ constructor(apiKey, model = "deepseek-chat", config = {}) {
1070
+ super();
1071
+ this.messages = new Messages();
1072
+ this.apiClient = new ApiClient(apiKey);
1073
+ this.requestBuilder = new RequestBuilder(model, this.messages, config);
1074
+ this.toolManager = new ToolManager();
1075
+ this._setupDefaultListeners();
1076
+ }
1077
+ _setupDefaultListeners() {
1078
+ this.apiClient.on("request-start", (data) => {
1079
+ this.emit("request-start", data);
1080
+ });
1081
+ this.apiClient.on("request-success", (data) => {
1082
+ this.emit("request-success", data);
1083
+ });
1084
+ this.apiClient.on("request-error", (data) => {
1085
+ this.emit("request-error", data);
1086
+ });
1087
+ this.apiClient.on("stream-chunk", (data) => {
1088
+ this.emit("stream-chunk", data);
1089
+ });
1090
+ this.toolManager.on("tool-execute-start", (data) => {
1091
+ this.emit("tool-execute-start", data);
1092
+ });
1093
+ this.toolManager.on("tool-execute-success", (data) => {
1094
+ this.emit("tool-execute-success", data);
1095
+ });
1096
+ this.toolManager.on("tool-execute-error", (data) => {
1097
+ this.emit("tool-execute-error", data);
1098
+ });
1099
+ }
1100
+ /**
1101
+ * 注册工具
1102
+ */
1103
+ registerTool(name, definition, executor) {
1104
+ this.toolManager.registerTool(name, definition, executor);
1105
+ this.messages.addTool(definition);
1106
+ return this;
1107
+ }
1108
+ /**
1109
+ * 发送消息(支持工具调用)
1110
+ */
1111
+ async send(userMessage, options = {}) {
1112
+ try {
1113
+ this.emit("sending", {
1114
+ role: "user",
1115
+ content: userMessage,
1116
+ timestamp: /* @__PURE__ */ new Date()
1117
+ });
1118
+ this.messages.addUserMessage(userMessage);
1119
+ const requestBody = this.requestBuilder.toJSON(
1120
+ options.baseRounds,
1121
+ options.cycleRounds
1122
+ );
1123
+ const response = await this.apiClient.send(requestBody);
1124
+ const aiMessage = response.choices[0].message;
1125
+ if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {
1126
+ return await this._handleToolCalls(aiMessage);
1127
+ } else {
1128
+ return await this._handleNormalResponse(aiMessage);
1129
+ }
1130
+ } catch (error) {
1131
+ this.emit("error", {
1132
+ error,
1133
+ message: userMessage,
1134
+ timestamp: /* @__PURE__ */ new Date()
1135
+ });
1136
+ throw error;
1137
+ }
1138
+ }
1139
+ /**
1140
+ * 处理工具调用(支持循环调用)
1141
+ */
1142
+ async _handleToolCalls(aiMessage, maxIterations = 5) {
1143
+ console.log("🔍 处理工具调用,aiMessage:", aiMessage);
1144
+ let iteration = 0;
1145
+ let currentMessage = aiMessage;
1146
+ while (iteration < maxIterations) {
1147
+ iteration++;
1148
+ console.log(`🔄 工具调用迭代 ${iteration}/${maxIterations}`);
1149
+ this.messages.addAssistantMessage(currentMessage.content || "", {
1150
+ tool_calls: currentMessage.tool_calls,
1151
+ reasoning_content: currentMessage.reasoning_content || ""
1152
+ // ✅ 新增:保存思考内容
1153
+ });
1154
+ this.emit("tool-call-requested", {
1155
+ tool_calls: currentMessage.tool_calls,
1156
+ reasoning_content: currentMessage.reasoning_content,
1157
+ // ✅ 新增:包含思考内容
1158
+ timestamp: /* @__PURE__ */ new Date(),
1159
+ iteration
1160
+ });
1161
+ const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
1162
+ console.log("🔍 工具执行结果:", toolResults);
1163
+ for (const result of toolResults) {
1164
+ console.log("🔍 添加工具消息,result:", result);
1165
+ this.messages.addToolMessage(
1166
+ result.result || result.error || "",
1167
+ result.tool_call_id
1168
+ );
1169
+ }
1170
+ console.log("🔍 当前所有消息:", this.messages.getMessages());
1171
+ const requestBody = this.requestBuilder.toJSON();
1172
+ console.log("🔍 第", iteration, "次请求体:", requestBody);
1173
+ const response = await this.apiClient.send(requestBody);
1174
+ currentMessage = response.choices[0].message;
1175
+ if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1176
+ console.log("✅ 工具调用完成,AI给出最终回复");
1177
+ break;
1178
+ }
1179
+ console.log("🔄 AI请求了新的工具调用,继续处理...");
1180
+ }
1181
+ this.messages.addAssistantMessage(currentMessage.content || "", {
1182
+ reasoning_content: currentMessage.reasoning_content || ""
1183
+ // ✅ 新增:保存最终思考内容
1184
+ });
1185
+ this.emit("message", {
1186
+ role: "assistant",
1187
+ content: currentMessage.content,
1188
+ reasoning_content: currentMessage.reasoning_content,
1189
+ // ✅ 新增:包含思考内容
1190
+ timestamp: /* @__PURE__ */ new Date(),
1191
+ response: { choices: [{ message: currentMessage }] },
1192
+ toolIterations: iteration
1193
+ });
1194
+ return currentMessage.content;
1195
+ }
1196
+ /**
1197
+ * 处理普通回复
1198
+ */
1199
+ async _handleNormalResponse(aiMessage) {
1200
+ this.messages.addAssistantMessage(aiMessage.content || "", {
1201
+ reasoning_content: aiMessage.reasoning_content
1202
+ });
1203
+ this.emit("message", {
1204
+ role: "assistant",
1205
+ content: aiMessage.content,
1206
+ timestamp: /* @__PURE__ */ new Date(),
1207
+ response: { choices: [{ message: aiMessage }] }
1208
+ });
1209
+ return aiMessage.content;
1210
+ }
1211
+ /**
1212
+ * 流式发送消息(支持工具调用)
1213
+ */
1214
+ async stream(userMessage, onProgress, onDone, options = {}) {
1215
+ try {
1216
+ this.emit("sending", {
1217
+ role: "user",
1218
+ content: userMessage,
1219
+ timestamp: /* @__PURE__ */ new Date()
1220
+ });
1221
+ this.messages.addUserMessage(userMessage);
1222
+ const requestBuilder = new RequestBuilder(this.requestBuilder.model, this.messages, {
1223
+ ...this.requestBuilder.config,
1224
+ stream: true
1225
+ // ✅ 必须设置为true!
1226
+ });
1227
+ const requestBody = requestBuilder.toJSON(
1228
+ options.baseRounds,
1229
+ options.cycleRounds
1230
+ );
1231
+ const response = await this.apiClient.strSend(
1232
+ requestBody,
1233
+ (chunk) => {
1234
+ this.emit("stream-progress", chunk);
1235
+ onProgress(chunk);
1236
+ },
1237
+ async (finalMessage) => {
1238
+ if (finalMessage.tool_calls && finalMessage.tool_calls.length > 0) {
1239
+ await this._handleStreamToolCalls(finalMessage, onProgress, onDone);
1240
+ } else {
1241
+ this.messages.addAssistantMessage(finalMessage.content || "", {
1242
+ reasoning_content: finalMessage.reasoning_content
1243
+ });
1244
+ this.emit("stream-done", { message: finalMessage });
1245
+ onDone(finalMessage);
1246
+ }
1247
+ }
1248
+ );
1249
+ return response;
1250
+ } catch (error) {
1251
+ this.emit("error", {
1252
+ error,
1253
+ message: userMessage,
1254
+ timestamp: /* @__PURE__ */ new Date()
1255
+ });
1256
+ throw error;
1257
+ }
1258
+ }
1259
+ /**
1260
+ * 处理流式传输中的工具调用(支持循环调用)
1261
+ */
1262
+ async _handleStreamToolCalls(aiMessage, onProgress, onDone, maxIterations = 5) {
1263
+ let iteration = 0;
1264
+ let currentMessage = aiMessage;
1265
+ while (iteration < maxIterations) {
1266
+ iteration++;
1267
+ this.messages.addAssistantMessage(currentMessage.content || "", {
1268
+ tool_calls: currentMessage.tool_calls,
1269
+ reasoning_content: currentMessage.reasoning_content || ""
1270
+ // ✅ 新增:保存思考内容
1271
+ });
1272
+ this.emit("tool-call-requested", {
1273
+ tool_calls: currentMessage.tool_calls,
1274
+ reasoning_content: currentMessage.reasoning_content,
1275
+ // ✅ 新增:包含思考内容
1276
+ timestamp: /* @__PURE__ */ new Date(),
1277
+ iteration
1278
+ });
1279
+ const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
1280
+ for (const result of toolResults) {
1281
+ this.messages.addToolMessage(result.result || result.error, result.tool_call_id);
1282
+ }
1283
+ const requestBody = this.requestBuilder.toJSON();
1284
+ await new Promise((resolve, reject) => {
1285
+ this.apiClient.strSend(
1286
+ requestBody,
1287
+ (chunk) => {
1288
+ this.emit("stream-progress", chunk);
1289
+ onProgress(chunk);
1290
+ },
1291
+ (finalMessage) => {
1292
+ currentMessage = finalMessage;
1293
+ if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1294
+ resolve();
1295
+ } else {
1296
+ resolve();
1297
+ }
1298
+ }
1299
+ ).catch(reject);
1300
+ });
1301
+ if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1302
+ break;
1303
+ }
1304
+ }
1305
+ this.messages.addAssistantMessage(currentMessage.content, {
1306
+ reasoning_content: currentMessage.reasoning_content || ""
1307
+ // ✅ 新增:保存最终思考内容
1308
+ });
1309
+ this.emit("stream-done", {
1310
+ message: currentMessage,
1311
+ reasoning_content: currentMessage.reasoning_content,
1312
+ // ✅ 新增:包含思考内容
1313
+ toolIterations: iteration
1314
+ });
1315
+ onDone(currentMessage);
1316
+ }
1317
+ /**
1318
+ * 撤回消息
1319
+ */
1320
+ undo() {
1321
+ const removed = this.messages.undoToAssistant();
1322
+ if (removed.length > 0) {
1323
+ this.emit("undo", {
1324
+ removedMessages: removed,
1325
+ timestamp: /* @__PURE__ */ new Date()
1326
+ });
1327
+ }
1328
+ return removed;
1329
+ }
1330
+ /**
1331
+ * 清空消息
1332
+ */
1333
+ clear() {
1334
+ const removed = this.messages.clearMessages();
1335
+ this.emit("clear", {
1336
+ removedMessages: removed,
1337
+ timestamp: /* @__PURE__ */ new Date()
1338
+ });
1339
+ return removed;
1340
+ }
1341
+ /**
1342
+ * 导出对话数据
1343
+ */
1344
+ export() {
1345
+ const data = this.messages.export();
1346
+ this.emit("export", {
1347
+ data,
1348
+ timestamp: /* @__PURE__ */ new Date()
1349
+ });
1350
+ return data;
1351
+ }
1352
+ /**
1353
+ * 导入对话数据
1354
+ */
1355
+ import(data) {
1356
+ this.messages.import(data);
1357
+ this.emit("import", {
1358
+ data,
1359
+ timestamp: /* @__PURE__ */ new Date()
1360
+ });
1361
+ return this;
1362
+ }
1363
+ }
1364
+ const index = {
1365
+ Messages,
1366
+ RequestBuilder,
1367
+ ApiClient,
1368
+ EventEmitter,
1369
+ MessageFormatter,
1370
+ ToolManager,
1371
+ ChatService
1372
+ };
1373
+ exports.ApiClient = ApiClient;
1374
+ exports.ChatService = ChatService;
1375
+ exports.EventEmitter = EventEmitter;
1376
+ exports.MessageFormatter = MessageFormatter;
1377
+ exports.Messages = Messages;
1378
+ exports.RequestBuilder = RequestBuilder;
1379
+ exports.ToolManager = ToolManager;
1380
+ exports.default = index;
1381
+ //# sourceMappingURL=my-ai-chat-framework.node.cjs.js.map