my-ai-chat-framework 1.1.0 → 2.7.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
@@ -1,492 +1,304 @@
1
- # 🤖 My AI Chat Framework / 我的AI聊天框架
2
1
 
3
- ## 🎯 概述 / Overview
4
- 这是一个现代化的AI聊天框架,支持工具调用、流式传输和事件驱动架构。旨在帮助开发者构建功能丰富的AI聊天应用。
2
+ # 🤖 My AI Chat Framework
5
3
 
6
- This is a modern AI chat framework with tool calling, streaming, and event-driven architecture. Designed to help developers build feature-rich AI chat applications.
4
+ A lightweight, modular AI chat framework with plugin system, unified message format, and tool calling support.
7
5
 
8
- ## 新功能特性 / New Features
9
- - **🔧 工具调用系统** / **Tool Calling System**: 完整的OpenAI兼容工具调用支持,包括工具注册、执行和错误处理
10
- - **🌊 流式传输** / **Streaming**: 实时流式传输,支持工具调用和进度回调
11
- - **⚡ 事件驱动架构** / **Event-Driven Architecture**: 基于EventEmitter的丰富事件系统
12
- - **📦 模块化设计** / **Modular Design**: 清晰的关注点分离,易于扩展和维护
6
+ > **⚠️ Note**: This project is created for **learning purposes** and is **AI‑generated**. It is not intended for production use. No backward compatibility is guaranteed. Use at your own risk.
13
7
 
14
- ## 核心功能 / Core Features
15
- - **消息管理** / **Message Management**: 包含一个`Messages`类,用于处理聊天消息的存储和操作
16
- - **请求构建** / **Request Building**: `RequestBuilder`类构建发送到聊天API的请求体
17
- - **API交互** / **API Interaction**: `ApiClient`类管理与聊天API的HTTP请求,支持标准和流式请求
18
- - **工具管理** / **Tool Management**: `ToolManager`类负责工具的注册、管理和执行
19
- - **事件系统** / **Event System**: `EventEmitter`类提供完整的事件驱动架构
20
- - **格式转换** / **Format Conversion**: `MessageFormatter`类负责消息格式转换
8
+ ## Features
21
9
 
22
- ## 📁 项目结构 / Project Structure
23
- ```
24
- my-ai-chat-framework/
25
- ├── dist/ # 打包输出目录 / Build output
26
- │ ├── my-ai-chat-framework.es.js # ES模块 / ES Module
27
- │ ├── my-ai-chat-framework.umd.js # UMD模块(注册到window.AIChatFramework)/ UMD Module
28
- │ └── my-ai-chat-framework.cjs.js # CommonJS模块 / CommonJS Module
29
- ├── src/ # 源代码 / Source code
30
- │ ├── core/ # 核心类 / Core classes
31
- │ │ ├── EventEmitter.js # 事件系统 / Event System
32
- │ │ ├── Messages.js # 消息状态管理 / Message State Management
33
- │ │ ├── MessageFormatter.js # 消息格式转换 / Message Format Conversion
34
- │ │ ├── RequestBuilder.js # 请求构建器 / Request Builder
35
- │ │ ├── ApiClient.js # API客户端(使用axios)/ API Client (axios)
36
- │ │ └── ToolManager.js # 工具管理器 / Tool Manager
37
- │ ├── utils/ # 工具函数 / Utility functions
38
- │ └── index.js # 主入口文件 / Main entry point
39
- ├── test-*.html # 各种测试页面 / Various test pages
40
- ├── README_ZH.md # 详细中文文档 / Detailed Chinese documentation
41
- ├── FIX_SUMMARY.md # 修复总结 / Fix summary
42
- ├── vite.config.js # Vite配置 / Vite configuration
43
- └── package.json # 项目配置 / Project configuration
44
- ```
45
-
46
- ## 🎯 统一数据格式 / Unified Data Format
47
-
48
- 从v1.1.0开始,框架使用统一的数据格式在所有组件之间传递消息,简化了使用体验。
10
+ - **Lightweight Core** ~300 lines, easy to understand and extend.
11
+ - **Plugin System** – Add features (tool calling, reasoning, custom adapters) without touching the core.
12
+ - **Unified Message Format** – Consistent data structure across all components.
13
+ - **Multi‑Environment** Builds ES module, UMD, and CommonJS for browser & Node.js.
14
+ - **No External Dependencies** – Uses native `fetch` (Node 18+ & modern browsers).
15
+ - **Tool Calling** – Built‑in plugin to handle function calls from AI models.
16
+ - **Streaming** Full support for real‑time responses.
17
+ - **Flexible Configuration** Supports both flat and nested `modelParams` structure.
18
+ - **Event‑Driven** Built‑in EventEmitter for `message`, `sending`, `error`, `stream-progress` events.
19
+ - **Custom Error Classes** `APIError`, `NetworkError`, `ConfigurationError`, `ParsingError` for fine‑grained error handling.
49
20
 
