diff --git a/src/gateway/routes/settings.ts b/src/gateway/routes/settings.ts index 49d9d10..b5e1d01 100644 --- a/src/gateway/routes/settings.ts +++ b/src/gateway/routes/settings.ts @@ -4,6 +4,7 @@ import path from 'path'; import { getConfig, ConfigManager } from '../../config/config.js'; import { resetProvider } from '../../providers/factory.js'; import { readUsageRows, summarize } from '../../providers/cost-estimate.js'; +import { getClaudeSearchConfig, getClaudeSearchUsage } from '../../tools/claude-search.js'; // ── Helpers ────────────────────────────────────────────────────────────────── @@ -192,6 +193,28 @@ export function registerSettingsRoutes(app: Express): void { res.json({ success: true, model: cm.getConfig().models.primary }); }); + // ── Claude 자체 웹 검색(web_search 1순위 백엔드) ─────────────────────────────────── + app.get('/api/settings/claude-search', (_req, res) => { + res.json({ success: true, ...getClaudeSearchConfig(), usage: getClaudeSearchUsage() }); + }); + + app.post('/api/settings/claude-search', (req, res) => { + const b = req.body || {}; + const current = cm.getConfig() as any; + const prev = current.search?.claude || {}; + const next: Record = { ...prev }; + if (b.enabled !== undefined) next.enabled = b.enabled === true; + if (b.monthly_limit !== undefined) { + const v = Number(b.monthly_limit); + if (!Number.isFinite(v) || v < 0 || v > 100000) { res.status(400).json({ success: false, error: 'monthly_limit must be 0..100000' }); return; } + next.monthly_limit = Math.floor(v); + } + if (b.max_uses !== undefined) next.max_uses = Math.min(Math.max(Number(b.max_uses) || 3, 1), 6); + if (b.model !== undefined && /^claude-[\w.-]{3,60}$/.test(String(b.model))) next.model = String(b.model); + cm.updateConfig({ search: { ...(current.search || {}), claude: next } } as any); + res.json({ success: true, ...getClaudeSearchConfig(), usage: getClaudeSearchUsage() }); + }); + // ── 사용 비용 추산 (token-usage.jsonl × 단가표) + 앤트로픽 잔액 추산 ───────────────────── app.get('/api/usage/cost', (_req, res) => { const billing = ((cm.getConfig() as any).billing?.anthropic) || {}; diff --git a/src/providers/cost-estimate.ts b/src/providers/cost-estimate.ts index a14a61e..a58ed83 100644 --- a/src/providers/cost-estimate.ts +++ b/src/providers/cost-estimate.ts @@ -30,12 +30,13 @@ export function priceFor(model: string, promptTokens: number, isoDate: string): return null; } -export interface UsageRow { ts: string; model: string; promptTokens: number; completionTokens: number } +export interface UsageRow { ts: string; model: string; promptTokens: number; completionTokens: number; extraUsd?: number } export function costOf(row: UsageRow): number | null { const p = priceFor(row.model, row.promptTokens, row.ts.slice(0, 10)); - if (!p) return null; - return (row.promptTokens * p.in + row.completionTokens * p.out) / 1_000_000; + const extra = row.extraUsd || 0; + if (!p) return extra || null; + return (row.promptTokens * p.in + row.completionTokens * p.out) / 1_000_000 + extra; } const KST_MS = 9 * 3600_000; @@ -51,7 +52,7 @@ export function readUsageRows(file?: string): UsageRow[] { if (!line.trim()) continue; try { const r = JSON.parse(line); - if (r?.ts && r?.model) rows.push({ ts: String(r.ts), model: String(r.model), promptTokens: Number(r.promptTokens) || 0, completionTokens: Number(r.completionTokens) || 0 }); + if (r?.ts && r?.model) rows.push({ ts: String(r.ts), model: String(r.model), promptTokens: Number(r.promptTokens) || 0, completionTokens: Number(r.completionTokens) || 0, ...(r.extraUsd ? { extraUsd: Number(r.extraUsd) } : {}) }); } catch { /* 깨진 줄은 건너뜀 */ } } return rows; diff --git a/src/providers/usage-log.ts b/src/providers/usage-log.ts index 73c260b..72eb96d 100644 --- a/src/providers/usage-log.ts +++ b/src/providers/usage-log.ts @@ -19,12 +19,13 @@ const USAGE_LOG_PATH = (() => { catch { return null; } })(); -export function logUsage(model: string, promptTokens: number, completionTokens: number): void { - if (!USAGE_LOG_PATH || (!promptTokens && !completionTokens)) return; +export function logUsage(model: string, promptTokens: number, completionTokens: number, extraUsd = 0): void { + if (!USAGE_LOG_PATH || (!promptTokens && !completionTokens && !extraUsd)) return; try { fs.mkdirSync(path.dirname(USAGE_LOG_PATH), { recursive: true }); fs.appendFileSync(USAGE_LOG_PATH, JSON.stringify({ ts: new Date().toISOString(), model, promptTokens, completionTokens, + ...(extraUsd ? { extraUsd } : {}), // 토큰 외 과금(예: Claude 웹 검색 수수료) }) + '\n'); } catch { /* non-fatal */ } } diff --git a/src/tools/claude-search.ts b/src/tools/claude-search.ts new file mode 100644 index 0000000..59b3d66 --- /dev/null +++ b/src/tools/claude-search.ts @@ -0,0 +1,128 @@ +/** + * claude-search.ts — Claude 자체 웹 검색(Anthropic 서버 도구)을 web_search의 1순위 백엔드로. + * + * 2026-10-17 10개 질문 비교(Haiku 5.5): Claude 자체 검색 8.0점 / 올라마 검색 결과 3.9 / 기존 병행 구성 4.2. + * 모델이 필요한 만큼(질문당 평균 2회) 검색을 되풀이하고 여러 출처에서 사실을 모아 인용을 붙인다. + * 대가는 검색 1회 $0.01(+ 토큰, 질문당 합계 약 $0.022)라서 월 사용 횟수에 상한을 둔다. + * 어떤 이유로든 실패하면 null을 돌려주고 호출자가 기존 검색 체인(SearXNG·올라마·…)으로 넘어간다. + */ +import fs from 'fs'; +import path from 'path'; +import { getConfig } from '../config/config'; +import { logUsage } from '../providers/usage-log'; +import type { ToolResult } from '../types'; + +const SEARCH_FEE_USD = 0.01; +const DEFAULT_MODEL = 'claude-haiku-5-5'; + +const SYSTEM = [ + '당신은 웹 검색 보조원입니다. 웹 검색 도구로 최신 정보를 확인한 뒤, 질문에 직접 답하는 사실 위주의 요약을 한국어로 쓰세요.', + '- 수치·날짜·이름은 출처에 나온 그대로 쓰고 지어내지 마세요. 출처 간 값이 다르면 둘 다 밝히세요.', + '- 핵심 사실마다 출처 도메인을 괄호로 적으세요. 8문장 이내.', + '- 확인하지 못한 것은 "확인하지 못했다"고 쓰세요.', +].join('\n'); + +export interface ClaudeSearchConfig { enabled: boolean; model: string; max_uses: number; monthly_limit: number } + +export function getClaudeSearchConfig(): ClaudeSearchConfig { + let c: any = {}; + try { c = (getConfig().getConfig() as any)?.search?.claude || {}; } catch { /* 기본값 */ } + return { + enabled: c.enabled !== false, // 기본 켜짐(키가 없으면 자동으로 건너뜀) + model: String(c.model || DEFAULT_MODEL), + max_uses: Math.min(Math.max(Number(c.max_uses) || 3, 1), 6), + monthly_limit: Number.isFinite(Number(c.monthly_limit)) && Number(c.monthly_limit) >= 0 ? Number(c.monthly_limit) : 300, + }; +} + +function usageFile(): string | null { + try { return path.join(getConfig().getConfigDir(), 'claude-search-usage.json'); } catch { return null; } +} +const monthKey = (d = new Date()) => new Date(d.getTime() + 9 * 3600_000).toISOString().slice(0, 7); // KST 기준 월 + +export function getClaudeSearchUsage(): { month: string; count: number } { + const f = usageFile(); + try { const r = JSON.parse(fs.readFileSync(f as string, 'utf-8')); if (r.month === monthKey()) return { month: r.month, count: Number(r.count) || 0 }; } catch { /* 새 달/없음 */ } + return { month: monthKey(), count: 0 }; +} +function addClaudeSearchUsage(n: number): void { + const f = usageFile(); if (!f) return; + const u = getClaudeSearchUsage(); + try { fs.writeFileSync(f, JSON.stringify({ month: u.month, count: u.count + n })); } catch { /* non-fatal */ } +} + +export interface ParsedNative { text: string; sources: Array<{ title: string; url: string }>; searches: number; inputTokens: number; outputTokens: number; paused: boolean } + +/** Anthropic 응답(들)에서 답변 텍스트·출처·사용량을 뽑는다 (순수 함수 — 테스트 대상). */ +export function parseNativeResponses(responses: any[]): ParsedNative { + const sources: Array<{ title: string; url: string }> = []; + const seen = new Set(); + const add = (url?: string, title?: string) => { if (url && !seen.has(url)) { seen.add(url); sources.push({ title: String(title || url), url }); } }; + let text = '', searches = 0, inputTokens = 0, outputTokens = 0, paused = false; + for (const d of responses) { + const u = d?.usage || {}; + inputTokens += (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0); + outputTokens += u.output_tokens || 0; + searches += u.server_tool_use?.web_search_requests || 0; + paused = d?.stop_reason === 'pause_turn'; + for (const b of d?.content || []) { + if (b.type === 'text') { text += b.text || ''; for (const c of b.citations || []) add(c.url, c.title); } + if (b.type === 'web_search_tool_result' && Array.isArray(b.content)) for (const r of b.content) add(r.url, r.title); + } + } + return { text: text.trim(), sources, searches, inputTokens, outputTokens, paused }; +} + +/** 성공하면 ToolResult, 꺼짐·키 없음·한도 초과·오류면 null. */ +export async function claudeWebSearch(query: string): Promise { + const cfg = getClaudeSearchConfig(); + if (!cfg.enabled || !query?.trim()) return null; + const usage = getClaudeSearchUsage(); + if (usage.count >= cfg.monthly_limit) { + console.log(`[v2] claude_search: monthly limit reached (${usage.count}/${cfg.monthly_limit}) — falling back to the standard search chain`); + return null; + } + let apiKey: string | undefined; + try { + const c: any = getConfig(); + apiKey = c.resolveSecret(c.getConfig()?.llm?.providers?.anthropic?.api_key) || c.resolveSecret('vault:anthropic.api_key'); + } catch { /* 키 없음 */ } + if (!apiKey) return null; + + const started = Date.now(); + try { + const responses: any[] = []; + let messages: any[] = [{ role: 'user', content: `다음 내용을 웹에서 검색해 확인하고 답하세요:\n${query.trim()}` }]; + for (let round = 0; round < 4; round++) { + const res = await fetch('https://api.anthropic.com/v1/messages', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' }, + body: JSON.stringify({ + model: cfg.model, max_tokens: 1800, system: SYSTEM, messages, + tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: cfg.max_uses, allowed_callers: ['direct'] }], + }), + signal: AbortSignal.timeout(60_000), + }); + if (!res.ok) { console.log(`[v2] claude_search: HTTP ${res.status} — fallback`); return null; } + const data: any = await res.json(); + responses.push(data); + if (data.stop_reason !== 'pause_turn') break; + messages = [messages[0], { role: 'assistant', content: data.content }]; // 일시정지된 턴은 그대로 돌려보내 이어간다 + } + const p = parseNativeResponses(responses); + if (!p.text) { console.log(`[v2] claude_search: empty answer (stop=${responses[responses.length - 1]?.stop_reason}, searches=${p.searches}) — fallback`); return null; } + // 비용 기록: 토큰은 모델 단가로, 검색 수수료는 별도 필드로(비용 패널이 합산) + logUsage(cfg.model, p.inputTokens, p.outputTokens, p.searches * SEARCH_FEE_USD); + addClaudeSearchUsage(p.searches); + const srcLines = p.sources.slice(0, 10).map((s, i) => `[${i + 1}] ${s.title}\n ${s.url}`).join('\n'); + console.log(`[v2] claude_search: ${p.searches} search(es), ${p.sources.length} sources, ${Date.now() - started}ms (month ${usage.count + p.searches}/${cfg.monthly_limit})`); + return { + success: true, + data: { query, provider: 'claude_native', results: p.sources.map(s => ({ title: s.title, url: s.url, snippet: '' })), answer: p.text, searches: p.searches }, + stdout: `[Claude 웹 검색 결과 — 모델이 웹을 직접 검색해 확인한 내용입니다]\n${p.text}\n\n[출처]\n${srcLines || '(출처 없음)'}`, + }; + } catch (e: any) { + console.log(`[v2] claude_search: ${e?.message || e} — fallback`); + return null; + } +} diff --git a/src/tools/web.ts b/src/tools/web.ts index 2a8107f..26dd192 100644 --- a/src/tools/web.ts +++ b/src/tools/web.ts @@ -3,6 +3,7 @@ import { getConfig } from '../config/config.js'; import { lookupGpuSpecs } from './gpu-specs.js'; import { lookupDanawa } from './danawa.js'; import { fetchMainText } from './web-extract.js'; +import { claudeWebSearch } from './claude-search.js'; import { mergeSearchResults, renderMergedStdout, normalizePreferredProvider } from './search-merge.js'; type SearchResultItem = { title: string; url: string; snippet: string }; @@ -1407,6 +1408,9 @@ async function deepReadResults(results: any[], maxPages = 3, perPageChars = 2500 } export async function executeWebSearchWithExtraction(args: { query: string; max_results?: number }): Promise { + // 1순위: Claude 자체 웹 검색(꺼짐·키 없음·월 한도 초과·오류면 null → 아래 기존 체인으로) + const claude = await claudeWebSearch(args.query); + if (claude) return claude; let res = await executeWebSearch(args); if (!res.success || !res.stdout) return res; diff --git a/tests/claude-search.test.ts b/tests/claude-search.test.ts new file mode 100644 index 0000000..d276b1f --- /dev/null +++ b/tests/claude-search.test.ts @@ -0,0 +1,47 @@ +/** + * claude-search — 응답 파싱(출처·인용·사용량)과 비용 합산. + */ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseNativeResponses } from '../src/tools/claude-search'; +import { costOf } from '../src/providers/cost-estimate'; + +const resp = (over: any = {}) => ({ + stop_reason: 'end_turn', + usage: { input_tokens: 5000, output_tokens: 400, server_tool_use: { web_search_requests: 2 } }, + content: [ + { type: 'text', text: '재판은 2027년 6월 14일 시작합니다 ' , citations: [{ type: 'web_search_result_location', url: 'https://a.com/x', title: 'A' }] }, + { type: 'server_tool_use', name: 'web_search', input: { query: 'q' } }, + { type: 'web_search_tool_result', content: [{ type: 'web_search_result', url: 'https://a.com/x', title: 'A' }, { type: 'web_search_result', url: 'https://b.com/y', title: 'B' }] }, + { type: 'text', text: '(abc7.com).' }, + ], + ...over, +}); + +describe('parseNativeResponses', () => { + test('텍스트 이어 붙이기·출처 중복 제거·검색 횟수·토큰', () => { + const p = parseNativeResponses([resp()]); + assert.equal(p.text, '재판은 2027년 6월 14일 시작합니다 (abc7.com).'); + assert.deepEqual(p.sources.map(s => s.url), ['https://a.com/x', 'https://b.com/y']); + assert.equal(p.searches, 2); + assert.equal(p.inputTokens, 5000); + assert.equal(p.paused, false); + }); + test('pause_turn은 이어서 합산하고 마지막 상태를 반영', () => { + const p = parseNativeResponses([resp({ stop_reason: 'pause_turn' }), resp()]); + assert.equal(p.searches, 4); + assert.equal(p.paused, false); + }); + test('오류 결과(content가 객체)여도 예외 없이', () => { + const p = parseNativeResponses([{ stop_reason: 'end_turn', usage: {}, content: [{ type: 'web_search_tool_result', content: { type: 'web_search_tool_result_error', error_code: 'unavailable' } }, { type: 'text', text: '확인하지 못했다' }] }]); + assert.equal(p.sources.length, 0); + assert.equal(p.text, '확인하지 못했다'); + }); +}); + +describe('비용 합산', () => { + test('토큰 비용 + 검색 수수료($0.01/회)', () => { + const c = costOf({ ts: '2026-10-17T00:00:00Z', model: 'claude-haiku-5-5', promptTokens: 5000, completionTokens: 400, extraUsd: 0.02 })!; + assert.ok(Math.abs(c - ((5000 * 0.1 + 400 * 0.5) / 1e6 + 0.02)) < 1e-12); + }); +}); diff --git a/web-ui/html/index.html b/web-ui/html/index.html index db7be40..f98cb0e 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -1123,6 +1123,23 @@
날씨·뉴스 등 실시간/사실 조회, 모델을 직접 고른 대화, 이미지가 있는 대화는 항상 기본 모델이 처리합니다. 이 항목은 아래 전체 저장 버튼과 별개로 이 버튼에서 바로 저장됩니다.
+ +
+
Claude 웹 검색 (검색 1순위)
+ +
+ + + + +
+
검색 1회 $0.01 + 토큰으로 질문당 약 2센트입니다(10개 질문 비교에서 품질 8.0점 대 기존 약 4점). 이번 달 사용 횟수는 위에 표시되고, 비용은 아래 "사용 비용" 패널에 합산됩니다.
+
+
사용 비용 (추산)
diff --git a/web-ui/js/app/settings-provider.js b/web-ui/js/app/settings-provider.js index 1aa3da8..056d095 100644 --- a/web-ui/js/app/settings-provider.js +++ b/web-ui/js/app/settings-provider.js @@ -188,7 +188,7 @@ function setSettingsTab(tab) { if (t === tab) { panel.style.display = 'block'; if (t === 'channels') loadChannelsStatus(); - if (t === 'models') { loadModelSettings().finally(() => { try { loadRoutingSettings(); loadCostPanel(); } catch {} }); } + if (t === 'models') { loadModelSettings().finally(() => { try { loadRoutingSettings(); loadClaudeSearch(); loadCostPanel(); } catch {} }); } if (t === 'agents') loadAgentsTab(); if (t === 'integrations') loadIntegrationsTab(); if (t === 'credentials') loadCredentialsTab(); @@ -1631,3 +1631,28 @@ async function saveCostBalance() { if (note) { note.style.color = '#c0392b'; note.textContent = '저장 실패: ' + e.message; } } } + + +// ── Claude 웹 검색 설정 ─────────────────────────────────────────────────────── +async function loadClaudeSearch() { + const st = document.getElementById('cs-status'); + try { + const r = await api('/api/settings/claude-search'); + document.getElementById('cs-enabled').checked = r.enabled === true; + document.getElementById('cs-limit').value = r.monthly_limit; + document.getElementById('cs-max-uses').value = r.max_uses; + if (st) st.textContent = '이번 달 ' + r.usage.count + ' / ' + r.monthly_limit + '회 사용'; + } catch (e) { if (st) st.textContent = '불러오기 실패: ' + e.message; } +} + +async function saveClaudeSearch() { + const st = document.getElementById('cs-status'); + try { + const r = await api('/api/settings/claude-search', { method: 'POST', body: JSON.stringify({ + enabled: !!document.getElementById('cs-enabled').checked, + monthly_limit: Number(document.getElementById('cs-limit').value), + max_uses: Number(document.getElementById('cs-max-uses').value), + }) }); + if (st) st.textContent = '저장됨 — ' + (r.enabled ? '켜짐' : '꺼짐') + ' · 이번 달 ' + r.usage.count + ' / ' + r.monthly_limit + '회'; + } catch (e) { if (st) st.textContent = '저장 실패: ' + e.message; } +}