53129
Pa
PAT / files
PAT / src / lib / tools / websearch.ts
1.7 KB
1import { getCache, setCache } from "@/src/lib/cache"; 2 3const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours 4 5type SearXNGResult = { 6 title: string; 7 url: string; 8 content: string; 9 score: number; 10}; 11 12export async function webSearch(query: string): Promise<SearXNGResult[] | null> { 13 // Check cache first 14 const cacheKey = `websearch:${query.toLowerCase().trim()}`; 15 const cached = await getCache<SearXNGResult[]>(cacheKey); 16 if (cached !== null) { 17 return cached; 18 } 19 20 const searxngUrl = process.env.SEARXNG_URL || "http://localhost:8888"; 21 const searchUrl = new URL("/search", searxngUrl); 22 searchUrl.searchParams.set("q", query); 23 searchUrl.searchParams.set("format", "json"); 24 25 const response = await fetch(searchUrl.toString()); 26 if (!response.ok) { 27 throw new Error(`SearXNG request failed: ${response.statusText}`); 28 } 29 30 const { results } = await response.json(); 31 if (!results || results.length === 0) { 32 return null; 33 } 34 const prunnedResults = results.map((result: SearXNGResult) => ({ 35 title: result.title, 36 url: result.url, 37 content: result.content, 38 score: result.score, 39 })); 40 41 await setCache<SearXNGResult[]>(cacheKey, prunnedResults, CACHE_TTL_MS); 42 return prunnedResults; 43} 44 45export const webSearchTool = { 46 type: "function" as const, 47 function: { 48 name: "web_search", 49 description: 50 "Search the web, use this tool to augment your responses with current and local information, news, articles, or any other relevant content.", 51 parameters: { 52 type: "object", 53 properties: { 54 query: { 55 type: "string", 56 description: "Search query", 57 }, 58 }, 59 required: ["query"], 60 }, 61 }, 62};