50
- ### 核心消息格式
21
+ ---
51
22
 
52
- 所有消息都遵循以下格式:
23
+ ## 🧱 Architecture
53
24
 
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
25
  ```
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
- });
26
+ src/
27
+ ├── index.js # Public entry point (re-exports)
28
+ ├── core/
29
+ │ ├── ChatService.js # Main service: config, send/stream, plugin hosting
30
+ │ ├── MessageStore.js # In-memory message list with CRUD helpers
31
+ │ ├── EventEmitter.js # Minimal pub/sub (on/off/emit)
32
+ │ └── Errors.js # Custom error classes
33
+ ├── adapters/
34
+ │ └── openai.js # OpenAI‑compatible API adapter (plugin pattern)
35
+ ├── plugins/
36
+ │ └── tool-calling.js # Tool calling plugin (auto‑detect & loop)
37
+ └── utils/
38
+ ├── typeCheck.js # Type checking helpers
39
+ └── url.js # URL joining utility
101
40
  ```
102
41
 
103
- ## 📦 安装和使用 / Installation and Usage
42
+ **Data flow**:
104
43
 
105
- ### 浏览器中使用 / For Browser Usage
106
-
107
- #### 方式1:直接引入UMD版本(推荐)
108
- ```html
109
- <script src="https://unpkg.com/my-ai-chat-framework@latest/dist/my-ai-chat-framework.browser.umd.js"></script>
110
- <script>
111
- // 全局变量 AIChatFramework 可用
112
- const { ChatService, Messages } = AIChatFramework;
113
-
114
- // 创建聊天服务
115
- const chat = new ChatService('your-api-key');
116
- </script>
117
44
  ```
118
-
119
- #### 方式2:使用ES模块
120
- ```html
121
- <script type="module">
122
- import { ChatService, Messages } from 'https://unpkg.com/my-ai-chat-framework@latest/dist/my-ai-chat-framework.browser.es.js';
123
-
124
- const chat = new ChatService('your-api-key');
125
- </script>
45
+ User calls chat.send(input)
46
+ ChatService._request()
47
+ → emits 'sending'
48
+ MessageStore.add(userMsg)
49
+ adapter.buildRequest(messages, config) ← formats request body
50
+ → adapter.send(requestBody, config) ← HTTP call (fetch)
51
+ adapter.parseResponse(response) ← normalize response
52
+ → MessageStore.add(assistantMsg)
53
+ → emits 'message'
54
+ → returns assistantMsg
126
55
  ```
127
56
 
128
- ### Node.js中使用 / For Node.js Usage
57
+ With `toolCallingPlugin`, the flow loops: response → detect tool_calls → execute tools → add tool results → sendExisting → repeat (max 5 iterations).
129
58
 
130
- #### 安装
131
- ```bash
132
- npm install my-ai-chat-framework axios
133
- # 或
134
- yarn add my-ai-chat-framework axios
135
- # 或
136
- pnpm add my-ai-chat-framework axios
137
- ```
138
-
139
- #### 使用
140
- ```javascript
141
- // CommonJS
142
- const { ChatService, Messages } = require('my-ai-chat-framework');
59
+ ---
143
60
 
144
- // ES模块
145
- import { ChatService, Messages } from 'my-ai-chat-framework';
61
+ ## 📦 Installation
146
62
 
147
- // 创建聊天服务
148
- const chat = new ChatService('your-api-key');
63
+ ```bash
64
+ npm install my-ai-chat-framework
149
65
  ```
150
66
 
151
- ### 本地开发 / Local Development
67
+ ---
152
68
 
153
- #### 安装依赖
154
- ```bash
155
- npm install
156
- ```
69
+ ## 🚀 Quick Start
157
70
 
158
- ### 构建项目 / Build Project
159
- ```bash
160
- npm run build
161
- ```
71
+ ### Basic Usage (Flat Configuration)
72
+
73
+ ```javascript
74
+ import { ChatService, openaiAdapter, toolCallingPlugin } from 'my-ai-chat-framework';
162
75
 
