diff --git a/src/services/conversationManager.js b/src/services/conversationManager.js index 80071f3..5c3e9cc 100644 --- a/src/services/conversationManager.js +++ b/src/services/conversationManager.js @@ -22,6 +22,7 @@ import { createSearchImagesTool } from '../tools/search-images.js'; import { createAnalyzeImageTool } from '../tools/analyze-image.js'; import { createEditImageTool } from '../tools/edit-image.js'; import { createWebSearchTool } from '../tools/web-search.js'; +import { createSearchWebPriceTool } from '../tools/search-web-price.js'; import { createUrlGetTool } from '../tools/url-get.js'; import { createPdfReadTool } from '../tools/pdf-read.js'; import { createSearchArticlesTool } from '../tools/search-articles.js'; @@ -748,6 +749,7 @@ export class ConversationManager { createAnalyzeImageTool({ googleAuthId, model }), createEditImageTool({ googleAuthId, model }), createWebSearchTool({ googleAuthId }), + createSearchWebPriceTool({ googleAuthId }), createUrlGetTool({ googleAuthId }), createPdfReadTool({ googleAuthId }), createResetVfsTool({ googleAuthId }), diff --git a/src/tools/prompts.js b/src/tools/prompts.js index 3d2cb0b..9c18fe9 100644 --- a/src/tools/prompts.js +++ b/src/tools/prompts.js @@ -69,6 +69,9 @@ export const TOOL_DESCRIPTIONS = { web_search: 'Search Google via Serper.dev. Use timePeriod "day" or "week" for news/recent events. 10 results/page.', + search_web_price: + 'Search Google Shopping for product prices.', + url_get: 'Fetch and scrape web page content (text, markdown, metadata) via Serper Scrape.', @@ -190,6 +193,15 @@ export const TOOL_PARAMETER_DESCRIPTIONS = { page: 'Result page number (10/page, default 1).', }, + search_web_price: { + note: NOTE_DESC, + query: 'Product name or search keywords.', + num: 'Number of results to return (default 40).', + gl: 'Country code (default "de").', + hl: 'Language code (default "de").', + page: 'Result page number (default 1).', + }, + url_get: { url: 'Target URL.', }, diff --git a/src/tools/search-web-price.js b/src/tools/search-web-price.js new file mode 100644 index 0000000..c0ba630 --- /dev/null +++ b/src/tools/search-web-price.js @@ -0,0 +1,153 @@ +import { defineTool, ToolError } from 'libllmorbiter'; +import * as dbCompanySetting from '../db/companysetting.js'; +import { TOOL_DESCRIPTIONS, TOOL_PARAMETER_DESCRIPTIONS } from './prompts.js'; + +const SERPER_SHOPPING_ENDPOINT = 'https://google.serper.dev/shopping'; +const SEARCH_TIMEOUT_MS = 15_000; +const DEFAULT_NUM = 40; + +/** + * search_web_price — Google Shopping search via Serper.dev. + * + * Queries Google Shopping via Serper and returns the full `shopping` results array + * containing product offers, vendor sources, prices, links, ratings, and image URLs. + */ + +/** + * Queries Serper for Google Shopping results. + * + * @param {string} query + * @param {string} apiKey + * @param {{ gl?: string, hl?: string, num?: number, page?: number, signal?: AbortSignal }} [options] + * @returns {Promise>} raw `shopping` array from Serper + */ +async function serperShoppingSearch(query, apiKey, { gl = 'de', hl = 'de', num = DEFAULT_NUM, 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, + num, + }; + if (page && page > 1) payload.page = page; + + let response; + try { + response = await fetch(SERPER_SHOPPING_ENDPOINT, { + method: 'POST', + headers, + body: JSON.stringify(payload), + redirect: 'follow', + signal: combined, + }); + } catch (err) { + throw new ToolError(`search_web_price: 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(`search_web_price: Serper API error: ${detail}`); + } + + const data = await response.json(); + return Array.isArray(data?.shopping) ? data.shopping : (data?.shopping || []); +} + +/** + * Creates the search_web_price tool. + * @param {{ googleAuthId: number }} ctx + */ +export function createSearchWebPriceTool({ googleAuthId }) { + return defineTool({ + name: 'search_web_price', + description: TOOL_DESCRIPTIONS.search_web_price, + strict: false, + parameters: { + type: 'object', + additionalProperties: false, + required: ['query'], + properties: { + note: { + type: ['string', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.note, + }, + query: { + type: 'string', + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.query, + }, + num: { + type: ['number', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.num, + }, + gl: { + type: ['string', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.gl, + }, + hl: { + type: ['string', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.hl, + }, + page: { + type: ['number', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.search_web_price?.page, + }, + }, + }, + invoke: async ({ query, num = DEFAULT_NUM, count, gl = 'de', hl = 'de', page = 1, note } = {}, { signal } = {}) => { + const term = typeof query === 'string' ? query.trim() : ''; + if (!term) { + throw new ToolError('search_web_price requires a non-empty "query".'); + } + + const rawNum = num ?? count; + const resolvedNum = rawNum != null ? Number(rawNum) : DEFAULT_NUM; + if (!Number.isInteger(resolvedNum) || resolvedNum < 1) { + throw new ToolError(`"num" must be a positive integer (received ${rawNum}).`); + } + + 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 resolvedGl = gl || 'de'; + const resolvedHl = hl || 'de'; + + let apiKey = null; + try { + const setting = await dbCompanySetting.getByKey(googleAuthId, 'keys.serper', { maskWriteonly: false }); + apiKey = setting?.value?.trim() || null; + } catch (err) { + console.warn('search_web_price: 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( + 'search_web_price is unavailable: Serper API key not configured (companysetting: keys.serper).' + ); + } + + return await serperShoppingSearch(term, apiKey, { + gl: resolvedGl, + hl: resolvedHl, + num: resolvedNum, + page: parsedPage, + signal, + }); + }, + }); +} diff --git a/src/tools/subagent.js b/src/tools/subagent.js index de6e70b..1151252 100644 --- a/src/tools/subagent.js +++ b/src/tools/subagent.js @@ -21,6 +21,7 @@ import { createSearchImagesTool } from './search-images.js'; import { createAnalyzeImageTool } from './analyze-image.js'; import { createEditImageTool } from './edit-image.js'; import { createWebSearchTool } from './web-search.js'; +import { createSearchWebPriceTool } from './search-web-price.js'; import { createUrlGetTool } from './url-get.js'; import { createPdfReadTool } from './pdf-read.js'; import { createResetVfsTool } from './reset-vfs.js'; @@ -174,6 +175,7 @@ function createSubagentTools({ googleAuthId, companyId, model }) { createAnalyzeImageTool({ googleAuthId, model }), createEditImageTool({ googleAuthId, model }), createWebSearchTool({ googleAuthId }), + createSearchWebPriceTool({ googleAuthId }), createUrlGetTool({ googleAuthId }), createPdfReadTool({ googleAuthId }), createResetVfsTool({ googleAuthId }),