my-ai-chat-framework 1.0.2 → 1.1.0

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 CHANGED
@@ -43,6 +43,63 @@ my-ai-chat-framework/
43
43
  └── package.json # 项目配置 / Project configuration
44
44
  ```
45
45
 
46
+ ## 🎯 统一数据格式 / Unified Data Format
47
+
48
+ 从v1.1.0开始,框架使用统一的数据格式在所有组件之间传递消息,简化了使用体验。
49
+
50
+ ### 核心消息格式
51
+
52
+ 所有消息都遵循以下格式:
53
+
54
+ ```javascript
55
+ {
56
+ // 必需字段 / Required fields
57
+ role: 'user' | 'assistant' | 'system' | 'tool',
58
+ content: string, // 允许空字符串 / Empty string allowed
59
+
60
+ // 标准扩展字段 / Standard extension fields
61
+ timestamp: string, // ISO格式时间戳,自动生成 / ISO timestamp, auto-generated
62
+ metadata?: object, // 自定义元数据 / Custom metadata
63
+
64
+ // 角色特定字段 / Role-specific fields
65
+ reasoning_content?: string, // 助手消息的推理内容 / Reasoning content for assistant messages
66
+ tool_calls?: array, // 助手消息的工具调用 / Tool calls for assistant messages
67
+ tool_call_id?: string, // 工具消息的调用ID / Call ID for tool messages
68
+ name?: string, // 工具消息的工具名称 / Tool name for tool messages
69
+
70
+ // 自定义字段(任意)/ Custom fields (any)
71
+ [key: string]: any // 所有自定义字段都会被保留 / All custom fields are preserved
72
+ }
73
+ ```
74
+
75
+ ### 关键特性
76
+
77
+ 1. **字段保留** / **Field Preservation**: 所有自定义字段都被保留,不再丢失
78
+ 2. **空内容处理** / **Empty Content Handling**: 允许空字符串内容,仅在API请求时过滤
79
+ 3. **工具消息特殊处理** / **Tool Message Special Handling**: tool消息可以没有content
80
+ 4. **事件数据统一** / **Event Data Unification**: 所有事件使用相同的数据结构
81
+ 5. **向后兼容** / **Backward Compatibility**: 现有API保持不变
82
+
83
+ ### 使用示例
84
+
85
+ ```javascript
86
+ // 添加带自定义字段的消息 / Add message with custom fields
87
+ const msgIndex = chatService.messages.addUserMessage('Hello', {
88
+ metadata: { userId: '123', priority: 'high' },
89
+ customData: { session: 'test' }
90
+ });
91
+
92
+ // 获取完整消息 / Get complete message
93
+ const fullMessage = chatService.messages.getMessages()[msgIndex];
94
+ // 包含所有字段 / Contains all fields
95
+
96
+ // 监听事件获取统一格式数据 / Listen to events for unified data format
97
+ chatService.on('response', (data) => {
98
+ console.log('收到响应 / Response received:', data.message);
99
+ // data.message包含所有字段 / data.message contains all fields
100
+ });
101
+ ```
102
+
46
103
  ## 📦 安装和使用 / Installation and Usage
47
104
 
48
105
  ### 浏览器中使用 / For Browser Usage
@@ -198,7 +255,7 @@ chat.undo();
198
255
  // 导出对话 / Export conversation
199
256
  const exportData = chat.export();
200
257
 
201
- ## 📤 npm发布 / npm Publishing
258
+ ## 🤤 npm发布 / npm Publishing
202
259
 
203
260
  ### 发布准备
204
261
  1. 确保已登录npm账号:
@@ -302,4 +359,134 @@ This project is licensed under the MIT License. See the LICENSE file for more de
302
359
  ---
303
360
 
304
361
  *此文档由AI辅助生成,内容可能不完整或存在错误,请以实际代码为准。*
305
- *This document is AI-assisted and may be incomplete or contain errors. Please refer to the actual code for accurate information.*
362
+ *This document is AI-assisted and may be incomplete or contain errors. Please refer to the actual code for accurate information.*
363
+
364
+ ### 配置系统章节
365
+ 需要在两个 README 中都添加:
366
+
367
+ ```markdown
368
+ ## 🔧 配置系统 / Configuration System
369
+
370
+ ### 配置结构
371
+ ```javascript
372
+ {
373
+ api: {
374
+ key: '', // API密钥
375
+ url: 'https://api.deepseek.com/v1/chat/completions',
376
+ timeout: 30000
377
+ },
378
+ model: {
379
+ name: 'deepseek-chat',
380
+ temperature: 0.7,
381
+ maxTokens: 2000,
382
+ stream: false,
383
+ reasoningEffort: 'medium'
384
+ }
385
+ // ...
386
+ }
387
+ ```
388
+ ```
389
+ ````
390
+ This is the code block that represents the suggested code change:
391
+ ````markdown
392
+ ## 🔧 配置系统 / Configuration System
393
+
394
+ ### 配置结构 / Configuration Structure
395
+ ```javascript
396
+ // 完整配置结构 / Complete configuration structure
397
+ {
398
+ api: {
399
+ key: '', // API密钥(必填)/ API Key (required)
400
+ url: 'https://api.deepseek.com/v1/chat/completions',
401
+ timeout: 30000 // 请求超时(毫秒)/ Request timeout (ms)
402
+ },
403
+ model: {
404
+ name: 'deepseek-chat', // 模型名称 / Model name
405
+ temperature: 0.7, // 温度(0-2)/ Temperature (0-2)
406
+ maxTokens: 2000, // 最大token数 / Max tokens
407
+ stream: false, // 是否流式传输 / Whether to use streaming
408
+ reasoningEffort: 'medium' // 推理强度(仅DeepSeek)/ Reasoning effort (DeepSeek only)
409
+ },
410
+ conversation: {
411
+ baseRounds: 10, // 基础对话轮次 / Base conversation rounds
412
+ cycleRounds: 5 // 循环对话轮次 / Cycle conversation rounds
413
+ },
414
+ debug: false // 调试模式 / Debug mode
415
+ }
416
+ ```
417
+
418
+ ### 使用方式 / Usage
419
+
420
+ #### 方式1:基本使用 / Basic Usage
421
+ ```javascript
422
+ import { ChatService } from './src/index.js';
423
+
424
+ // 最小配置 / Minimal configuration
425
+ const chat = new ChatService({
426
+ api: { key: 'your-api-key' }
427
+ });
428
+
429
+ // 完整配置 / Complete configuration
430
+ const chat = new ChatService({
431
+ api: {
432
+ key: 'your-api-key',
433
+ url: 'https://api.openai.com/v1/chat/completions'
434
+ },
435
+ model: {
436
+ name: 'gpt-4',
437
+ temperature: 0.8,
438
+ stream: true
439
+ }
440
+ });
441
+ ```
442
+
443
+ #### 方式2:动态配置更新 / Dynamic Configuration Updates
444
+ ```javascript
445
+ // 创建服务后更新配置 / Update configuration after creating service
446
+ const chat = new ChatService({ api: { key: 'initial-key' } });
447
+
448
+ // 方法1:直接修改配置(自动同步)/ Method 1: Direct modification (auto-sync)
449
+ chat.configManager.config.api.key = 'new-key';
450
+ chat.configManager.config.model.temperature = 0.9;
451
+
452
+ // 方法2:批量更新 / Method 2: Batch update
453
+ chat.configManager.update({
454
+ api: { url: 'https://custom-api.com/v1/chat/completions' },
455
+ model: { name: 'custom-model' }
456
+ });
457
+
458
+ // 方法3:便捷方法 / Method 3: Convenience methods
459
+ chat.setApi('new-key', 'https://api.openai.com/v1/chat/completions');
460
+ chat.setModel('gpt-4', 0.8);
461
+ ```
462
+
463
+ #### 方式3:配置事件监听 / Configuration Event Listening
464
+ ```javascript
465
+ // 监听配置变更 / Listen to configuration changes
466
+ chat.configManager.on('config-changed', (data) => {
467
+ console.log(`配置 ${data.path} 已更新:`, data.oldValue, '→', data.newValue);
468
+ console.log(`Configuration ${data.path} updated:`, data.oldValue, '→', data.newValue);
469
+ });
470
+
471
+ // 监听特定配置变更 / Listen to specific configuration changes
472
+ chat.configManager.on('config-changed:model.temperature', (data) => {
473
+ console.log('温度已更新:', data.newValue);
474
+ console.log('Temperature updated:', data.newValue);
475
+ });
476
+ ```
477
+
478
+ ### 配置验证 / Configuration Validation
479
+ 框架会自动验证配置 / The framework automatically validates configuration:
480
+ - ✅ API Key 格式检查 / API Key format check
481
+ - ✅ URL 格式验证 / URL format validation
482
+ - ✅ 数值范围检查(temperature: 0-2)/ Value range check (temperature: 0-2)
483
+ - ✅ 枚举值验证(reasoningEffort: 'low'/'medium'/'high')/ Enum value validation
484
+
485
+ 发现无效配置时会发出警告,但不会阻止执行 / Warnings are issued for invalid configurations, but execution is not blocked.
486
+
487
+ ### 最佳实践 / Best Practices
488
+ 1. **环境变量** / **Environment Variables**: 在生产环境中使用环境变量存储API Key / Use environment variables to store API keys in production
489
+ 2. **配置分离** / **Configuration Separation**: 将配置提取到单独的文件中 / Extract configuration to separate files
490
+ 3. **类型检查** / **Type Checking**: 使用TypeScript获得更好的类型安全 / Use TypeScript for better type safety
491
+ 4. **版本控制** / **Version Control**: 不要将敏感配置提交到版本控制系统 / Do not commit sensitive configurations to version control
492
+ ````
package/README_ZH.md CHANGED
@@ -45,6 +45,49 @@ npm install
45
45
  npm run build
46
46
  ```
