/* ------------------------------------------------------------------ * * 工具:定義 + 真正可執行的實作 * * 純前端只能呼叫「有開 CORS」的公開 API,以下每個都實測過可從瀏覽器直連: * Wikipedia / Wikidata(origin=*)、DuckDuckGo Instant Answer、 * Open-Meteo(天氣)、open.er-api.com(匯率)、GitHub、HN Algolia、 * Crossref(論文)、Open Library(書)、 * Tavily(選用,需金鑰,真正的全網搜尋)、Jina Reader(選用,讀任意網頁) * ------------------------------------------------------------------ */ import { safeCalc } from '../utils/calc' const MAX_RESULT_CHARS = 8000 const clip = (s, n = MAX_RESULT_CHARS) => { const str = typeof s === 'string' ? s : JSON.stringify(s, null, 2) return str.length > n ? `${str.slice(0, n)}\n…(已截斷,共 ${str.length} 字)` : str } const stripHtml = (html) => String(html || '') .replace(//gi, ' ') .replace(//gi, ' ') .replace(/<[^>]+>/g, ' ') .replace(/ /g, ' ') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/\s+/g, ' ') .trim() /** 依查詢字串猜 Wikipedia 語言:含中日韓字元就用 zh,否則 en */ const guessLang = (q) => (/[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]/.test(q || '') ? 'zh' : 'en') async function getJSON(url, init = {}) { const res = await fetch(url, init) if (!res.ok) { let detail = '' try { detail = (await res.text()).slice(0, 200) } catch { /* ignore */ } throw new Error(`HTTP ${res.status} ${detail}`) } return res.json() } /* ------------------------------ 搜尋 ------------------------------ */ async function wikipediaSearch(query, lang, limit = 5, signal) { const base = `https://${lang}.wikipedia.org/w/api.php` const params = new URLSearchParams({ action: 'query', format: 'json', origin: '*', generator: 'search', gsrsearch: query, gsrlimit: String(limit), prop: 'extracts|info', exintro: '1', explaintext: '1', exsentences: '4', inprop: 'url', ...(lang === 'zh' ? { variant: 'zh-tw' } : {}), }) const data = await getJSON(`${base}?${params}`, { signal }) const pages = Object.values(data?.query?.pages || {}).sort((a, b) => (a.index || 0) - (b.index || 0)) return pages.map((p) => ({ source: `Wikipedia (${lang})`, title: p.title, url: p.fullurl || `https://${lang}.wikipedia.org/wiki/${encodeURIComponent(p.title)}`, snippet: (p.extract || '').trim(), })) } async function duckduckgo(query, signal) { const params = new URLSearchParams({ q: query, format: 'json', no_html: '1', skip_disambig: '1' }) const data = await getJSON(`https://api.duckduckgo.com/?${params}`, { signal }) const out = [] if (data.AbstractText) out.push({ source: 'DuckDuckGo', title: data.Heading, url: data.AbstractURL, snippet: data.AbstractText }) if (data.Answer) out.push({ source: 'DuckDuckGo', title: '即時答案', url: '', snippet: String(data.Answer) }) for (const t of (data.RelatedTopics || []).slice(0, 5)) { if (t.Text) out.push({ source: 'DuckDuckGo', title: t.Text.split(' - ')[0], url: t.FirstURL, snippet: t.Text }) } return out } async function tavily(query, key, signal, maxResults = 6) { const data = await getJSON('https://api.tavily.com/search', { method: 'POST', signal, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, body: JSON.stringify({ query, max_results: maxResults, include_answer: true }), }) const out = [] if (data.answer) out.push({ source: 'Tavily', title: '摘要答案', url: '', snippet: data.answer }) for (const r of data.results || []) out.push({ source: 'Tavily', title: r.title, url: r.url, snippet: r.content }) return out } function formatResults(query, results, notes) { if (!results.length) return `「${query}」沒有找到結果。${notes.length ? `\n${notes.join('\n')}` : ''}` const body = results .map((r, i) => `[${i + 1}] ${r.title}\n來源:${r.source}${r.url ? ` · ${r.url}` : ''}\n${r.snippet}`) .join('\n\n') return `搜尋「${query}」的結果:\n\n${body}${notes.length ? `\n\n(${notes.join(';')})` : ''}` } /* ------------------------------ 定義 ------------------------------ */ export const BUILTIN_TOOLS = [ { name: 'web_search', label: '網路搜尋', description: '搜尋網路資訊。預設查 Wikipedia + DuckDuckGo;若使用者在設定填了 Tavily 金鑰,會改用 Tavily 做全網搜尋。回傳標題、網址與摘要。', parameters: { type: 'object', properties: { query: { type: 'string', description: '搜尋關鍵字或問題' }, lang: { type: 'string', description: 'Wikipedia 語言代碼,例如 zh、en、ja;省略則自動判斷' }, }, required: ['query'], }, async run({ query, lang }, ctx) { const results = [] const notes = [] const key = ctx.settings?.tavilyKey?.trim() if (key) { try { results.push(...(await tavily(query, key, ctx.signal))) } catch (e) { notes.push(`Tavily 失敗:${e.message}`) } } const wl = lang || guessLang(query) try { results.push(...(await wikipediaSearch(query, wl, key ? 3 : 5, ctx.signal))) } catch (e) { notes.push(`Wikipedia 失敗:${e.message}`) } // 中文查不到時再用英文 Wikipedia 補 if (!results.length && wl !== 'en') { try { results.push(...(await wikipediaSearch(query, 'en', 4, ctx.signal))) } catch { /* ignore */ } } if (!key) { try { results.push(...(await duckduckgo(query, ctx.signal))) } catch (e) { notes.push(`DuckDuckGo 失敗:${e.message}`) } } return formatResults(query, results, notes) }, }, { name: 'wikipedia_article', label: 'Wikipedia 全文', description: '讀取指定 Wikipedia 條目的內容(純文字)。適合在 web_search 找到條目後讀細節。', parameters: { type: 'object', properties: { title: { type: 'string', description: '條目標題,例如「臺北市」或「Large language model」' }, lang: { type: 'string', description: '語言代碼,預設依標題自動判斷' }, full: { type: 'boolean', description: 'true 讀全文,false 只讀導言(預設 false)' }, }, required: ['title'], }, async run({ title, lang, full }, ctx) { const wl = lang || guessLang(title) const params = new URLSearchParams({ action: 'query', format: 'json', origin: '*', redirects: '1', prop: 'extracts|info', explaintext: '1', inprop: 'url', titles: title, ...(full ? {} : { exintro: '1' }), ...(wl === 'zh' ? { variant: 'zh-tw' } : {}), }) const data = await getJSON(`https://${wl}.wikipedia.org/w/api.php?${params}`, { signal: ctx.signal }) const page = Object.values(data?.query?.pages || {})[0] if (!page || page.missing !== undefined) return `找不到條目「${title}」(${wl}.wikipedia.org)。可先用 web_search 找正確標題。` return clip(`# ${page.title}\n${page.fullurl}\n\n${page.extract || '(無內容)'}`) }, }, { name: 'fetch_url', label: '讀取網頁', description: '讀取任意網址的文字內容(透過 Jina Reader 轉成純文字;對有開 CORS 的網址也能直接讀)。', parameters: { type: 'object', properties: { url: { type: 'string', description: '完整網址,http(s):// 開頭' } }, required: ['url'], }, async run({ url }, ctx) { if (!/^https?:\/\//i.test(url || '')) return '網址必須以 http:// 或 https:// 開頭' const errors = [] const jinaKey = ctx.settings?.jinaKey?.trim() try { const res = await fetch(`https://r.jina.ai/${url}`, { signal: ctx.signal, headers: jinaKey ? { Authorization: `Bearer ${jinaKey}` } : {}, }) if (res.ok) return clip(await res.text()) errors.push(`Jina Reader HTTP ${res.status}${res.status === 401 ? '(需在設定填 Jina 金鑰)' : ''}`) } catch (e) { errors.push(`Jina Reader:${e.message}`) } try { const res = await fetch(url, { signal: ctx.signal }) const type = res.headers.get('content-type') || '' const text = await res.text() return clip(type.includes('html') ? stripHtml(text) : text) } catch (e) { errors.push(`直接讀取:${e.message}(多半是對方網站沒開 CORS)`) } return `無法讀取 ${url}:\n${errors.join('\n')}` }, }, { name: 'get_weather', label: '天氣', description: '查詢城市的目前天氣與未來幾天預報(Open-Meteo)。', parameters: { type: 'object', properties: { city: { type: 'string', description: '城市名稱,例如 Taipei、東京' }, days: { type: 'integer', description: '預報天數 1-7,預設 3' }, }, required: ['city'], }, async run({ city, days = 3 }, ctx) { const geo = await getJSON( `https://geocoding-api.open-meteo.com/v1/search?${new URLSearchParams({ name: city, count: '1', language: 'zh' })}`, { signal: ctx.signal }, ) const place = geo?.results?.[0] if (!place) return `找不到城市「${city}」,可改用英文名稱再試。` const d = Math.min(Math.max(Number(days) || 3, 1), 7) const params = new URLSearchParams({ latitude: place.latitude, longitude: place.longitude, timezone: 'auto', forecast_days: String(d), current: 'temperature_2m,apparent_temperature,relative_humidity_2m,precipitation,weather_code,wind_speed_10m', daily: 'weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max', }) const w = await getJSON(`https://api.open-meteo.com/v1/forecast?${params}`, { signal: ctx.signal }) const c = w.current || {} const daily = (w.daily?.time || []).map((t, i) => `${t}:${weatherText(w.daily.weather_code[i])},${w.daily.temperature_2m_min[i]}~${w.daily.temperature_2m_max[i]}°C,降雨機率 ${w.daily.precipitation_probability_max?.[i] ?? '?'}%`) return [ `${place.name}${place.admin1 ? `,${place.admin1}` : ''},${place.country}(${w.timezone})`, `現在(${c.time}):${weatherText(c.weather_code)},${c.temperature_2m}°C(體感 ${c.apparent_temperature}°C),濕度 ${c.relative_humidity_2m}%,風速 ${c.wind_speed_10m} km/h,降水 ${c.precipitation} mm`, '預報:', ...daily, ].join('\n') }, }, { name: 'currency_convert', label: '匯率換算', description: '用最新匯率換算貨幣(open.er-api.com,每日更新)。', parameters: { type: 'object', properties: { amount: { type: 'number', description: '金額' }, from: { type: 'string', description: '來源幣別代碼,例如 USD' }, to: { type: 'string', description: '目標幣別代碼,例如 TWD' }, }, required: ['amount', 'from', 'to'], }, async run({ amount, from, to }, ctx) { const f = String(from).toUpperCase() const t = String(to).toUpperCase() const data = await getJSON(`https://open.er-api.com/v6/latest/${encodeURIComponent(f)}`, { signal: ctx.signal }) if (data.result !== 'success') return `查不到 ${f} 的匯率` const rate = data.rates?.[t] if (!rate) return `查不到 ${t} 的匯率` const value = Math.round(Number(amount) * rate * 100) / 100 return `${amount} ${f} = ${value} ${t}(匯率 1 ${f} = ${rate} ${t},更新於 ${data.time_last_update_utc})` }, }, { name: 'calculate', label: '計算機', description: '精確計算數學運算式。支援 + - * / % ^、括號、pi、e、sqrt、abs、round、floor、ceil、exp、ln、log、sin、cos、tan、min、max、pow。', parameters: { type: 'object', properties: { expression: { type: 'string', description: '運算式,例如 (2+3)^2 * sqrt(16)' } }, required: ['expression'], }, run: ({ expression }) => safeCalc(expression), }, { name: 'get_current_time', label: '目前時間', description: '取得目前日期時間,可指定 IANA 時區(例如 Asia/Taipei、America/New_York)。', parameters: { type: 'object', properties: { timezone: { type: 'string', description: 'IANA 時區,省略則用使用者瀏覽器時區' } }, }, run({ timezone }) { const tz = timezone || Intl.DateTimeFormat().resolvedOptions().timeZone try { const fmt = new Intl.DateTimeFormat('zh-TW', { timeZone: tz, dateStyle: 'full', timeStyle: 'long', hour12: false, }) return `${tz}:${fmt.format(new Date())}(ISO:${new Date().toISOString()})` } catch { return `無效的時區:${tz}` } }, }, { name: 'search_github', label: 'GitHub 搜尋', description: '搜尋 GitHub 開源專案(依星數排序),回傳名稱、星數、說明、網址。', parameters: { type: 'object', properties: { query: { type: 'string', description: '關鍵字,可用 GitHub 語法,例如 "agent language:python"' }, limit: { type: 'integer', description: '筆數,預設 5' }, }, required: ['query'], }, async run({ query, limit = 5 }, ctx) { const params = new URLSearchParams({ q: query, sort: 'stars', order: 'desc', per_page: String(Math.min(limit, 10)) }) const data = await getJSON(`https://api.github.com/search/repositories?${params}`, { signal: ctx.signal, headers: { Accept: 'application/vnd.github+json' }, }) const items = data.items || [] if (!items.length) return `GitHub 找不到「${query}」` return items.map((r, i) => `[${i + 1}] ${r.full_name} ⭐${r.stargazers_count}${r.language ? ` · ${r.language}` : ''}\n${r.description || ''}\n${r.html_url}(最後更新 ${r.pushed_at?.slice(0, 10)})`).join('\n\n') }, }, { name: 'search_hackernews', label: 'Hacker News', description: '搜尋 Hacker News 上的科技新聞與討論(Algolia)。', parameters: { type: 'object', properties: { query: { type: 'string', description: '關鍵字' }, recent: { type: 'boolean', description: 'true 依時間排序(最新),false 依熱門度(預設)' }, }, required: ['query'], }, async run({ query, recent }, ctx) { const ep = recent ? 'search_by_date' : 'search' const params = new URLSearchParams({ query, tags: 'story', hitsPerPage: '8', ...(recent ? { numericFilters: 'points>=5' } : {}) }) const data = await getJSON(`https://hn.algolia.com/api/v1/${ep}?${params}`, { signal: ctx.signal }) const hits = data.hits || [] if (!hits.length) return `Hacker News 找不到「${query}」` return hits.map((h, i) => `[${i + 1}] ${h.title}(${h.points} 分,${h.num_comments} 則留言,${h.created_at?.slice(0, 10)})\n${h.url || ''}\n討論:https://news.ycombinator.com/item?id=${h.objectID}`).join('\n\n') }, }, { name: 'search_papers', label: '論文搜尋', description: '搜尋學術論文(Crossref),回傳標題、作者、年份、期刊、DOI。', parameters: { type: 'object', properties: { query: { type: 'string', description: '論文關鍵字' } }, required: ['query'], }, async run({ query }, ctx) { const params = new URLSearchParams({ query, rows: '6', select: 'title,author,issued,container-title,DOI,URL,is-referenced-by-count' }) const data = await getJSON(`https://api.crossref.org/works?${params}`, { signal: ctx.signal }) const items = data?.message?.items || [] if (!items.length) return `找不到「${query}」相關論文` return items.map((p, i) => { const authors = (p.author || []).slice(0, 3).map((a) => [a.given, a.family].filter(Boolean).join(' ')).join(', ') const year = p.issued?.['date-parts']?.[0]?.[0] || '?' return `[${i + 1}] ${p.title?.[0] || '(無標題)'}\n${authors}${(p.author || []).length > 3 ? ' 等' : ''} · ${year} · ${p['container-title']?.[0] || ''} · 被引用 ${p['is-referenced-by-count'] ?? 0}\nhttps://doi.org/${p.DOI}` }).join('\n\n') }, }, { name: 'search_books', label: '書籍搜尋', description: '搜尋書籍(Open Library),回傳書名、作者、出版年。', parameters: { type: 'object', properties: { query: { type: 'string', description: '書名或作者' } }, required: ['query'], }, async run({ query }, ctx) { // Open Library 要求查詢至少 3 字元;短的中文書名加萬用字元 const q = query.trim().length < 3 ? `${query.trim()}*` : query.trim() const params = new URLSearchParams({ q, limit: '6', fields: 'title,author_name,first_publish_year,key,edition_count' }) const data = await getJSON(`https://openlibrary.org/search.json?${params}`, { signal: ctx.signal }) const docs = data.docs || [] if (!docs.length) return `找不到「${query}」` return docs.map((b, i) => `[${i + 1}] ${b.title} — ${(b.author_name || []).slice(0, 2).join(', ')}(${b.first_publish_year || '?'},${b.edition_count || 1} 個版本)\nhttps://openlibrary.org${b.key}`).join('\n\n') }, }, { name: 'save_note', label: '寫入專案筆記', description: '把重要資訊、結論或待辦寫進目前專案的筆記,之後同專案的任何對話都讀得到。', parameters: { type: 'object', properties: { title: { type: 'string', description: '筆記標題' }, content: { type: 'string', description: '筆記內容(可用 Markdown)' }, }, required: ['title', 'content'], }, run({ title, content }, ctx) { if (!ctx.project) return '目前沒有專案' ctx.addNote(ctx.project.id, { title, content }) return `已寫入專案「${ctx.project.name}」的筆記:${title}` }, }, { name: 'read_notes', label: '讀取專案筆記', description: '讀取目前專案的筆記,可用關鍵字過濾。', parameters: { type: 'object', properties: { keyword: { type: 'string', description: '關鍵字(可省略,省略則全部列出)' } }, }, run({ keyword }, ctx) { const notes = ctx.project?.notes || [] const k = (keyword || '').toLowerCase() const hit = k ? notes.filter((n) => `${n.title}\n${n.content}`.toLowerCase().includes(k)) : notes if (!hit.length) return k ? `沒有包含「${keyword}」的筆記` : '專案目前沒有筆記' return clip(hit.map((n) => `## ${n.title}(${n.updatedAt?.slice(0, 10) || ''})\n${n.content}`).join('\n\n')) }, }, ] export const BUILTIN_TOOL_NAMES = BUILTIN_TOOLS.map((t) => t.name) /* ------------------------------ 自訂 HTTP 工具 ------------------------------ */ /** * 自訂工具可設定 endpoint,例如: * GET https://api.example.com/v1/items?q={query} * POST https://api.example.com/run (參數以 JSON body 送出) * {參數名} 會被替換成 URL 編碼後的參數值。沒有 endpoint 的自訂工具只會回「未實作」。 */ async function runCustomTool(tool, args, ctx) { if (!tool.endpoint?.trim()) { return `自訂工具「${tool.name}」沒有設定 endpoint,無法執行。收到參數:${JSON.stringify(args)}` } const url = tool.endpoint.replace(/\{(\w+)\}/g, (_, k) => encodeURIComponent(args?.[k] ?? '')) const method = (tool.method || 'GET').toUpperCase() let headers = {} if (tool.headers?.trim()) { try { headers = JSON.parse(tool.headers) } catch { return '自訂工具 headers 不是合法 JSON' } } const init = { method, signal: ctx.signal, headers } if (method !== 'GET' && method !== 'HEAD') { init.headers = { 'Content-Type': 'application/json', ...headers } init.body = JSON.stringify(args || {}) } const res = await fetch(url, init) const text = await res.text() return clip(`HTTP ${res.status}\n${text}`) } /* ------------------------------ 對外 API ------------------------------ */ /** 取得某 Agent 可用的工具清單(內建 + 自訂) */ export function resolveTools(enabledNames, customTools) { const all = [...BUILTIN_TOOLS, ...(customTools || []).map((t) => ({ ...t, custom: true }))] const set = new Set(enabledNames || []) return all.filter((t) => set.has(t.name)) } /** 轉成 OpenAI 相容 tools 格式 */ export function toOpenAITools(list) { return (list || []).map((t) => ({ type: 'function', function: { name: t.name, description: t.description || '', parameters: t.parameters || { type: 'object', properties: {} }, }, })) } /** 執行一個 tool_call,永遠回傳字串,不丟例外 */ export async function executeToolCall(call, tools, ctx) { const name = call?.function?.name let args = {} try { args = call?.function?.arguments ? JSON.parse(call.function.arguments) : {} } catch { return `工具參數不是合法 JSON:${call?.function?.arguments}` } const tool = tools.find((t) => t.name === name) if (!tool) return `工具「${name}」不存在或未啟用` try { const out = tool.custom ? await runCustomTool(tool, args, ctx) : await tool.run(args || {}, ctx) return clip(out) } catch (e) { if (e.name === 'AbortError') return '已中止' return `工具「${name}」執行失敗:${e.message}` } } function weatherText(code) { const map = { 0: '晴', 1: '大致晴朗', 2: '局部多雲', 3: '陰', 45: '霧', 48: '霧凇', 51: '毛毛雨', 53: '毛毛雨', 55: '濃毛毛雨', 61: '小雨', 63: '中雨', 65: '大雨', 66: '凍雨', 67: '強凍雨', 71: '小雪', 73: '中雪', 75: '大雪', 77: '雪粒', 80: '陣雨', 81: '較強陣雨', 82: '豪大陣雨', 85: '陣雪', 86: '強陣雪', 95: '雷雨', 96: '雷雨夾冰雹', 99: '強雷雨夾冰雹', } return map[code] ?? `天氣代碼 ${code}` }