163
- ### 输出文件 / Output Files
164
- 构建后会在 `dist/` 目录生成以下文件:
165
- - `my-ai-chat-framework.es.js` - ES模块格式(包含axios依赖)
166
- - `my-ai-chat-framework.umd.js` - UMD格式(包含axios依赖)
167
- - `my-ai-chat-framework.cjs.js` - CommonJS格式(包含axios依赖)
76
+ const chat = new ChatService({
77
+ apiKey: 'your-api-key',
78
+ baseUrl: 'https://api.deepseek.com', // optional, defaults to OpenAI
79
+ model: 'deepseek-chat',
80
+ temperature: 0.7,
81
+ maxTokens: 2000
82
+ });
168
83
 
169
- **注意**: axios已被打包进所有输出文件中,用户无需额外安装axios依赖。
84
+ chat.use(openaiAdapter);
85
+ chat.use(toolCallingPlugin);
170
86
 
171
- ### 预览构建结果 / Preview Build
172
- ```bash
173
- npm run preview
87
+ chat.on('message', msg => console.log(msg.content));
88
+ await chat.send('Hello!');
174
89
  ```
175
90
 
176
- ### 在浏览器中使用 / Usage in Browser
91
+ ### Using `modelParams` (Recommended for Many Parameters)
177
92
 
178
- #### 传统浏览器(UMD模块)/ Traditional Browser (UMD Module)
179
- ```html
180
- <script src="./dist/my-ai-chat-framework.umd.js"></script>
181
- <script>
182
- // 使用全局变量 / Use global variable
183
- const { Messages, ApiClient, ChatRequestBuilder, ChatService } = window.AIChatFramework;
184
- const chat = new ChatService('your-api-key');
185
- </script>
93
+ ```javascript
94
+ const chat = new ChatService({
95
+ apiKey: 'your-api-key',
96
+ baseUrl: 'https://api.deepseek.com',
97
+ model: 'deepseek-chat', // still at top level for convenience
98
+ modelParams: { // optional parameters grouped
99
+ temperature: 0.8,
100
+ maxTokens: 1500,
101
+ reasoningEffort: 'medium' // for deepseek-reasoner
102
+ }
103
+ });
186
104
  ```
187
105
 
188
- #### 现代浏览器(ES模块)/ Modern Browser (ES Module)
189
- ```html
190
- <script type="module">
191
- import { Messages, ChatService } from './dist/my-ai-chat-framework.es.js';
192
- const chat = new ChatService('your-api-key');
193
- </script>
194
- ```
106
+ ### Registering a Tool
195
107
 
196
- ### 在Node.js中使用 / Usage in Node.js
197
108
  ```javascript
198
- const { Messages, ChatService } = require('./dist/my-ai-chat-framework.cjs.js');
199
- const chat = new ChatService('your-api-key');
200
- ```
109
+ chat.registerTool('get_weather', 'Get current weather for a city',
110
+ async (args) => {
111
+ // args = { city: 'Beijing' }
112
+ return `Weather in ${args.city}: 22°C, sunny`;
113
+ },
114
+ { // parameter schema (optional but recommended)
115
+ city: { type: 'string', description: 'City name', required: true }
116
+ }
117
+ );
201
118
 
202
- ## 核心类说明 / Core Classes Description
119
+ await chat.send('What\'s the weather in Beijing?');
120
+ // → AI calls get_weather, framework executes it, AI responds with weather info
121
+ ```
203
122
 
204
- ### Messages 类
205
- 管理对话消息的核心类,支持:
206
- - 消息的推送、修改、撤回
207
- - 系统提示词管理
208
- - 工具定义管理
209
- - 数据导入/导出
123
+ ---
210
124
 
211
- ### ChatRequestBuilder
212
- 构建符合API规范的请求体,支持:
213
- - 自动格式化消息
214
- - 配置模型参数
215
- - 生成JSON请求体
125
+ ## 🔌 Plugins & Adapters
216
126
 
217
- ### ApiClient 类
218
- HTTP客户端,支持:
219
- - 普通请求和流式请求
220
- - 请求中断
221
- - 错误处理
222
- - 前后端通用(使用axios)
127
+ ### openaiAdapter
223
128
 
