-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathtool.ts
More file actions
517 lines (488 loc) · 13.3 KB
/
Copy pathtool.ts
File metadata and controls
517 lines (488 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import { tool, DynamicStructuredTool } from '@langchain/core/tools';
import type { RunnableConfig } from '@langchain/core/runnables';
import type * as t from './types';
import {
WebSearchToolDescription,
WebSearchToolName,
countrySchema,
imagesSchema,
videosSchema,
querySchema,
dateSchema,
newsSchema,
DATE_RANGE,
} from './schema';
import { createSearchAPI, createSourceProcessor } from './search';
import { createSerperScraper } from './serper-scraper';
import { createTavilyScraper } from './tavily-scraper';
import { createFirecrawlScraper } from './firecrawl';
import { expandHighlights } from './highlights';
import { formatResultsForLLM } from './format';
import { createDefaultLogger } from './utils';
import { createReranker } from './rerankers';
import { Constants } from '@/common';
/**
* Executes parallel searches and merges the results,
* deduplicating top stories by link
*/
export async function executeParallelSearches({
searchAPI,
query,
date,
country,
safeSearch,
images,
videos,
news,
logger,
}: {
searchAPI: ReturnType<typeof createSearchAPI>;
query: string;
date?: DATE_RANGE;
country?: string;
safeSearch: t.SearchToolConfig['safeSearch'];
images: boolean;
videos: boolean;
news: boolean;
logger: t.Logger;
}): Promise<t.SearchResult> {
// Prepare all search tasks to run in parallel
const searchTasks: Promise<t.SearchResult>[] = [
// Main search
searchAPI.getSources({
query,
date,
country,
safeSearch,
}),
];
if (images) {
searchTasks.push(
searchAPI
.getSources({
query,
date,
country,
safeSearch,
type: 'images',
})
.catch((error) => {
logger.error('Error fetching images:', error);
return {
success: false,
error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,
};
})
);
}
if (videos) {
searchTasks.push(
searchAPI
.getSources({
query,
date,
country,
safeSearch,
type: 'videos',
})
.catch((error) => {
logger.error('Error fetching videos:', error);
return {
success: false,
error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,
};
})
);
}
if (news) {
searchTasks.push(
searchAPI
.getSources({
query,
date,
country,
safeSearch,
type: 'news',
})
.catch((error) => {
logger.error('Error fetching news:', error);
return {
success: false,
error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,
};
})
);
}
// Run all searches in parallel
const results = await Promise.all(searchTasks);
// Get the main search result (first result)
const mainResult = results[0];
if (!mainResult.success) {
throw new Error(mainResult.error ?? 'Search failed');
}
// Merge additional results with the main results
const mergedResults = { ...mainResult.data };
// Convert existing news to topStories if present
if (mergedResults.news !== undefined && mergedResults.news.length > 0) {
const existingNewsAsTopStories = mergedResults.news
.filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')
.map((newsItem) => ({
title: newsItem.title ?? '',
link: newsItem.link ?? '',
source: newsItem.source ?? '',
date: newsItem.date ?? '',
imageUrl: newsItem.imageUrl ?? '',
processed: false,
}));
mergedResults.topStories = [
...(mergedResults.topStories ?? []),
...existingNewsAsTopStories,
];
delete mergedResults.news;
}
results.slice(1).forEach((result) => {
if (result.success && result.data !== undefined) {
if (result.data.images !== undefined && result.data.images.length > 0) {
mergedResults.images = [
...(mergedResults.images ?? []),
...result.data.images,
];
}
if (result.data.videos !== undefined && result.data.videos.length > 0) {
mergedResults.videos = [
...(mergedResults.videos ?? []),
...result.data.videos,
];
}
if (result.data.news !== undefined && result.data.news.length > 0) {
const newsAsTopStories = result.data.news.map((newsItem) => ({
...newsItem,
link: newsItem.link ?? '',
}));
mergedResults.topStories = [
...(mergedResults.topStories ?? []),
...newsAsTopStories,
];
}
}
});
if (
mergedResults.topStories !== undefined &&
mergedResults.topStories.length > 1
) {
/** The main search's own news results and the parallel news sub-search
* frequently return the same stories — keep the first occurrence of each
* link so duplicates aren't scraped, reranked, and formatted repeatedly */
const seenLinks = new Set<string>();
mergedResults.topStories = mergedResults.topStories.filter((story) => {
if (!story.link || seenLinks.has(story.link)) {
return false;
}
seenLinks.add(story.link);
return true;
});
}
return { success: true, data: mergedResults };
}
function createSearchProcessor({
searchAPI,
safeSearch,
supportsImages,
supportsVideos,
supportsNews,
sourceProcessor,
onGetHighlights,
logger,
}: {
safeSearch: t.SearchToolConfig['safeSearch'];
supportsImages: boolean;
supportsVideos: boolean;
supportsNews: boolean;
searchAPI: ReturnType<typeof createSearchAPI>;
sourceProcessor: ReturnType<typeof createSourceProcessor>;
onGetHighlights: t.SearchToolConfig['onGetHighlights'];
logger: t.Logger;
}) {
return async function ({
query,
date,
country,
proMode = true,
maxSources = 5,
onSearchResults,
images = false,
videos = false,
news = false,
}: {
query: string;
country?: string;
date?: DATE_RANGE;
proMode?: boolean;
maxSources?: number;
onSearchResults: t.SearchToolConfig['onSearchResults'];
images?: boolean;
videos?: boolean;
news?: boolean;
}): Promise<t.SearchResultData> {
try {
// Execute parallel searches and merge results
const searchResult = await executeParallelSearches({
searchAPI,
query,
date,
country,
safeSearch,
images: supportsImages && images,
videos: supportsVideos && videos,
news: supportsNews && news,
logger,
});
onSearchResults?.(searchResult);
const processedSources = await sourceProcessor.processSources({
query,
news,
result: searchResult,
proMode,
onGetHighlights,
numElements: maxSources,
});
return expandHighlights(processedSources);
} catch (error) {
logger.error('Error in search:', error);
return {
organic: [],
topStories: [],
images: [],
videos: [],
news: [],
relatedSearches: [],
error: error instanceof Error ? error.message : String(error),
};
}
};
}
function createOnSearchResults({
runnableConfig,
onSearchResults,
}: {
runnableConfig: RunnableConfig;
onSearchResults: t.SearchToolConfig['onSearchResults'];
}) {
return function (results: t.SearchResult): void {
if (!onSearchResults) {
return;
}
onSearchResults(results, runnableConfig);
};
}
function createTool({
schema,
search,
maxOutputChars,
onSearchResults: _onSearchResults,
}: {
schema: Record<string, unknown>;
search: ReturnType<typeof createSearchProcessor>;
maxOutputChars?: number;
onSearchResults: t.SearchToolConfig['onSearchResults'];
}): DynamicStructuredTool {
return tool(
async (rawParams, runnableConfig) => {
const params = rawParams as SearchToolParams;
const { query, date, country: _c, images, videos, news } = params;
const country = typeof _c === 'string' && _c ? _c : undefined;
const searchResult = await search({
query,
date,
country,
images,
videos,
news,
onSearchResults: createOnSearchResults({
runnableConfig,
onSearchResults: _onSearchResults,
}),
});
const turn = runnableConfig.toolCall?.turn ?? 0;
const { output, references } = formatResultsForLLM(
turn,
searchResult,
maxOutputChars
);
const data: t.SearchResultData = { turn, ...searchResult, references };
return [output, { [Constants.WEB_SEARCH]: data }];
},
{
name: WebSearchToolName,
description: WebSearchToolDescription,
schema: schema,
responseFormat: Constants.CONTENT_AND_ARTIFACT,
}
);
}
/**
* Creates a search tool with configurable search and scraper providers.
*
* Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized).
* Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction).
*
* The country schema field is exposed to the LLM for providers that support localized results.
*/
/** Input params type for search tool */
interface SearchToolParams {
query: string;
date?: DATE_RANGE;
country?: string;
images?: boolean;
videos?: boolean;
news?: boolean;
}
export const createSearchTool = (
config: t.SearchToolConfig = {}
): DynamicStructuredTool => {
const {
searchProvider = 'serper',
serperApiKey,
searxngInstanceUrl,
searxngApiKey,
tavilyApiKey,
tavilySearchUrl,
tavilyExtractUrl,
tavilySearchOptions,
keenableApiKey,
keenableApiUrl,
keenableSearchOptions,
rerankerType = 'cohere',
rerankerTimeout,
topResults = 5,
maxContentLength,
chunkSize,
chunkOverlap,
maxOutputChars,
strategies = ['no_extraction'],
filterContent = true,
safeSearch = 1,
scraperProvider = 'firecrawl',
firecrawlApiKey,
firecrawlApiUrl,
firecrawlVersion,
firecrawlOptions,
serperScraperOptions,
tavilyScraperOptions,
scraperTimeout,
jinaApiKey,
jinaApiUrl,
cohereApiKey,
onSearchResults: _onSearchResults,
onGetHighlights,
} = config;
const logger = config.logger || createDefaultLogger();
const effectiveTavilySearchOptions =
searchProvider === 'tavily' && config.safeSearch != null
? {
...tavilySearchOptions,
safeSearch: config.safeSearch !== 0,
}
: tavilySearchOptions;
const schemaProperties: Record<string, unknown> = {
query: querySchema,
date: dateSchema,
images: imagesSchema,
videos: videosSchema,
news: newsSchema,
};
if (searchProvider === 'serper' || searchProvider === 'tavily') {
schemaProperties.country = countrySchema;
}
const toolSchema = {
type: 'object',
properties: schemaProperties,
required: ['query'],
};
const searchAPI = createSearchAPI({
searchProvider,
serperApiKey,
searxngInstanceUrl,
searxngApiKey,
tavilyApiKey,
tavilySearchUrl,
tavilySearchOptions: effectiveTavilySearchOptions,
keenableApiKey,
keenableApiUrl,
keenableSearchOptions,
});
/** Create scraper based on scraperProvider */
let scraperInstance: t.BaseScraper;
if (scraperProvider === 'serper') {
scraperInstance = createSerperScraper({
...serperScraperOptions,
apiKey: serperApiKey,
timeout: scraperTimeout ?? serperScraperOptions?.timeout,
logger,
});
} else if (scraperProvider === 'tavily') {
scraperInstance = createTavilyScraper({
...tavilyScraperOptions,
apiKey:
tavilyScraperOptions?.apiKey ??
tavilyApiKey ??
process.env.TAVILY_API_KEY,
apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,
timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,
logger,
});
} else {
scraperInstance = createFirecrawlScraper({
...firecrawlOptions,
apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,
apiUrl: firecrawlApiUrl,
version: firecrawlVersion,
timeout: scraperTimeout ?? firecrawlOptions?.timeout,
formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],
logger,
});
}
const selectedReranker = createReranker({
rerankerType,
jinaApiKey,
jinaApiUrl,
cohereApiKey,
rerankerTimeout,
logger,
});
if (!selectedReranker) {
logger.warn('No reranker selected. Using default ranking.');
}
const sourceProcessor = createSourceProcessor(
{
reranker: selectedReranker,
topResults,
maxContentLength,
chunkSize,
chunkOverlap,
strategies,
filterContent,
logger,
},
scraperInstance
);
const search = createSearchProcessor({
searchAPI,
safeSearch,
// Keenable is organic-only: its API ignores `type`, so image/news
// sub-searches would spend rate limit and merge nothing.
supportsImages: searchProvider !== 'keenable',
supportsVideos:
searchProvider !== 'tavily' && searchProvider !== 'keenable',
supportsNews: searchProvider !== 'keenable',
sourceProcessor,
onGetHighlights,
logger,
});
return createTool({
search,
schema: toolSchema,
maxOutputChars,
onSearchResults: _onSearchResults,
});
};