@lobehub/chat 1.52.18 → 1.52.19

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/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 1.52.19](https://github.com/lobehub/lobe-chat/compare/v1.52.18...v1.52.19)
6
+
7
+ <sup>Released on **2025-02-11**</sup>
8
+
9
+ #### ♻ Code Refactoring
10
+
11
+ - **misc**: Refactor the agent runtime test case.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### Code refactoring
19
+
20
+ - **misc**: Refactor the agent runtime test case, closes [#6025](https://github.com/lobehub/lobe-chat/issues/6025) ([3414fdd](https://github.com/lobehub/lobe-chat/commit/3414fdd))
21
+
22
+ </details>
23
+
24
+ <div align="right">
25
+
26
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
27
+
28
+ </div>
29
+
5
30
  ### [Version 1.52.18](https://github.com/lobehub/lobe-chat/compare/v1.52.17...v1.52.18)
6
31
 
7
32
  <sup>Released on **2025-02-11**</sup>
package/changelog/v1.json CHANGED
@@ -1,4 +1,13 @@
1
1
  [
2
+ {
3
+ "children": {
4
+ "improvements": [
5
+ "Refactor the agent runtime test case."
6
+ ]
7
+ },
8
+ "date": "2025-02-11",
9
+ "version": "1.52.19"
10
+ },
2
11
  {
3
12
  "children": {},
4
13
  "date": "2025-02-11",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "1.52.18",
3
+ "version": "1.52.19",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -1,255 +1,13 @@
1
1
  // @vitest-environment node
2
- import OpenAI from 'openai';
3
- import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { ModelProvider } from '@/libs/agent-runtime';
4
3
 
5
- import {
6
- ChatStreamCallbacks,
7
- LobeOpenAICompatibleRuntime,
8
- ModelProvider,
9
- } from '@/libs/agent-runtime';
10
-
11
- import * as debugStreamModule from '../utils/debugStream';
4
+ import { testProvider } from '../providerTestUtils';
12
5
  import { LobeHunyuanAI } from './index';
13
6
 
14
- const provider = ModelProvider.Hunyuan;
15
- const defaultBaseURL = 'https://api.hunyuan.cloud.tencent.com/v1';
16
-
17
- const bizErrorType = 'ProviderBizError';
18
- const invalidErrorType = 'InvalidProviderAPIKey';
19
-
20
- // Mock the console.error to avoid polluting test output
21
- vi.spyOn(console, 'error').mockImplementation(() => {});
22
-
23
- let instance: LobeOpenAICompatibleRuntime;
24
-
25
- beforeEach(() => {
26
- instance = new LobeHunyuanAI({ apiKey: 'test' });
27
-
28
- // 使用 vi.spyOn 来模拟 chat.completions.create 方法
29
- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
30
- new ReadableStream() as any,
31
- );
32
- });
33
-
34
- afterEach(() => {
35
- vi.clearAllMocks();
36
- });
37
-
38
- describe('LobeHunyuanAI', () => {
39
- describe('init', () => {
40
- it('should correctly initialize with an API key', async () => {
41
- const instance = new LobeHunyuanAI({ apiKey: 'test_api_key' });
42
- expect(instance).toBeInstanceOf(LobeHunyuanAI);
43
- expect(instance.baseURL).toEqual(defaultBaseURL);
44
- });
45
- });
46
-
47
- describe('chat', () => {
48
- describe('Error', () => {
49
- it('should return OpenAIBizError with an openai error response when OpenAI.APIError is thrown', async () => {
50
- // Arrange
51
- const apiError = new OpenAI.APIError(
52
- 400,
53
- {
54
- status: 400,
55
- error: {
56
- message: 'Bad Request',
57
- },
58
- },
59
- 'Error message',
60
- {},
61
- );
62
-
63
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
64
-
65
- // Act
66
- try {
67
- await instance.chat({
68
- messages: [{ content: 'Hello', role: 'user' }],
69
- model: 'hunyuan-lite',
70
- temperature: 0,
71
- });
72
- } catch (e) {
73
- expect(e).toEqual({
74
- endpoint: defaultBaseURL,
75
- error: {
76
- error: { message: 'Bad Request' },
77
- status: 400,
78
- },
79
- errorType: bizErrorType,
80
- provider,
81
- });
82
- }
83
- });
84
-
85
- it('should throw AgentRuntimeError with NoOpenAIAPIKey if no apiKey is provided', async () => {
86
- try {
87
- new LobeHunyuanAI({});
88
- } catch (e) {
89
- expect(e).toEqual({ errorType: invalidErrorType });
90
- }
91
- });
92
-
93
- it('should return OpenAIBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
94
- // Arrange
95
- const errorInfo = {
96
- stack: 'abc',
97
- cause: {
98
- message: 'api is undefined',
99
- },
100
- };
101
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
102
-
103
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
104
-
105
- // Act
106
- try {
107
- await instance.chat({
108
- messages: [{ content: 'Hello', role: 'user' }],
109
- model: 'hunyuan-lite',
110
- temperature: 0,
111
- });
112
- } catch (e) {
113
- expect(e).toEqual({
114
- endpoint: defaultBaseURL,
115
- error: {
116
- cause: { message: 'api is undefined' },
117
- stack: 'abc',
118
- },
119
- errorType: bizErrorType,
120
- provider,
121
- });
122
- }
123
- });
124
-
125
- it('should return OpenAIBizError with an cause response with desensitize Url', async () => {
126
- // Arrange
127
- const errorInfo = {
128
- stack: 'abc',
129
- cause: { message: 'api is undefined' },
130
- };
131
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
132
-
133
- instance = new LobeHunyuanAI({
134
- apiKey: 'test',
135
-
136
- baseURL: 'https://api.abc.com/v1',
137
- });
138
-
139
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
140
-
141
- // Act
142
- try {
143
- await instance.chat({
144
- messages: [{ content: 'Hello', role: 'user' }],
145
- model: 'hunyuan-lite',
146
- temperature: 0,
147
- });
148
- } catch (e) {
149
- expect(e).toEqual({
150
- endpoint: 'https://api.***.com/v1',
151
- error: {
152
- cause: { message: 'api is undefined' },
153
- stack: 'abc',
154
- },
155
- errorType: bizErrorType,
156
- provider,
157
- });
158
- }
159
- });
160
-
161
- it('should throw an InvalidHunyuanAPIKey error type on 401 status code', async () => {
162
- // Mock the API call to simulate a 401 error
163
- const error = new Error('Unauthorized') as any;
164
- error.status = 401;
165
- vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
166
-
167
- try {
168
- await instance.chat({
169
- messages: [{ content: 'Hello', role: 'user' }],
170
- model: 'hunyuan-lite',
171
- temperature: 0,
172
- });
173
- } catch (e) {
174
- // Expect the chat method to throw an error with InvalidHunyuanAPIKey
175
- expect(e).toEqual({
176
- endpoint: defaultBaseURL,
177
- error: new Error('Unauthorized'),
178
- errorType: invalidErrorType,
179
- provider,
180
- });
181
- }
182
- });
183
-
184
- it('should return AgentRuntimeError for non-OpenAI errors', async () => {
185
- // Arrange
186
- const genericError = new Error('Generic Error');
187
-
188
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
189
-
190
- // Act
191
- try {
192
- await instance.chat({
193
- messages: [{ content: 'Hello', role: 'user' }],
194
- model: 'hunyuan-lite',
195
- temperature: 0,
196
- });
197
- } catch (e) {
198
- expect(e).toEqual({
199
- endpoint: defaultBaseURL,
200
- errorType: 'AgentRuntimeError',
201
- provider,
202
- error: {
203
- name: genericError.name,
204
- cause: genericError.cause,
205
- message: genericError.message,
206
- stack: genericError.stack,
207
- },
208
- });
209
- }
210
- });
211
- });
212
-
213
- describe('DEBUG', () => {
214
- it('should call debugStream and return StreamingTextResponse when DEBUG_HUNYUAN_CHAT_COMPLETION is 1', async () => {
215
- // Arrange
216
- const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
217
- const mockDebugStream = new ReadableStream({
218
- start(controller) {
219
- controller.enqueue('Debug stream content');
220
- controller.close();
221
- },
222
- }) as any;
223
- mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
224
-
225
- // 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
226
- (instance['client'].chat.completions.create as Mock).mockResolvedValue({
227
- tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
228
- });
229
-
230
- // 保存原始环境变量值
231
- const originalDebugValue = process.env.DEBUG_HUNYUAN_CHAT_COMPLETION;
232
-
233
- // 模拟环境变量
234
- process.env.DEBUG_HUNYUAN_CHAT_COMPLETION = '1';
235
- vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
236
-
237
- // 执行测试
238
- // 运行你的测试函数,确保它会在条件满足时调用 debugStream
239
- // 假设的测试函数调用,你可能需要根据实际情况调整
240
- await instance.chat({
241
- messages: [{ content: 'Hello', role: 'user' }],
242
- model: 'hunyuan-lite',
243
- stream: true,
244
- temperature: 0,
245
- });
246
-
247
- // 验证 debugStream 被调用
248
- expect(debugStreamModule.debugStream).toHaveBeenCalled();
249
-
250
- // 恢复原始环境变量值
251
- process.env.DEBUG_HUNYUAN_CHAT_COMPLETION = originalDebugValue;
252
- });
253
- });
254
- });
7
+ testProvider({
8
+ Runtime: LobeHunyuanAI,
9
+ provider: ModelProvider.Hunyuan,
10
+ defaultBaseURL: 'https://api.hunyuan.cloud.tencent.com/v1',
11
+ chatDebugEnv: 'DEBUG_HUNYUAN_CHAT_COMPLETION',
12
+ chatModel: 'hunyuan-lite',
255
13
  });
@@ -0,0 +1,263 @@
1
+ import OpenAI from 'openai';
2
+ import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { LobeOpenAICompatibleRuntime } from '@/libs/agent-runtime';
5
+
6
+ import * as debugStreamModule from './utils/debugStream';
7
+
8
+ interface TesstProviderParams {
9
+ Runtime: any;
10
+ bizErrorType?: string;
11
+ chatDebugEnv: string;
12
+ chatModel: string;
13
+ defaultBaseURL: string;
14
+ invalidErrorType?: string;
15
+ provider: string;
16
+ }
17
+
18
+ export const testProvider = ({
19
+ provider,
20
+ invalidErrorType = 'InvalidProviderAPIKey',
21
+ bizErrorType = 'ProviderBizError',
22
+ defaultBaseURL,
23
+ Runtime,
24
+ chatDebugEnv,
25
+ chatModel,
26
+ }: TesstProviderParams) => {
27
+ // Mock the console.error to avoid polluting test output
28
+ vi.spyOn(console, 'error').mockImplementation(() => {});
29
+
30
+ let instance: LobeOpenAICompatibleRuntime;
31
+
32
+ beforeEach(() => {
33
+ instance = new Runtime({ apiKey: 'test' });
34
+
35
+ // 使用 vi.spyOn 来模拟 chat.completions.create 方法
36
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
37
+ new ReadableStream() as any,
38
+ );
39
+ });
40
+
41
+ afterEach(() => {
42
+ vi.clearAllMocks();
43
+ });
44
+
45
+ describe(`${provider} Runtime`, () => {
46
+ describe('init', () => {
47
+ it('should correctly initialize with an API key', async () => {
48
+ const instance = new Runtime({ apiKey: 'test_api_key' });
49
+ expect(instance).toBeInstanceOf(Runtime);
50
+ expect(instance.baseURL).toEqual(defaultBaseURL);
51
+ });
52
+ });
53
+
54
+ describe('chat', () => {
55
+ describe('Error', () => {
56
+ it('should return OpenAIBizError with an openai error response when OpenAI.APIError is thrown', async () => {
57
+ // Arrange
58
+ const apiError = new OpenAI.APIError(
59
+ 400,
60
+ {
61
+ error: {
62
+ message: 'Bad Request',
63
+ },
64
+ status: 400,
65
+ },
66
+ 'Error message',
67
+ {},
68
+ );
69
+
70
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
71
+
72
+ // Act
73
+ try {
74
+ await instance.chat({
75
+ messages: [{ content: 'Hello', role: 'user' }],
76
+ model: chatModel,
77
+ temperature: 0,
78
+ });
79
+ } catch (e) {
80
+ expect(e).toEqual({
81
+ endpoint: defaultBaseURL,
82
+ error: {
83
+ error: { message: 'Bad Request' },
84
+ status: 400,
85
+ },
86
+ errorType: bizErrorType,
87
+ provider,
88
+ });
89
+ }
90
+ });
91
+
92
+ it('should throw AgentRuntimeError with NoOpenAIAPIKey if no apiKey is provided', async () => {
93
+ try {
94
+ new Runtime({});
95
+ } catch (e) {
96
+ expect(e).toEqual({ errorType: invalidErrorType });
97
+ }
98
+ });
99
+
100
+ it('should return OpenAIBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
101
+ // Arrange
102
+ const errorInfo = {
103
+ cause: {
104
+ message: 'api is undefined',
105
+ },
106
+ stack: 'abc',
107
+ };
108
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
109
+
110
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
111
+
112
+ // Act
113
+ try {
114
+ await instance.chat({
115
+ messages: [{ content: 'Hello', role: 'user' }],
116
+ model: chatModel,
117
+ temperature: 0,
118
+ });
119
+ } catch (e) {
120
+ expect(e).toEqual({
121
+ endpoint: defaultBaseURL,
122
+ error: {
123
+ cause: { message: 'api is undefined' },
124
+ stack: 'abc',
125
+ },
126
+ errorType: bizErrorType,
127
+ provider,
128
+ });
129
+ }
130
+ });
131
+
132
+ it('should return OpenAIBizError with an cause response with desensitize Url', async () => {
133
+ // Arrange
134
+ const errorInfo = {
135
+ cause: { message: 'api is undefined' },
136
+ stack: 'abc',
137
+ };
138
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
139
+
140
+ instance = new Runtime({
141
+ apiKey: 'test',
142
+
143
+ baseURL: 'https://api.abc.com/v1',
144
+ });
145
+
146
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
147
+
148
+ // Act
149
+ try {
150
+ await instance.chat({
151
+ messages: [{ content: 'Hello', role: 'user' }],
152
+ model: chatModel,
153
+ temperature: 0,
154
+ });
155
+ } catch (e) {
156
+ expect(e).toEqual({
157
+ endpoint: 'https://api.***.com/v1',
158
+ error: {
159
+ cause: { message: 'api is undefined' },
160
+ stack: 'abc',
161
+ },
162
+ errorType: bizErrorType,
163
+ provider,
164
+ });
165
+ }
166
+ });
167
+
168
+ it('should throw an InvalidHunyuanAPIKey error type on 401 status code', async () => {
169
+ // Mock the API call to simulate a 401 error
170
+ const error = new Error('Unauthorized') as any;
171
+ error.status = 401;
172
+ vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
173
+
174
+ try {
175
+ await instance.chat({
176
+ messages: [{ content: 'Hello', role: 'user' }],
177
+ model: chatModel,
178
+ temperature: 0,
179
+ });
180
+ } catch (e) {
181
+ // Expect the chat method to throw an error with InvalidHunyuanAPIKey
182
+ expect(e).toEqual({
183
+ endpoint: defaultBaseURL,
184
+ error: new Error('Unauthorized'),
185
+ errorType: invalidErrorType,
186
+ provider,
187
+ });
188
+ }
189
+ });
190
+
191
+ it('should return AgentRuntimeError for non-OpenAI errors', async () => {
192
+ // Arrange
193
+ const genericError = new Error('Generic Error');
194
+
195
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
196
+
197
+ // Act
198
+ try {
199
+ await instance.chat({
200
+ messages: [{ content: 'Hello', role: 'user' }],
201
+ model: chatModel,
202
+ temperature: 0,
203
+ });
204
+ } catch (e) {
205
+ expect(e).toEqual({
206
+ endpoint: defaultBaseURL,
207
+ error: {
208
+ cause: genericError.cause,
209
+ message: genericError.message,
210
+ name: genericError.name,
211
+ stack: genericError.stack,
212
+ },
213
+ errorType: 'AgentRuntimeError',
214
+ provider,
215
+ });
216
+ }
217
+ });
218
+ });
219
+
220
+ describe('DEBUG', () => {
221
+ it(`should call debugStream and return StreamingTextResponse when ${chatDebugEnv} is 1`, async () => {
222
+ // Arrange
223
+ const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
224
+ const mockDebugStream = new ReadableStream({
225
+ start(controller) {
226
+ controller.enqueue('Debug stream content');
227
+ controller.close();
228
+ },
229
+ }) as any;
230
+ mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
231
+
232
+ // 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
233
+ (instance['client'].chat.completions.create as Mock).mockResolvedValue({
234
+ tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
235
+ });
236
+
237
+ // 保存原始环境变量值
238
+ const originalDebugValue = process.env[chatDebugEnv];
239
+
240
+ // 模拟环境变量
241
+ process.env[chatDebugEnv] = '1';
242
+ vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
243
+
244
+ // 执行测试
245
+ // 运行你的测试函数,确保它会在条件满足时调用 debugStream
246
+ // 假设的测试函数调用,你可能需要根据实际情况调整
247
+ await instance.chat({
248
+ messages: [{ content: 'Hello', role: 'user' }],
249
+ model: chatModel,
250
+ stream: true,
251
+ temperature: 0,
252
+ });
253
+
254
+ // 验证 debugStream 被调用
255
+ expect(debugStreamModule.debugStream).toHaveBeenCalled();
256
+
257
+ // 恢复原始环境变量值
258
+ process.env[chatDebugEnv] = originalDebugValue;
259
+ });
260
+ });
261
+ });
262
+ });
263
+ };