224
- ### ChatService
225
- 高级封装类,简化使用:
226
- - 集成所有核心功能
227
- - 提供简单API接口
228
- - 自动管理消息状态
129
+ Converts internal messages to OpenAI‑compatible format. Supports:
130
+ - `apiUrl` – full URL (highest priority)
131
+ - `baseUrl` + `path` – base domain + API path
132
+ - Defaults to `https://api.openai.com/v1/chat/completions`
229
133
 
230
- ## 示例代码 / Example Code
134
+ | Config field | Type | Default | Description |
135
+ |-------------|------|---------|-------------|
136
+ | `apiKey` | string | **required** | Bearer token for Authorization header |
137
+ | `apiUrl` | string | – | Full request URL (overrides baseUrl+path) |
138
+ | `baseUrl` | string | `https://api.openai.com` | API base domain |
139
+ | `path` | string | `/v1/chat/completions` | API endpoint path |
231
140
 
232
- ```javascript
233
- // 创建聊天服务 / Create chat service
234
- const chat = new ChatService('your-api-key', 'deepseek-chat');
141
+ ### toolCallingPlugin
235
142
 
236
- // 发送消息 / Send message
237
- const response = await chat.send('你好,世界!');
238
- console.log('AI回复:', response);
143
+ Detects `tool_calls` in assistant responses, executes registered tools, feeds results back, and continues the conversation (up to `maxIterations` = 5).
239
144
 
240
- // 流式消息 / Stream message
241
- await chat.stream('告诉我一个故事',
242
- (chunk) => console.log('收到数据:', chunk),
243
- () => console.log('流式传输完成')
244
- );
145
+ - `chat.registerTool(name, description, executor, parameters?)` – register a tool
146
+ - Automatically injects `tool` role messages into the conversation
147
+ - Recovers from tool execution errors gracefully (logs error, returns error message to model)
245
148
 
246
- // 流式传输中的工具调用 / Tool calling in streaming
247
- await chat.stream('查询北京天气',
248
- (chunk) => console.log('实时数据:', chunk.content),
249
- (final) => console.log('最终结果:', final.content)
250
- );
149
+ ---
251
150
 
252
- // 撤回消息 / Undo message
253
- chat.undo();
151
+ ## 📡 Events (EventEmitter)
254
152
 
255
- // 导出对话 / Export conversation
256
- const exportData = chat.export();
153
+ `ChatService` extends `EventEmitter`. Subscribe with `chat.on(event, handler)`:
257
154
 
258
- ## 🤤 npm发布 / npm Publishing
155
+ | Event | Payload | When |
156
+ |-------|---------|------|
157
+ | `sending` | `{ addUser, userInput, timestamp }` | Before each request |
158
+ | `message` | `{ role, content, ... }` | Full assistant message received |
159
+ | `stream-progress` | chunk object | Each streaming chunk arrives |
160
+ | `error` | `{ error, timestamp }` | Any error during request |
259
161
 
260
- ### 发布准备
261
- 1. 确保已登录npm账号:
262
- ```bash
263
- npm login
264
- ```
162
+ ```javascript
163
+ chat.on('sending', ({ userInput }) => console.log('Sending:', userInput));
164
+ chat.on('message', msg => console.log('Got:', msg.content));
165
+ chat.on('error', ({ error }) => console.error('Error:', error.message));
265
166
 
266
- 2. 更新版本号(如果需要):
267
- ```bash
268
- npm version patch # 小版本更新
269
- npm version minor # 中版本更新
270
- npm version major # 大版本更新
167
+ // on() returns an unsubscribe function
168
+ const unsubscribe = chat.on('message', handler);
169
+ unsubscribe(); // stop listening
271
170
  ```
272
171
 
273
- 3. 构建项目:
274
- ```bash
275
- npm run build
276
- ```
172
+ ---
277
173
 
278
- ### 发布到npm
279
- ```bash
280
- npm publish
281
- ```
174
+ ## 🧩 ChatService API
282
175
 
283
- ### 发布后验证
284
- 1. 检查包是否发布成功:
285
- ```bash
286
- npm view my-ai-chat-framework
287
- ```
176
+ | Method | Returns | Description |
177
+ |--------|---------|-------------|
178
+ | `chat.send(userInput)` | `Promise<Message>` | Send a message, get reply (non‑streaming) |
179
+ | `chat.stream(userInput, onProgress, onDone)` | `Promise<Message>` | Send a message, get streaming reply |
180
+ | `chat.sendExisting()` | `Promise<Message>` | Re‑send current messages without adding user input |
181
+ | `chat.sendExistingStream(onProgress, onDone)` | `Promise<Message>` | Same as above, streaming |
182
+ | `chat.use(plugin)` | `this` | Install a plugin/adapter |
183
+ | `chat.setAdapter(adapter)` | `void` | Manually set the adapter |
184
+ | `chat.on(event, handler)` | `unsubscribe function` | Subscribe to events |
185
+ | `chat.registerTool(name, desc, fn, params?)` | `this` | Register a tool (requires toolCallingPlugin) |
186
+ | `chat.messages` | `MessageStore` | Access the message store directly |
288
187
 
