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 +218 -406
- package/dist/my-ai-chat-framework.browser.es.js +1284 -2904
- package/dist/my-ai-chat-framework.browser.es.js.map +1 -1
- package/dist/my-ai-chat-framework.browser.umd.js +1310 -2917
- package/dist/my-ai-chat-framework.browser.umd.js.map +1 -1
- package/dist/my-ai-chat-framework.node.cjs.js +1296 -1654
- package/dist/my-ai-chat-framework.node.cjs.js.map +1 -1
- package/package.json +18 -35
- package/src/adapters/openai.js +280 -0
- package/src/core/ChatService.js +298 -0
- package/src/core/Errors.js +60 -0
- package/src/core/EventEmitter.js +51 -126
- package/src/core/MessageStore.js +112 -0
- package/src/core/SystemPromptStore.js +118 -0
- package/src/index.js +11 -540
- package/src/plugins/model-registry.js +187 -0
- package/src/plugins/tool-calling.js +213 -0
- package/src/utils/MessageFormatter.js +204 -0
- package/src/utils/typeCheck.js +12 -0
- package/src/utils/url.js +18 -0
- package/README_ZH.md +0 -545
- package/src/config/defaults.js +0 -25
- package/src/core/ApiClient.js +0 -316
- package/src/core/ConfigManager.js +0 -173
- package/src/core/MessageFormatter.js +0 -136
- package/src/core/Messages.js +0 -589
- package/src/core/RequestBuilder.js +0 -99
- package/src/core/ToolManager.js +0 -175
- package/src/utils/index.js +0 -21
package/README.md
CHANGED
|
@@ -1,492 +1,304 @@
|
|
|
1
|
-
# 🤖 My AI Chat Framework / 我的AI聊天框架
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
这是一个现代化的AI聊天框架,支持工具调用、流式传输和事件驱动架构。旨在帮助开发者构建功能丰富的AI聊天应用。
|
|
2
|
+
# 🤖 My AI Chat Framework
|
|
5
3
|
|
|
6
|
-
|
|
4
|
+
A lightweight, modular AI chat framework with plugin system, unified message format, and tool calling support.
|
|
7
5
|
|
|
8
|
-
|
|
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
|
-
##
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
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
|
-
|
|
145
|
-
import { ChatService, Messages } from 'my-ai-chat-framework';
|
|
61
|
+
## 📦 Installation
|
|
146
62
|
|
|
147
|
-
|
|
148
|
-
|
|
63
|
+
```bash
|
|
64
|
+
npm install my-ai-chat-framework
|
|
149
65
|
```
|
|
150
66
|
|
|
151
|
-
|
|
67
|
+
---
|
|
152
68
|
|
|
153
|
-
|
|
154
|
-
```bash
|
|
155
|
-
npm install
|
|
156
|
-
```
|
|
69
|
+
## 🚀 Quick Start
|
|
157
70
|
|
|
158
|
-
###
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
71
|
+
### Basic Usage (Flat Configuration)
|
|
72
|
+
|
|
73
|
+
```javascript
|
|
74
|
+
import { ChatService, openaiAdapter, toolCallingPlugin } from 'my-ai-chat-framework';
|
|
162
75
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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
|
-
|
|
84
|
+
chat.use(openaiAdapter);
|
|
85
|
+
chat.use(toolCallingPlugin);
|
|
170
86
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
npm run preview
|
|
87
|
+
chat.on('message', msg => console.log(msg.content));
|
|
88
|
+
await chat.send('Hello!');
|
|
174
89
|
```
|
|
175
90
|
|
|
176
|
-
###
|
|
91
|
+
### Using `modelParams` (Recommended for Many Parameters)
|
|
177
92
|
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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
|
-
|
|
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
|
-
|
|
199
|
-
|
|
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
|
-
|
|
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
|
-
|
|
205
|
-
管理对话消息的核心类,支持:
|
|
206
|
-
- 消息的推送、修改、撤回
|
|
207
|
-
- 系统提示词管理
|
|
208
|
-
- 工具定义管理
|
|
209
|
-
- 数据导入/导出
|
|
123
|
+
---
|
|
210
124
|
|
|
211
|
-
|
|
212
|
-
构建符合API规范的请求体,支持:
|
|
213
|
-
- 自动格式化消息
|
|
214
|
-
- 配置模型参数
|
|
215
|
-
- 生成JSON请求体
|
|
125
|
+
## 🔌 Plugins & Adapters
|
|
216
126
|
|
|
217
|
-
###
|
|
218
|
-
HTTP客户端,支持:
|
|
219
|
-
- 普通请求和流式请求
|
|
220
|
-
- 请求中断
|
|
221
|
-
- 错误处理
|
|
222
|
-
- 前后端通用(使用axios)
|
|
127
|
+
### openaiAdapter
|
|
223
128
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
-
|
|
227
|
-
-
|
|
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
|
-
|
|
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
|
-
|
|
233
|
-
// 创建聊天服务 / Create chat service
|
|
234
|
-
const chat = new ChatService('your-api-key', 'deepseek-chat');
|
|
141
|
+
### toolCallingPlugin
|
|
235
142
|
|
|
236
|
-
|
|
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
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
-
|
|
247
|
-
await chat.stream('查询北京天气',
|
|
248
|
-
(chunk) => console.log('实时数据:', chunk.content),
|
|
249
|
-
(final) => console.log('最终结果:', final.content)
|
|
250
|
-
);
|
|
149
|
+
---
|
|
251
150
|
|
|
252
|
-
|
|
253
|
-
chat.undo();
|
|
151
|
+
## 📡 Events (EventEmitter)
|
|
254
152
|
|
|
255
|
-
|
|
256
|
-
const exportData = chat.export();
|
|
153
|
+
`ChatService` extends `EventEmitter`. Subscribe with `chat.on(event, handler)`:
|
|
257
154
|
|
|
258
|
-
|
|
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
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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
|
-
|
|
274
|
-
```bash
|
|
275
|
-
npm run build
|
|
276
|
-
```
|
|
172
|
+
---
|
|
277
173
|
|
|
278
|
-
|
|
279
|
-
```bash
|
|
280
|
-
npm publish
|
|
281
|
-
```
|
|
174
|
+
## 🧩 ChatService API
|
|
282
175
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
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
|
-
|
|
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
|
-
|
|
301
|
-
|
|
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
|
-
|
|
304
|
-
欢迎提交Issue和Pull Request!
|
|
204
|
+
**Message format**:
|
|
305
205
|
|
|
306
|
-
|
|
307
|
-
|
|
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
|
-
|
|
312
|
-
|
|
313
|
-
// 导入对话 / Import conversation
|
|
314
|
-
chat.import(exportData);
|
|
315
|
-
```
|
|
221
|
+
## ❌ Error Handling
|
|
316
222
|
|
|
317
|
-
|
|
223
|
+
The framework throws typed errors for different failure modes:
|
|
318
224
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
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
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
(
|
|
335
|
-
|
|
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
|
-
|
|
347
|
-
- **[详细中文文档](README_ZH.md)** - 完整的功能说明和使用示例
|
|
348
|
-
- **[修复总结](FIX_SUMMARY.md)** - 技术修复细节和架构改进
|
|
349
|
-
|
|
350
|
-
## 许可证 / License
|
|
351
|
-
本项目采用MIT许可证。详见LICENSE文件。
|
|
246
|
+
---
|
|
352
247
|
|
|
353
|
-
|
|
248
|
+
## 📚 Configuration Reference
|
|
354
249
|
|
|
355
|
-
|
|
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
|
-
|
|
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
|
-
|
|
368
|
-
## 🔧 配置系统 / Configuration System
|
|
268
|
+
## 🧪 Testing
|
|
369
269
|
|
|
370
|
-
|
|
371
|
-
|
|
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
|
-
|
|
395
|
-
|
|
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
|
-
|
|
278
|
+
The test script (`test.js`) sends a simple message and logs the response.
|
|
419
279
|
|
|
420
|
-
|
|
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
|
-
|
|
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
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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
|
-
|
|
449
|
-
|
|
450
|
-
chat.configManager.config.model.temperature = 0.9;
|
|
289
|
+
# Dev mode (watching)
|
|
290
|
+
npm run dev
|
|
451
291
|
|
|
452
|
-
|
|
453
|
-
|
|
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
|
-
|
|
459
|
-
|
|
460
|
-
chat.setModel('gpt-4', 0.8);
|
|
295
|
+
# Run tests
|
|
296
|
+
npm test
|
|
461
297
|
```
|
|
462
298
|
|
|
463
|
-
|
|
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
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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
|
-
````
|