feat(search): Ollama 웹검색 1순위 + SearXNG 항상 병행, 결과 합치기(Ollama 앞·URL 중복 제거·본문 6,000자 상한) — 실측에서 Ollama가 약어·최신 질의에 정확, SearXNG는 건수·속도 강점. search.parallel_searxng=false로 끌 수 있음
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f9c8f760fe
commit
6677c4ff71
3 files changed
+197
-4
No files matched your search
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* search-merge.ts
|
||||
*
|
||||
* Ollama 웹검색(1순위)과 SearXNG를 병행할 때 두 결과 목록을 합치는 순수 함수들.
|
||||
*
|
||||
* 왜 합치는가(2026-09-30 실측, 질의 8개). Ollama는 결과가 항상 3건뿐이지만 본문을 통째로
|
||||
* 주고 약어·최신 사실 질의(BPI-R2 MT7623, 기준금리)에서 정확한 출처를 골랐다. SearXNG는 건수가
|
||||
* 많고 빠르지만 같은 질의에서 은행 BPI나 옛 기사를 올렸다. 서로 약점이 다르므로 Ollama 결과를
|
||||
* 앞에 두고 SearXNG로 폭을 채운다.
|
||||
*/
|
||||
|
||||
export type MergeItem = { title: string; url: string; snippet: string };
|
||||
|
||||
/** 같은 문서를 가리키는 URL을 같은 키로 만든다(프로토콜·www·해시·추적 파라미터·끝 슬래시 무시). */
|
||||
export function normalizeUrlKey(url: string): string {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
const host = u.hostname.replace(/^www\./i, '').toLowerCase();
|
||||
const params = new URLSearchParams(u.search);
|
||||
for (const k of Array.from(params.keys())) {
|
||||
if (/^(utm_|fbclid$|gclid$|ref$|source$)/i.test(k)) params.delete(k);
|
||||
}
|
||||
const q = params.toString();
|
||||
const path = u.pathname.replace(/\/+$/, '');
|
||||
return `${host}${path}${q ? `?${q}` : ''}`;
|
||||
} catch {
|
||||
return String(url || '').trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
export interface MergeOptions {
|
||||
/** 뒤쪽(SearXNG) 목록에서 가져올 최대 건수. */
|
||||
maxSecondary: number;
|
||||
/** 앞쪽(Ollama) 결과당 본문 상한 글자수 — 34만자짜리 페이지 한 건이 컨텍스트를 터뜨리지 않게. */
|
||||
primaryCharCap: number;
|
||||
/** 뒤쪽 결과당 본문 상한 글자수. */
|
||||
secondaryCharCap: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* primary를 앞에 그대로 두고, secondary는 primary와 URL이 겹치지 않는 것만 이어 붙인다.
|
||||
* 겹치는 URL이 secondary 쪽 본문이 더 길면 그 본문을 primary 항목에 채워 넣는다(정보 손실 방지).
|
||||
*/
|
||||
export function mergeSearchResults(primary: MergeItem[], secondary: MergeItem[], opts: MergeOptions): MergeItem[] {
|
||||
const cap = (s: string, n: number) => (s.length > n ? s.slice(0, n) : s);
|
||||
const out: MergeItem[] = primary.map((r) => ({ ...r, snippet: cap(r.snippet || '', opts.primaryCharCap) }));
|
||||
const index = new Map<string, MergeItem>();
|
||||
for (const r of out) index.set(normalizeUrlKey(r.url), r);
|
||||
|
||||
let added = 0;
|
||||
for (const r of secondary) {
|
||||
const key = normalizeUrlKey(r.url);
|
||||
const existing = index.get(key);
|
||||
if (existing) {
|
||||
const alt = cap(r.snippet || '', opts.primaryCharCap);
|
||||
if (alt.length > existing.snippet.length) existing.snippet = alt;
|
||||
continue;
|
||||
}
|
||||
if (added >= opts.maxSecondary) continue;
|
||||
const item = { ...r, snippet: cap(r.snippet || '', opts.secondaryCharCap) };
|
||||
out.push(item);
|
||||
index.set(key, item);
|
||||
added++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 본문을 자르지 않는 stdout 렌더링(SearXNG 쪽은 호출자가 짧게 잘라 넘긴다). */
|
||||
export function renderMergedStdout(results: MergeItem[]): string {
|
||||
return results
|
||||
.map((r, i) => `[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet}`)
|
||||
.join('\n\n');
|
||||
}
|
||||
+62
-4
@@ -2,6 +2,7 @@ import { ToolResult } from '../types.js';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { lookupGpuSpecs } from './gpu-specs.js';
|
||||
import { lookupDanawa } from './danawa.js';
|
||||
import { mergeSearchResults, renderMergedStdout } from './search-merge.js';
|
||||
|
||||
type SearchResultItem = { title: string; url: string; snippet: string };
|
||||
|
||||
@@ -520,7 +521,7 @@ function rankResults(query: string, results: SearchResultItem[]) {
|
||||
|
||||
// ── Load optional API keys from config ─────────────────────────────────────
|
||||
// Cached with 5-minute TTL so config changes are picked up without restart.
|
||||
type SearchConfig = { preferred: 'tavily' | 'google' | 'brave' | 'ddg' | 'searxng' | 'ollama_cloud'; tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?: string; searxngUrl?: string; ollamaApiKey?: string };
|
||||
type SearchConfig = { parallelSearxng?: boolean; preferred: 'tavily' | 'google' | 'brave' | 'ddg' | 'searxng' | 'ollama_cloud'; tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?: string; searxngUrl?: string; ollamaApiKey?: string };
|
||||
let _searchConfigCache: { value: SearchConfig; expiresAt: number } | null = null;
|
||||
|
||||
function getSearchConfig(): SearchConfig {
|
||||
@@ -541,6 +542,8 @@ function getSearchConfig(): SearchConfig {
|
||||
braveKey: cm.resolveSecret(data.search?.brave_api_key),
|
||||
searxngUrl: searxngRaw || undefined,
|
||||
ollamaApiKey: cm.resolveSecret(data.search?.ollama_api_key),
|
||||
// Ollama가 1순위일 때 SearXNG를 항상 병행할지. 명시적으로 false가 아니면 켠다.
|
||||
parallelSearxng: (data.search as any)?.parallel_searxng !== false,
|
||||
};
|
||||
} catch {}
|
||||
_searchConfigCache = { value, expiresAt: now + 5 * 60_000 };
|
||||
@@ -696,7 +699,9 @@ async function searchSearXNG(
|
||||
}
|
||||
|
||||
// ── Ollama Cloud web search API (ollama.com, requires OLLAMA_API_KEY) ─────────
|
||||
async function searchOllamaCloud(query: string, limit: number, apiKey: string): Promise<ToolResult> {
|
||||
// snippetCap: 결과당 본문 글자 상한. 기본(400)은 기존 동작 그대로 — data엔 원문을 두고 stdout만 자른다.
|
||||
// 병행 모드(runDualSearch)는 큰 값을 넘겨 data와 stdout 모두 그 길이로 자르고 본문을 거의 다 싣는다.
|
||||
async function searchOllamaCloud(query: string, limit: number, apiKey: string, snippetCap = 400): Promise<ToolResult> {
|
||||
const res = await fetch('https://ollama.com/api/web_search', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
||||
@@ -709,7 +714,7 @@ async function searchOllamaCloud(query: string, limit: number, apiKey: string):
|
||||
const raw: SearchResultItem[] = (data.results || []).slice(0, limit).map((r: any) => ({
|
||||
title: r.title || '',
|
||||
url: r.url || '',
|
||||
snippet: r.content || '',
|
||||
snippet: snippetCap > 400 ? String(r.content || '').slice(0, snippetCap) : (r.content || ''),
|
||||
}));
|
||||
const ranked = rankResults(query, raw);
|
||||
const answer = buildDirectPriceAnswer(query, ranked);
|
||||
@@ -718,7 +723,7 @@ async function searchOllamaCloud(query: string, limit: number, apiKey: string):
|
||||
success: true,
|
||||
data: { query, results: ranked, answer: answer || undefined },
|
||||
stdout: (answer ? `${answer}\n\n` : '') + ranked.map((r, i) =>
|
||||
`[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet.slice(0, 400)}`
|
||||
`[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet.slice(0, snippetCap)}`
|
||||
).join('\n\n'),
|
||||
};
|
||||
}
|
||||
@@ -1018,6 +1023,9 @@ async function withHardwareContext(query: string, res: ToolResult): Promise<Tool
|
||||
}
|
||||
}
|
||||
|
||||
// 병행 모드에서 Ollama 결과당 싣는 본문 상한. 원본은 34만자짜리 페이지도 오므로(STM32 질의) 상한이 필수.
|
||||
const DUAL_OLLAMA_SNIPPET_CAP = 6000;
|
||||
|
||||
async function runSearchProviders(args: { query: string; max_results?: number }): Promise<ToolResult> {
|
||||
if (!args.query?.trim()) return { success: false, error: 'query is required' };
|
||||
let limit = Math.min(args.max_results ?? 5, 10);
|
||||
@@ -1049,6 +1057,55 @@ async function runSearchProviders(args: { query: string; max_results?: number })
|
||||
}
|
||||
};
|
||||
|
||||
// DUAL SEARCH (2026-09-30). Ollama가 1순위로 설정돼 있으면 SearXNG를 항상 병행하고 두 결과를
|
||||
// 합친다. 실측에서 Ollama는 약어·최신 사실 질의에 정확한 출처를 골랐고(결과 3건, 본문 통째),
|
||||
// SearXNG는 건수·속도가 강점이지만 같은 질의에서 빗나갔다 — 약점이 서로 달라 합칠 값이 있다.
|
||||
// 한쪽이 실패하거나 비어도 다른 쪽 결과만으로 답한다. 둘 다 비면 아래 기존 폴백 체인으로 넘어간다.
|
||||
const triedInDual = new Set<SearchProvider>();
|
||||
if (cfg.preferred === 'ollama_cloud' && cfg.parallelSearxng !== false && cfg.ollamaApiKey && cfg.searxngUrl) {
|
||||
triedInDual.add('ollama_cloud');
|
||||
triedInDual.add('searxng');
|
||||
const started = Date.now();
|
||||
const newsOpts = isNewsSeekingQuery(args.query) ? { category: 'news', timeRange: 'week' as const } : undefined;
|
||||
const timed = async (provider: SearchProvider, run: () => Promise<ToolResult>) => {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const r = await run();
|
||||
const n = Array.isArray(r.data?.results) ? r.data.results.length : 0;
|
||||
diagnostics.attempted.push({ provider, status: r.success && n > 0 ? 'success' : (r.success ? 'empty' : 'failed'), duration_ms: Date.now() - t0, result_count: n, ...(!r.success && { reason: r.error }) });
|
||||
return r;
|
||||
} catch (err) {
|
||||
diagnostics.attempted.push({ provider, status: 'failed', reason: (err as any)?.message || String(err), duration_ms: Date.now() - t0 });
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const [ol, sx] = await Promise.all([
|
||||
timed('ollama_cloud', () => searchOllamaCloud(args.query, limit, cfg.ollamaApiKey as string, DUAL_OLLAMA_SNIPPET_CAP)),
|
||||
timed('searxng', () => searchSearXNG(args.query, limit, cfg.searxngUrl as string, newsOpts)),
|
||||
]);
|
||||
const olItems: SearchResultItem[] = ol?.success && Array.isArray(ol.data?.results) ? (ol.data!.results as SearchResultItem[]) : [];
|
||||
let sxItems: SearchResultItem[] = sx?.success && Array.isArray(sx.data?.results) ? (sx.data!.results as SearchResultItem[]) : [];
|
||||
if (isNewsSeekingQuery(args.query)) sxItems = sxItems.filter((r) => !isLowValueNewsResult(r.url));
|
||||
const merged = mergeSearchResults(olItems, sxItems, {
|
||||
maxSecondary: Math.min(Math.max(limit, 5), 10),
|
||||
primaryCharCap: DUAL_OLLAMA_SNIPPET_CAP,
|
||||
secondaryCharCap: 400,
|
||||
});
|
||||
if (merged.length > 0) {
|
||||
const answer = (ol?.data as any)?.answer || (sx?.data as any)?.answer;
|
||||
const res: ToolResult = {
|
||||
success: true,
|
||||
data: { query: args.query, results: merged, answer: answer || undefined },
|
||||
stdout: (answer ? `${answer}\n\n` : '') + renderMergedStdout(merged),
|
||||
};
|
||||
await augmentEventContract(args.query, res);
|
||||
diagnostics.selected_provider = olItems.length > 0 ? 'ollama_cloud' : 'searxng';
|
||||
res.data = { ...(res.data || {}), provider: diagnostics.selected_provider, search_diagnostics: diagnostics };
|
||||
console.log(`[v2] web_search DUAL: ollama=${olItems.length} searxng=${sxItems.length} merged=${merged.length} (${Date.now() - started}ms)`);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
let lastErr = null;
|
||||
// A provider that returned HTTP-OK but zero results is kept as a last-resort answer —
|
||||
// better than a hard error if every provider ends up empty for this query.
|
||||
@@ -1056,6 +1113,7 @@ async function runSearchProviders(args: { query: string; max_results?: number })
|
||||
let bestEmptyProvider: SearchProvider | null = null;
|
||||
|
||||
for (const provider of providerOrder) {
|
||||
if (triedInDual.has(provider)) continue;
|
||||
if (provider === 'tavily' && !cfg.tavilyKey) {
|
||||
diagnostics.attempted.push({ provider, status: 'skipped', reason: 'missing_tavily_api_key' });
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* search-merge — Ollama(1순위) + SearXNG 병행 결과 합치기
|
||||
*
|
||||
* 표본은 2026-09-30 실측: Ollama는 3건에 본문 통째, SearXNG는 건수 많고 본문 짧음.
|
||||
* 고정하는 것: Ollama가 앞, 중복 URL 제거, 본문 상한(34만자 사고 방지), SearXNG 건수 상한.
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mergeSearchResults, normalizeUrlKey, renderMergedStdout } from '../src/tools/search-merge';
|
||||
|
||||
const OPTS = { maxSecondary: 5, primaryCharCap: 6000, secondaryCharCap: 400 };
|
||||
const it = (url: string, snippet = 'x'.repeat(50), title = 't') => ({ title, url, snippet });
|
||||
|
||||
describe('normalizeUrlKey', () => {
|
||||
test('프로토콜·www·끝 슬래시·해시·추적 파라미터를 무시한다', () => {
|
||||
const a = normalizeUrlKey('https://www.news1.kr/a/b/?utm_source=x&id=3#top');
|
||||
const b = normalizeUrlKey('http://news1.kr/a/b?id=3');
|
||||
assert.equal(a, b);
|
||||
});
|
||||
test('id 같은 실제 파라미터는 구분한다', () => {
|
||||
assert.notEqual(normalizeUrlKey('https://a.com/p?id=1'), normalizeUrlKey('https://a.com/p?id=2'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeSearchResults', () => {
|
||||
test('Ollama 결과가 앞에 온다', () => {
|
||||
const m = mergeSearchResults([it('https://o.com/1')], [it('https://s.com/1'), it('https://s.com/2')], OPTS);
|
||||
assert.deepEqual(m.map((r) => r.url), ['https://o.com/1', 'https://s.com/1', 'https://s.com/2']);
|
||||
});
|
||||
|
||||
test('겹치는 URL은 한 번만 나오고, SearXNG 쪽 본문이 더 길면 채워 넣는다', () => {
|
||||
const m = mergeSearchResults([it('https://www.a.com/x', 'short')], [it('http://a.com/x/', 'a much longer snippet from the other engine')], OPTS);
|
||||
assert.equal(m.length, 1);
|
||||
assert.equal(m[0].snippet, 'a much longer snippet from the other engine');
|
||||
});
|
||||
|
||||
test('본문 상한: 34만자 결과가 상한에서 잘린다', () => {
|
||||
const m = mergeSearchResults([it('https://st.com/p', 'y'.repeat(340_000))], [], OPTS);
|
||||
assert.equal(m[0].snippet.length, 6000);
|
||||
});
|
||||
|
||||
test('SearXNG는 건수 상한과 본문 상한을 지킨다', () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => it(`https://s.com/${i}`, 'z'.repeat(900)));
|
||||
const m = mergeSearchResults([], many, OPTS);
|
||||
assert.equal(m.length, 5);
|
||||
assert.equal(m[0].snippet.length, 400);
|
||||
});
|
||||
|
||||
test('한쪽이 비어도 다른 쪽 결과만으로 돌려준다', () => {
|
||||
assert.equal(mergeSearchResults([], [it('https://s.com/1')], OPTS).length, 1);
|
||||
assert.equal(mergeSearchResults([it('https://o.com/1')], [], OPTS).length, 1);
|
||||
assert.equal(mergeSearchResults([], [], OPTS).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderMergedStdout', () => {
|
||||
test('[N] 제목 / URL / 본문 형식을 유지한다 — 다른 가드가 이 형식을 파싱한다', () => {
|
||||
const out = renderMergedStdout([it('https://a.com', 'body text that is long enough to count', 'T1'), it('https://b.com', 'second body text that is long enough', 'T2')]);
|
||||
assert.match(out, /^\[1\] T1\n https:\/\/a\.com\n body text/);
|
||||
assert.match(out, /\n\n\[2\] T2\n/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user