289
- 2. 测试安装:
290
- ```bash
291
- npm install my-ai-chat-framework@latest
292
- ```
188
+ ---
293
189
 
294
- ### 包信息
295
- - **包名**: `my-ai-chat-framework`
296
- - **当前版本**: 1.0.2
297
- - **许可证**: MIT
298
- - **关键词**: AI, chat, framework, messages, API, deepseek, openai, tool-calling
190
+ ## 🗄️ MessageStore API
299
191
 
300
- ## 📄 许可证 / License
301
- MIT License - 详见 [LICENSE](LICENSE) 文件
192
+ | Method | Description |
193
+ |--------|-------------|
194
+ | `add(message)` | Add a raw message object |
195
+ | `addUser(content, meta?)` | Add a user message |
196
+ | `addAssistant(content, meta?)` | Add an assistant message |
197
+ | `addSystem(content, meta?)` | Add a system message |
198
+ | `addTool(content, toolCallId, meta?)` | Add a tool result message |
199
+ | `getAll()` | Return a shallow copy of all messages |
200
+ | `getLast()` | Return the last message (or null) |
201
+ | `clear()` | Remove all messages |
202
+ | `undoToLastAssistant()` | Remove messages after the last assistant message |
302
203
 
303
- ## 🤝 贡献 / Contributing
304
- 欢迎提交Issue和Pull Request!
204
+ **Message format**:
305
205
 
306
- ## 📞 支持 / Support
307
- 如有问题,请提交Issue或联系作者。
206
+ ```javascript
207
+ {
208
+ id: string, // auto‑generated if not provided
209
+ role: 'user' | 'assistant' | 'system' | 'tool',
210
+ content: string,
211
+ toolCalls?: Array, // assistant messages with tool calls
212
+ toolCallId?: string, // tool messages
213
+ reasoningContent?: string, // deepseek-reasoner
214
+ timestamp?: number,
215
+ metadata?: any
216
+ }
217
+ ```
308
218
 
309
219
  ---
310
220
 
311
- **✨ 感谢使用 My AI Chat Framework! ✨**
312
-
313
- // 导入对话 / Import conversation
314
- chat.import(exportData);
315
- ```
221
+ ## Error Handling
316
222
 
317
- ## 🌊 流式传输下的工具调用 / Tool Calling in Streaming
223
+ The framework throws typed errors for different failure modes:
318
224
 
319
- ### 工作原理 / How It Works
320
- 框架自动处理流式传输中的工具调用:
321
- 1. **流式收集** / **Stream Collection**: 在流式传输过程中收集完整的工具调用信息
322
- 2. **工具执行** / **Tool Execution**: 执行所有请求的工具
323
- 3. **继续流式** / **Continue Streaming**: 将工具结果发送给AI并继续流式传输
225
+ | Error Class | `.name` | When |
226
+ |------------|---------|------|
227
+ | `APIError` | `'APIError'` | Non‑2xx HTTP responses (401, 429, 500, etc.) |
228
+ | `NetworkError` | `'NetworkError'` | `fetch` failures, connection timeouts |
229
+ | `ConfigurationError` | `'ConfigurationError'` | Missing required config |
230
+ | `ParsingError` | `'ParsingError'` | Malformed API response |
324
231
 
325
- ### 代码示例 / Code Example
326
232
  ```javascript
