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 into Google's qdr syntax. * Supported: * - "day" / "24h" / "d" -> "qdr:d" * - "week" / "w" -> "qdr:w" * - "month" / "m" -> "qdr:m" * - "year" / "y" -> "qdr:y" * - "hour" / "h" -> "qdr:h" * * @param {string|null} time * @returns {string|undefined} */ function normalizeTbs(time) { if (!time || typeof time !== 'string') return undefined; const trimmed = time.trim().toLowerCase(); if (!trimmed) return undefined; if (trimmed === 'day' || trimmed === 'd' || trimmed === '24h' || trimmed === 'today') return 'qdr:d'; if (trimmed === 'week' || trimmed === 'w') return 'qdr:w'; if (trimmed === 'month' || trimmed === 'm') return 'qdr:m'; if (trimmed === 'year' || trimmed === 'y') return 'qdr:y'; if (trimmed === 'hour' || trimmed === 'h') return 'qdr:h'; if (trimmed.startsWith('qdr:')) return trimmed; return undefined; } /** * 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} 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 Google via Serper.dev. Use timePeriod "day" or "week" for news/recent events. Returns 10 results per page.', strict: false, parameters: { type: 'object', additionalProperties: false, required: ['query'], properties: { note: { type: ['string', 'null'], description: 'A note explaining what this search is doing (or null). This note will be displayed to the user while the search is executing.', }, query: { type: 'string', description: 'Search query.', }, timePeriod: { type: ['string', 'null'], enum: ['day', 'week', 'month', 'year', null], description: 'Time filter: "day", "week", "month", or "year", or null.', }, gl: { type: ['string', 'null'], description: 'Country code or null. Default "de".', }, hl: { type: ['string', 'null'], description: 'Language code or null. Default "de".', }, page: { type: ['number', 'null'], description: 'Result page number (10/page) or null. Default 1.', }, }, }, invoke: async ({ query, timePeriod, tbs, gl = 'de', hl = 'de', page = 1, note } = {}, { signal } = {}) => { const term = typeof query === 'string' ? query.trim() : ''; if (!term) { throw new ToolError('web_search requires a non-empty "query".'); } const parsedPage = page != null ? Number(page) : 1; if (!Number.isInteger(parsedPage) || parsedPage < 1) { throw new ToolError(`"page" must be a positive integer (received ${page}).`); } const normalizedTbs = normalizeTbs(timePeriod || 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, }); }, }); }