@lobehub/chat 1.68.9 → 1.68.11

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/changelog/v1.json +18 -0
  3. package/docs/usage/providers/ppio.mdx +5 -5
  4. package/docs/usage/providers/ppio.zh-CN.mdx +7 -7
  5. package/locales/ar/chat.json +5 -1
  6. package/locales/ar/models.json +12 -9
  7. package/locales/bg-BG/chat.json +5 -1
  8. package/locales/bg-BG/models.json +12 -9
  9. package/locales/de-DE/chat.json +5 -1
  10. package/locales/de-DE/models.json +12 -9
  11. package/locales/en-US/chat.json +5 -1
  12. package/locales/en-US/models.json +12 -9
  13. package/locales/es-ES/chat.json +5 -1
  14. package/locales/es-ES/models.json +12 -9
  15. package/locales/fa-IR/chat.json +5 -1
  16. package/locales/fa-IR/models.json +12 -9
  17. package/locales/fr-FR/chat.json +5 -1
  18. package/locales/fr-FR/models.json +12 -9
  19. package/locales/it-IT/chat.json +5 -1
  20. package/locales/it-IT/models.json +12 -9
  21. package/locales/ja-JP/chat.json +5 -1
  22. package/locales/ja-JP/models.json +12 -9
  23. package/locales/ko-KR/chat.json +5 -1
  24. package/locales/ko-KR/models.json +12 -9
  25. package/locales/nl-NL/chat.json +5 -1
  26. package/locales/nl-NL/models.json +12 -9
  27. package/locales/pl-PL/chat.json +5 -1
  28. package/locales/pl-PL/models.json +12 -9
  29. package/locales/pt-BR/chat.json +5 -1
  30. package/locales/pt-BR/models.json +12 -9
  31. package/locales/ru-RU/chat.json +5 -1
  32. package/locales/ru-RU/models.json +12 -9
  33. package/locales/tr-TR/chat.json +5 -1
  34. package/locales/tr-TR/models.json +12 -9
  35. package/locales/vi-VN/chat.json +5 -1
  36. package/locales/vi-VN/models.json +12 -9
  37. package/locales/zh-CN/chat.json +5 -1
  38. package/locales/zh-CN/models.json +12 -9
  39. package/locales/zh-TW/chat.json +5 -1
  40. package/locales/zh-TW/models.json +12 -9
  41. package/package.json +1 -1
  42. package/src/config/aiModels/google.ts +37 -0
  43. package/src/config/aiModels/perplexity.ts +36 -20
  44. package/src/config/aiModels/qwen.ts +64 -25
  45. package/src/config/modelProviders/ppio.ts +1 -1
  46. package/src/features/Conversation/Extras/Usage/UsageDetail/ModelCard.tsx +27 -9
  47. package/src/features/Conversation/Extras/Usage/UsageDetail/index.tsx +77 -35
  48. package/src/features/Conversation/Extras/Usage/UsageDetail/tokens.test.ts +253 -0
  49. package/src/features/Conversation/Extras/Usage/UsageDetail/tokens.ts +65 -46
  50. package/src/libs/agent-runtime/baichuan/index.test.ts +58 -1
  51. package/src/libs/agent-runtime/groq/index.test.ts +36 -284
  52. package/src/libs/agent-runtime/mistral/index.test.ts +39 -300
  53. package/src/libs/agent-runtime/perplexity/index.test.ts +12 -10
  54. package/src/libs/agent-runtime/providerTestUtils.ts +58 -0
  55. package/src/libs/agent-runtime/togetherai/index.test.ts +7 -295
  56. package/src/libs/agent-runtime/utils/openaiCompatibleFactory/index.test.ts +3 -0
  57. package/src/libs/agent-runtime/utils/openaiCompatibleFactory/index.ts +5 -2
  58. package/src/libs/agent-runtime/utils/streams/anthropic.test.ts +89 -5
  59. package/src/libs/agent-runtime/utils/streams/anthropic.ts +25 -8
  60. package/src/libs/agent-runtime/utils/streams/openai.test.ts +188 -84
  61. package/src/libs/agent-runtime/utils/streams/openai.ts +8 -17
  62. package/src/libs/agent-runtime/utils/usageConverter.test.ts +249 -0
  63. package/src/libs/agent-runtime/utils/usageConverter.ts +50 -0
  64. package/src/libs/agent-runtime/zeroone/index.test.ts +7 -294
  65. package/src/locales/default/chat.ts +4 -0
  66. package/src/types/message/base.ts +14 -4
  67. package/src/utils/filter.test.ts +0 -122
  68. package/src/utils/filter.ts +0 -29
