@lobehub/chat 0.138.2 → 0.139.1
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/.env.example +6 -0
- package/CHANGELOG.md +50 -0
- package/Dockerfile +3 -0
- package/docs/self-hosting/environment-variables/model-provider.mdx +14 -4
- package/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx +8 -0
- package/docs/usage/features/agent-market.mdx +2 -0
- package/docs/usage/providers/groq.mdx +44 -0
- package/docs/usage/providers/groq.zh-CN.mdx +42 -0
- package/locales/ar/common.json +2 -1
- package/locales/ar/error.json +7 -1
- package/locales/ar/setting.json +16 -0
- package/locales/de-DE/common.json +2 -1
- package/locales/de-DE/error.json +7 -1
- package/locales/de-DE/setting.json +16 -0
- package/locales/en-US/common.json +2 -1
- package/locales/en-US/error.json +7 -1
- package/locales/en-US/setting.json +16 -0
- package/locales/es-ES/common.json +2 -1
- package/locales/es-ES/error.json +7 -1
- package/locales/es-ES/setting.json +16 -0
- package/locales/fr-FR/common.json +2 -1
- package/locales/fr-FR/error.json +7 -1
- package/locales/fr-FR/setting.json +16 -0
- package/locales/it-IT/common.json +2 -1
- package/locales/it-IT/error.json +7 -1
- package/locales/it-IT/setting.json +16 -0
- package/locales/ja-JP/common.json +2 -1
- package/locales/ja-JP/error.json +7 -1
- package/locales/ja-JP/setting.json +16 -0
- package/locales/ko-KR/common.json +2 -1
- package/locales/ko-KR/error.json +7 -1
- package/locales/ko-KR/setting.json +16 -0
- package/locales/nl-NL/common.json +2 -1
- package/locales/nl-NL/error.json +7 -1
- package/locales/nl-NL/setting.json +16 -0
- package/locales/pl-PL/common.json +2 -1
- package/locales/pl-PL/error.json +7 -1
- package/locales/pl-PL/setting.json +16 -0
- package/locales/pt-BR/common.json +2 -1
- package/locales/pt-BR/error.json +7 -1
- package/locales/pt-BR/setting.json +16 -0
- package/locales/ru-RU/common.json +2 -1
- package/locales/ru-RU/error.json +7 -1
- package/locales/ru-RU/setting.json +16 -0
- package/locales/tr-TR/common.json +2 -1
- package/locales/tr-TR/error.json +7 -1
- package/locales/tr-TR/setting.json +16 -0
- package/locales/vi-VN/common.json +2 -1
- package/locales/vi-VN/error.json +7 -1
- package/locales/vi-VN/setting.json +16 -0
- package/locales/zh-CN/common.json +2 -1
- package/locales/zh-CN/error.json +7 -1
- package/locales/zh-CN/setting.json +16 -0
- package/locales/zh-TW/common.json +2 -1
- package/locales/zh-TW/error.json +7 -1
- package/locales/zh-TW/setting.json +16 -0
- package/package.json +4 -4
- package/src/app/api/chat/[provider]/agentRuntime.test.ts +26 -0
- package/src/app/api/chat/[provider]/agentRuntime.ts +14 -0
- package/src/app/api/config/route.ts +2 -0
- package/src/app/api/errorResponse.test.ts +7 -0
- package/src/app/api/errorResponse.ts +3 -0
- package/src/app/settings/llm/OpenRouter/index.tsx +64 -0
- package/src/app/settings/llm/index.tsx +2 -0
- package/src/components/ModelProviderIcon/index.tsx +5 -0
- package/src/config/modelProviders/index.ts +3 -0
- package/src/config/modelProviders/openrouter.ts +44 -0
- package/src/config/server/provider.ts +8 -0
- package/src/const/settings.ts +4 -0
- package/src/features/Conversation/Error/APIKeyForm/OpenRouter.tsx +40 -0
- package/src/features/Conversation/Error/APIKeyForm/index.tsx +5 -0
- package/src/features/Conversation/Error/index.tsx +1 -0
- package/src/libs/agent-runtime/error.ts +3 -0
- package/src/libs/agent-runtime/index.ts +1 -0
- package/src/libs/agent-runtime/openrouter/index.test.ts +347 -0
- package/src/libs/agent-runtime/openrouter/index.ts +86 -0
- package/src/libs/agent-runtime/types/type.ts +1 -0
- package/src/locales/default/common.ts +1 -0
- package/src/locales/default/error.ts +7 -0
- package/src/locales/default/setting.ts +16 -0
- package/src/services/_auth.test.ts +10 -0
- package/src/services/_auth.ts +4 -0
- package/src/store/global/slices/settings/selectors/modelProvider.ts +14 -0
- package/src/types/settings/modelProvider.ts +7 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
import OpenAI from 'openai';
|
|
3
|
+
import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import { ChatStreamCallbacks } from '@/libs/agent-runtime';
|
|
6
|
+
|
|
7
|
+
import * as debugStreamModule from '../utils/debugStream';
|
|
8
|
+
import { LobeOpenRouterAI } from './index';
|
|
9
|
+
|
|
10
|
+
const provider = 'openrouter';
|
|
11
|
+
const defaultBaseURL = 'https://openrouter.ai/api/v1';
|
|
12
|
+
const bizErrorType = 'OpenRouterBizError';
|
|
13
|
+
const invalidErrorType = 'InvalidOpenRouterAPIKey';
|
|
14
|
+
|
|
15
|
+
// Mock the console.error to avoid polluting test output
|
|
16
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
17
|
+
|
|
18
|
+
let instance: LobeOpenRouterAI;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
instance = new LobeOpenRouterAI({ apiKey: 'test' });
|
|
22
|
+
|
|
23
|
+
// 使用 vi.spyOn 来模拟 chat.completions.create 方法
|
|
24
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
|
|
25
|
+
new ReadableStream() as any,
|
|
26
|
+
);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
vi.clearAllMocks();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('LobeOpenRouterAI', () => {
|
|
34
|
+
describe('init', () => {
|
|
35
|
+
it('should correctly initialize with an API key', async () => {
|
|
36
|
+
const instance = new LobeOpenRouterAI({ apiKey: 'test_api_key' });
|
|
37
|
+
expect(instance).toBeInstanceOf(LobeOpenRouterAI);
|
|
38
|
+
expect(instance.baseURL).toEqual(defaultBaseURL);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('chat', () => {
|
|
43
|
+
it('should return a StreamingTextResponse on successful API call', async () => {
|
|
44
|
+
// Arrange
|
|
45
|
+
const mockStream = new ReadableStream();
|
|
46
|
+
const mockResponse = Promise.resolve(mockStream);
|
|
47
|
+
|
|
48
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
|
|
49
|
+
|
|
50
|
+
// Act
|
|
51
|
+
const result = await instance.chat({
|
|
52
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
53
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
54
|
+
temperature: 0,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Assert
|
|
58
|
+
expect(result).toBeInstanceOf(Response);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('should call OpenRouter API with corresponding options', async () => {
|
|
62
|
+
// Arrange
|
|
63
|
+
const mockStream = new ReadableStream();
|
|
64
|
+
const mockResponse = Promise.resolve(mockStream);
|
|
65
|
+
|
|
66
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
|
|
67
|
+
|
|
68
|
+
// Act
|
|
69
|
+
const result = await instance.chat({
|
|
70
|
+
max_tokens: 1024,
|
|
71
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
72
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
73
|
+
temperature: 0.7,
|
|
74
|
+
top_p: 1,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// Assert
|
|
78
|
+
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith({
|
|
79
|
+
max_tokens: 1024,
|
|
80
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
81
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
82
|
+
temperature: 0.7,
|
|
83
|
+
top_p: 1,
|
|
84
|
+
})
|
|
85
|
+
expect(result).toBeInstanceOf(Response);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe('Error', () => {
|
|
89
|
+
it('should return OpenRouterBizError with an openai error response when OpenAI.APIError is thrown', async () => {
|
|
90
|
+
// Arrange
|
|
91
|
+
const apiError = new OpenAI.APIError(
|
|
92
|
+
400,
|
|
93
|
+
{
|
|
94
|
+
status: 400,
|
|
95
|
+
error: {
|
|
96
|
+
message: 'Bad Request',
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
'Error message',
|
|
100
|
+
{},
|
|
101
|
+
);
|
|
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: 'mistralai/mistral-7b-instruct:free',
|
|
110
|
+
temperature: 0,
|
|
111
|
+
});
|
|
112
|
+
} catch (e) {
|
|
113
|
+
expect(e).toEqual({
|
|
114
|
+
endpoint: defaultBaseURL,
|
|
115
|
+
error: {
|
|
116
|
+
error: { message: 'Bad Request' },
|
|
117
|
+
status: 400,
|
|
118
|
+
},
|
|
119
|
+
errorType: bizErrorType,
|
|
120
|
+
provider,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('should throw AgentRuntimeError with InvalidOpenRouterAPIKey if no apiKey is provided', async () => {
|
|
126
|
+
try {
|
|
127
|
+
new LobeOpenRouterAI({});
|
|
128
|
+
} catch (e) {
|
|
129
|
+
expect(e).toEqual({ errorType: invalidErrorType });
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('should return OpenRouterBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
|
|
134
|
+
// Arrange
|
|
135
|
+
const errorInfo = {
|
|
136
|
+
stack: 'abc',
|
|
137
|
+
cause: {
|
|
138
|
+
message: 'api is undefined',
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
|
142
|
+
|
|
143
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
|
144
|
+
|
|
145
|
+
// Act
|
|
146
|
+
try {
|
|
147
|
+
await instance.chat({
|
|
148
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
149
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
150
|
+
temperature: 0,
|
|
151
|
+
});
|
|
152
|
+
} catch (e) {
|
|
153
|
+
expect(e).toEqual({
|
|
154
|
+
endpoint: defaultBaseURL,
|
|
155
|
+
error: {
|
|
156
|
+
cause: { message: 'api is undefined' },
|
|
157
|
+
stack: 'abc',
|
|
158
|
+
},
|
|
159
|
+
errorType: bizErrorType,
|
|
160
|
+
provider,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('should return OpenRouterBizError with an cause response with desensitize Url', async () => {
|
|
166
|
+
// Arrange
|
|
167
|
+
const errorInfo = {
|
|
168
|
+
stack: 'abc',
|
|
169
|
+
cause: { message: 'api is undefined' },
|
|
170
|
+
};
|
|
171
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
|
172
|
+
|
|
173
|
+
instance = new LobeOpenRouterAI({
|
|
174
|
+
apiKey: 'test',
|
|
175
|
+
|
|
176
|
+
baseURL: 'https://api.abc.com/v1',
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
|
180
|
+
|
|
181
|
+
// Act
|
|
182
|
+
try {
|
|
183
|
+
await instance.chat({
|
|
184
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
185
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
186
|
+
temperature: 0,
|
|
187
|
+
});
|
|
188
|
+
} catch (e) {
|
|
189
|
+
expect(e).toEqual({
|
|
190
|
+
endpoint: 'https://api.***.com/v1',
|
|
191
|
+
error: {
|
|
192
|
+
cause: { message: 'api is undefined' },
|
|
193
|
+
stack: 'abc',
|
|
194
|
+
},
|
|
195
|
+
errorType: bizErrorType,
|
|
196
|
+
provider,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('should throw an InvalidOpenRouterAPIKey error type on 401 status code', async () => {
|
|
202
|
+
// Mock the API call to simulate a 401 error
|
|
203
|
+
const error = new Error('Unauthorized') as any;
|
|
204
|
+
error.status = 401;
|
|
205
|
+
vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
await instance.chat({
|
|
209
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
210
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
211
|
+
temperature: 0,
|
|
212
|
+
});
|
|
213
|
+
} catch (e) {
|
|
214
|
+
// Expect the chat method to throw an error with InvalidMoonshotAPIKey
|
|
215
|
+
expect(e).toEqual({
|
|
216
|
+
endpoint: defaultBaseURL,
|
|
217
|
+
error: new Error('Unauthorized'),
|
|
218
|
+
errorType: invalidErrorType,
|
|
219
|
+
provider,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('should return AgentRuntimeError for non-OpenAI errors', async () => {
|
|
225
|
+
// Arrange
|
|
226
|
+
const genericError = new Error('Generic Error');
|
|
227
|
+
|
|
228
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
|
|
229
|
+
|
|
230
|
+
// Act
|
|
231
|
+
try {
|
|
232
|
+
await instance.chat({
|
|
233
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
234
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
235
|
+
temperature: 0,
|
|
236
|
+
});
|
|
237
|
+
} catch (e) {
|
|
238
|
+
expect(e).toEqual({
|
|
239
|
+
endpoint: defaultBaseURL,
|
|
240
|
+
errorType: 'AgentRuntimeError',
|
|
241
|
+
provider,
|
|
242
|
+
error: {
|
|
243
|
+
name: genericError.name,
|
|
244
|
+
cause: genericError.cause,
|
|
245
|
+
message: genericError.message,
|
|
246
|
+
stack: genericError.stack,
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
describe('LobeOpenRouterAI chat with callback and headers', () => {
|
|
254
|
+
it('should handle callback and headers correctly', async () => {
|
|
255
|
+
// 模拟 chat.completions.create 方法返回一个可读流
|
|
256
|
+
const mockCreateMethod = vi
|
|
257
|
+
.spyOn(instance['client'].chat.completions, 'create')
|
|
258
|
+
.mockResolvedValue(
|
|
259
|
+
new ReadableStream({
|
|
260
|
+
start(controller) {
|
|
261
|
+
controller.enqueue({
|
|
262
|
+
id: 'chatcmpl-8xDx5AETP8mESQN7UB30GxTN2H1SO',
|
|
263
|
+
object: 'chat.completion.chunk',
|
|
264
|
+
created: 1709125675,
|
|
265
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
266
|
+
system_fingerprint: 'fp_86156a94a0',
|
|
267
|
+
choices: [
|
|
268
|
+
{ index: 0, delta: { content: 'hello' }, logprobs: null, finish_reason: null },
|
|
269
|
+
],
|
|
270
|
+
});
|
|
271
|
+
controller.close();
|
|
272
|
+
},
|
|
273
|
+
}) as any,
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
// 准备 callback 和 headers
|
|
277
|
+
const mockCallback: ChatStreamCallbacks = {
|
|
278
|
+
onStart: vi.fn(),
|
|
279
|
+
onToken: vi.fn(),
|
|
280
|
+
};
|
|
281
|
+
const mockHeaders = { 'Custom-Header': 'TestValue' };
|
|
282
|
+
|
|
283
|
+
// 执行测试
|
|
284
|
+
const result = await instance.chat(
|
|
285
|
+
{
|
|
286
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
287
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
288
|
+
temperature: 0,
|
|
289
|
+
},
|
|
290
|
+
{ callback: mockCallback, headers: mockHeaders },
|
|
291
|
+
);
|
|
292
|
+
|
|
293
|
+
// 验证 callback 被调用
|
|
294
|
+
await result.text(); // 确保流被消费
|
|
295
|
+
expect(mockCallback.onStart).toHaveBeenCalled();
|
|
296
|
+
expect(mockCallback.onToken).toHaveBeenCalledWith('hello');
|
|
297
|
+
|
|
298
|
+
// 验证 headers 被正确传递
|
|
299
|
+
expect(result.headers.get('Custom-Header')).toEqual('TestValue');
|
|
300
|
+
|
|
301
|
+
// 清理
|
|
302
|
+
mockCreateMethod.mockRestore();
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
describe('DEBUG', () => {
|
|
307
|
+
it('should call debugStream and return StreamingTextResponse when DEBUG_OPENROUTER_CHAT_COMPLETION is 1', async () => {
|
|
308
|
+
// Arrange
|
|
309
|
+
const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
|
|
310
|
+
const mockDebugStream = new ReadableStream({
|
|
311
|
+
start(controller) {
|
|
312
|
+
controller.enqueue('Debug stream content');
|
|
313
|
+
controller.close();
|
|
314
|
+
},
|
|
315
|
+
}) as any;
|
|
316
|
+
mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
|
|
317
|
+
|
|
318
|
+
// 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
|
|
319
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue({
|
|
320
|
+
tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// 保存原始环境变量值
|
|
324
|
+
const originalDebugValue = process.env.DEBUG_OPENROUTER_CHAT_COMPLETION;
|
|
325
|
+
|
|
326
|
+
// 模拟环境变量
|
|
327
|
+
process.env.DEBUG_OPENROUTER_CHAT_COMPLETION = '1';
|
|
328
|
+
vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
|
|
329
|
+
|
|
330
|
+
// 执行测试
|
|
331
|
+
// 运行你的测试函数,确保它会在条件满足时调用 debugStream
|
|
332
|
+
// 假设的测试函数调用,你可能需要根据实际情况调整
|
|
333
|
+
await instance.chat({
|
|
334
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
|
335
|
+
model: 'mistralai/mistral-7b-instruct:free',
|
|
336
|
+
temperature: 0,
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// 验证 debugStream 被调用
|
|
340
|
+
expect(debugStreamModule.debugStream).toHaveBeenCalled();
|
|
341
|
+
|
|
342
|
+
// 恢复原始环境变量值
|
|
343
|
+
process.env.DEBUG_OPENROUTER_CHAT_COMPLETION = originalDebugValue;
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { OpenAIStream, StreamingTextResponse } from 'ai';
|
|
2
|
+
import OpenAI, { ClientOptions } from 'openai';
|
|
3
|
+
|
|
4
|
+
import { LobeRuntimeAI } from '../BaseAI';
|
|
5
|
+
import { AgentRuntimeErrorType } from '../error';
|
|
6
|
+
import { ChatCompetitionOptions, ChatStreamPayload, ModelProvider } from '../types';
|
|
7
|
+
import { AgentRuntimeError } from '../utils/createError';
|
|
8
|
+
import { debugStream } from '../utils/debugStream';
|
|
9
|
+
import { desensitizeUrl } from '../utils/desensitizeUrl';
|
|
10
|
+
import { handleOpenAIError } from '../utils/handleOpenAIError';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';
|
|
13
|
+
|
|
14
|
+
export class LobeOpenRouterAI implements LobeRuntimeAI {
|
|
15
|
+
private client: OpenAI;
|
|
16
|
+
|
|
17
|
+
baseURL: string;
|
|
18
|
+
|
|
19
|
+
constructor({ apiKey, baseURL = DEFAULT_BASE_URL, ...res }: ClientOptions) {
|
|
20
|
+
if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidOpenRouterAPIKey);
|
|
21
|
+
|
|
22
|
+
this.client = new OpenAI({
|
|
23
|
+
apiKey,
|
|
24
|
+
baseURL,
|
|
25
|
+
defaultHeaders: {
|
|
26
|
+
"HTTP-Referer": "https://chat-preview.lobehub.com",
|
|
27
|
+
"X-Title": "Lobe Chat"
|
|
28
|
+
},
|
|
29
|
+
...res
|
|
30
|
+
});
|
|
31
|
+
this.baseURL = this.client.baseURL;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async chat(payload: ChatStreamPayload, options?: ChatCompetitionOptions) {
|
|
35
|
+
try {
|
|
36
|
+
const response = await this.client.chat.completions.create(
|
|
37
|
+
payload as unknown as OpenAI.ChatCompletionCreateParamsStreaming
|
|
38
|
+
);
|
|
39
|
+
const [prod, debug] = response.tee();
|
|
40
|
+
|
|
41
|
+
if (process.env.DEBUG_OPENROUTER_CHAT_COMPLETION === '1') {
|
|
42
|
+
debugStream(debug.toReadableStream()).catch(console.error);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return new StreamingTextResponse(OpenAIStream(prod, options?.callback), {
|
|
46
|
+
headers: options?.headers,
|
|
47
|
+
});
|
|
48
|
+
} catch (error) {
|
|
49
|
+
let desensitizedEndpoint = this.baseURL;
|
|
50
|
+
|
|
51
|
+
if (this.baseURL !== DEFAULT_BASE_URL) {
|
|
52
|
+
desensitizedEndpoint = desensitizeUrl(this.baseURL);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if ('status' in (error as any)) {
|
|
56
|
+
switch ((error as Response).status) {
|
|
57
|
+
case 401: {
|
|
58
|
+
throw AgentRuntimeError.chat({
|
|
59
|
+
endpoint: desensitizedEndpoint,
|
|
60
|
+
error: error as any,
|
|
61
|
+
errorType: AgentRuntimeErrorType.InvalidOpenRouterAPIKey,
|
|
62
|
+
provider: ModelProvider.OpenRouter,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
default: {
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const { errorResult, RuntimeError } = handleOpenAIError(error);
|
|
73
|
+
|
|
74
|
+
const errorType = RuntimeError || AgentRuntimeErrorType.OpenRouterBizError;
|
|
75
|
+
|
|
76
|
+
throw AgentRuntimeError.chat({
|
|
77
|
+
endpoint: desensitizedEndpoint,
|
|
78
|
+
error: errorResult,
|
|
79
|
+
errorType,
|
|
80
|
+
provider: ModelProvider.OpenRouter,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export default LobeOpenRouterAI;
|
|
@@ -84,6 +84,9 @@ export default {
|
|
|
84
84
|
|
|
85
85
|
InvalidGroqAPIKey: 'Groq API Key 不正确或为空,请检查 Groq API Key 后重试',
|
|
86
86
|
GroqBizError: '请求 Groq 服务出错,请根据以下信息排查或重试',
|
|
87
|
+
|
|
88
|
+
InvalidOpenRouterAPIKey: 'OpenRouter API Key 不正确或为空,请检查 OpenRouter API Key 后重试',
|
|
89
|
+
OpenRouterBizError: '请求 OpenRouter AI 服务出错,请根据以下信息排查或重试',
|
|
87
90
|
|
|
88
91
|
InvalidOllamaArgs: 'Ollama 配置不正确,请检查 Ollama 配置后重试',
|
|
89
92
|
OllamaBizError: '请求 Ollama 服务出错,请根据以下信息排查或重试',
|
|
@@ -131,6 +134,10 @@ export default {
|
|
|
131
134
|
description: '输入你的 OpenAI API Key 即可开始会话。应用不会记录你的 API Key',
|
|
132
135
|
title: '使用自定义 OpenAI API Key',
|
|
133
136
|
},
|
|
137
|
+
OpenRouter: {
|
|
138
|
+
description: '输入你的 OpenRouter API Key 即可开始会话。应用不会记录你的 API Key',
|
|
139
|
+
title: '使用自定义 OpenRouter API Key',
|
|
140
|
+
},
|
|
134
141
|
Perplexity: {
|
|
135
142
|
description: '输入你的 Perplexity API Key 即可开始会话。应用不会记录你的 API Key',
|
|
136
143
|
title: '使用自定义 Perplexity API Key',
|
|
@@ -178,6 +178,22 @@ export default {
|
|
|
178
178
|
title: 'Azure OpenAI',
|
|
179
179
|
},
|
|
180
180
|
},
|
|
181
|
+
OpenRouter: {
|
|
182
|
+
checker: {
|
|
183
|
+
desc: '测试代理地址是否正确填写',
|
|
184
|
+
},
|
|
185
|
+
customModelName: {
|
|
186
|
+
desc: '增加自定义模型,多个模型使用逗号(,)隔开',
|
|
187
|
+
placeholder: 'mistralai/mistral-7b-instruct:free,openchat/openchat-7b:free',
|
|
188
|
+
title: '自定义模型名称',
|
|
189
|
+
},
|
|
190
|
+
title: 'OpenRouter',
|
|
191
|
+
token: {
|
|
192
|
+
desc: '填入来自 OpenRouter AI 的 API Key',
|
|
193
|
+
placeholder: 'OpenRouter AI API Key',
|
|
194
|
+
title: 'API Key',
|
|
195
|
+
},
|
|
196
|
+
},
|
|
181
197
|
Perplexity: {
|
|
182
198
|
title: 'Perplexity',
|
|
183
199
|
token: {
|
|
@@ -13,6 +13,7 @@ const mockMoonshotAPIKey = 'moonshot-api-key';
|
|
|
13
13
|
const mockGoogleAPIKey = 'google-api-key';
|
|
14
14
|
const mockAnthropicAPIKey = 'anthropic-api-key';
|
|
15
15
|
const mockMistralAPIKey = 'mistral-api-key';
|
|
16
|
+
const mockOpenRouterAPIKey = 'openrouter-api-key';
|
|
16
17
|
|
|
17
18
|
// mock the traditional zustand
|
|
18
19
|
vi.mock('zustand/traditional');
|
|
@@ -63,6 +64,15 @@ describe('getProviderAuthPayload', () => {
|
|
|
63
64
|
expect(payload).toEqual({ apiKey: mockMistralAPIKey });
|
|
64
65
|
});
|
|
65
66
|
|
|
67
|
+
it('should return correct payload for OpenRouter provider', () => {
|
|
68
|
+
act(() => {
|
|
69
|
+
setModelProviderConfig('openrouter', { apiKey: mockOpenRouterAPIKey });
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const payload = getProviderAuthPayload(ModelProvider.OpenRouter);
|
|
73
|
+
expect(payload).toEqual({ apiKey: mockOpenRouterAPIKey });
|
|
74
|
+
});
|
|
75
|
+
|
|
66
76
|
it('should return correct payload for Google provider', () => {
|
|
67
77
|
act(() => {
|
|
68
78
|
setModelProviderConfig('google', { apiKey: mockGoogleAPIKey });
|
package/src/services/_auth.ts
CHANGED
|
@@ -65,6 +65,10 @@ export const getProviderAuthPayload = (provider: string) => {
|
|
|
65
65
|
case ModelProvider.Groq: {
|
|
66
66
|
return { apiKey: modelProviderSelectors.groqAPIKey(useGlobalStore.getState()) };
|
|
67
67
|
}
|
|
68
|
+
|
|
69
|
+
case ModelProvider.OpenRouter: {
|
|
70
|
+
return { apiKey: modelProviderSelectors.openrouterAPIKey(useGlobalStore.getState()) };
|
|
71
|
+
}
|
|
68
72
|
|
|
69
73
|
default:
|
|
70
74
|
case ModelProvider.OpenAI: {
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
MoonshotProvider,
|
|
11
11
|
OllamaProvider,
|
|
12
12
|
OpenAIProvider,
|
|
13
|
+
OpenRouterProvider,
|
|
13
14
|
PerplexityProvider,
|
|
14
15
|
ZhiPuProvider,
|
|
15
16
|
} from '@/config/modelProviders';
|
|
@@ -62,6 +63,9 @@ const anthropicProxyUrl = (s: GlobalStore) => modelProvider(s).anthropic.endpoin
|
|
|
62
63
|
const enableGroq = (s: GlobalStore) => modelProvider(s).groq.enabled;
|
|
63
64
|
const groqAPIKey = (s: GlobalStore) => modelProvider(s).groq.apiKey;
|
|
64
65
|
|
|
66
|
+
const enableOpenrouter = (s: GlobalStore) => modelProvider(s).openrouter.enabled;
|
|
67
|
+
const openrouterAPIKey = (s: GlobalStore) => modelProvider(s).openrouter.apiKey;
|
|
68
|
+
|
|
65
69
|
// const azureModelList = (s: GlobalStore): ModelProviderCard => {
|
|
66
70
|
// const azure = azureConfig(s);
|
|
67
71
|
// return {
|
|
@@ -141,6 +145,11 @@ const modelSelectList = (s: GlobalStore): ModelProviderCard[] => {
|
|
|
141
145
|
|
|
142
146
|
const ollamaChatModels = processChatModels(ollamaModelConfig, OllamaProvider.chatModels);
|
|
143
147
|
|
|
148
|
+
const openrouterModelConfig = parseModelString(
|
|
149
|
+
currentSettings(s).languageModel.openrouter.customModelName,
|
|
150
|
+
)
|
|
151
|
+
const openrouterChatModels = processChatModels(openrouterModelConfig, OpenRouterProvider.chatModels);
|
|
152
|
+
|
|
144
153
|
return [
|
|
145
154
|
{
|
|
146
155
|
...OpenAIProvider,
|
|
@@ -156,6 +165,7 @@ const modelSelectList = (s: GlobalStore): ModelProviderCard[] => {
|
|
|
156
165
|
{ ...GroqProvider, enabled: enableGroq(s) },
|
|
157
166
|
{ ...ZhiPuProvider, enabled: enableZhipu(s) },
|
|
158
167
|
{ ...MoonshotProvider, enabled: enableMoonshot(s) },
|
|
168
|
+
{ ...OpenRouterProvider, chatModels: openrouterChatModels, enabled: enableOpenrouter(s)}
|
|
159
169
|
];
|
|
160
170
|
};
|
|
161
171
|
|
|
@@ -242,4 +252,8 @@ export const modelProviderSelectors = {
|
|
|
242
252
|
// Groq
|
|
243
253
|
enableGroq,
|
|
244
254
|
groqAPIKey,
|
|
255
|
+
|
|
256
|
+
// OpenRouter
|
|
257
|
+
enableOpenrouter,
|
|
258
|
+
openrouterAPIKey,
|
|
245
259
|
};
|
|
@@ -76,6 +76,12 @@ export interface GroqConfig {
|
|
|
76
76
|
enabled: boolean;
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
export interface OpenRouterConfig {
|
|
80
|
+
apiKey?: string;
|
|
81
|
+
customModelName?: string;
|
|
82
|
+
enabled?: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
79
85
|
export interface GlobalLLMConfig {
|
|
80
86
|
anthropic: AnthropicConfig;
|
|
81
87
|
azure: AzureOpenAIConfig;
|
|
@@ -86,6 +92,7 @@ export interface GlobalLLMConfig {
|
|
|
86
92
|
moonshot: MoonshotConfig;
|
|
87
93
|
ollama: OllamaConfig;
|
|
88
94
|
openAI: OpenAIConfig;
|
|
95
|
+
openrouter: OpenRouterConfig;
|
|
89
96
|
perplexity: PerplexityConfig;
|
|
90
97
|
zhipu: ZhiPuConfig;
|
|
91
98
|
}
|