327
- // 注册工具 / Register tool
328
- chat.registerTool('get_weather', toolDefinition, async (args) => {
329
- return { temperature: '25°C', condition: 'Sunny' };
330
- });
331
-
332
- // 流式传输会自动处理工具调用 / Streaming automatically handles tool calls
333
- await chat.stream('What is the weather in Beijing?',
334
- (chunk) => {
335
- // 实时接收流式数据 / Receive streaming data in real-time
336
- if (chunk.content) console.log('Content:', chunk.content);
337
- if (chunk.tool_calls) console.log('Tool calls:', chunk.tool_calls);
338
- },
339
- (final) => {
340
- // 流式传输完成 / Streaming completed
341
- console.log('Final result:', final.content);
233
+ import { APIError, NetworkError, ConfigurationError, ParsingError } from 'my-ai-chat-framework';
234
+
235
+ try {
236
+ await chat.send('Hello');
237
+ } catch (error) {
238
+ if (error instanceof APIError) {
239
+ console.error(`API ${error.statusCode}: ${error.message}`);
240
+ } else if (error instanceof NetworkError) {
241
+ console.error('Network issue:', error.message);
342
242
  }
343
- );
243
+ }
344
244
  ```
345
245
 
346
- ## 📚 更多文档 / More Documentation
347
- - **[详细中文文档](README_ZH.md)** - 完整的功能说明和使用示例
348
- - **[修复总结](FIX_SUMMARY.md)** - 技术修复细节和架构改进
349
-
350
- ## 许可证 / License
351
- 本项目采用MIT许可证。详见LICENSE文件。
246
+ ---
352
247
 
353
- This project is licensed under the MIT License. See the LICENSE file for more details.
248
+ ## 📚 Configuration Reference
354
249
 
355
- ## 依赖库 / Dependencies
356
- - [axios](https://github.com/axios/axios) - MIT License
357
- - [vite](https://vitejs.dev/) - MIT License
250
+ `new ChatService(config)` accepts:
358
251
 
359
- ---
252
+ | Option | Type | Default | Description |
253
+ |--------|------|---------|-------------|
254
+ | `apiKey` | string | **required** | Your API key |
255
+ | `baseUrl` | string | `'https://api.openai.com'` | API base URL (used with `path`) |
256
+ | `path` | string | `'/v1/chat/completions'` | API path (used with `baseUrl`) |
257
+ | `apiUrl` | string | – | Full API URL (overrides `baseUrl`+`path`) |
258
+ | `model` | string | **required** | Model name (e.g., `deepseek-chat`) |
259
+ | `modelParams` | object | `{}` | Grouped model parameters (see below) |
260
+ | `temperature` | number | `0.7` | Sampling temperature (0–2) |
261
+ | `maxTokens` | number | `2000` | Max tokens to generate |
262
+ | `reasoningEffort` | string | – | For `deepseek-reasoner`: `'low'`, `'medium'`, `'high'` |
360
263
 
361
- *此文档由AI辅助生成,内容可能不完整或存在错误,请以实际代码为准。*
362
- *This document is AI-assisted and may be incomplete or contain errors. Please refer to the actual code for accurate information.*
264
+ > Both flat and `modelParams` styles work. `modelParams` takes precedence over top‑level values.
363
265
 
364
- ### 配置系统章节
365
- 需要在两个 README 中都添加:
266
+ ---
366
267
 
367
- ```markdown
368
- ## 🔧 配置系统 / Configuration System
268
+ ## 🧪 Testing
369
269
 
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
270
+ ```bash
271
+ # 1. Create a .env file with your API key
272
+ echo "DEEPSEEK_API_KEY=sk-xxxxx" > .env
393
273
 
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
- }
274
+ # 2. Run the test
275
+ npm test
416
276
  ```
417
277
 
418
- ### 使用方式 / Usage
278
+ The test script (`test.js`) sends a simple message and logs the response.
419
279
 
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
- });
280
+ ---
428
281
 
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
- ```
282
+ ## 🛠️ Development
442
283
 
443
- #### 方式2:动态配置更新 / Dynamic Configuration Updates
444
- ```javascript
445
- // 创建服务后更新配置 / Update configuration after creating service
446
- const chat = new ChatService({ api: { key: 'initial-key' } });
284
+ ```bash
285
+ git clone https://github.com/your-username/my-ai-chat-framework.git
286
+ cd my-ai-chat-framework
287
+ npm install
447
288
 
448
- // 方法1:直接修改配置(自动同步)/ Method 1: Direct modification (auto-sync)
449
- chat.configManager.config.api.key = 'new-key';
450
- chat.configManager.config.model.temperature = 0.9;
289
+ # Dev mode (watching)
290
+ npm run dev
451
291
 
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
- });
292
+ # Build the library (ES + UMD + CJS)
293
+ npm run build
457
294
 
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);
295
+ # Run tests
296
+ npm test
461
297
  ```
462
298
 
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
- });
299
+ ---
470
300
 
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
- ```
301
+ ## 📄 License
302
+
303
+ MIT
477
304
 
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
- ````