/** * ============================================================ * src/tools/websearch.ts —— WebSearch 工具(联网搜索) * ------------------------------------------------------------ * 底层调用 Tavily Search API(https://tavily.com/)。 * 发请求带退避重试(见下「4b. 退避重试」):并发突发 + dev/免费 key 被前端切 socket * 的瞬态不再直接当失败喂回 LLM。次数由 TAVILY_MAX_RETRIES 控(默认 3)。 * * 为什么选 Tavily: * - LLM 友好:返回结构化 JSON,自带 content 摘要;不用我们再去抓 HTML * - 接口简单:一个 POST + JSON body 搞定,不用 OAuth / 翻墙 * - 免费额度:每月 1000 次足够学习用 * * Key 配置: * 在项目根 .env 里加: * TAVILY_API_KEY= * 没设的话,工具会返回友好错误(不影响 agent 启动)。 * * 输入: * query 必填,搜索关键词 * max_results 可选,默认 5(Tavily 上限 20) * search_depth 可选 'basic' | 'advanced',默认 basic * topic 可选 'general' | 'news',默认 general * recency 可选自动/相对/本年时间窗口 * start_date 可选 YYYY-MM-DD 绝对起始日期 * end_date 可选 YYYY-MM-DD 绝对结束日期 * * 输出: * 每条结果一段: * [1] 标题 * URL: https://... * 内容摘要(content) * 如有 answer 字段(advanced 才返回),先列在最上面。 * ============================================================ */ import { z } from 'zod'; import type { Tool, ToolResult } from '../../types.js'; import { configService } from '../../config/configService.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; // ---------------- 1. Zod 输入 schema ---------------- const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; function isValidIsoDate(value: string): boolean { if (!ISO_DATE.test(value)) return false; const [year, month, day] = value.split('-').map(Number); const date = new Date(Date.UTC(year!, month! - 1, day)); return date.getUTCFullYear() === year && date.getUTCMonth() === month! - 1 && date.getUTCDate() === day; } const inputSchema = z.object({ query: z .string() .min(1, '必须提供搜索关键词') .max(400, '搜索关键词太长(>400 字)') .describe('搜索关键词,建议自然语言描述需要查的信息'), max_results: z .number() .int() .min(1) .max(20) .optional() .describe('返回结果数量,1-20,默认 5'), search_depth: z .enum(['basic', 'advanced']) .optional() .describe('basic 快但浅;advanced 慢但深(含 answer 摘要),默认 basic'), topic: z .enum(['general', 'news']) .optional() .describe('general=通用网页;news=偏新闻源;默认 general'), recency: z .enum(['auto', 'none', 'day', 'week', 'month', 'year', 'current_year']) .optional() .describe('时效范围:auto 根据查询识别;none 不限时间;day/week/month/year 为相对窗口;current_year 今年优先且结果不足时扩展到去年'), start_date: z .string() .refine(isValidIsoDate, 'start_date 必须是有效的 YYYY-MM-DD 日期') .optional() .describe('只返回该日期之后发布或更新的结果;与 end_date 配合使用'), end_date: z .string() .refine(isValidIsoDate, 'end_date 必须是有效的 YYYY-MM-DD 日期') .optional() .describe('只返回该日期之前发布或更新的结果;与 start_date 配合使用'), }).superRefine((input, ctx) => { if (input.start_date && input.end_date && input.start_date > input.end_date) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['end_date'], message: 'end_date 不能早于 start_date' }); } if ((input.start_date || input.end_date) && input.recency && !['auto', 'none'].includes(input.recency)) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['recency'], message: '绝对日期范围与相对 recency 不能同时使用' }); } }); type WebSearchInput = z.infer; // ---------------- 2. JSON Schema(由 Zod 自动派生) ---------------- const parameters = toToolParameters(inputSchema); // ---------------- 3. Description(给 LLM 看的工具说明) ---------------- const description = `Searches the public web through Tavily and returns structured source candidates. - Use it to discover sources, verify current information, compare multiple sources, or locate current documentation. - It does not open or operate a browser. Use returned URLs with WebFetch when full source text is needed. - Results contain title, URL and a text snippet. They are discovery evidence, not a substitute for reading a high-value source in full. - Keep each query focused on one sub-question. When another search is needed, change the keywords, source, or angle instead of repeating the same query. - Stable concepts and explicit historical queries remain unfiltered. Use recency="day" for today, and recency="current_year" for current/latest/this-year facts; current-year searches widen to the previous year only when the current-year result set is sparse. recency="auto" is a convenience classifier when the query still contains its temporal wording. - Use recency="none" to explicitly disable automatic freshness, or start_date/end_date for an exact historical range. - \`search_depth: "advanced"\` is slower but can return a synthesized answer; \`topic: "news"\` favors news sources. - Requires a configured Tavily API key.`; // ---------------- 4. Tavily 响应类型(仅取我们用到的字段) ---------------- interface TavilyResult { title: string; url: string; content: string; score?: number; published_date?: string; } interface TavilyResponse { query?: string; answer?: string; results: TavilyResult[]; } type RelativeRange = 'day' | 'week' | 'month' | 'year'; type SearchWindow = { timeRange?: RelativeRange; startDate?: string; endDate?: string; currentYearFallback?: { expandedStartDate: string; minimumResults: number }; label?: string; source: 'none' | 'auto' | 'explicit'; }; function localIsoDate(now: Date): string { const parts = new Intl.DateTimeFormat('en-CA', { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, year: 'numeric', month: '2-digit', day: '2-digit', }).formatToParts(now); const part = (type: Intl.DateTimeFormatPartTypes): string => parts.find((item) => item.type === type)?.value ?? ''; return `${part('year')}-${part('month')}-${part('day')}`; } function resolveSearchWindow(input: WebSearchInput, now: Date): SearchWindow { if (input.start_date || input.end_date) { return { ...(input.start_date ? { startDate: input.start_date } : {}), ...(input.end_date ? { endDate: input.end_date } : {}), label: `${input.start_date ?? '最早'} 至 ${input.end_date ?? '今天'}`, source: 'explicit', }; } const requested = input.recency ?? 'auto'; if (requested === 'none') return { source: 'none' }; const today = localIsoDate(now); const year = Number(today.slice(0, 4)); const makeCurrentYear = (source: SearchWindow['source']): SearchWindow => ({ startDate: `${year}-01-01`, endDate: today, currentYearFallback: { expandedStartDate: `${year - 1}-01-01`, minimumResults: 3 }, label: `${year}-01-01 至 ${today}`, source, }); if (requested === 'current_year') return makeCurrentYear('explicit'); const relativeLabel = (range: RelativeRange): string => ({ day: '最近一天', week: '最近一周', month: '最近一个月', year: '最近一年', })[range]; if (requested !== 'auto') return { timeRange: requested, label: relativeLabel(requested), source: 'explicit' }; const query = input.query.toLowerCase(); // An explicit past year means the user is asking about history; do not let a // nearby word such as "current comparison" erase that requested period. const explicitYears = [...query.matchAll(/(?:19|20)\d{2}/g)].map((match) => Number(match[0])); if (explicitYears.some((value) => value !== year)) return { source: 'none' }; if (/(?:今天|今日|当天|\btoday\b)/i.test(query)) return { timeRange: 'day', label: relativeLabel('day'), source: 'auto' }; if (/(?:本周|这周|最近一周|\bthis week\b|\bpast week\b)/i.test(query)) return { timeRange: 'week', label: relativeLabel('week'), source: 'auto' }; if (/(?:本月|这个月|最近一个月|近期|\bthis month\b|\bpast month\b|\brecent(?:ly)?\b)/i.test(query)) return { timeRange: 'month', label: relativeLabel('month'), source: 'auto' }; if (/(?:今年|本年|当前|目前|现任|最新|最新版|实时|截至现在|\bthis year\b|\bcurrent\b|\blatest\b|\bnewest\b|\bup[- ]to[- ]date\b)/i.test(query)) { return makeCurrentYear('auto'); } return { source: 'none' }; } // ---------------- 4b. 退避重试 ---------------- // // 为什么需要(与单发 fetch 零重试的旧行为对比):WebSearch 是 isConcurrencySafe 工具, // 主循环把同一轮的多个 WebSearch 调用 **并行**发火(loop.ts,Promise.all)。研究类 // prompt 又常让模型「围绕 3–6 个子问题分别检索」——于是一瞬间 3~6 条连接同时打向 // 同一个 Tavily key。dev / 免费 ティア 的并发/速率上限被触发时,CDN 前端常**直接切断 // socket** 而非返回干净的 429(错误落进 fetch 的 catch:「socket connection closed // unexpectedly」)。旧代码单发 fetch、零重试,这类瞬态会被直接当失败喂回 LLM —— // 表现为「突然连续搜索失败,但单发检索仍通」。 // // 对策与 llm/client.ts 的自适应退避同思想(本地、有界、带抖动): // 可重试:fetch 抛错(socket 切断/超时)+ HTTP 429 + 5xx(尊重 Retry-After)。 // 不重试:用户中断(signal)、其它 4xx(401 key 错 / 400 参数错,重试无意义)、 // JSON 解析失败(body 已到、重发大概率同样坏)。 // 次数:默认 3 次重试(共 4 次尝试),可用 TAVILY_MAX_RETRIES 覆盖。 // 抖动:±15% 把并发重试**散开**,避免落 socket 的几条同时再殺到、又一起被切。 const TAVILY_ENDPOINT = 'https://api.tavily.com/search'; function tavilyMaxRetries(): number { const n = Number(process.env.TAVILY_MAX_RETRIES); return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 3; } /** 退避时长(ms):优先 Retry-After;否则指数 500·2^n 封顶 8s,再叠 ±15% 抖动。 */ function backoffDelayMs(attempt: number, retryAfterMs?: number): number { if (retryAfterMs && retryAfterMs > 0) return Math.min(retryAfterMs, 15000); const capped = Math.min(500 * 2 ** attempt, 8000); return Math.round(capped * (0.85 + Math.random() * 0.3)); } /** Retry-After 头解析(秒数 或 HTTP-date)→ ms;无法解析返回 undefined。 */ function parseRetryAfter(h: string | null): number | undefined { if (!h) return undefined; const secs = Number(h); if (Number.isFinite(secs)) return Math.max(0, secs * 1000); const at = Date.parse(h); return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now()); } /** 可中断退避:signal abort 时立即 resolve(让外层据 signal 收口,不在这里抛)。 */ function sleep(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve) => { if (signal?.aborted) return resolve(); const onAbort = (): void => { clearTimeout(timer); resolve(); }; const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms); signal?.addEventListener('abort', onAbort, { once: true }); }); } /** 发 Tavily 请求并按上述策略重试。成功返回已解析的 data,失败返回 friendly error。 */ async function fetchTavilyWithRetry( body: unknown, signal?: AbortSignal, request: typeof fetch = fetch, ): Promise<{ ok: true; data: TavilyResponse } | { ok: false; error: string }> { const maxRetries = tavilyMaxRetries(); let lastErr = ''; for (let attempt = 0; attempt <= maxRetries; attempt++) { if (signal?.aborted) return { ok: false, error: '搜索已被中断' }; const requestSignal = AbortSignal.any([ ...(signal ? [signal] : []), AbortSignal.timeout(60_000), ]); let res: Response; try { res = await request(TAVILY_ENDPOINT, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: requestSignal, }); } catch (e) { if (signal?.aborted) return { ok: false, error: '搜索已被中断' }; lastErr = `调用 Tavily 失败(网络):${(e as Error).message}`; if (attempt < maxRetries) { await sleep(backoffDelayMs(attempt), signal); continue; } break; } // 429 / 5xx:服务端瞬态(限流 / 过载 / 切 socket 后偶发的 5xx)→ 可重试 if (res.status === 429 || res.status >= 500) { const text = await res.text().catch(() => ''); lastErr = `Tavily HTTP ${res.status}:${text.slice(0, 300)}`; if (attempt < maxRetries) { const wait = backoffDelayMs(attempt, parseRetryAfter(res.headers.get('retry-after'))); await sleep(wait, signal); continue; } break; } // 其它 4xx(401 key 无效 / 400 参数错…):重试无意义,立即返回 if (!res.ok) { const text = await res.text().catch(() => ''); return { ok: false, error: `Tavily HTTP ${res.status}:${text.slice(0, 500)}` }; } // 解析 JSON(坏响应不重试——body 已到、重发大概率同样坏) try { const data = (await res.json()) as TavilyResponse; if (!data || typeof data !== 'object' || !Array.isArray(data.results) || data.results.some((item) => !item || typeof item.url !== 'string' || typeof item.title !== 'string' || (item.content != null && typeof item.content !== 'string'))) { return { ok: false, error: 'Tavily 响应缺少合法 results 数组,不能当作无搜索结果。' }; } return { ok: true, data }; } catch (e) { return { ok: false, error: `Tavily 响应不是合法 JSON:${(e as Error).message}` }; } } return { ok: false, error: `${lastErr}(已重试 ${maxRetries} 次仍失败;请根据实际网络或服务响应排查,不再重复相同请求。)`, }; } // ---------------- 5. call() ---------------- async function call( input: WebSearchInput, signal?: AbortSignal, getApiKey: () => Promise = async () => (await configService.tool('webSearch'))?.apiKey, now: () => Date = () => new Date(), request?: typeof fetch, ): Promise { // 5a. 取 key const apiKey = await getApiKey(); if (!apiKey) { return { ok: false, error: 'WebSearch 不可用:尚未配置 Tavily API Key。\n' + '请在 KakadeAI 设置 → 工具 → 联网搜索中配置,或在 env 模式提供 TAVILY_API_KEY。', }; } const window = resolveSearchWindow(input, now()); const baseBody = { api_key: apiKey, // Preserve the exact research query. The prompt layer adds a date only // when recency matters; unconditional mutation hurts exact names, // historical topics, and stable technical documentation. query: input.query, max_results: input.max_results ?? 5, search_depth: input.search_depth ?? 'basic', topic: input.topic ?? 'general', // 让 advanced 模式自动给 answer;basic 不会有 include_answer: input.search_depth === 'advanced', }; const buildBody = (selected: SearchWindow): Record => ({ ...baseBody, ...(selected.timeRange ? { time_range: selected.timeRange } : {}), ...(selected.startDate ? { start_date: selected.startDate } : {}), ...(selected.endDate ? { end_date: selected.endDate } : {}), }); // 5c. 发请求(带退避重试,吸收 dev/免费 key 在并发突发下的 socket 切断 + 429/5xx) const fetched = await fetchTavilyWithRetry(buildBody(window), signal, request); if (!fetched.ok) return { ok: false, error: fetched.error }; let data = fetched.data; let effectiveWindow = window; let fallbackNote = ''; const fallback = window.currentYearFallback; const minimumResults = Math.min(fallback?.minimumResults ?? 0, input.max_results ?? 5); if (fallback && (data.results?.length ?? 0) < minimumResults) { const expanded: SearchWindow = { ...window, startDate: fallback.expandedStartDate, label: `${fallback.expandedStartDate} 至 ${window.endDate}`, }; const wider = await fetchTavilyWithRetry(buildBody(expanded), signal, request); if (signal?.aborted) return { ok: false, error: '搜索已被中断' }; if (wider.ok && wider.data.results.length >= data.results.length) { data = wider.data; effectiveWindow = expanded; fallbackNote = `今年结果不足 ${minimumResults} 条,已自动扩展到上一年。`; } else if (wider.ok) { fallbackNote = '扩展时间范围未获得更多结果,以下保留今年结果。'; } else if ((data.results?.length ?? 0) === 0) { return { ok: false, error: wider.error }; } else { fallbackNote = `今年结果不足 ${minimumResults} 条;扩展到上一年的检索失败,以下保留今年结果。`; } } // 5d. 取结果 const results = data.results ?? []; if (results.length === 0) { return { ok: true, content: `${effectiveWindow.label ? `【检索时间范围】${effectiveWindow.label}\n` : ''}(no results for "${input.query}")`, }; } // 5e. 拼输出 const parts: string[] = []; if (effectiveWindow.label) { parts.push(`【检索时间范围】${effectiveWindow.label}${fallbackNote ? `;${fallbackNote}` : ''}`); } if (data.answer) { parts.push(`【综合回答】\n${data.answer}\n`); } parts.push(`【共 ${results.length} 条结果】`); results.forEach((r, i) => { const date = r.published_date ? `(${r.published_date})` : ''; parts.push( `\n[${i + 1}] ${r.title}${date}\nURL: ${r.url}\n${(r.content ?? '').trim()}`, ); }); let content = parts.join('\n'); if (content.length > DEFAULT_MAX_RESULT_SIZE_CHARS) { content = content.slice(0, DEFAULT_MAX_RESULT_SIZE_CHARS) + `\n\n... (输出超过 ${DEFAULT_MAX_RESULT_SIZE_CHARS} 字符,已截断)`; } return { ok: true, content }; } // ---------------- 6. 导出 ---------------- export function createWebSearchTool( getApiKey: () => Promise = async () => (await configService.tool('webSearch'))?.apiKey, now: () => Date = () => new Date(), request?: typeof fetch, ): Tool { return { name: 'WebSearch', description, inputSchema, parameters, isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'cancel', call: (input, signal) => call(input, signal, getApiKey, now, request), }; } export const webSearchTool = createWebSearchTool(); export { resolveSearchWindow as _resolveSearchWindow };