47
47
 
48
+ ### 基本使用
49
+ ```javascript
50
+ import { ChatService } from './src/index.js';
51
+
52
+ // 创建聊天服务(新版配置方式)
53
+ const chat = new ChatService({
54
+ api: { key: 'your-api-key' },
55
+ model: { name: 'deepseek-chat' }
56
+ });
57
+
58
+ // 发送消息
59
+ const response = await chat.send('你好!');
60
+ console.log('AI回复:', response);
61
+ ```
62
+
63
+ ### 完整示例
64
+ ```javascript
65
+ import { ChatService } from './src/index.js';
66
+
67
+ // 创建带完整配置的聊天服务
68
+ const chat = new ChatService({
69
+ api: {
70
+ key: 'your-api-key',
71
+ url: 'https://api.deepseek.com/v1/chat/completions'
72
+ },
73
+ model: {
74
+ name: 'deepseek-chat',
75
+ temperature: 0.8,
76
+ stream: false
77
+ },
78
+ debug: true
79
+ });
80
+
81
+ // 注册工具
82
+ chat.registerTool('get_weather', { /* 工具定义 */ }, async (args) => {
83
+ return { temperature: '25°C', condition: '晴朗' };
84
+ });
85
+
86
+ // 发送消息并处理工具调用
87
+ const response = await chat.send('北京的天气怎么样?');
88
+ console.log('最终回复:', response);
89
+ ```
90
+
48
91
  ### 输出文件
