@lobehub/chat 0.156.1 → 0.157.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/CHANGELOG.md +42 -0
- package/Dockerfile +4 -1
- package/package.json +3 -2
- package/src/config/modelProviders/anthropic.ts +3 -0
- package/src/config/modelProviders/google.ts +3 -0
- package/src/config/modelProviders/groq.ts +5 -1
- package/src/config/modelProviders/minimax.ts +10 -7
- package/src/config/modelProviders/mistral.ts +1 -0
- package/src/config/modelProviders/moonshot.ts +3 -0
- package/src/config/modelProviders/zhipu.ts +2 -6
- package/src/config/server/provider.ts +1 -1
- package/src/database/client/core/db.ts +32 -0
- package/src/database/client/core/schemas.ts +9 -0
- package/src/database/client/models/__tests__/message.test.ts +2 -2
- package/src/database/client/schemas/message.ts +8 -1
- package/src/features/AgentSetting/store/action.ts +15 -6
- package/src/features/Conversation/Actions/Tool.tsx +16 -0
- package/src/features/Conversation/Actions/index.ts +2 -2
- package/src/features/Conversation/Messages/Assistant/ToolCalls/index.tsx +78 -0
- package/src/features/Conversation/Messages/Assistant/ToolCalls/style.ts +25 -0
- package/src/features/Conversation/Messages/Assistant/index.tsx +47 -0
- package/src/features/Conversation/Messages/Default.tsx +4 -1
- package/src/features/Conversation/{Plugins → Messages/Tool}/Inspector/index.tsx +34 -35
- package/src/features/Conversation/Messages/Tool/index.tsx +44 -0
- package/src/features/Conversation/Messages/index.ts +3 -2
- package/src/features/Conversation/Plugins/Render/StandaloneType/Iframe.tsx +1 -1
- package/src/features/Conversation/components/SkeletonList.tsx +2 -2
- package/src/features/Conversation/index.tsx +2 -3
- package/src/libs/agent-runtime/BaseAI.ts +2 -9
- package/src/libs/agent-runtime/anthropic/index.test.ts +195 -0
- package/src/libs/agent-runtime/anthropic/index.ts +71 -15
- package/src/libs/agent-runtime/azureOpenai/index.ts +12 -13
- package/src/libs/agent-runtime/bedrock/index.ts +24 -18
- package/src/libs/agent-runtime/google/index.test.ts +154 -0
- package/src/libs/agent-runtime/google/index.ts +91 -10
- package/src/libs/agent-runtime/groq/index.test.ts +41 -72
- package/src/libs/agent-runtime/groq/index.ts +7 -0
- package/src/libs/agent-runtime/minimax/index.test.ts +2 -2
- package/src/libs/agent-runtime/minimax/index.ts +14 -37
- package/src/libs/agent-runtime/mistral/index.test.ts +0 -53
- package/src/libs/agent-runtime/mistral/index.ts +1 -0
- package/src/libs/agent-runtime/moonshot/index.test.ts +1 -71
- package/src/libs/agent-runtime/ollama/index.test.ts +197 -0
- package/src/libs/agent-runtime/ollama/index.ts +3 -3
- package/src/libs/agent-runtime/openai/index.test.ts +0 -53
- package/src/libs/agent-runtime/openrouter/index.test.ts +1 -53
- package/src/libs/agent-runtime/perplexity/index.test.ts +0 -71
- package/src/libs/agent-runtime/perplexity/index.ts +2 -3
- package/src/libs/agent-runtime/togetherai/__snapshots__/index.test.ts.snap +886 -0
- package/src/libs/agent-runtime/togetherai/fixtures/models.json +8111 -0
- package/src/libs/agent-runtime/togetherai/index.test.ts +16 -54
- package/src/libs/agent-runtime/types/chat.ts +19 -3
- package/src/libs/agent-runtime/utils/anthropicHelpers.test.ts +120 -1
- package/src/libs/agent-runtime/utils/anthropicHelpers.ts +67 -4
- package/src/libs/agent-runtime/utils/debugStream.test.ts +70 -0
- package/src/libs/agent-runtime/utils/debugStream.ts +39 -9
- package/src/libs/agent-runtime/utils/openaiCompatibleFactory/index.test.ts +521 -0
- package/src/libs/agent-runtime/utils/openaiCompatibleFactory/index.ts +76 -5
- package/src/libs/agent-runtime/utils/response.ts +12 -0
- package/src/libs/agent-runtime/utils/streams/anthropic.test.ts +197 -0
- package/src/libs/agent-runtime/utils/streams/anthropic.ts +91 -0
- package/src/libs/agent-runtime/utils/streams/bedrock/claude.ts +21 -0
- package/src/libs/agent-runtime/utils/streams/bedrock/common.ts +32 -0
- package/src/libs/agent-runtime/utils/streams/bedrock/index.ts +3 -0
- package/src/libs/agent-runtime/utils/streams/bedrock/llama.test.ts +196 -0
- package/src/libs/agent-runtime/utils/streams/bedrock/llama.ts +51 -0
- package/src/libs/agent-runtime/utils/streams/google-ai.test.ts +97 -0
- package/src/libs/agent-runtime/utils/streams/google-ai.ts +68 -0
- package/src/libs/agent-runtime/utils/streams/index.ts +7 -0
- package/src/libs/agent-runtime/utils/streams/minimax.ts +39 -0
- package/src/libs/agent-runtime/utils/streams/ollama.test.ts +77 -0
- package/src/libs/agent-runtime/utils/streams/ollama.ts +38 -0
- package/src/libs/agent-runtime/utils/streams/openai.test.ts +263 -0
- package/src/libs/agent-runtime/utils/streams/openai.ts +79 -0
- package/src/libs/agent-runtime/utils/streams/protocol.ts +100 -0
- package/src/libs/agent-runtime/zeroone/index.test.ts +1 -53
- package/src/libs/agent-runtime/zhipu/index.test.ts +1 -1
- package/src/libs/agent-runtime/zhipu/index.ts +3 -2
- package/src/locales/default/plugin.ts +3 -4
- package/src/migrations/FromV4ToV5/fixtures/from-v1-to-v5-output.json +245 -0
- package/src/migrations/FromV4ToV5/fixtures/function-input-v4.json +96 -0
- package/src/migrations/FromV4ToV5/fixtures/function-output-v5.json +120 -0
- package/src/migrations/FromV4ToV5/index.ts +58 -0
- package/src/migrations/FromV4ToV5/migrations.test.ts +49 -0
- package/src/migrations/FromV4ToV5/types/v4.ts +21 -0
- package/src/migrations/FromV4ToV5/types/v5.ts +27 -0
- package/src/migrations/index.ts +8 -1
- package/src/services/__tests__/chat.test.ts +10 -20
- package/src/services/chat.ts +78 -65
- package/src/store/chat/slices/enchance/action.ts +15 -10
- package/src/store/chat/slices/message/action.test.ts +36 -86
- package/src/store/chat/slices/message/action.ts +70 -79
- package/src/store/chat/slices/message/reducer.ts +18 -1
- package/src/store/chat/slices/message/selectors.test.ts +38 -68
- package/src/store/chat/slices/message/selectors.ts +1 -22
- package/src/store/chat/slices/plugin/action.test.ts +147 -203
- package/src/store/chat/slices/plugin/action.ts +96 -82
- package/src/store/chat/slices/share/action.test.ts +3 -3
- package/src/store/chat/slices/share/action.ts +1 -1
- package/src/store/chat/slices/topic/action.ts +7 -2
- package/src/store/tool/selectors/tool.ts +6 -24
- package/src/store/tool/slices/builtin/action.test.ts +90 -0
- package/src/types/llm.ts +1 -1
- package/src/types/message/index.ts +9 -4
- package/src/types/message/tools.ts +57 -0
- package/src/types/openai/chat.ts +6 -0
- package/src/utils/fetch.test.ts +245 -1
- package/src/utils/fetch.ts +120 -44
- package/src/utils/toolCall.ts +21 -0
- package/src/features/Conversation/Messages/Assistant.tsx +0 -26
- package/src/features/Conversation/Messages/Function.tsx +0 -35
- package/src/libs/agent-runtime/ollama/stream.ts +0 -31
- /package/src/features/Conversation/{Plugins → Messages/Tool}/Inspector/PluginResultJSON.tsx +0 -0
- /package/src/features/Conversation/{Plugins → Messages/Tool}/Inspector/Settings.tsx +0 -0
- /package/src/features/Conversation/{Plugins → Messages/Tool}/Inspector/style.ts +0 -0
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
import OpenAI from 'openai';
|
|
3
|
+
import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
AgentRuntimeErrorType,
|
|
7
|
+
ChatStreamCallbacks,
|
|
8
|
+
LobeOpenAICompatibleRuntime,
|
|
9
|
+
ModelProvider,
|
|
10
|
+
} from '@/libs/agent-runtime';
|
|
11
|
+
|
|
12
|
+
import * as debugStreamModule from '../debugStream';
|
|
13
|
+
import { LobeOpenAICompatibleFactory } from './index';
|
|
14
|
+
|
|
15
|
+
const provider = 'groq';
|
|
16
|
+
const defaultBaseURL = 'https://api.groq.com/openai/v1';
|
|
17
|
+
const bizErrorType = 'GroqBizError';
|
|
18
|
+
const invalidErrorType = 'InvalidGroqAPIKey';
|
|
19
|
+
|
|
20
|
+
// Mock the console.error to avoid polluting test output
|
|
21
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
22
|
+
|
|
23
|
+
let instance: LobeOpenAICompatibleRuntime;
|
|
24
|
+
|
|
25
|
+
const LobeMockProvider = LobeOpenAICompatibleFactory({
|
|
26
|
+
baseURL: defaultBaseURL,
|
|
27
|
+
chatCompletion: {
|
|
28
|
+
handleError: (error) => {
|
|
29
|
+
// 403 means the location is not supporteds
|
|
30
|
+
if (error.status === 403)
|
|
31
|
+
return { error, errorType: AgentRuntimeErrorType.LocationNotSupportError };
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
debug: {
|
|
35
|
+
chatCompletion: () => process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION === '1',
|
|
36
|
+
},
|
|
37
|
+
errorType: {
|
|
38
|
+
bizError: AgentRuntimeErrorType.GroqBizError,
|
|
39
|
+
invalidAPIKey: AgentRuntimeErrorType.InvalidGroqAPIKey,
|
|
40
|
+
},
|
|
41
|
+
provider: ModelProvider.Groq,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
instance = new LobeMockProvider({ apiKey: 'test' });
|
|
46
|
+
|
|
47
|
+
// 使用 vi.spyOn 来模拟 chat.completions.create 方法
|
|
48
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
|
|
49
|
+
new ReadableStream() as any,
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
afterEach(() => {
|
|
54
|
+
vi.clearAllMocks();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('LobeOpenAICompatibleFactory', () => {
|
|
58
|
+
describe('init', () => {
|
|
59
|
+
it('should correctly initialize with an API key', async () => {
|
|
60
|
+
const instance = new LobeMockProvider({ apiKey: 'test_api_key' });
|
|
61
|
+
expect(instance).toBeInstanceOf(LobeMockProvider);
|
|
62
|
+
expect(instance.baseURL).toEqual(defaultBaseURL);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('chat', () => {
|
|
67
|
+
it('should return a Response on successful API call', async () => {
|
|
68
|
+
// Arrange
|
|
69
|
+
const mockStream = new ReadableStream();
|
|
70
|
+
const mockResponse = Promise.resolve(mockStream);
|
|
71
|
+
|
|
72
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
|
|
73
|
+
|
|
74
|
+
// Act
|
|
75
|
+
const result = await instance.chat({
|
|
76
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
77
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
78
|
+
temperature: 0,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Assert
|
|
82
|
+
expect(result).toBeInstanceOf(Response);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('should call chat API with corresponding options', async () => {
|
|
86
|
+
// Arrange
|
|
87
|
+
const mockStream = new ReadableStream();
|
|
88
|
+
const mockResponse = Promise.resolve(mockStream);
|
|
89
|
+
|
|
90
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
|
|
91
|
+
|
|
92
|
+
// Act
|
|
93
|
+
const result = await instance.chat({
|
|
94
|
+
max_tokens: 1024,
|
|
95
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
96
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
97
|
+
temperature: 0.7,
|
|
98
|
+
top_p: 1,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Assert
|
|
102
|
+
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
|
|
103
|
+
{
|
|
104
|
+
max_tokens: 1024,
|
|
105
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
106
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
107
|
+
temperature: 0.7,
|
|
108
|
+
stream: true,
|
|
109
|
+
top_p: 1,
|
|
110
|
+
},
|
|
111
|
+
{ headers: { Accept: '*/*' } },
|
|
112
|
+
);
|
|
113
|
+
expect(result).toBeInstanceOf(Response);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe('streaming response', () => {
|
|
117
|
+
it('should handle multiple data chunks correctly', async () => {
|
|
118
|
+
const mockStream = new ReadableStream({
|
|
119
|
+
start(controller) {
|
|
120
|
+
controller.enqueue({
|
|
121
|
+
id: 'a',
|
|
122
|
+
object: 'chat.completion.chunk',
|
|
123
|
+
created: 1709125675,
|
|
124
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
125
|
+
system_fingerprint: 'fp_86156a94a0',
|
|
126
|
+
choices: [
|
|
127
|
+
{ index: 0, delta: { content: 'hello' }, logprobs: null, finish_reason: null },
|
|
128
|
+
],
|
|
129
|
+
});
|
|
130
|
+
controller.close();
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
|
|
134
|
+
mockStream as any,
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
const result = await instance.chat({
|
|
138
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
139
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
140
|
+
temperature: 0,
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const decoder = new TextDecoder();
|
|
144
|
+
const reader = result.body!.getReader();
|
|
145
|
+
expect(decoder.decode((await reader.read()).value)).toEqual('id: a\n');
|
|
146
|
+
expect(decoder.decode((await reader.read()).value)).toEqual('event: text\n');
|
|
147
|
+
expect(decoder.decode((await reader.read()).value)).toEqual('data: "hello"\n\n');
|
|
148
|
+
expect((await reader.read()).done).toBe(true);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('should transform non-streaming response to stream correctly', async () => {
|
|
152
|
+
const mockResponse: OpenAI.ChatCompletion = {
|
|
153
|
+
id: 'a',
|
|
154
|
+
object: 'chat.completion',
|
|
155
|
+
created: 123,
|
|
156
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
157
|
+
choices: [
|
|
158
|
+
{
|
|
159
|
+
index: 0,
|
|
160
|
+
message: { role: 'assistant', content: 'Hello' },
|
|
161
|
+
finish_reason: 'stop',
|
|
162
|
+
logprobs: null,
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
usage: {
|
|
166
|
+
prompt_tokens: 5,
|
|
167
|
+
completion_tokens: 5,
|
|
168
|
+
total_tokens: 10,
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
|
|
172
|
+
mockResponse as any,
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const result = await instance.chat({
|
|
176
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
177
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
178
|
+
temperature: 0,
|
|
179
|
+
stream: false,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const decoder = new TextDecoder();
|
|
183
|
+
|
|
184
|
+
const reader = result.body!.getReader();
|
|
185
|
+
expect(decoder.decode((await reader.read()).value)).toContain('id: a\n');
|
|
186
|
+
expect(decoder.decode((await reader.read()).value)).toContain('event: text\n');
|
|
187
|
+
expect(decoder.decode((await reader.read()).value)).toContain('data: "Hello"\n\n');
|
|
188
|
+
|
|
189
|
+
expect(decoder.decode((await reader.read()).value)).toContain('id: a\n');
|
|
190
|
+
expect(decoder.decode((await reader.read()).value)).toContain('event: text\n');
|
|
191
|
+
expect(decoder.decode((await reader.read()).value)).toContain('');
|
|
192
|
+
|
|
193
|
+
expect((await reader.read()).done).toBe(true);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe('handlePayload option', () => {
|
|
198
|
+
it('should modify request payload correctly', async () => {
|
|
199
|
+
const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');
|
|
200
|
+
|
|
201
|
+
await instance.chat({
|
|
202
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
203
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
204
|
+
temperature: 0,
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
expect(mockCreateMethod).toHaveBeenCalledWith(
|
|
208
|
+
expect.objectContaining({
|
|
209
|
+
// 根据实际的 handlePayload 函数,添加断言
|
|
210
|
+
}),
|
|
211
|
+
expect.anything(),
|
|
212
|
+
);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
describe('cancel request', () => {
|
|
217
|
+
it('should cancel ongoing request correctly', async () => {
|
|
218
|
+
const controller = new AbortController();
|
|
219
|
+
const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');
|
|
220
|
+
|
|
221
|
+
instance.chat(
|
|
222
|
+
{
|
|
223
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
224
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
225
|
+
temperature: 0,
|
|
226
|
+
},
|
|
227
|
+
{ signal: controller.signal },
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
controller.abort();
|
|
231
|
+
|
|
232
|
+
expect(mockCreateMethod).toHaveBeenCalledWith(
|
|
233
|
+
expect.anything(),
|
|
234
|
+
expect.objectContaining({
|
|
235
|
+
signal: controller.signal,
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
describe('Error', () => {
|
|
242
|
+
it('should return bizErrorType with an openai error response when OpenAI.APIError is thrown', async () => {
|
|
243
|
+
// Arrange
|
|
244
|
+
const apiError = new OpenAI.APIError(
|
|
245
|
+
400,
|
|
246
|
+
{
|
|
247
|
+
status: 400,
|
|
248
|
+
error: {
|
|
249
|
+
message: 'Bad Request',
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
'Error message',
|
|
253
|
+
{},
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
|
257
|
+
|
|
258
|
+
// Act
|
|
259
|
+
try {
|
|
260
|
+
await instance.chat({
|
|
261
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
262
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
263
|
+
temperature: 0,
|
|
264
|
+
});
|
|
265
|
+
} catch (e) {
|
|
266
|
+
expect(e).toEqual({
|
|
267
|
+
endpoint: defaultBaseURL,
|
|
268
|
+
error: {
|
|
269
|
+
error: { message: 'Bad Request' },
|
|
270
|
+
status: 400,
|
|
271
|
+
},
|
|
272
|
+
errorType: bizErrorType,
|
|
273
|
+
provider,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('should throw AgentRuntimeError with invalidErrorType if no apiKey is provided', async () => {
|
|
279
|
+
try {
|
|
280
|
+
new LobeMockProvider({});
|
|
281
|
+
} catch (e) {
|
|
282
|
+
expect(e).toEqual({ errorType: invalidErrorType });
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it('should return bizErrorType with the cause when OpenAI.APIError is thrown with cause', async () => {
|
|
287
|
+
// Arrange
|
|
288
|
+
const errorInfo = {
|
|
289
|
+
stack: 'abc',
|
|
290
|
+
cause: {
|
|
291
|
+
message: 'api is undefined',
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
|
295
|
+
|
|
296
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
|
297
|
+
|
|
298
|
+
// Act
|
|
299
|
+
try {
|
|
300
|
+
await instance.chat({
|
|
301
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
302
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
303
|
+
temperature: 0,
|
|
304
|
+
});
|
|
305
|
+
} catch (e) {
|
|
306
|
+
expect(e).toEqual({
|
|
307
|
+
endpoint: defaultBaseURL,
|
|
308
|
+
error: {
|
|
309
|
+
cause: { message: 'api is undefined' },
|
|
310
|
+
stack: 'abc',
|
|
311
|
+
},
|
|
312
|
+
errorType: bizErrorType,
|
|
313
|
+
provider,
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it('should return bizErrorType with an cause response with desensitize Url', async () => {
|
|
319
|
+
// Arrange
|
|
320
|
+
const errorInfo = {
|
|
321
|
+
stack: 'abc',
|
|
322
|
+
cause: { message: 'api is undefined' },
|
|
323
|
+
};
|
|
324
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
|
325
|
+
|
|
326
|
+
instance = new LobeMockProvider({
|
|
327
|
+
apiKey: 'test',
|
|
328
|
+
|
|
329
|
+
baseURL: 'https://api.abc.com/v1',
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
|
333
|
+
|
|
334
|
+
// Act
|
|
335
|
+
try {
|
|
336
|
+
await instance.chat({
|
|
337
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
338
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
339
|
+
temperature: 0,
|
|
340
|
+
});
|
|
341
|
+
} catch (e) {
|
|
342
|
+
expect(e).toEqual({
|
|
343
|
+
endpoint: 'https://api.***.com/v1',
|
|
344
|
+
error: {
|
|
345
|
+
cause: { message: 'api is undefined' },
|
|
346
|
+
stack: 'abc',
|
|
347
|
+
},
|
|
348
|
+
errorType: bizErrorType,
|
|
349
|
+
provider,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
describe('handleError option', () => {
|
|
355
|
+
it('should return correct error type for 403 status code', async () => {
|
|
356
|
+
const error = { status: 403 };
|
|
357
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(error);
|
|
358
|
+
|
|
359
|
+
try {
|
|
360
|
+
await instance.chat({
|
|
361
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
362
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
363
|
+
temperature: 0,
|
|
364
|
+
});
|
|
365
|
+
} catch (e) {
|
|
366
|
+
expect(e).toEqual({
|
|
367
|
+
error,
|
|
368
|
+
errorType: AgentRuntimeErrorType.LocationNotSupportError,
|
|
369
|
+
provider,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it('should throw an InvalidOpenRouterAPIKey error type on 401 status code', async () => {
|
|
376
|
+
// Mock the API call to simulate a 401 error
|
|
377
|
+
const error = new Error('Unauthorized') as any;
|
|
378
|
+
error.status = 401;
|
|
379
|
+
vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
|
|
380
|
+
|
|
381
|
+
try {
|
|
382
|
+
await instance.chat({
|
|
383
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
384
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
385
|
+
temperature: 0,
|
|
386
|
+
});
|
|
387
|
+
} catch (e) {
|
|
388
|
+
// Expect the chat method to throw an error with InvalidMoonshotAPIKey
|
|
389
|
+
expect(e).toEqual({
|
|
390
|
+
endpoint: defaultBaseURL,
|
|
391
|
+
error: new Error('Unauthorized'),
|
|
392
|
+
errorType: invalidErrorType,
|
|
393
|
+
provider,
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
it('should return AgentRuntimeError for non-OpenAI errors', async () => {
|
|
399
|
+
// Arrange
|
|
400
|
+
const genericError = new Error('Generic Error');
|
|
401
|
+
|
|
402
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
|
|
403
|
+
|
|
404
|
+
// Act
|
|
405
|
+
try {
|
|
406
|
+
await instance.chat({
|
|
407
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
408
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
409
|
+
temperature: 0,
|
|
410
|
+
});
|
|
411
|
+
} catch (e) {
|
|
412
|
+
expect(e).toEqual({
|
|
413
|
+
endpoint: defaultBaseURL,
|
|
414
|
+
errorType: 'AgentRuntimeError',
|
|
415
|
+
provider,
|
|
416
|
+
error: {
|
|
417
|
+
name: genericError.name,
|
|
418
|
+
cause: genericError.cause,
|
|
419
|
+
message: genericError.message,
|
|
420
|
+
stack: genericError.stack,
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
describe('chat with callback and headers', () => {
|
|
428
|
+
it('should handle callback and headers correctly', async () => {
|
|
429
|
+
// 模拟 chat.completions.create 方法返回一个可读流
|
|
430
|
+
const mockCreateMethod = vi
|
|
431
|
+
.spyOn(instance['client'].chat.completions, 'create')
|
|
432
|
+
.mockResolvedValue(
|
|
433
|
+
new ReadableStream({
|
|
434
|
+
start(controller) {
|
|
435
|
+
controller.enqueue({
|
|
436
|
+
id: 'chatcmpl-8xDx5AETP8mESQN7UB30GxTN2H1SO',
|
|
437
|
+
object: 'chat.completion.chunk',
|
|
438
|
+
created: 1709125675,
|
|
439
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
440
|
+
system_fingerprint: 'fp_86156a94a0',
|
|
441
|
+
choices: [
|
|
442
|
+
{ index: 0, delta: { content: 'hello' }, logprobs: null, finish_reason: null },
|
|
443
|
+
],
|
|
444
|
+
});
|
|
445
|
+
controller.close();
|
|
446
|
+
},
|
|
447
|
+
}) as any,
|
|
448
|
+
);
|
|
449
|
+
|
|
450
|
+
// 准备 callback 和 headers
|
|
451
|
+
const mockCallback: ChatStreamCallbacks = {
|
|
452
|
+
onStart: vi.fn(),
|
|
453
|
+
onToken: vi.fn(),
|
|
454
|
+
};
|
|
455
|
+
const mockHeaders = { 'Custom-Header': 'TestValue' };
|
|
456
|
+
|
|
457
|
+
// 执行测试
|
|
458
|
+
const result = await instance.chat(
|
|
459
|
+
{
|
|
460
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
461
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
462
|
+
temperature: 0,
|
|
463
|
+
},
|
|
464
|
+
{ callback: mockCallback, headers: mockHeaders },
|
|
465
|
+
);
|
|
466
|
+
|
|
467
|
+
// 验证 callback 被调用
|
|
468
|
+
await result.text(); // 确保流被消费
|
|
469
|
+
expect(mockCallback.onStart).toHaveBeenCalled();
|
|
470
|
+
expect(mockCallback.onToken).toHaveBeenCalledWith('hello');
|
|
471
|
+
|
|
472
|
+
// 验证 headers 被正确传递
|
|
473
|
+
expect(result.headers.get('Custom-Header')).toEqual('TestValue');
|
|
474
|
+
|
|
475
|
+
// 清理
|
|
476
|
+
mockCreateMethod.mockRestore();
|
|
477
|
+
});
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
describe('DEBUG', () => {
|
|
481
|
+
it('should call debugStream and return StreamingTextResponse when DEBUG_OPENROUTER_CHAT_COMPLETION is 1', async () => {
|
|
482
|
+
// Arrange
|
|
483
|
+
const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
|
|
484
|
+
const mockDebugStream = new ReadableStream({
|
|
485
|
+
start(controller) {
|
|
486
|
+
controller.enqueue('Debug stream content');
|
|
487
|
+
controller.close();
|
|
488
|
+
},
|
|
489
|
+
}) as any;
|
|
490
|
+
mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
|
|
491
|
+
|
|
492
|
+
// 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
|
|
493
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue({
|
|
494
|
+
tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
// 保存原始环境变量值
|
|
498
|
+
const originalDebugValue = process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION;
|
|
499
|
+
|
|
500
|
+
// 模拟环境变量
|
|
501
|
+
process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION = '1';
|
|
502
|
+
vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
|
|
503
|
+
|
|
504
|
+
// 执行测试
|
|
505
|
+
// 运行你的测试函数,确保它会在条件满足时调用 debugStream
|
|
506
|
+
// 假设的测试函数调用,你可能需要根据实际情况调整
|
|
507
|
+
await instance.chat({
|
|
508
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
509
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
510
|
+
temperature: 0,
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
// 验证 debugStream 被调用
|
|
514
|
+
expect(debugStreamModule.debugStream).toHaveBeenCalled();
|
|
515
|
+
|
|
516
|
+
// 恢复原始环境变量值
|
|
517
|
+
process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION = originalDebugValue;
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
});
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { OpenAIStream, StreamingTextResponse } from 'ai';
|
|
2
1
|
import OpenAI, { ClientOptions } from 'openai';
|
|
3
2
|
|
|
4
3
|
import { LOBE_DEFAULT_MODEL_LIST } from '@/config/modelProviders';
|
|
@@ -11,6 +10,8 @@ import { AgentRuntimeError } from '../createError';
|
|
|
11
10
|
import { debugStream } from '../debugStream';
|
|
12
11
|
import { desensitizeUrl } from '../desensitizeUrl';
|
|
13
12
|
import { handleOpenAIError } from '../handleOpenAIError';
|
|
13
|
+
import { StreamingResponse } from '../response';
|
|
14
|
+
import { OpenAIStream } from '../streams';
|
|
14
15
|
|
|
15
16
|
// the model contains the following keywords is not a chat model, so we should filter them out
|
|
16
17
|
const CHAT_MODELS_BLOCK_LIST = [
|
|
@@ -72,7 +73,10 @@ export const LobeOpenAICompatibleFactory = ({
|
|
|
72
73
|
try {
|
|
73
74
|
const postPayload = chatCompletion?.handlePayload
|
|
74
75
|
? chatCompletion.handlePayload(payload)
|
|
75
|
-
: (
|
|
76
|
+
: ({
|
|
77
|
+
...payload,
|
|
78
|
+
stream: payload.stream ?? true,
|
|
79
|
+
} as OpenAI.ChatCompletionCreateParamsStreaming);
|
|
76
80
|
|
|
77
81
|
const response = await this.client.chat.completions.create(postPayload, {
|
|
78
82
|
// https://github.com/lobehub/lobe-chat/pull/318
|
|
@@ -80,13 +84,26 @@ export const LobeOpenAICompatibleFactory = ({
|
|
|
80
84
|
signal: options?.signal,
|
|
81
85
|
});
|
|
82
86
|
|
|
83
|
-
|
|
87
|
+
if (postPayload.stream) {
|
|
88
|
+
const [prod, useForDebug] = response.tee();
|
|
89
|
+
|
|
90
|
+
if (debug?.chatCompletion?.()) {
|
|
91
|
+
debugStream(useForDebug.toReadableStream()).catch(console.error);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return StreamingResponse(OpenAIStream(prod, options?.callback), {
|
|
95
|
+
headers: options?.headers,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
84
98
|
|
|
85
99
|
if (debug?.chatCompletion?.()) {
|
|
86
|
-
|
|
100
|
+
console.log('\n[no stream response]\n');
|
|
101
|
+
console.log(JSON.stringify(response) + '\n');
|
|
87
102
|
}
|
|
88
103
|
|
|
89
|
-
|
|
104
|
+
const stream = this.transformResponseToStream(response as unknown as OpenAI.ChatCompletion);
|
|
105
|
+
|
|
106
|
+
return StreamingResponse(OpenAIStream(stream, options?.callback), {
|
|
90
107
|
headers: options?.headers,
|
|
91
108
|
});
|
|
92
109
|
} catch (error) {
|
|
@@ -160,4 +177,58 @@ export const LobeOpenAICompatibleFactory = ({
|
|
|
160
177
|
|
|
161
178
|
.filter(Boolean) as ChatModelCard[];
|
|
162
179
|
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* make the OpenAI response data as a stream
|
|
183
|
+
* @private
|
|
184
|
+
*/
|
|
185
|
+
private transformResponseToStream(data: OpenAI.ChatCompletion) {
|
|
186
|
+
return new ReadableStream({
|
|
187
|
+
start(controller) {
|
|
188
|
+
const chunk: OpenAI.ChatCompletionChunk = {
|
|
189
|
+
choices: data.choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
|
|
190
|
+
delta: {
|
|
191
|
+
content: choice.message.content,
|
|
192
|
+
role: choice.message.role,
|
|
193
|
+
tool_calls: choice.message.tool_calls?.map(
|
|
194
|
+
(tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => ({
|
|
195
|
+
function: tool.function,
|
|
196
|
+
id: tool.id,
|
|
197
|
+
index,
|
|
198
|
+
type: tool.type,
|
|
199
|
+
}),
|
|
200
|
+
),
|
|
201
|
+
},
|
|
202
|
+
finish_reason: null,
|
|
203
|
+
index: choice.index,
|
|
204
|
+
logprobs: choice.logprobs,
|
|
205
|
+
})),
|
|
206
|
+
created: data.created,
|
|
207
|
+
id: data.id,
|
|
208
|
+
model: data.model,
|
|
209
|
+
object: 'chat.completion.chunk',
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
controller.enqueue(chunk);
|
|
213
|
+
|
|
214
|
+
controller.enqueue({
|
|
215
|
+
choices: data.choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
|
|
216
|
+
delta: {
|
|
217
|
+
content: choice.message.content,
|
|
218
|
+
role: choice.message.role,
|
|
219
|
+
},
|
|
220
|
+
finish_reason: choice.finish_reason,
|
|
221
|
+
index: choice.index,
|
|
222
|
+
logprobs: choice.logprobs,
|
|
223
|
+
})),
|
|
224
|
+
created: data.created,
|
|
225
|
+
id: data.id,
|
|
226
|
+
model: data.model,
|
|
227
|
+
object: 'chat.completion.chunk',
|
|
228
|
+
system_fingerprint: data.system_fingerprint,
|
|
229
|
+
} as OpenAI.ChatCompletionChunk);
|
|
230
|
+
controller.close();
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
}
|
|
163
234
|
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const StreamingResponse = (
|
|
2
|
+
stream: ReadableStream,
|
|
3
|
+
options?: { headers?: Record<string, string> },
|
|
4
|
+
) => {
|
|
5
|
+
return new Response(stream, {
|
|
6
|
+
headers: {
|
|
7
|
+
'Cache-Control': 'no-cache',
|
|
8
|
+
'Content-Type': 'text/event-stream',
|
|
9
|
+
...options?.headers,
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
};
|