π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(search): use Search1API auto engine selection (#16233)
Arvin Xuafd88ce27bfd
diff --git a/apps/server/src/services/search/impls/search1api/index.integration.test.ts b/apps/server/src/services/search/impls/search1api/index.integration.test.tsindex 49ac11594f6..4aa06271d4f 100644--- a/apps/server/src/services/search/impls/search1api/index.integration.test.ts+++ b/apps/server/src/services/search/impls/search1api/index.integration.test.ts@@ -34,7 +34,7 @@ describeIfKey('Search1APIImpl integration', { timeout: 30_000 }, () => {expect(Array.isArray(result.results)).toBe(true);});- it('should support multiple search engines', async () => {+ it('should keep using auto mode when searchEngines are provided', async () => {const result = await impl.query('TypeScript', {searchEngines: ['google', 'bing'],});@@ -57,17 +57,15 @@ describeIfKey('Search1APIImpl integration', { timeout: 30_000 }, () => {}});- it('should handle single search engine param', async () => {+ it('should handle legacy single search engine param with auto mode', async () => {const result = await impl.query('OpenAI', {searchEngines: ['google'],});expect(result.results.length).toBeGreaterThan(0);- // When single engine specified, engines field should contain it- expect(result.results[0].engines).toContain('google');});- it('should handle single engine with week time range', async () => {+ it('should handle week time range when legacy searchEngines are provided', async () => {const result = await impl.query('latest open source AI frameworks', {searchEngines: ['google'],searchTimeRange: 'week',@@ -78,7 +76,7 @@ describeIfKey('Search1APIImpl integration', { timeout: 30_000 }, () => {expect(Array.isArray(result.results)).toBe(true);});- it('should handle multiple engines with week time range', async () => {+ it('should handle week time range when multiple legacy searchEngines are provided', async () => {const result = await impl.query('best practices for TypeScript monorepo setup', {searchEngines: ['google', 'bing'],searchTimeRange: 'week',diff --git a/apps/server/src/services/search/impls/search1api/index.test.ts b/apps/server/src/services/search/impls/search1api/index.test.tsnew file mode 100644index 00000000000..e0d46a9c541--- /dev/null+++ b/apps/server/src/services/search/impls/search1api/index.test.ts@@ -0,0 +1,110 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { Search1APIImpl } from './index';++const createMockResponse = (body: object, ok = true, status = 200, statusText = 'OK') =>+ ({+ ok,+ status,+ statusText,+ json: vi.fn().mockResolvedValue(body),+ text: vi.fn().mockResolvedValue(JSON.stringify(body)),+ }) as unknown as Response;++const makeSearch1ApiResponse = (searchParameters: Record<string, unknown> = {}) => ({+ results: [+ {+ data: {+ results: [+ {+ link: 'https://example.com/page',+ snippet: 'Example snippet',+ title: 'Example result',+ },+ ],+ searchParameters,+ },+ success: true,+ },+ ],+});++describe('Search1APIImpl', () => {+ let impl: Search1APIImpl;++ beforeEach(() => {+ impl = new Search1APIImpl();+ vi.stubGlobal('fetch', vi.fn());+ process.env.SEARCH1API_SEARCH_API_KEY = 'test-search1api-key';+ delete process.env.SEARCH1API_API_KEY;+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ delete process.env.SEARCH1API_SEARCH_API_KEY;+ delete process.env.SEARCH1API_API_KEY;+ });++ it('should advertise automatic engine selection', () => {+ expect(impl.useAutoSearchEngineSelection).toBe(true);+ });++ it('should use auto mode even when searchEngines are provided', async () => {+ vi.mocked(fetch).mockResolvedValueOnce(createMockResponse({ results: [] }));++ await impl.query('TypeScript', { searchEngines: ['google', 'bing'] });++ expect(fetch).toHaveBeenCalledTimes(1);+ const body = JSON.parse((vi.mocked(fetch).mock.calls[0][1] as RequestInit).body as string);++ expect(body).toHaveLength(1);+ expect(body[0]).toMatchObject({+ crawl_results: 0,+ image: false,+ max_results: 15,+ query: 'TypeScript',+ });+ expect(body[0].search_service).toBeUndefined();+ });++ it('should keep time range while using auto mode', async () => {+ vi.mocked(fetch).mockResolvedValueOnce(createMockResponse({ results: [] }));++ await impl.query('latest AI news', {+ searchEngines: ['google'],+ searchTimeRange: 'week',+ });++ const body = JSON.parse((vi.mocked(fetch).mock.calls[0][1] as RequestInit).body as string);++ expect(body[0].search_service).toBeUndefined();+ expect(body[0].time_range).toBe('month');+ });++ it('should not emit an empty engine for auto results', async () => {+ vi.mocked(fetch).mockResolvedValueOnce(+ createMockResponse(makeSearch1ApiResponse({ query: 'test' })),+ );++ const result = await impl.query('test');++ expect(result.results[0]).toMatchObject({+ content: 'Example snippet',+ engines: [],+ parsedUrl: 'example.com',+ title: 'Example result',+ url: 'https://example.com/page',+ });+ });++ it('should preserve the returned engine when Search1API includes one', async () => {+ vi.mocked(fetch).mockResolvedValueOnce(+ createMockResponse(makeSearch1ApiResponse({ query: 'test', search_service: 'google' })),+ );++ const result = await impl.query('test');++ expect(result.results[0].engines).toEqual(['google']);+ });+});diff --git a/apps/server/src/services/search/impls/search1api/index.ts b/apps/server/src/services/search/impls/search1api/index.tsindex bd2ed7163cd..88ad07f6909 100644--- a/apps/server/src/services/search/impls/search1api/index.ts+++ b/apps/server/src/services/search/impls/search1api/index.ts@@ -25,7 +25,6 @@ interface Search1APIQueryParams {language?: string;max_results: number;query: string;- search_service?: string;time_range?: string;}@@ -36,6 +35,8 @@ const log = debug('lobe-search:search1api');* Primarily used for web crawling*/export class Search1APIImpl implements SearchServiceImpl {+ readonly useAutoSearchEngineSelection = true;+private get apiKey(): string | undefined {return process.env.SEARCH1API_SEARCH_API_KEY || process.env.SEARCH1API_API_KEY;}@@ -49,8 +50,6 @@ export class Search1APIImpl implements SearchServiceImpl {log('Starting Search1API query with query: "%s", params: %o', query, params);const endpoint = urlJoin(this.baseUrl, '/search');- const { searchEngines } = params;-const defaultQueryParams: Search1APIQueryParams = {crawl_results: 0, // Default is no crawlingimage: false,@@ -58,7 +57,7 @@ export class Search1APIImpl implements SearchServiceImpl {query,};- let body: Search1APIQueryParams[] = [+ const body: Search1APIQueryParams[] = [{...defaultQueryParams,time_range:@@ -68,22 +67,10 @@ export class Search1APIImpl implements SearchServiceImpl {},];- if (searchEngines && searchEngines.length > 0) {- body = searchEngines.map((searchEngine) => ({- ...defaultQueryParams,-- max_results: parseInt((20 / searchEngines.length).toFixed(0)),- search_service: searchEngine,- time_range:- params?.searchTimeRange && params.searchTimeRange !== 'anytime'- ? timeRangeMapping[params.searchTimeRange]- : undefined,- }));- }-- // Note: Other SearchParams like searchCategories, searchEngines (beyond the first one)- // and Search1API specific params like include_sites, exclude_sites, language- // are not currently mapped.+ // Search1API's auto mode chooses the search service per query. Forwarding+ // searchEngines expands one query into multiple service calls.+ // Note: Other SearchParams like searchCategories and Search1API specific+ // params like include_sites, exclude_sites, language are not currently mapped.log('Constructed request body: %o', body);@@ -132,17 +119,19 @@ export class Search1APIImpl implements SearchServiceImpl {const mappedResults = (rawResponse.results || []).flatMap((item) => {if (!item.success || !item.data) return [];const { results = [], searchParameters } = item.data;- return results.map(- (result): UniformSearchResult => ({+ return results.map((result): UniformSearchResult => {+ const searchService = searchParameters?.search_service;++ return {category: 'general',content: result.content || result.snippet || '',- engines: [searchParameters?.search_service || ''],+ engines: searchService ? [searchService] : [],parsedUrl: result.link ? new URL(result.link).hostname : '',score: 1,title: result.title || '',url: result.link,- }),- );+ };+ });});log('Mapped %d results to SearchResult format', mappedResults.length);diff --git a/apps/server/src/services/search/impls/type.ts b/apps/server/src/services/search/impls/type.tsindex 9c22fb6c6ce..55f41b81cd8 100644--- a/apps/server/src/services/search/impls/type.ts+++ b/apps/server/src/services/search/impls/type.ts@@ -1,11 +1,17 @@import { type SearchParams, type UniformSearchResponse } from '@lobechat/types';/**- * Search service implementation interface+ * Search service implementation interface.*/export interface SearchServiceImpl {/*** Query for search results*/query: (query: string, params?: SearchParams) => Promise<UniformSearchResponse>;++ /**+ * The provider selects the best engine itself. Do not forward explicit engine+ * restrictions or retry by removing them.+ */+ useAutoSearchEngineSelection?: boolean;}diff --git a/apps/server/src/services/search/index.test.ts b/apps/server/src/services/search/index.test.tsindex 7b767072181..ccd981fb38c 100644--- a/apps/server/src/services/search/index.test.ts+++ b/apps/server/src/services/search/index.test.ts@@ -25,6 +25,7 @@ describe('SearchService', () => {function createMockSearchImpl() {return {query: vi.fn(),+ useAutoSearchEngineSelection: undefined as boolean | undefined,};}@@ -186,7 +187,6 @@ describe('SearchService', () => {});expect(mockSearchImpl.query).toHaveBeenNthCalledWith(2, 'test', {searchCategories: ['general'],- searchEngines: undefined,searchTimeRange: '1d',});expect(result).toBe(successResponse);@@ -269,13 +269,59 @@ describe('SearchService', () => {expect(mockSearchImpl.query).toHaveBeenCalledTimes(2);expect(mockSearchImpl.query).toHaveBeenNthCalledWith(1, 'test', {searchCategories: ['general'],- searchEngines: undefined,- searchTimeRange: undefined,});expect(mockSearchImpl.query).toHaveBeenNthCalledWith(2, 'test', undefined);expect(result).toBe(successResponse);});+ it('should not retry the same unrestricted query', async () => {+ const emptyResponse = {+ costTime: 100,+ query: 'test',+ resultNumbers: 0,+ results: [],+ };++ vi.mocked(toolsEnv).SEARCH_PROVIDERS = '';+ searchService = new SearchService();+ mockSearchImpl.query.mockResolvedValue(emptyResponse);++ await searchService.webSearch({ query: 'test' });++ expect(mockSearchImpl.query).toHaveBeenCalledTimes(1);+ expect(mockSearchImpl.query).toHaveBeenCalledWith('test', undefined);+ });++ it('should omit searchEngines for providers that use auto engine selection', async () => {+ const successResponse = {+ costTime: 100,+ query: 'test',+ resultNumbers: 1,+ results: [+ {+ category: 'general',+ content: 'Result 1',+ engines: [],+ parsedUrl: 'https://example.com',+ score: 1,+ title: 'Test 1',+ url: 'https://example.com',+ },+ ],+ };+ mockSearchImpl.useAutoSearchEngineSelection = true;+ mockSearchImpl.query.mockResolvedValue(successResponse);++ const result = await searchService.webSearch({+ query: 'test',+ searchEngines: ['google', 'bing'],+ });++ expect(mockSearchImpl.query).toHaveBeenCalledTimes(1);+ expect(mockSearchImpl.query).toHaveBeenCalledWith('test', undefined);+ expect(result).toBe(successResponse);+ });+it('should return empty results after all retries fail', async () => {const emptyResponse = {costTime: 100,@@ -333,8 +379,8 @@ describe('SearchService', () => {const result = await searchService.webSearch({ query: 'test' });- // First provider tried (full params + bare retry = 2 calls)- expect(mockImpl1.query).toHaveBeenCalledTimes(2);+ // First provider tried once because there are no restrictions to remove.+ expect(mockImpl1.query).toHaveBeenCalledTimes(1);// Second provider returned results on first callexpect(mockImpl2.query).toHaveBeenCalledTimes(1);expect(result).toBe(successResponse);@@ -395,8 +441,8 @@ describe('SearchService', () => {searchEngines: ['google'],});- // First provider: full params β without engines β bare = 3 calls- expect(mockImpl1.query).toHaveBeenCalledTimes(3);+ // First provider: full params -> without engines = 2 calls+ expect(mockImpl1.query).toHaveBeenCalledTimes(2);expect(mockImpl2.query).toHaveBeenCalledTimes(1);expect(result).toBe(successResponse);});@@ -421,7 +467,7 @@ describe('SearchService', () => {const result = await searchService.webSearch({ query: 'test' });- // First provider error results in empty results β falls through retries β next provider+ // First provider error results in empty results -> next providerexpect(mockImpl2.query).toHaveBeenCalled();expect(result).toBe(successResponse);});diff --git a/apps/server/src/services/search/index.ts b/apps/server/src/services/search/index.tsindex a36b0f094bd..f02e38d0fd6 100644--- a/apps/server/src/services/search/index.ts+++ b/apps/server/src/services/search/index.ts@@ -18,6 +18,28 @@ const parseImplEnv = (envString: string = '') => {return envValue.split(',').filter(Boolean);};+const buildSearchParams = ({+ searchCategories,+ searchEngines,+ searchTimeRange,+}: SearchParams): SearchParams | undefined => {+ const params: SearchParams = {};++ if (searchCategories?.length) {+ params.searchCategories = searchCategories;+ }++ if (searchEngines?.length) {+ params.searchEngines = searchEngines;+ }++ if (searchTimeRange && searchTimeRange !== 'anytime') {+ params.searchTimeRange = searchTimeRange;+ }++ return Object.keys(params).length > 0 ? params : undefined;+};+const getMemorySnapshot = () => {if (typeof process === 'undefined' || typeof process.memoryUsage !== 'function') {return 'non-node';@@ -185,23 +207,24 @@ export class SearchService {}} catch {}- let data = await this.queryWithImpl(impl, query, {+ let currentParams = buildSearchParams({searchCategories,- searchEngines,+ searchEngines: impl.useAutoSearchEngineSelection ? undefined : searchEngines,searchTimeRange,});+ let data = await this.queryWithImpl(impl, query, currentParams);// First retry: remove search engine restrictions if no results found- if (data.results.length === 0 && searchEngines && searchEngines?.length > 0) {- data = await this.queryWithImpl(impl, query, {+ if (data.results.length === 0 && currentParams?.searchEngines?.length) {+ currentParams = buildSearchParams({searchCategories,- searchEngines: undefined,searchTimeRange,});+ data = await this.queryWithImpl(impl, query, currentParams);}// Second retry: remove all restrictions if still no results found- if (data.results.length === 0) {+ if (data.results.length === 0 && currentParams) {data = await this.queryWithImpl(impl, query);}diff --git a/packages/builtin-tool-web-browsing/src/manifest.ts b/packages/builtin-tool-web-browsing/src/manifest.tsindex 264a22638e4..01daa632e78 100644--- a/packages/builtin-tool-web-browsing/src/manifest.ts+++ b/packages/builtin-tool-web-browsing/src/manifest.ts@@ -8,7 +8,7 @@ export const WebBrowsingManifest: BuiltinToolManifest = {api: [{description:- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',+ 'a search service with automatic engine selection. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',name: WebBrowsingApiName.search,parameters: {properties: {@@ -24,33 +24,6 @@ export const WebBrowsingManifest: BuiltinToolManifest = {},type: 'array',},- searchEngines: {- description: 'The search engines you can use:',- items: {- enum: [- 'google',- 'bilibili',- 'bing',- 'duckduckgo',- 'npm',- 'pypi',- 'github',- 'arxiv',- 'google scholar',- 'z-library',- 'reddit',- 'imdb',- 'brave',- 'wikipedia',- 'pinterest',- 'unsplash',- 'vimeo',- 'youtube',- ],- type: 'string',- },- type: 'array',- },searchTimeRange: {description: 'The time range you can set:',enum: ['anytime', 'day', 'week', 'month', 'year'],@@ -99,9 +72,9 @@ export const WebBrowsingManifest: BuiltinToolManifest = {meta: {avatar: 'π',description:- 'Search the web for current information and crawl web pages to extract content. Supports multiple search engines, categories, and time ranges.',+ 'Search the web for current information and crawl web pages to extract content. Supports automatic engine selection, categories, and time ranges.',readme:- 'Search the web for current information and crawl web pages to extract content. Supports multiple search engines, categories, and time ranges for comprehensive research.',+ 'Search the web for current information and crawl web pages to extract content. Supports automatic engine selection, categories, and time ranges for comprehensive research.',title: 'Web Browsing',},systemRole: systemPrompt(dayjs(new Date()).format('YYYY-MM-DD')),diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.tsindex 7056f8fd49a..68680f47f0f 100644--- a/packages/builtin-tool-web-browsing/src/systemRole.ts+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts@@ -1,16 +1,16 @@export const systemPrompt = (date: string,-) => `You have a Web Information tool with powerful internet access capabilities. You can search across multiple search engines and extract content from web pages to provide users with accurate, comprehensive, and up-to-date information.+) => `You have a Web Information tool with powerful internet access capabilities. You can search the web with automatic engine selection and extract content from web pages to provide users with accurate, comprehensive, and up-to-date information.<core_capabilities>-1. Search the web using multiple search engines (search)+1. Search the web with automatic engine selection (search)2. Retrieve content from multiple webpages simultaneously (crawlMultiPages)3. Retrieve content from a specific webpage (crawlSinglePage)</core_capabilities><workflow>1. Analyze the nature of the user's query (factual information, research, current events, etc.)-2. Select the appropriate tool and search strategy based on the query type. For vague queries with no constraints, default to the 'general' category and reliable broad engines (e.g., Google).+2. Select the appropriate tool and search strategy based on the query type. For vague queries with no constraints, default to the 'general' category and let the search service choose the engine automatically.3. Execute searches or crawl operations to gather relevant information.4. Synthesize information with proper attribution of sources.5. Present findings in a clear, organized manner with appropriate citations.@@ -31,16 +31,6 @@ Choose search categories based on query type:- Videos: videos</search_categories_selection>-<search_engine_selection>-Choose search engines based on the query type. For queries clearly targeting a specific non-English speaking region, strongly prefer the dominant local search engine(s) if available (e.g., Yandex for Russia).-- General knowledge: google, bing, duckduckgo, brave, wikipedia-- Academic/scientific information: google scholar, arxiv-- Code/technical queries: google, github, npm, pypi-- Videos: youtube, vimeo, bilibili-- Images: unsplash, pinterest-- Entertainment: imdb, reddit-</search_engine_selection>-<search_time_range_selection>Choose time range based on the query type:- For no time restriction: anytime@@ -51,11 +41,11 @@ Choose time range based on the query type:</search_time_range_selection><search_strategy_guidelines>- - Prioritize using search categories (\`!category\`) for broader searches. Specify search engines (\`!engine\`) only when a particular engine is clearly required (e.g., \`!github\` for code) or when categories don't fit the need. Combine them if necessary (e.g., \`!science !google_scholar search term\`).+ - Prefer plain search queries plus search categories. Do not specify search engines or engine modifiers by default; the search service runs in auto mode and chooses the appropriate engine/query.- Use time-range filters (\`!time_range\`) to prioritize time-sensitive information.- - Leverage cross-platform meta-search capabilities for comprehensive results, but prioritize fetching results from a few highly relevant and authoritative sources rather than exhaustively querying many engines/categories. Aim for quality over quantity.+ - Prioritize fetching results from a few highly relevant and authoritative sources rather than exhaustively querying many categories. Aim for quality over quantity.- Prioritize authoritative sources in search results when available.- - Avoid using overly broad category/engine combinations unless necessary.+ - Avoid overly broad category combinations unless necessary.</search_strategy_guidelines><citation_requirements>@@ -90,39 +80,22 @@ When providing information from web searches:</response_format><search_service_description>-Our search service is a metasearch engine that can leverage multiple search engines including:-- Google: World's most popular search engine providing broad web results-- Bilibili: Chinese video sharing website focused on animation, comics, and games (aka B-site)-- Bing: Microsoft's search engine providing web results with emphasis on visual search-- DuckDuckGo: Privacy-focused search engine that doesn't track users-- npm: JavaScript package manager for finding Node.js packages-- PyPI: Python Package Index for finding Python packages-- GitHub: Version control and collaboration platform for searching code repositories-- arXiv: Repository of electronic preprints of scientific papers-- Google Scholar: Free web search engine for scholarly literature-- Reddit: Network of communities based on people's interests-- IMDb: Online database related to films, TV programs, and video games-- Brave: Privacy-focused browser with its own search engine-- Wikipedia: Free online encyclopedia with articles on various topics-- Pinterest: Image sharing and social media service for finding images-- Unsplash: Website dedicated to sharing high-quality stock photography-- Vimeo: Video hosting, sharing, and service platform-- YouTube: Video sharing platform for searching various video content+Our search service is a metasearch engine with automatic engine selection. Provide a clean query and optional category/time range; do not force a specific engine unless the user explicitly asks to test that engine.<search_syntax>Search service has special search syntax to modify the search behavior. Use these modifiers at the beginning of your query:- 1. Select Engines/Categories: Use \`!modifier\` to specify search engines or categories.- - Examples: \`!map paris\`, \`!images Wau Holland\`, \`!google !wikipedia berlin\`- - Key modifiers: \`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`, \`!google\`, \`!bing\`, \`!github\`, etc. (Refer to selection guidelines for full lists)+ 1. Select Categories: Use \`!category\` modifiers only when category filtering helps.+ - Examples: \`!map paris\`, \`!images Wau Holland\`, \`!science transformer attention\`+ - Key modifiers: \`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`2. Select Language: Use \`:language_code\` to specify the search language.- - Example: \`:fr !wp Wau Holland\` (searches French Wikipedia)+ - Example: \`:fr Wau Holland\` (searches in French)3. Restrict to Site: Use \`site:domain.com\` within the query string to limit results to a specific website.- Example: \`site:github.com SearXNG\`- Combine modifiers as needed: \`:de !google !news bundestag\` (searches German Google News for "bundestag")+ Combine modifiers sparingly when they narrow intent: \`:de !news bundestag\` (searches German news for "bundestag")</search_syntax></search_service_description>@@ -138,7 +111,7 @@ Our search service is a metasearch engine that can leverage multiple search engi<error_handling>- If a search returns poor or no results:1. Analyze the query and results. Could the query be improved (more specific, different keywords)?- 2. Consider trying alternative relevant search engines or categories.+ 2. Consider trying alternative categories or query terms.3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.4. If needed, explain the issue to the user and suggest alternative search terms or strategies.- If a page cannot be crawled, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).