@lobehub/chat 1.67.1 → 1.68.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/.env.example +4 -0
- package/CHANGELOG.md +58 -0
- package/Dockerfile +2 -0
- package/Dockerfile.database +2 -0
- package/README.md +3 -2
- package/README.zh-CN.md +1 -1
- package/changelog/v1.json +21 -0
- package/docs/self-hosting/advanced/auth.mdx +6 -5
- package/docs/self-hosting/advanced/auth.zh-CN.mdx +6 -5
- package/docs/self-hosting/environment-variables/model-provider.mdx +16 -0
- package/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx +16 -0
- package/docs/usage/providers/ppio.mdx +57 -0
- package/docs/usage/providers/ppio.zh-CN.mdx +55 -0
- package/locales/ar/models.json +3 -0
- package/locales/ar/plugin.json +1 -1
- package/locales/bg-BG/models.json +3 -0
- package/locales/bg-BG/plugin.json +1 -1
- package/locales/de-DE/models.json +3 -0
- package/locales/de-DE/plugin.json +1 -1
- package/locales/en-US/models.json +3 -0
- package/locales/en-US/plugin.json +1 -1
- package/locales/en-US/providers.json +3 -0
- package/locales/es-ES/models.json +3 -0
- package/locales/es-ES/plugin.json +1 -1
- package/locales/fa-IR/models.json +3 -0
- package/locales/fa-IR/plugin.json +1 -1
- package/locales/fr-FR/models.json +3 -0
- package/locales/fr-FR/plugin.json +1 -1
- package/locales/it-IT/models.json +3 -0
- package/locales/it-IT/plugin.json +1 -1
- package/locales/ja-JP/models.json +3 -0
- package/locales/ja-JP/plugin.json +1 -1
- package/locales/ko-KR/models.json +3 -0
- package/locales/ko-KR/plugin.json +1 -1
- package/locales/nl-NL/models.json +3 -0
- package/locales/nl-NL/plugin.json +1 -1
- package/locales/pl-PL/models.json +3 -0
- package/locales/pl-PL/plugin.json +1 -1
- package/locales/pt-BR/models.json +3 -0
- package/locales/pt-BR/plugin.json +1 -1
- package/locales/ru-RU/models.json +3 -0
- package/locales/ru-RU/plugin.json +1 -1
- package/locales/tr-TR/models.json +3 -0
- package/locales/tr-TR/plugin.json +1 -1
- package/locales/vi-VN/models.json +3 -0
- package/locales/vi-VN/plugin.json +1 -1
- package/locales/zh-CN/models.json +3 -0
- package/locales/zh-CN/plugin.json +1 -1
- package/locales/zh-CN/providers.json +4 -0
- package/locales/zh-TW/models.json +3 -0
- package/locales/zh-TW/plugin.json +1 -1
- package/package.json +5 -5
- package/packages/web-crawler/src/__test__/crawler.test.ts +176 -0
- package/packages/web-crawler/src/crawler.ts +12 -6
- package/packages/web-crawler/src/type.ts +3 -0
- package/packages/web-crawler/src/urlRules.ts +11 -0
- package/packages/web-crawler/src/utils/appUrlRules.test.ts +76 -0
- package/packages/web-crawler/src/utils/appUrlRules.ts +3 -0
- package/src/app/[variants]/(main)/settings/llm/ProviderList/providers.tsx +2 -0
- package/src/config/aiModels/index.ts +3 -0
- package/src/config/aiModels/ppio.ts +276 -0
- package/src/config/llm.ts +6 -0
- package/src/config/modelProviders/index.ts +4 -0
- package/src/config/modelProviders/ppio.ts +249 -0
- package/src/libs/agent-runtime/AgentRuntime.ts +7 -0
- package/src/libs/agent-runtime/ppio/__snapshots__/index.test.ts.snap +26 -0
- package/src/libs/agent-runtime/ppio/fixtures/models.json +42 -0
- package/src/libs/agent-runtime/ppio/index.test.ts +264 -0
- package/src/libs/agent-runtime/ppio/index.ts +51 -0
- package/src/libs/agent-runtime/ppio/type.ts +12 -0
- package/src/libs/agent-runtime/types/type.ts +1 -0
- package/src/libs/agent-runtime/utils/anthropicHelpers.ts +2 -2
- package/src/locales/default/plugin.ts +1 -1
- package/src/server/routers/tools/__test__/search.test.ts +146 -0
- package/src/server/routers/tools/search.ts +1 -1
- package/src/store/chat/slices/builtinTool/actions/searXNG.test.ts +67 -0
- package/src/store/chat/slices/builtinTool/actions/searXNG.ts +2 -1
- package/src/store/tool/slices/builtin/selectors.test.ts +12 -0
- package/src/store/tool/slices/builtin/selectors.ts +4 -1
- package/src/tools/web-browsing/Portal/PageContent/index.tsx +13 -7
- package/src/tools/web-browsing/const.ts +2 -0
- package/src/types/user/settings/keyVaults.ts +1 -0
@@ -0,0 +1,264 @@
|
|
1
|
+
// @vitest-environment node
|
2
|
+
import OpenAI from 'openai';
|
3
|
+
import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
4
|
+
|
5
|
+
import { LobeOpenAICompatibleRuntime } from '@/libs/agent-runtime';
|
6
|
+
import { ModelProvider } from '@/libs/agent-runtime';
|
7
|
+
import { AgentRuntimeErrorType } from '@/libs/agent-runtime';
|
8
|
+
|
9
|
+
import * as debugStreamModule from '../utils/debugStream';
|
10
|
+
import models from './fixtures/models.json';
|
11
|
+
import { LobePPIOAI } from './index';
|
12
|
+
|
13
|
+
const provider = ModelProvider.PPIO;
|
14
|
+
const defaultBaseURL = 'https://api.ppinfra.com/v3/openai';
|
15
|
+
const bizErrorType = AgentRuntimeErrorType.ProviderBizError;
|
16
|
+
const invalidErrorType = AgentRuntimeErrorType.InvalidProviderAPIKey;
|
17
|
+
|
18
|
+
// Mock the console.error to avoid polluting test output
|
19
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
20
|
+
|
21
|
+
let instance: LobeOpenAICompatibleRuntime;
|
22
|
+
|
23
|
+
beforeEach(() => {
|
24
|
+
instance = new LobePPIOAI({ apiKey: 'test' });
|
25
|
+
|
26
|
+
// 使用 vi.spyOn 来模拟 chat.completions.create 方法
|
27
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
|
28
|
+
new ReadableStream() as any,
|
29
|
+
);
|
30
|
+
vi.spyOn(instance['client'].models, 'list').mockResolvedValue({ data: [] } as any);
|
31
|
+
});
|
32
|
+
|
33
|
+
afterEach(() => {
|
34
|
+
vi.clearAllMocks();
|
35
|
+
});
|
36
|
+
|
37
|
+
describe('PPIO', () => {
|
38
|
+
describe('init', () => {
|
39
|
+
it('should correctly initialize with an API key', async () => {
|
40
|
+
const instance = new LobePPIOAI({ apiKey: 'test_api_key' });
|
41
|
+
expect(instance).toBeInstanceOf(LobePPIOAI);
|
42
|
+
expect(instance.baseURL).toEqual(defaultBaseURL);
|
43
|
+
});
|
44
|
+
});
|
45
|
+
|
46
|
+
describe('chat', () => {
|
47
|
+
describe('Error', () => {
|
48
|
+
it('should return Error with an openai error response when OpenAI.APIError is thrown', async () => {
|
49
|
+
// Arrange
|
50
|
+
const apiError = new OpenAI.APIError(
|
51
|
+
400,
|
52
|
+
{
|
53
|
+
status: 400,
|
54
|
+
error: {
|
55
|
+
message: 'Bad Request',
|
56
|
+
},
|
57
|
+
},
|
58
|
+
'Error message',
|
59
|
+
{},
|
60
|
+
);
|
61
|
+
|
62
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
63
|
+
|
64
|
+
// Act
|
65
|
+
try {
|
66
|
+
await instance.chat({
|
67
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
68
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
69
|
+
temperature: 0.999,
|
70
|
+
});
|
71
|
+
} catch (e) {
|
72
|
+
expect(e).toEqual({
|
73
|
+
endpoint: defaultBaseURL,
|
74
|
+
error: {
|
75
|
+
error: { message: 'Bad Request' },
|
76
|
+
status: 400,
|
77
|
+
},
|
78
|
+
errorType: bizErrorType,
|
79
|
+
provider,
|
80
|
+
});
|
81
|
+
}
|
82
|
+
});
|
83
|
+
|
84
|
+
it('should throw AgentRuntimeError if no apiKey is provided', async () => {
|
85
|
+
try {
|
86
|
+
new LobePPIOAI({});
|
87
|
+
} catch (e) {
|
88
|
+
expect(e).toEqual({ errorType: invalidErrorType });
|
89
|
+
}
|
90
|
+
});
|
91
|
+
|
92
|
+
it('should return Error with the cause when OpenAI.APIError is thrown with cause', async () => {
|
93
|
+
// Arrange
|
94
|
+
const errorInfo = {
|
95
|
+
stack: 'abc',
|
96
|
+
cause: {
|
97
|
+
message: 'api is undefined',
|
98
|
+
},
|
99
|
+
};
|
100
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
101
|
+
|
102
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
103
|
+
|
104
|
+
// Act
|
105
|
+
try {
|
106
|
+
await instance.chat({
|
107
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
108
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
109
|
+
temperature: 0.999,
|
110
|
+
});
|
111
|
+
} catch (e) {
|
112
|
+
expect(e).toEqual({
|
113
|
+
endpoint: defaultBaseURL,
|
114
|
+
error: {
|
115
|
+
cause: { message: 'api is undefined' },
|
116
|
+
stack: 'abc',
|
117
|
+
},
|
118
|
+
errorType: bizErrorType,
|
119
|
+
provider,
|
120
|
+
});
|
121
|
+
}
|
122
|
+
});
|
123
|
+
|
124
|
+
it('should return Error with an cause response with desensitize Url', async () => {
|
125
|
+
// Arrange
|
126
|
+
const errorInfo = {
|
127
|
+
stack: 'abc',
|
128
|
+
cause: { message: 'api is undefined' },
|
129
|
+
};
|
130
|
+
const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
|
131
|
+
|
132
|
+
instance = new LobePPIOAI({
|
133
|
+
apiKey: 'test',
|
134
|
+
|
135
|
+
baseURL: 'https://api.abc.com/v1',
|
136
|
+
});
|
137
|
+
|
138
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
|
139
|
+
|
140
|
+
// Act
|
141
|
+
try {
|
142
|
+
await instance.chat({
|
143
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
144
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
145
|
+
temperature: 0.999,
|
146
|
+
});
|
147
|
+
} catch (e) {
|
148
|
+
expect(e).toEqual({
|
149
|
+
endpoint: 'https://api.***.com/v1',
|
150
|
+
error: {
|
151
|
+
cause: { message: 'api is undefined' },
|
152
|
+
stack: 'abc',
|
153
|
+
},
|
154
|
+
errorType: bizErrorType,
|
155
|
+
provider,
|
156
|
+
});
|
157
|
+
}
|
158
|
+
});
|
159
|
+
|
160
|
+
it('should throw an error type on 401 status code', async () => {
|
161
|
+
// Mock the API call to simulate a 401 error
|
162
|
+
const error = new Error('InvalidApiKey') as any;
|
163
|
+
error.status = 401;
|
164
|
+
vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
|
165
|
+
|
166
|
+
try {
|
167
|
+
await instance.chat({
|
168
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
169
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
170
|
+
temperature: 0.999,
|
171
|
+
});
|
172
|
+
} catch (e) {
|
173
|
+
expect(e).toEqual({
|
174
|
+
endpoint: defaultBaseURL,
|
175
|
+
error: new Error('InvalidApiKey'),
|
176
|
+
errorType: invalidErrorType,
|
177
|
+
provider,
|
178
|
+
});
|
179
|
+
}
|
180
|
+
});
|
181
|
+
|
182
|
+
it('should return AgentRuntimeError for non-OpenAI errors', async () => {
|
183
|
+
// Arrange
|
184
|
+
const genericError = new Error('Generic Error');
|
185
|
+
|
186
|
+
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
|
187
|
+
|
188
|
+
// Act
|
189
|
+
try {
|
190
|
+
await instance.chat({
|
191
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
192
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
193
|
+
temperature: 0.999,
|
194
|
+
});
|
195
|
+
} catch (e) {
|
196
|
+
expect(e).toEqual({
|
197
|
+
endpoint: defaultBaseURL,
|
198
|
+
errorType: 'AgentRuntimeError',
|
199
|
+
provider,
|
200
|
+
error: {
|
201
|
+
name: genericError.name,
|
202
|
+
cause: genericError.cause,
|
203
|
+
message: genericError.message,
|
204
|
+
stack: genericError.stack,
|
205
|
+
},
|
206
|
+
});
|
207
|
+
}
|
208
|
+
});
|
209
|
+
});
|
210
|
+
|
211
|
+
describe('DEBUG', () => {
|
212
|
+
it('should call debugStream and return StreamingTextResponse when DEBUG_PPIO_CHAT_COMPLETION is 1', async () => {
|
213
|
+
// Arrange
|
214
|
+
const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
|
215
|
+
const mockDebugStream = new ReadableStream({
|
216
|
+
start(controller) {
|
217
|
+
controller.enqueue('Debug stream content');
|
218
|
+
controller.close();
|
219
|
+
},
|
220
|
+
}) as any;
|
221
|
+
mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
|
222
|
+
|
223
|
+
// 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
|
224
|
+
(instance['client'].chat.completions.create as Mock).mockResolvedValue({
|
225
|
+
tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
|
226
|
+
});
|
227
|
+
|
228
|
+
// 保存原始环境变量值
|
229
|
+
const originalDebugValue = process.env.DEBUG_PPIO_CHAT_COMPLETION;
|
230
|
+
|
231
|
+
// 模拟环境变量
|
232
|
+
process.env.DEBUG_PPIO_CHAT_COMPLETION = '1';
|
233
|
+
vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
|
234
|
+
|
235
|
+
// 执行测试
|
236
|
+
// 运行你的测试函数,确保它会在条件满足时调用 debugStream
|
237
|
+
// 假设的测试函数调用,你可能需要根据实际情况调整
|
238
|
+
await instance.chat({
|
239
|
+
messages: [{ content: 'Hello', role: 'user' }],
|
240
|
+
model: 'meta-llama/llama-3-8b-instruct',
|
241
|
+
stream: true,
|
242
|
+
temperature: 0.999,
|
243
|
+
});
|
244
|
+
|
245
|
+
// 验证 debugStream 被调用
|
246
|
+
expect(debugStreamModule.debugStream).toHaveBeenCalled();
|
247
|
+
|
248
|
+
// 恢复原始环境变量值
|
249
|
+
process.env.DEBUG_PPIO_CHAT_COMPLETION = originalDebugValue;
|
250
|
+
});
|
251
|
+
});
|
252
|
+
});
|
253
|
+
|
254
|
+
describe('models', () => {
|
255
|
+
it('should get models', async () => {
|
256
|
+
// mock the models.list method
|
257
|
+
(instance['client'].models.list as Mock).mockResolvedValue({ data: models });
|
258
|
+
|
259
|
+
const list = await instance.models();
|
260
|
+
|
261
|
+
expect(list).toMatchSnapshot();
|
262
|
+
});
|
263
|
+
});
|
264
|
+
});
|
@@ -0,0 +1,51 @@
|
|
1
|
+
import { ModelProvider } from '../types';
|
2
|
+
import { LobeOpenAICompatibleFactory } from '../utils/openaiCompatibleFactory';
|
3
|
+
import { PPIOModelCard } from './type';
|
4
|
+
|
5
|
+
import type { ChatModelCard } from '@/types/llm';
|
6
|
+
|
7
|
+
export const LobePPIOAI = LobeOpenAICompatibleFactory({
|
8
|
+
baseURL: 'https://api.ppinfra.com/v3/openai',
|
9
|
+
constructorOptions: {
|
10
|
+
defaultHeaders: {
|
11
|
+
'X-API-Source': 'lobechat',
|
12
|
+
},
|
13
|
+
},
|
14
|
+
debug: {
|
15
|
+
chatCompletion: () => process.env.DEBUG_PPIO_CHAT_COMPLETION === '1',
|
16
|
+
},
|
17
|
+
models: async ({ client }) => {
|
18
|
+
const { LOBE_DEFAULT_MODEL_LIST } = await import('@/config/aiModels');
|
19
|
+
|
20
|
+
const reasoningKeywords = [
|
21
|
+
'deepseek-r1',
|
22
|
+
];
|
23
|
+
|
24
|
+
const modelsPage = await client.models.list() as any;
|
25
|
+
const modelList: PPIOModelCard[] = modelsPage.data;
|
26
|
+
|
27
|
+
return modelList
|
28
|
+
.map((model) => {
|
29
|
+
const knownModel = LOBE_DEFAULT_MODEL_LIST.find((m) => model.id.toLowerCase() === m.id.toLowerCase());
|
30
|
+
|
31
|
+
return {
|
32
|
+
contextWindowTokens: model.context_size,
|
33
|
+
description: model.description,
|
34
|
+
displayName: model.display_name?.replace("(", " (").replace(")", ")").replace("\t", "") || model.title || model.id,
|
35
|
+
enabled: knownModel?.enabled || false,
|
36
|
+
functionCall: knownModel?.abilities?.functionCall || false,
|
37
|
+
id: model.id,
|
38
|
+
reasoning:
|
39
|
+
reasoningKeywords.some(keyword => model.id.toLowerCase().includes(keyword))
|
40
|
+
|| knownModel?.abilities?.reasoning
|
41
|
+
|| false,
|
42
|
+
vision:
|
43
|
+
model.description.toLowerCase().includes('视觉')
|
44
|
+
|| knownModel?.abilities?.vision
|
45
|
+
|| false,
|
46
|
+
};
|
47
|
+
})
|
48
|
+
.filter(Boolean) as ChatModelCard[];
|
49
|
+
},
|
50
|
+
provider: ModelProvider.PPIO,
|
51
|
+
});
|
@@ -0,0 +1,12 @@
|
|
1
|
+
export interface PPIOModelCard {
|
2
|
+
context_size: number;
|
3
|
+
created: number;
|
4
|
+
description: string;
|
5
|
+
display_name: string;
|
6
|
+
id: string;
|
7
|
+
input_token_price_per_m: number;
|
8
|
+
output_token_price_per_m: number;
|
9
|
+
status: number;
|
10
|
+
tags: string[];
|
11
|
+
title: string;
|
12
|
+
}
|
@@ -28,7 +28,7 @@ export const buildAnthropicBlock = async (
|
|
28
28
|
return {
|
29
29
|
source: {
|
30
30
|
data: base64 as string,
|
31
|
-
media_type: mimeType as Anthropic.
|
31
|
+
media_type: mimeType as Anthropic.Base64ImageSource['media_type'],
|
32
32
|
type: 'base64',
|
33
33
|
},
|
34
34
|
type: 'image',
|
@@ -39,7 +39,7 @@ export const buildAnthropicBlock = async (
|
|
39
39
|
return {
|
40
40
|
source: {
|
41
41
|
data: base64 as string,
|
42
|
-
media_type: mimeType as Anthropic.
|
42
|
+
media_type: mimeType as Anthropic.Base64ImageSource['media_type'],
|
43
43
|
type: 'base64',
|
44
44
|
},
|
45
45
|
type: 'image',
|
@@ -0,0 +1,146 @@
|
|
1
|
+
// @vitest-environment node
|
2
|
+
import { TRPCError } from '@trpc/server';
|
3
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
4
|
+
|
5
|
+
import { toolsEnv } from '@/config/tools';
|
6
|
+
import { SearXNGClient } from '@/server/modules/SearXNG';
|
7
|
+
import { SEARCH_SEARXNG_NOT_CONFIG } from '@/types/tool/search';
|
8
|
+
|
9
|
+
import { searchRouter } from '../search';
|
10
|
+
|
11
|
+
// Mock JWT verification
|
12
|
+
vi.mock('@/utils/server/jwt', () => ({
|
13
|
+
getJWTPayload: vi.fn().mockResolvedValue({ userId: '1' }),
|
14
|
+
}));
|
15
|
+
|
16
|
+
vi.mock('@lobechat/web-crawler', () => ({
|
17
|
+
Crawler: vi.fn().mockImplementation(() => ({
|
18
|
+
crawl: vi.fn().mockResolvedValue({ content: 'test content' }),
|
19
|
+
})),
|
20
|
+
}));
|
21
|
+
|
22
|
+
vi.mock('@/server/modules/SearXNG');
|
23
|
+
|
24
|
+
describe('searchRouter', () => {
|
25
|
+
const mockContext = {
|
26
|
+
req: {
|
27
|
+
headers: {
|
28
|
+
authorization: 'Bearer mock-token',
|
29
|
+
},
|
30
|
+
},
|
31
|
+
authorizationHeader: 'Bearer mock-token',
|
32
|
+
jwtPayload: { userId: '1' },
|
33
|
+
};
|
34
|
+
|
35
|
+
beforeEach(() => {
|
36
|
+
vi.clearAllMocks();
|
37
|
+
// @ts-ignore
|
38
|
+
toolsEnv.SEARXNG_URL = 'http://test-searxng.com';
|
39
|
+
});
|
40
|
+
|
41
|
+
describe('crawlPages', () => {
|
42
|
+
it('should crawl multiple pages successfully', async () => {
|
43
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
44
|
+
|
45
|
+
const result = await caller.crawlPages({
|
46
|
+
urls: ['http://test1.com', 'http://test2.com'],
|
47
|
+
impls: ['naive'],
|
48
|
+
});
|
49
|
+
|
50
|
+
expect(result.results).toHaveLength(2);
|
51
|
+
expect(result.results[0]).toEqual({ content: 'test content' });
|
52
|
+
expect(result.results[1]).toEqual({ content: 'test content' });
|
53
|
+
});
|
54
|
+
|
55
|
+
it('should work without specifying impls', async () => {
|
56
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
57
|
+
|
58
|
+
const result = await caller.crawlPages({
|
59
|
+
urls: ['http://test.com'],
|
60
|
+
});
|
61
|
+
|
62
|
+
expect(result.results).toHaveLength(1);
|
63
|
+
expect(result.results[0]).toEqual({ content: 'test content' });
|
64
|
+
});
|
65
|
+
});
|
66
|
+
|
67
|
+
describe('query', () => {
|
68
|
+
it('should throw error if SEARXNG_URL is not configured', async () => {
|
69
|
+
// @ts-ignore
|
70
|
+
toolsEnv.SEARXNG_URL = undefined;
|
71
|
+
|
72
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
73
|
+
|
74
|
+
await expect(
|
75
|
+
caller.query({
|
76
|
+
query: 'test query',
|
77
|
+
}),
|
78
|
+
).rejects.toThrow(
|
79
|
+
new TRPCError({ code: 'NOT_IMPLEMENTED', message: SEARCH_SEARXNG_NOT_CONFIG }),
|
80
|
+
);
|
81
|
+
});
|
82
|
+
|
83
|
+
it('should return search results successfully', async () => {
|
84
|
+
const mockSearchResult = {
|
85
|
+
results: [
|
86
|
+
{
|
87
|
+
title: 'Test Result',
|
88
|
+
url: 'http://test.com',
|
89
|
+
content: 'Test content',
|
90
|
+
},
|
91
|
+
],
|
92
|
+
};
|
93
|
+
|
94
|
+
(SearXNGClient as any).mockImplementation(() => ({
|
95
|
+
search: vi.fn().mockResolvedValue(mockSearchResult),
|
96
|
+
}));
|
97
|
+
|
98
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
99
|
+
|
100
|
+
const result = await caller.query({
|
101
|
+
query: 'test query',
|
102
|
+
searchEngine: ['google'],
|
103
|
+
});
|
104
|
+
|
105
|
+
expect(result).toEqual(mockSearchResult);
|
106
|
+
});
|
107
|
+
|
108
|
+
it('should work without specifying search engines', async () => {
|
109
|
+
const mockSearchResult = {
|
110
|
+
results: [
|
111
|
+
{
|
112
|
+
title: 'Test Result',
|
113
|
+
url: 'http://test.com',
|
114
|
+
content: 'Test content',
|
115
|
+
},
|
116
|
+
],
|
117
|
+
};
|
118
|
+
|
119
|
+
(SearXNGClient as any).mockImplementation(() => ({
|
120
|
+
search: vi.fn().mockResolvedValue(mockSearchResult),
|
121
|
+
}));
|
122
|
+
|
123
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
124
|
+
|
125
|
+
const result = await caller.query({
|
126
|
+
query: 'test query',
|
127
|
+
});
|
128
|
+
|
129
|
+
expect(result).toEqual(mockSearchResult);
|
130
|
+
});
|
131
|
+
|
132
|
+
it('should handle search errors', async () => {
|
133
|
+
(SearXNGClient as any).mockImplementation(() => ({
|
134
|
+
search: vi.fn().mockRejectedValue(new Error('Search failed')),
|
135
|
+
}));
|
136
|
+
|
137
|
+
const caller = searchRouter.createCaller(mockContext as any);
|
138
|
+
|
139
|
+
await expect(
|
140
|
+
caller.query({
|
141
|
+
query: 'test query',
|
142
|
+
}),
|
143
|
+
).rejects.toThrow(new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Search failed' }));
|
144
|
+
});
|
145
|
+
});
|
146
|
+
});
|
@@ -4,6 +4,7 @@ import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
4
|
import { searchService } from '@/services/search';
|
5
5
|
import { useChatStore } from '@/store/chat';
|
6
6
|
import { chatSelectors } from '@/store/chat/selectors';
|
7
|
+
import { CRAWL_CONTENT_LIMITED_COUNT } from '@/tools/web-browsing/const';
|
7
8
|
import { ChatMessage } from '@/types/message';
|
8
9
|
import { SearchContent, SearchQuery, SearchResponse } from '@/types/tool/search';
|
9
10
|
|
@@ -11,6 +12,7 @@ import { SearchContent, SearchQuery, SearchResponse } from '@/types/tool/search'
|
|
11
12
|
vi.mock('@/services/search', () => ({
|
12
13
|
searchService: {
|
13
14
|
search: vi.fn(),
|
15
|
+
crawlPages: vi.fn(),
|
14
16
|
},
|
15
17
|
}));
|
16
18
|
|
@@ -181,6 +183,71 @@ describe('searXNG actions', () => {
|
|
181
183
|
});
|
182
184
|
});
|
183
185
|
|
186
|
+
describe('crawlMultiPages', () => {
|
187
|
+
it('should truncate content that exceeds limit', async () => {
|
188
|
+
const longContent = 'a'.repeat(CRAWL_CONTENT_LIMITED_COUNT + 1000);
|
189
|
+
const mockResponse = {
|
190
|
+
results: [
|
191
|
+
{
|
192
|
+
data: {
|
193
|
+
content: longContent,
|
194
|
+
title: 'Test Page',
|
195
|
+
},
|
196
|
+
crawler: 'naive',
|
197
|
+
originalUrl: 'https://test.com',
|
198
|
+
},
|
199
|
+
],
|
200
|
+
};
|
201
|
+
|
202
|
+
(searchService.crawlPages as Mock).mockResolvedValue(mockResponse);
|
203
|
+
|
204
|
+
const { result } = renderHook(() => useChatStore());
|
205
|
+
const messageId = 'test-message-id';
|
206
|
+
|
207
|
+
await act(async () => {
|
208
|
+
await result.current.crawlMultiPages(messageId, { urls: ['https://test.com'] });
|
209
|
+
});
|
210
|
+
|
211
|
+
const expectedContent = [
|
212
|
+
{
|
213
|
+
content: longContent.slice(0, CRAWL_CONTENT_LIMITED_COUNT),
|
214
|
+
title: 'Test Page',
|
215
|
+
},
|
216
|
+
];
|
217
|
+
|
218
|
+
expect(result.current.internal_updateMessageContent).toHaveBeenCalledWith(
|
219
|
+
messageId,
|
220
|
+
JSON.stringify(expectedContent),
|
221
|
+
);
|
222
|
+
});
|
223
|
+
|
224
|
+
it('should handle crawl errors', async () => {
|
225
|
+
const mockResponse = {
|
226
|
+
results: [
|
227
|
+
{
|
228
|
+
errorMessage: 'Failed to crawl',
|
229
|
+
errorType: 'CRAWL_ERROR',
|
230
|
+
originalUrl: 'https://test.com',
|
231
|
+
},
|
232
|
+
],
|
233
|
+
};
|
234
|
+
|
235
|
+
(searchService.crawlPages as Mock).mockResolvedValue(mockResponse);
|
236
|
+
|
237
|
+
const { result } = renderHook(() => useChatStore());
|
238
|
+
const messageId = 'test-message-id';
|
239
|
+
|
240
|
+
await act(async () => {
|
241
|
+
await result.current.crawlMultiPages(messageId, { urls: ['https://test.com'] });
|
242
|
+
});
|
243
|
+
|
244
|
+
expect(result.current.internal_updateMessageContent).toHaveBeenCalledWith(
|
245
|
+
messageId,
|
246
|
+
JSON.stringify(mockResponse.results),
|
247
|
+
);
|
248
|
+
});
|
249
|
+
});
|
250
|
+
|
184
251
|
describe('reSearchWithSearXNG', () => {
|
185
252
|
it('should update arguments and perform search', async () => {
|
186
253
|
const { result } = renderHook(() => useChatStore());
|
@@ -3,6 +3,7 @@ import { StateCreator } from 'zustand/vanilla';
|
|
3
3
|
import { searchService } from '@/services/search';
|
4
4
|
import { chatSelectors } from '@/store/chat/selectors';
|
5
5
|
import { ChatStore } from '@/store/chat/store';
|
6
|
+
import { CRAWL_CONTENT_LIMITED_COUNT } from '@/tools/web-browsing/const';
|
6
7
|
import { CreateMessageParams } from '@/types/message';
|
7
8
|
import {
|
8
9
|
SEARCH_SEARXNG_NOT_CONFIG,
|
@@ -66,7 +67,7 @@ export const searchSlice: StateCreator<
|
|
66
67
|
...item.data,
|
67
68
|
// if crawl too many content
|
68
69
|
// slice the top 10000 char
|
69
|
-
content: item.data.content?.slice(0,
|
70
|
+
content: item.data.content?.slice(0, CRAWL_CONTENT_LIMITED_COUNT),
|
70
71
|
},
|
71
72
|
);
|
72
73
|
|
@@ -41,6 +41,18 @@ describe('builtinToolSelectors', () => {
|
|
41
41
|
]);
|
42
42
|
});
|
43
43
|
|
44
|
+
it('should hide tool when not need visible with hidden', () => {
|
45
|
+
const state = {
|
46
|
+
...initialState,
|
47
|
+
builtinTools: [
|
48
|
+
{ identifier: 'tool-1', hidden: true, manifest: { meta: { title: 'Tool 1' } } },
|
49
|
+
{ identifier: DalleManifest.identifier, manifest: { meta: { title: 'Dalle' } } },
|
50
|
+
],
|
51
|
+
} as ToolStoreState;
|
52
|
+
const result = builtinToolSelectors.metaList(false)(state);
|
53
|
+
expect(result).toEqual([]);
|
54
|
+
});
|
55
|
+
|
44
56
|
it('should return an empty list if no builtin tools are available', () => {
|
45
57
|
const state: ToolStoreState = {
|
46
58
|
...initialState,
|
@@ -7,7 +7,10 @@ const metaList =
|
|
7
7
|
(showDalle?: boolean) =>
|
8
8
|
(s: ToolStoreState): LobeToolMeta[] =>
|
9
9
|
s.builtinTools
|
10
|
-
.filter(
|
10
|
+
.filter(
|
11
|
+
(item) =>
|
12
|
+
!item.hidden && (!showDalle ? item.identifier !== DalleManifest.identifier : true),
|
13
|
+
)
|
11
14
|
.map((t) => ({
|
12
15
|
author: 'LobeHub',
|
13
16
|
identifier: t.identifier,
|