49
92
  构建后会在 `dist/` 目录生成以下文件:
50
93
  - `my-ai-chat-framework.es.js` - ES模块格式(包含axios依赖)
@@ -398,4 +441,105 @@ MIT License - 详见LICENSE文件
398
441
  **流式传输**: ✅ 完全支持
399
442
  **事件系统**: ✅ 完全支持
400
443
 
401
- **提示**: 这是一个学习项目,旨在帮助理解AI聊天框架的设计和实现。欢迎反馈和建议!
444
+ **提示**: 这是一个学习项目,旨在帮助理解AI聊天框架的设计和实现。欢迎反馈和建议!
445
+
446
+ ## 🔧 配置系统 / Configuration System
447
+
448
+ ### 配置结构 / Configuration Structure
449
+ ```javascript
450
+ // 完整配置结构 / Complete configuration structure
451
+ {
452
+ api: {
453
+ key: '', // API密钥(必填)/ API Key (required)
454
+ url: 'https://api.deepseek.com/v1/chat/completions',
455
+ timeout: 30000 // 请求超时(毫秒)/ Request timeout (ms)
456
+ },
457
+ model: {
458
+ name: 'deepseek-chat', // 模型名称 / Model name
459
+ temperature: 0.7, // 温度(0-2)/ Temperature (0-2)
460
+ maxTokens: 2000, // 最大token数 / Max tokens
461
+ stream: false, // 是否流式传输 / Whether to use streaming
462
+ reasoningEffort: 'medium' // 推理强度(仅DeepSeek)/ Reasoning effort (DeepSeek only)
463
+ },
464
+ conversation: {
465
+ baseRounds: 10, // 基础对话轮次 / Base conversation rounds
466
+ cycleRounds: 5 // 循环对话轮次 / Cycle conversation rounds
467
+ },
468
+ debug: false // 调试模式 / Debug mode
469
+ }
470
+ ```
471
+
472
+ ### 使用方式 / Usage
473
+
474
+ #### 方式1:基本使用 / Basic Usage
475
+ ```javascript
476
+ import { ChatService } from './src/index.js';
477
+
478
+ // 最小配置 / Minimal configuration
479
+ const chat = new ChatService({
480
+ api: { key: 'your-api-key' }
481
+ });
482
+
483
+ // 完整配置 / Complete configuration
484
+ const chat = new ChatService({
485
+ api: {
486
+ key: 'your-api-key',
487
+ url: 'https://api.openai.com/v1/chat/completions'
488
+ },
489
+ model: {
490
+ name: 'gpt-4',
491
+ temperature: 0.8,
492
+ stream: true
493
+ }
494
+ });
495
+ ```
496
+
497
+ #### 方式2:动态配置更新 / Dynamic Configuration Updates
498
+ ```javascript
499
+ // 创建服务后更新配置 / Update configuration after creating service
500
+ const chat = new ChatService({ api: { key: 'initial-key' } });
501
+
502
+ // 方法1:直接修改配置(自动同步)/ Method 1: Direct modification (auto-sync)
503
+ chat.configManager.config.api.key = 'new-key';
504
+ chat.configManager.config.model.temperature = 0.9;
505
+
506
+ // 方法2:批量更新 / Method 2: Batch update
507
+ chat.configManager.update({
508
+ api: { url: 'https://custom-api.com/v1/chat/completions' },
509
+ model: { name: 'custom-model' }
510
+ });
511
+
512
+ // 方法3:便捷方法 / Method 3: Convenience methods
513
+ chat.setApi('new-key', 'https://api.openai.com/v1/chat/completions');
514
+ chat.setModel('gpt-4', 0.8);
515
+ ```
516
+
517
+ #### 方式3:配置事件监听 / Configuration Event Listening
518
+ ```javascript
519
+ // 监听配置变更 / Listen to configuration changes
520
+ chat.configManager.on('config-changed', (data) => {
521
+ console.log(`配置 ${data.path} 已更新:`, data.oldValue, '→', data.newValue);
522
+ console.log(`Configuration ${data.path} updated:`, data.oldValue, '→', data.newValue);
523
+ });
524
+
525
+ // 监听特定配置变更 / Listen to specific configuration changes
526
+ chat.configManager.on('config-changed:model.temperature', (data) => {
527
+ console.log('温度已更新:', data.newValue);
528
+ console.log('Temperature updated:', data.newValue);
529
+ });
530
+ ```
531
+
532
+ ### 配置验证 / Configuration Validation
533
+ 框架会自动验证配置 / The framework automatically validates configuration:
534
+ - ✅ API Key 格式检查 / API Key format check
535
+ - ✅ URL 格式验证 / URL format validation
536
+ - ✅ 数值范围检查(temperature: 0-2)/ Value range check (temperature: 0-2)
537
+ - ✅ 枚举值验证(reasoningEffort: 'low'/'medium'/'high')/ Enum value validation
538
+
539
+ 发现无效配置时会发出警告,但不会阻止执行 / Warnings are issued for invalid configurations, but execution is not blocked.
540
+
541
+ ### 最佳实践 / Best Practices
542
+ 1. **环境变量** / **Environment Variables**: 在生产环境中使用环境变量存储API Key / Use environment variables to store API keys in production
543
+ 2. **配置分离** / **Configuration Separation**: 将配置提取到单独的文件中 / Extract configuration to separate files
544
+ 3. **类型检查** / **Type Checking**: 使用TypeScript获得更好的类型安全 / Use TypeScript for better type safety
545
+ 4. **版本控制** / **Version Control**: 不要将敏感配置提交到版本控制系统 / Do not commit sensitive configurations to version control