@@ -1,299 +1,12 @@
1
1
  // @vitest-environment node
2
- import OpenAI from 'openai';
3
- import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { testProvider } from '@/libs/agent-runtime/providerTestUtils';
4
3
 
5
- import { ChatStreamCallbacks, LobeOpenAICompatibleRuntime } from '@/libs/agent-runtime';
6
-
7
- import * as debugStreamModule from '../utils/debugStream';
8
4
  import { LobeZeroOneAI } from './index';
9
5
 
10
- const provider = 'zeroone';
11
- const defaultBaseURL = 'https://api.lingyiwanwu.com/v1';
12
-
13
- const bizErrorType = 'ProviderBizError';
14
- const invalidErrorType = 'InvalidProviderAPIKey';
15
-
16
- // Mock the console.error to avoid polluting test output
17
- vi.spyOn(console, 'error').mockImplementation(() => {});
18
-
19
- let instance: LobeOpenAICompatibleRuntime;
20
-
21
- beforeEach(() => {
22
- instance = new LobeZeroOneAI({ apiKey: 'test' });
23
-
24
- // 使用 vi.spyOn 来模拟 chat.completions.create 方法
25
- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
26
- new ReadableStream() as any,
27
- );
28
- });
29
-
30
- afterEach(() => {
31
- vi.clearAllMocks();
32
- });
33
-
34
- describe('LobeZeroOneAI', () => {
35
- describe('init', () => {
36
- it('should correctly initialize with an API key', async () => {
37
- const instance = new LobeZeroOneAI({ apiKey: 'test_api_key' });
38
- expect(instance).toBeInstanceOf(LobeZeroOneAI);
39
- expect(instance.baseURL).toEqual(defaultBaseURL);
40
- });
41
- });
42
-
43
- describe('chat', () => {
44
- it('should return a StreamingTextResponse on successful API call', async () => {
45
- // Arrange
46
- const mockStream = new ReadableStream();
47
- const mockResponse = Promise.resolve(mockStream);
48
-
49
- (instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
50
-
51
- // Act
52
- const result = await instance.chat({
53
- messages: [{ content: 'Hello', role: 'user' }],
54
- model: 'yi-34b-chat-0205',
55
- temperature: 0,
56
- });
57
-
58
- // Assert
59
- expect(result).toBeInstanceOf(Response);
60
- });
61
-
62
- it('should call ZeroOne API with corresponding options', async () => {
63
- // Arrange
64
- const mockStream = new ReadableStream();
65
- const mockResponse = Promise.resolve(mockStream);
66
-
67
- (instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
68
-
69
- // Act
70
- const result = await instance.chat({
71
- max_tokens: 1024,
72
- messages: [{ content: 'Hello', role: 'user' }],
73
- model: 'yi-34b-chat-0205',
74
- temperature: 0.7,
75
- top_p: 1,
76
- });
77
-
78
- // Assert
79
- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
80
- {
81
- max_tokens: 1024,
82
- messages: [{ content: 'Hello', role: 'user' }],
83
- model: 'yi-34b-chat-0205',
84
- temperature: 0.7,
85
- stream: true,
86
- top_p: 1,
87
- },
88
- { headers: { Accept: '*/*' } },
89
- );
90
- expect(result).toBeInstanceOf(Response);
91
- });
92
-
93
- describe('Error', () => {
94
- it('should return ZeroOneBizError with an openai error response when OpenAI.APIError is thrown', async () => {
95
- // Arrange
96
- const apiError = new OpenAI.APIError(
97
- 400,
98
- {
99
- status: 400,
100
- error: {
101
- message: 'Bad Request',
102
- },
103
- },
104
- 'Error message',
105
- {},
106
- );
107
-
108
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
109
-
110
- // Act
111
- try {
112
- await instance.chat({
113
- messages: [{ content: 'Hello', role: 'user' }],
114
- model: 'yi-34b-chat-0205',
115
- temperature: 0,
116
- });
117
- } catch (e) {
118
- expect(e).toEqual({
119
- endpoint: defaultBaseURL,
120
- error: {
121
- error: { message: 'Bad Request' },
122
- status: 400,
123
- },
124
- errorType: bizErrorType,
125
- provider,
126
- });
127
- }
128
- });
129
-
130
- it('should throw AgentRuntimeError with InvalidZeroOneAPIKey if no apiKey is provided', async () => {
131
- try {
132
- new LobeZeroOneAI({});
133
- } catch (e) {
134
- expect(e).toEqual({ errorType: invalidErrorType });
135
- }
136
- });
137
-
138
- it('should return ZeroOneBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
139
- // Arrange
140
- const errorInfo = {
141
- stack: 'abc',
142
- cause: {
143
- message: 'api is undefined',
144
- },
145
- };
146
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
147
-
148
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
149
-
150
- // Act
151
- try {
152
- await instance.chat({
153
- messages: [{ content: 'Hello', role: 'user' }],
154
- model: 'yi-34b-chat-0205',
155
- temperature: 0,
156
- });
157
- } catch (e) {
158
- expect(e).toEqual({
159
- endpoint: defaultBaseURL,
160
- error: {
161
- cause: { message: 'api is undefined' },
162
- stack: 'abc',
163
- },
164
- errorType: bizErrorType,
165
- provider,
166
- });
167
- }
168
- });
169
-
170
- it('should return ZeroOneBizError with an cause response with desensitize Url', async () => {
171
- // Arrange
172
- const errorInfo = {
173
- stack: 'abc',
174
- cause: { message: 'api is undefined' },
175
- };
176
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
177
-
178
- instance = new LobeZeroOneAI({
179
- apiKey: 'test',
180
-
181
- baseURL: 'https://api.abc.com/v1',
182
- });
183
-
184
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
185
-
186
- // Act
187
- try {
188
- await instance.chat({
189
- messages: [{ content: 'Hello', role: 'user' }],
190
- model: 'yi-34b-chat-0205',
191
- temperature: 0,
192
- });
193
- } catch (e) {
194
- expect(e).toEqual({
195
- endpoint: 'https://api.***.com/v1',
196
- error: {
197
- cause: { message: 'api is undefined' },
198
- stack: 'abc',
199
- },
200
- errorType: bizErrorType,
201
- provider,
202
- });
203
- }
204
- });
205
-
206
- it('should throw an InvalidZeroOneAPIKey error type on 401 status code', async () => {
207
- // Mock the API call to simulate a 401 error
208
- const error = new Error('Unauthorized') as any;
209
- error.status = 401;
210
- vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
211
-
212
- try {
213
- await instance.chat({
214
- messages: [{ content: 'Hello', role: 'user' }],
215
- model: 'yi-34b-chat-0205',
216
- temperature: 0,
217
- });
218
- } catch (e) {
219
- // Expect the chat method to throw an error with InvalidMoonshotAPIKey
220
- expect(e).toEqual({
221
- endpoint: defaultBaseURL,
222
- error: new Error('Unauthorized'),
223
- errorType: invalidErrorType,
224
- provider,
225
- });
226
- }
227
- });
228
-
229
- it('should return AgentRuntimeError for non-OpenAI errors', async () => {
230
- // Arrange
231
- const genericError = new Error('Generic Error');
232
-
233
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
234
-
235
- // Act
236
- try {
237
- await instance.chat({
238
- messages: [{ content: 'Hello', role: 'user' }],
239
- model: 'yi-34b-chat-0205',
240
- temperature: 0,
241
- });
242
- } catch (e) {
243
- expect(e).toEqual({
244
- endpoint: defaultBaseURL,
245
- errorType: 'AgentRuntimeError',
246
- provider,
247
- error: {
248
- name: genericError.name,
249
- cause: genericError.cause,
250
- message: genericError.message,
251
- stack: genericError.stack,
252
- },
253
- });
254
- }
255
- });
256
- });
257
-
258
- describe('DEBUG', () => {
259
- it('should call debugStream and return StreamingTextResponse when DEBUG_ZEROONE_CHAT_COMPLETION is 1', async () => {
260
- // Arrange
261
- const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
262
- const mockDebugStream = new ReadableStream({
263
- start(controller) {
264
- controller.enqueue('Debug stream content');
265
- controller.close();
266
- },
267
- }) as any;
268
- mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
269
-
270
- // 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
271
- (instance['client'].chat.completions.create as Mock).mockResolvedValue({
272
- tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
273
- });
274
-
275
- // 保存原始环境变量值
276
- const originalDebugValue = process.env.DEBUG_ZEROONE_CHAT_COMPLETION;
277
-
278
- // 模拟环境变量
279
- process.env.DEBUG_ZEROONE_CHAT_COMPLETION = '1';
280
- vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
281
-
282
- // 执行测试
283
- // 运行你的测试函数,确保它会在条件满足时调用 debugStream
284
- // 假设的测试函数调用,你可能需要根据实际情况调整
285
- await instance.chat({
286
- messages: [{ content: 'Hello', role: 'user' }],
287
- model: 'yi-34b-chat-0205',
288
- temperature: 0,
289
- });
290
-
291
- // 验证 debugStream 被调用
292
- expect(debugStreamModule.debugStream).toHaveBeenCalled();
293
-
294
- // 恢复原始环境变量值
295
- process.env.DEBUG_ZEROONE_CHAT_COMPLETION = originalDebugValue;
296
- });
297
- });
298
- });
6
+ testProvider({
7
+ Runtime: LobeZeroOneAI,
8
+ provider: 'zeroone',
9
+ defaultBaseURL: 'https://api.lingyiwanwu.com/v1',
10
+ chatDebugEnv: 'DEBUG_ZEROONE_CHAT_COMPLETION',
11
+ chatModel: 'yi-34b-chat-0205',
299
12
  });
@@ -93,15 +93,19 @@ export default {
93
93
  inputMinutes: '${{amount}}/分钟',
94
94
  inputTokens: '输入 {{amount}}/积分 · ${{amount}}/M',
95
95
  outputTokens: '输出 {{amount}}/积分 · ${{amount}}/M',
96
+ writeCacheInputTokens: '缓存输入写入 {{amount}}/积分 · ${{amount}}/M',
96
97
  },
97
98
  },
98
99
  tokenDetails: {
100
+ average: '平均单价',
99
101
  input: '输入',
100
102
  inputAudio: '音频输入',
101
103
  inputCached: '输入缓存',
104
+ inputCitation: '引用输入',
102
105
  inputText: '文本输入',
103
106
  inputTitle: '输入明细',
104
107
  inputUncached: '输入未缓存',
108
+ inputWriteCached: '输入缓存写入',
105
109
  output: '输出',
106
110
  outputAudio: '音频输出',
107
111
  outputText: '文本输出',
@@ -15,14 +15,24 @@ export interface ModelReasoning {
15
15
 
16
16
  export interface ModelTokensUsage {
17
17
  acceptedPredictionTokens?: number;
18
- cachedTokens?: number;
19
18
  inputAudioTokens?: number;
20
19
  inputCacheMissTokens?: number;
21
- inputTokens?: number;
20
+ inputCachedTokens?: number;
21
+ /**
22
+ * currently only pplx has citation_tokens
23
+ */
24
+ inputCitationTokens?: number;
25
+ /**
26
+ * user prompt input
27
+ */
28
+ inputTextTokens?: number;
29
+ inputWriteCacheTokens?: number;
22
30
  outputAudioTokens?: number;
23
- outputTokens?: number;
24
- reasoningTokens?: number;
31
+ outputReasoningTokens?: number;
32
+ outputTextTokens?: number;
25
33
  rejectedPredictionTokens?: number;
34
+ totalInputTokens?: number;
35
+ totalOutputTokens?: number;
26
36
  totalTokens?: number;
27
37
  }
28
38
 
@@ -1,122 +0,0 @@
1
- import { test } from 'vitest';
2
-
3
- test('placeholder', () => {});
4
- // describe('filterWithKeywords', () => {
5
- // const data: Record<string, BaseDataModel> = {
6
- // 1: {
7
- // id: '1',
8
- // meta: {
9
- // title: 'hello world',
10
- // description: 'test case',
11
- // tag: ['a', 'b'],
12
- // },
13
- // },
14
- // 2: {
15
- // id: '2',
16
- // meta: {
17
- // title: 'goodbye',
18
- // description: 'hello world',
19
- // tag: ['c', 'd'],
20
- // },
21
- // },
22
- // };
23
- //
24
- // it('should return an empty object if map is empty', () => {
25
- // const result = filterWithKeywords({}, 'hello');
26
- // expect(result).toEqual({});
27
- // });
28
- //
29
- // it('should return the original map if keywords is empty', () => {
30
- // const result = filterWithKeywords(data, '');
31
- // expect(result).toEqual(data);
32
- // });
33
- //
34
- // it('should return a filtered map if keywords is not empty', () => {
35
- // const result = filterWithKeywords(data, 'world');
36
- // expect(result).toEqual({
37
- // 1: {
38
- // id: '1',
39
- // meta: {
40
- // title: 'hello world',
41
- // description: 'test case',
42
- // tag: ['a', 'b'],
43
- // },
44
- // },
45
- // 2: {
46
- // id: '2',
47
- // meta: {
48
- // title: 'goodbye',
49
- // description: 'hello world',
50
- // tag: ['c', 'd'],
51
- // },
52
- // },
53
- // });
54
- // });
55
- //
56
- // it('should only consider title, description and tag properties if extraSearchStr is not provided', () => {
57
- // const result = filterWithKeywords(data, 'test');
58
- // expect(result).toEqual({
59
- // 1: {
60
- // id: '1',
61
- // meta: {
62
- // title: 'hello world',
63
- // description: 'test case',
64
- // tag: ['a', 'b'],
65
- // },
66
- // },
67
- // });
68
- // });
69
- //
70
- // it('should consider extraSearchStr in addition to title, description and tag properties if provided', () => {
71
- // const extraSearchStr = (item: BaseDataModel) => {
72
- // return item.meta.avatar || '';
73
- // };
74
- // const data: Record<string, BaseDataModel> = {
75
- // a: {
76
- // id: 'a',
77
- // meta: {
78
- // title: 'hello world',
79
- // description: 'test case',
80
- // tag: ['a', 'b'],
81
- // avatar: 'xxx',
82
- // },
83
- // },
84
- // b: {
85
- // id: 'b',
86
- // meta: {
87
- // title: 'goodbye',
88
- // description: 'hello world',
89
- // tag: ['c', 'd'],
90
- // avatar: 'yyy',
91
- // },
92
- // },
93
- // };
94
- //
95
- // const result = filterWithKeywords(data, 'yyy', extraSearchStr);
96
- // expect(result).toEqual({
97
- // b: {
98
- // id: 'b',
99
- // meta: {
100
- // title: 'goodbye',
101
- // description: 'hello world',
102
- // tag: ['c', 'd'],
103
- // avatar: 'yyy',
104
- // },
105
- // },
106
- // });
107
- // });
108
- //
109
- // it('should ensure that each filtered object has at least one property that includes the keyword or extraSearchStr', () => {
110
- // const result = filterWithKeywords(data, 't');
111
- // expect(result).toEqual({
112
- // 1: {
113
- // id: '1',
114
- // meta: {
115
- // title: 'hello world',
116
- // description: 'test case',
117
- // tag: ['a', 'b'],
118
- // },
119
- // },
120
- // });
121
- // });
122
- // });
@@ -1,29 +0,0 @@
1
- import { BaseDataModel } from '@/types/meta';
2
-
3
- export const filterWithKeywords = <T extends BaseDataModel>(
4
- map: Record<string, T>,
5
- keywords: string,
6
- extraSearchStr?: (item: T) => string | string[],
7
- ) => {
8
- if (!keywords) return map;
9
-
10
- return Object.fromEntries(
11
- Object.entries(map).filter(([, item]) => {
12
- const meta = item.meta;
13
-
14
- const keyList = [meta.title, meta.description, meta.tags?.join('')].filter(
15
- Boolean,
16
- ) as string[];
17
-
18
- const defaultSearchKey = keyList.join('');
19
-
20
- let extraSearchKey: string = '';
21
- if (extraSearchStr) {
22
- const searchStr = extraSearchStr(item);
23
- extraSearchKey = Array.isArray(searchStr) ? searchStr.join('') : searchStr;
24
- }
25
-
26
- return `${defaultSearchKey}${extraSearchKey}`.toLowerCase().includes(keywords.toLowerCase());
27
- }),
28
- );
29
- };