u
This commit is contained in:
165
src/tools/web-search.js
Normal file
165
src/tools/web-search.js
Normal file
@@ -0,0 +1,165 @@
|
||||
import { defineTool, ToolError } from 'libllmorbiter';
|
||||
import * as dbCompanySetting from '../db/companysetting.js';
|
||||
|
||||
const SERPER_SEARCH_ENDPOINT = 'https://google.serper.dev/search';
|
||||
const SEARCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Normalizes user/model-supplied time filter (`tbs`) into Google's qdr syntax.
|
||||
* Supported:
|
||||
* - "qdr:d" or "d" / "day" / "24h" -> "qdr:d"
|
||||
* - "qdr:w" or "w" / "week" -> "qdr:w"
|
||||
* - "qdr:m" or "m" / "month" -> "qdr:m"
|
||||
* - "qdr:y" or "y" / "year" -> "qdr:y"
|
||||
* - "qdr:h" or "h" / "hour" -> "qdr:h"
|
||||
*
|
||||
* @param {string|null} tbs
|
||||
* @returns {string|undefined}
|
||||
*/
|
||||
function normalizeTbs(tbs) {
|
||||
if (!tbs || typeof tbs !== 'string') return undefined;
|
||||
const trimmed = tbs.trim().toLowerCase();
|
||||
if (!trimmed) return undefined;
|
||||
|
||||
if (trimmed.startsWith('qdr:')) return trimmed;
|
||||
if (trimmed === 'd' || trimmed === 'day' || trimmed === '24h') return 'qdr:d';
|
||||
if (trimmed === 'w' || trimmed === 'week') return 'qdr:w';
|
||||
if (trimmed === 'm' || trimmed === 'month') return 'qdr:m';
|
||||
if (trimmed === 'y' || trimmed === 'year') return 'qdr:y';
|
||||
if (trimmed === 'h' || trimmed === 'hour') return 'qdr:h';
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries Serper for Google web search results.
|
||||
*
|
||||
* @param {string} query
|
||||
* @param {string} apiKey
|
||||
* @param {{ gl?: string, hl?: string, tbs?: string, page?: number, signal?: AbortSignal }} [options]
|
||||
* @returns {Promise<object>} raw response from Serper
|
||||
*/
|
||||
async function serperWebSearch(query, apiKey, { gl = 'de', hl = 'de', tbs, page = 1, signal } = {}) {
|
||||
const headers = {
|
||||
'X-API-KEY': apiKey,
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
||||
const combined = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
||||
|
||||
const payload = {
|
||||
q: query,
|
||||
gl,
|
||||
hl,
|
||||
};
|
||||
if (tbs) payload.tbs = tbs;
|
||||
if (page && page > 1) payload.page = page;
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(SERPER_SEARCH_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(payload),
|
||||
redirect: 'follow',
|
||||
signal: combined,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new ToolError(`web_search: network failure contacting Serper (${query}): ${err.message}`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = `${response.status} ${response.statusText}`;
|
||||
try {
|
||||
const body = await response.text();
|
||||
if (body) detail += ` - ${body.slice(0, 300)}`;
|
||||
} catch { /* body already consumed or unreadable */ }
|
||||
throw new ToolError(`web_search: Serper API error: ${detail}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the web_search tool.
|
||||
* @param {{ googleAuthId: number }} ctx
|
||||
*/
|
||||
export function createWebSearchTool({ googleAuthId }) {
|
||||
return defineTool({
|
||||
name: 'web_search',
|
||||
description:
|
||||
'Search the web using Google Search via Serper.dev. ' +
|
||||
'Returns raw search results as-is from Serper. ' +
|
||||
'Supports time filters via `tbs` ("qdr:d" for past day, "qdr:w" for past week, ' +
|
||||
'"qdr:m" for past month, "qdr:y" for past year). Each page returns 10 results.',
|
||||
strict: false,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['query'],
|
||||
properties: {
|
||||
query: {
|
||||
type: 'string',
|
||||
description: 'Search query, e.g. "apple inc" or "vite vue3 release".',
|
||||
},
|
||||
tbs: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Time filter for results: "qdr:d" (past 24h / day), "qdr:w" (past week), ' +
|
||||
'"qdr:m" (past month), "qdr:y" (past year). Short forms like "d", "w", "m", "y" are also accepted.',
|
||||
},
|
||||
gl: {
|
||||
type: 'string',
|
||||
description: 'Geolocation country code. Default "de".',
|
||||
},
|
||||
hl: {
|
||||
type: 'string',
|
||||
description: 'Result language code. Default "de".',
|
||||
},
|
||||
page: {
|
||||
type: 'number',
|
||||
description: 'Page number of results. Default 1.',
|
||||
},
|
||||
},
|
||||
},
|
||||
invoke: async ({ query, tbs, gl = 'de', hl = 'de', page = 1 } = {}, { signal } = {}) => {
|
||||
const term = typeof query === 'string' ? query.trim() : '';
|
||||
if (!term) {
|
||||
throw new ToolError('web_search requires a non-empty "query".');
|
||||
}
|
||||
|
||||
const parsedPage = Number(page);
|
||||
if (!Number.isInteger(parsedPage) || parsedPage < 1) {
|
||||
throw new ToolError(`"page" must be a positive integer (received ${page}).`);
|
||||
}
|
||||
|
||||
const normalizedTbs = normalizeTbs(tbs);
|
||||
|
||||
let apiKey = null;
|
||||
try {
|
||||
const setting = await dbCompanySetting.getByKey(googleAuthId, 'keys.serper', { maskWriteonly: false });
|
||||
apiKey = setting?.value?.trim() || null;
|
||||
} catch (err) {
|
||||
console.warn('web_search: failed to read company setting keys.serper:', err?.message || err);
|
||||
}
|
||||
if (!apiKey && process.env.SERPER_API_KEY) {
|
||||
apiKey = process.env.SERPER_API_KEY.trim();
|
||||
}
|
||||
|
||||
if (!apiKey) {
|
||||
throw new ToolError(
|
||||
'web_search is unavailable: Serper API key not configured (companysetting: keys.serper).'
|
||||
);
|
||||
}
|
||||
|
||||
return await serperWebSearch(term, apiKey, {
|
||||
gl,
|
||||
hl,
|
||||
tbs: normalizedTbs,
|
||||
page: parsedPage,
|
||||
signal,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user