diff --git a/scripts/extract-daily-memory.ts b/scripts/extract-daily-memory.ts index a60d778..f2b6aab 100644 --- a/scripts/extract-daily-memory.ts +++ b/scripts/extract-daily-memory.ts @@ -5,6 +5,7 @@ // this replaces that approach with real extraction. import fs from 'fs'; import path from 'path'; +import { lightChat } from '../src/providers/light-chat'; import { addVector, hasAnyVector, DAILY_EXTRACTS_COLLECTION } from '../src/gateway/memory/memory-vector'; const WORKSPACES: { workspace: string; label: string }[] = [ @@ -14,8 +15,6 @@ const WORKSPACES: { workspace: string; label: string }[] = [ { workspace: '/srv/homeclaw/.smallclaw/workspace', label: 'global' }, ]; -const OLLAMA_ENDPOINT = 'http://localhost:11434'; -const EXTRACT_MODEL = 'gemma4:31b-cloud'; // matches homeclaw's configured primary model async function extractFacts(dayContent: string): Promise { const prompt = `다음은 하루치 대화 로그입니다. 이 중에서 나중에 다시 참고할 가치가 있는 사실만 뽑아줘. @@ -31,19 +30,9 @@ async function extractFacts(dayContent: string): Promise { ${dayContent} --- 로그 끝 ---`; - const res = await fetch(`${OLLAMA_ENDPOINT}/api/chat`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - model: EXTRACT_MODEL, - messages: [{ role: 'user', content: prompt }], - stream: false, - }), - signal: AbortSignal.timeout(120_000), - }); - if (!res.ok) throw new Error(`extract HTTP ${res.status}`); - const data: any = await res.json(); - const raw = String(data?.message?.content || '').trim(); + // 활성 provider의 싼 모델로(올라마 직접 호출 제거) — 실패하면 던져서 그 날을 '실패'로 세고 다음 실행에서 다시 시도한다 + const raw = await lightChat([{ role: 'user', content: prompt }], { max_tokens: 2000, temperature: 0.1, timeoutMs: 120_000 }); + if (raw === null) throw new Error('extract LLM call failed'); if (!raw || raw === '없음') return []; return raw diff --git a/scripts/tool-bench.py b/scripts/tool-bench.py index 6e195a1..89bf442 100644 --- a/scripts/tool-bench.py +++ b/scripts/tool-bench.py @@ -147,7 +147,8 @@ def _chat_anthropic(model, messages, timeout): tools = [{"name": t["function"]["name"], "description": t["function"]["description"], "input_schema": t["function"]["parameters"]} for t in TOOLS] data = _post("https://api.anthropic.com/v1/messages", - {"model": model, "max_tokens": 1024, "system": system, "messages": out, "tools": tools}, + {"model": model, "max_tokens": 1024, "system": system, "messages": out, "tools": tools, + **({"thinking": {"type": "disabled"}} if os.environ.get("ANTHROPIC_THINKING") == "off" else {})}, {"x-api-key": key, "anthropic-version": "2023-06-01"}, timeout) text = "".join(b.get("text", "") for b in data.get("content", []) if b.get("type") == "text") tcs = [{"id": b["id"], "function": {"name": b["name"], "arguments": b.get("input") or {}}} diff --git a/src/gateway/memory/memory-rerank.ts b/src/gateway/memory/memory-rerank.ts index eb4ba3c..4827b0e 100644 --- a/src/gateway/memory/memory-rerank.ts +++ b/src/gateway/memory/memory-rerank.ts @@ -10,6 +10,7 @@ // distance-threshold behavior — this must never be a hard dependency for prompt building, // same "best-effort" rule as the vector/FTS retrieval it sits on top of. import { getConfig } from '../../config/config.js'; +import { lightChat } from '../../providers/light-chat.js'; // "flash"-tier model chosen specifically for latency, not quality — this call is a small // classification task (pick relevant indices from a short list), not a task worth spending @@ -41,15 +42,9 @@ export async function rerankCandidates(query: string, candidates: RerankCandidat ${listText}`; try { - const res = await fetch(`${getOllamaEndpoint()}/api/chat`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model: RERANK_MODEL, messages: [{ role: 'user', content: prompt }], stream: false }), - signal: AbortSignal.timeout(RERANK_TIMEOUT_MS), - }); - if (!res.ok) throw new Error(`rerank HTTP ${res.status}`); - const data: any = await res.json(); - const raw = String(data?.message?.content || '').trim(); + // 활성 provider의 싼 모델로(올라마 직접 호출 제거 — light-chat.ts 참고) + const raw = await lightChat([{ role: 'user', content: prompt }], { max_tokens: 120, temperature: 0, timeoutMs: RERANK_TIMEOUT_MS }); + if (raw === null) throw new Error('rerank call failed'); if (!raw || raw === '없음') return []; const seen = new Set(); diff --git a/src/gateway/routes/routes-detective-dates.ts b/src/gateway/routes/routes-detective-dates.ts index 2f2bb45..5894ce4 100644 --- a/src/gateway/routes/routes-detective-dates.ts +++ b/src/gateway/routes/routes-detective-dates.ts @@ -5,6 +5,7 @@ * on-screen date — chat timestamps, receipt dates, etc.) and store it as a * pending suggestion on the case for the user to approve into the timeline. */ +import { visionModelOverride } from '../../providers/light-chat.js'; import express from 'express'; import path from 'path'; import fs from 'fs'; @@ -120,7 +121,7 @@ async function readVisionDate(imgPath: string): Promise<{ date?: string; monthDa ], }], 'executor', - { model: 'kimi-k2.6:cloud', num_predict: 1500, temperature: 0.1 }, + { model: visionModelOverride('kimi-k2.6:cloud'), num_predict: 1500, temperature: 0.1 }, ); const raw = String(result.message?.content || '').trim(); const m = raw.match(/\{[\s\S]*\}/); @@ -179,7 +180,7 @@ async function readTextDate(filePath: string): Promise<{ date?: string; monthDay const result = await ollama.chatWithThinking( [{ role: 'user', content: prompt }], 'executor', - { model: 'kimi-k2.6:cloud', num_predict: 1500, temperature: 0.1 }, + { model: visionModelOverride('kimi-k2.6:cloud'), num_predict: 1500, temperature: 0.1 }, ); const raw = String(result.message?.content || '').trim(); const m = raw.match(/\{[\s\S]*\}/); diff --git a/src/gateway/routes/routes-pptx.ts b/src/gateway/routes/routes-pptx.ts index d3e5977..22a13e2 100644 --- a/src/gateway/routes/routes-pptx.ts +++ b/src/gateway/routes/routes-pptx.ts @@ -1,3 +1,4 @@ +import { visionModelOverride } from '../../providers/light-chat.js'; import express from 'express'; import path from 'path'; import fs from 'fs'; @@ -915,7 +916,7 @@ app.post('/api/pptx/analyze-image', requireGatewayAuth, async (req: express.Requ const ollama2 = getOllamaClient(); const rawCfg2 = getConfig().getConfig() as any; const sec2 = rawCfg2.orchestration?.secondary; - const visionModel = (sec2?.model && sec2?.vision === true) ? sec2.model : 'mistral-large-3:675b-cloud'; + const visionModel = (sec2?.model && sec2?.vision === true) ? sec2.model : visionModelOverride('mistral-large-3:675b-cloud'); const result = await ollama2.chatWithThinking([{ role: 'user' as const, diff --git a/src/gateway/routes/settings.ts b/src/gateway/routes/settings.ts index b5e1d01..178baff 100644 --- a/src/gateway/routes/settings.ts +++ b/src/gateway/routes/settings.ts @@ -159,7 +159,7 @@ export function registerSettingsRoutes(app: Express): void { }); app.post('/api/settings/model', (req, res) => { - const { primary, roles, ollama_endpoint } = req.body; + const { primary, roles, ollama_endpoint, fallback } = req.body; const current = cm.getConfig(); if (primary || roles) { const newPrimary = primary || current.models.primary; @@ -189,6 +189,11 @@ export function registerSettingsRoutes(app: Express): void { ollama: { ...(current as any).ollama, endpoint: ollama_endpoint } } as any); } + // 오류(할당량·모델 폐기) 시 재시도할 대체 모델. 활성 provider의 모델 이름이어야 한다(예: Anthropic이면 claude-…) + if (typeof fallback === 'string' && fallback.length <= 120) { + const cur2 = cm.getConfig(); + cm.updateConfig({ models: { ...cur2.models, fallback: fallback.trim() } } as any); + } resetProvider(); res.json({ success: true, model: cm.getConfig().models.primary }); }); diff --git a/src/providers/anthropic-adapter.ts b/src/providers/anthropic-adapter.ts index f09cf18..7526afe 100644 --- a/src/providers/anthropic-adapter.ts +++ b/src/providers/anthropic-adapter.ts @@ -19,6 +19,16 @@ export function acceptsTemperature(model: string): boolean { return !/claude-(?:opus|sonnet|haiku|fable|mythos)-5/i.test(String(model || '')); } +/** + * Haiku 5.5는 기본으로 "생각"부터 한다. max_tokens가 작은 보조 호출(번역·재순위 등)은 생각만 하다 끝나 본문이 비고 + * (2026-10-17: 20토큰 한도 → thinking 블록만, 텍스트 없음), 일반 채팅도 생각 토큰만큼 느리고 비싸다. + * 요청이 생각을 원하지 않으면(options.think 없음/false) 끈다 — 도구호출 벤치마크는 끈 상태에서도 42/42, 속도 동일. + * Sonnet 5.5는 기본이 "생각 안 함"이고 disabled를 거부하며, Opus 5.5도 disabled를 거부하므로 Haiku에만 적용한다. + */ +export function shouldDisableThinking(model: string, think: unknown): boolean { + return !think && /claude-haiku-5/i.test(String(model || '')); +} + export class AnthropicAdapter implements LLMProvider { readonly id = 'anthropic' as const; private apiKey: string; @@ -63,6 +73,7 @@ export class AnthropicAdapter implements LLMProvider { }; if (system) body.system = system; if (options?.temperature !== undefined && acceptsTemperature(model)) body.temperature = options.temperature; + if (shouldDisableThinking(model, (options as any)?.think)) body.thinking = { type: 'disabled' }; if (Array.isArray(options?.tools) && options!.tools!.length) { body.tools = toAnthropicTools(options!.tools!); } @@ -89,6 +100,7 @@ export class AnthropicAdapter implements LLMProvider { }; if (options?.system) body.system = options.system; if (options?.temperature !== undefined && acceptsTemperature(model)) body.temperature = options.temperature; + if (shouldDisableThinking(model, undefined)) body.thinking = { type: 'disabled' }; const data = await this.post('/v1/messages', body); const text = (data.content || []).filter((b: any) => b.type === 'text').map((b: any) => b.text).join(''); diff --git a/src/providers/factory.ts b/src/providers/factory.ts index 2b8079e..f2ce73d 100644 --- a/src/providers/factory.ts +++ b/src/providers/factory.ts @@ -278,6 +278,11 @@ export function getFallbackModel(): string { * "모델은?" 같은 질문에 모델이 지어내지 않고 답하게 한다(2026-10-17: Gemini로 돌면서 "오픈소스 Ollama 모델"이라고 오답). * 구글 한도 때문에 대체 모델로 돌고 있으면 그 사실대로 반영한다. */ +/** 구글 한도 대체 등을 반영한, 지금 실제로 쓰는 provider ID. */ +export function getEffectiveActiveProvider(): string { + try { return String(getEffectiveProviderConfig().active); } catch { return 'ollama'; } +} + export function getActiveBackendLabel(): string { try { const { active, providers } = getEffectiveProviderConfig(); diff --git a/src/providers/light-chat.ts b/src/providers/light-chat.ts new file mode 100644 index 0000000..532c3d1 --- /dev/null +++ b/src/providers/light-chat.ts @@ -0,0 +1,49 @@ +/** + * light-chat.ts — 번역·재순위·요약처럼 가볍고 모델이 중요하지 않은 보조 LLM 호출을 "활성 provider의 싼 모델"로. + * + * 2026-10-17: 이 호출들이 올라마 /api/chat에 gemma4:31b-cloud를 직접 박아 두어서, 기본 모델을 Anthropic으로 옮기고도 + * 올라마 구독에 매여 있었다(기억 재순위·이미지 프롬프트 번역·논문 검색어 번역·검색 결과 요약·야간 기억 추출). + * 여기서는 활성 provider에 맞는 싼 모델로 provider 추상화를 통해 부른다. 실패하면 null(호출자는 모두 best-effort). + */ +import { getConfig } from '../config/config'; +import { getProvider, getEffectiveActiveProvider } from './factory'; +import { contentToString } from './content-utils'; + +/** 활성 provider별 "가볍고 싼" 모델. */ +export function lightModel(): string { + const cfg = getConfig().getConfig() as any; + const active = getEffectiveActiveProvider(); + const pm = (id: string) => String(cfg?.llm?.providers?.[id]?.model || '').trim(); + switch (active) { + case 'anthropic': return 'claude-haiku-5-5'; + case 'google': return pm('google') || 'gemini-3.5-flash-lite'; + case 'openai': return 'gpt-4o-mini'; + case 'ollama': + case 'ollama_local': return pm(active) || 'gemma4:31b-cloud'; + default: return pm(active) || String(cfg?.models?.primary || ''); + } +} + +/** + * 이미지를 읽는 호출에 줄 모델 이름. 올라마일 때만 비전 성능으로 고른 올라마 모델(ollamaModel)을 쓰고, + * 그 밖의 provider에서는 undefined → 호출자가 활성 provider의 기본 모델(Claude·Gemini·GPT는 모두 비전 지원)을 쓴다. + */ +export function visionModelOverride(ollamaModel: string): string | undefined { + const active = getEffectiveActiveProvider(); + return active === 'ollama' || active === 'ollama_local' ? ollamaModel : undefined; +} + +export async function lightChat( + messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>, + opts: { max_tokens?: number; temperature?: number; timeoutMs?: number } = {}, +): Promise { + try { + const timeoutMs = opts.timeoutMs ?? 30_000; + const call = getProvider().chat(messages as any, lightModel(), { max_tokens: opts.max_tokens ?? 1000, temperature: opts.temperature ?? 0.2 } as any); + const r: any = await Promise.race([call, new Promise((_, rej) => setTimeout(() => rej(new Error('lightChat timeout')), timeoutMs))]); + const text = contentToString(r?.message?.content ?? '').trim(); + return text || null; + } catch { + return null; + } +} diff --git a/src/tools/imagegen.ts b/src/tools/imagegen.ts index a54ac8b..7c2c2e3 100644 --- a/src/tools/imagegen.ts +++ b/src/tools/imagegen.ts @@ -4,7 +4,7 @@ import fs from 'fs'; import { ToolResult } from '../types.js'; import { getWorkspacePath } from '../config/paths.js'; import { buildImageMarkdown, toFiniteNumber, isPathInsideDir } from './image.js'; -import { getOllamaConfig } from './web.js'; +import { lightChat } from '../providers/light-chat.js'; // SDXL/LTX-Video's text encoders (CLIP/T5) are trained overwhelmingly on English // captions, so non-English prompts (e.g. Korean) produce poor prompt adherence. @@ -13,23 +13,10 @@ import { getOllamaConfig } from './web.js'; async function translatePromptToEnglish(text: string): Promise { if (!text || !/[^\x00-\x7F]/.test(text)) return null; try { - const { endpoint, model } = getOllamaConfig(); - const res = await fetch(`${endpoint}/api/chat`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - model, - messages: [{ - role: 'user', - content: `Translate the following image/video generation prompt into natural, descriptive English. Output ONLY the translated English text — no quotes, no explanation:\n\n${text}`, - }], - stream: false, - }), - signal: AbortSignal.timeout(30_000), - }); - if (!res.ok) return null; - const data: any = await res.json(); - const translated = String(data.message?.content || '').trim(); + const translated = await lightChat([{ + role: 'user', + content: `Translate the following image/video generation prompt into natural, descriptive English. Output ONLY the translated English text — no quotes, no explanation:\n\n${text}` + }], { max_tokens: 400, temperature: 0.2, timeoutMs: 30_000 }); return translated || null; } catch { return null; diff --git a/src/tools/query-translate.ts b/src/tools/query-translate.ts index fd3ce94..cd69965 100644 --- a/src/tools/query-translate.ts +++ b/src/tools/query-translate.ts @@ -1,4 +1,4 @@ -import { getOllamaConfig } from './web.js'; +import { lightChat } from '../providers/light-chat.js'; // Paper-search backends (PubMed, EuropePMC, Semantic Scholar) index English text only. // A Korean query makes PubMed fall back to arbitrary recent papers (cancer, neurology…), @@ -16,24 +16,11 @@ export async function toPaperSearchQuery(query: string): Promise { const hit = cache.get(q); if (hit) return hit; try { - const { endpoint, model } = getOllamaConfig(); - const res = await fetch(`${endpoint}/api/chat`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - model, - think: false, - messages: [{ - role: 'user', - content: `Convert this research topic into a concise English keyword query for PubMed/OpenAlex literature search. Use 2-6 specific scientific terms (MeSH-style). Drop filler words like "latest", "recent", "methods", "overview", "and". No boolean operators, no quotes. Output ONLY the keywords on one line.\n\nTopic: ${q}`, - }], - stream: false, - }), - signal: AbortSignal.timeout(20_000), - }); - if (!res.ok) return q; - const data: any = await res.json(); - const out = String(data.message?.content || '').split('\n')[0].replace(/^["'`]+|["'`]+$/g, '').trim(); + const raw = await lightChat([{ + role: 'user', + content: `Convert this research topic into a concise English keyword query for PubMed/OpenAlex literature search. Use 2-6 specific scientific terms (MeSH-style). Drop filler words like "latest", "recent", "methods", "overview", "and". No boolean operators, no quotes. Output ONLY the keywords on one line.\n\nTopic: ${q}` + }], { max_tokens: 100, temperature: 0, timeoutMs: 20_000 }); + const out = String(raw || '').split('\n')[0].replace(/^["'`]+|["'`]+$/g, '').trim(); if (!out || out.length > 200) return q; cache.set(q, out); return out; diff --git a/src/tools/web.ts b/src/tools/web.ts index b1b8e50..0cb1642 100644 --- a/src/tools/web.ts +++ b/src/tools/web.ts @@ -4,6 +4,7 @@ import { lookupGpuSpecs } from './gpu-specs.js'; import { lookupDanawa } from './danawa.js'; import { fetchMainText } from './web-extract.js'; import { claudeWebSearch } from './claude-search.js'; +import { lightChat } from '../providers/light-chat.js'; import { mergeSearchResults, renderMergedStdout, normalizePreferredProvider } from './search-merge.js'; type SearchResultItem = { title: string; url: string; snippet: string }; @@ -1264,30 +1265,11 @@ async function runSearchProviders(args: { query: string; max_results?: number }) // which reliably surfaces the fact. Reuse that same pattern here — prepend a focused extraction // on top of the raw results (not instead of: citations still need the original list/URLs). async function extractAnswerFromResults(query: string, rawResults: string): Promise { - try { - const { endpoint, model } = getOllamaConfig(); - const res = await fetch(`${endpoint}/api/chat`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - model, - messages: [ - { role: 'system', content: '아래 검색 결과만 근거로 질문에 답하세요. 검색 결과에 없는 내용은 추측하지 말고, 근거가 부족하면 그렇다고 말하세요. 2~4문장으로 간결하게.' }, - { role: 'user', content: `질문: ${query}\n\n검색 결과:\n${rawResults}` }, - ], - stream: false, - }), - signal: AbortSignal.timeout(15_000), - }); - if (!res.ok) return null; - const data: any = await res.json(); - const answer = String(data.message?.content || '').trim(); - return answer || null; - } catch { - // Extraction is a best-effort add-on — any failure (timeout, endpoint down) must fall - // back to the raw results silently rather than break web_search itself. - return null; - } + // 활성 provider의 싼 모델로 — 실패·시간 초과면 null(원문 결과만 반환). light-chat.ts 참고 + return lightChat([ + { role: 'system', content: '아래 검색 결과만 근거로 질문에 답하세요. 검색 결과에 없는 내용은 추측하지 말고, 근거가 부족하면 그렇다고 말하세요. 2~4문장으로 간결하게.' }, + { role: 'user', content: `질문: ${query}\n\n검색 결과:\n${rawResults}` }, + ], { max_tokens: 400, temperature: 0.2, timeoutMs: 15_000 }); } /**