From b4b82d1e13ef5659ca1199d6b6189ad0c5163791 Mon Sep 17 00:00:00 2001 From: kim Date: Sun, 18 Oct 2026 19:32:03 +0900 Subject: [PATCH] =?UTF-8?q?=EA=B2=80=EC=83=89=20=ED=8F=AC=EA=B8=B0=20?= =?UTF-8?q?=EA=B0=80=EB=93=9C=20=EC=9E=AC=EC=8B=9C=EB=8F=84=20=EC=A7=80?= =?UTF-8?q?=EC=8B=9C=EC=97=90=20'=EC=B4=88=EC=95=88=20=EC=96=B8=EA=B8=89?= =?UTF-8?q?=20=EA=B8=88=EC=A7=80'=20=EC=B6=94=EA=B0=80,=20Claude=20?= =?UTF-8?q?=EA=B2=80=EC=83=89=20max=5Ftokens=201800=E2=86=923500=20?= =?UTF-8?q?=EB=B0=8F=20=EB=B9=88=20=EB=8B=B5=EC=9D=B4=EC=96=B4=EB=8F=84=20?= =?UTF-8?q?=EC=88=98=EC=88=98=EB=A3=8C=20=EA=B8=B0=EB=A1=9D,=20=EB=82=A0?= =?UTF-8?q?=EC=94=A8=20=EB=8C=80=ED=99=94=20=EC=A4=91=20=EC=9E=A5=EC=86=8C?= =?UTF-8?q?=20=EC=A0=95=EC=A0=95=20=EC=9D=91=EB=8B=B5(=EC=95=84=EB=8B=88?= =?UTF-8?q?=20=EC=84=9C=EC=9A=B8)=EC=97=90=20=EC=9E=A5=EC=86=8C=20?= =?UTF-8?q?=EC=9E=AC=EC=A1=B0=ED=9A=8C=20=ED=9E=8C=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/chat/followup-hints.ts | 18 +++++++++++++++++- src/gateway/chat/handle-chat.ts | 2 +- src/tools/claude-search.ts | 8 ++++++-- tests/followup-hints.test.ts | 6 ++++++ 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/gateway/chat/followup-hints.ts b/src/gateway/chat/followup-hints.ts index 18bcefe..d095992 100644 --- a/src/gateway/chat/followup-hints.ts +++ b/src/gateway/chat/followup-hints.ts @@ -12,12 +12,17 @@ const UNTIL_RE = /(?:오늘|내일|모레|글피|주말|이번\s?주|\d{1,2}\s? const AMOUNT_RE = /강수량|비\s?양|적설|몇\s?mm|얼마나\s*(?:오|올|내릴|내려)/; const MAX_FOLLOWUP_CHARS = 40; +const SHORT_NON_PLACE = /^(네|예|응|어|그래|그래요|고마워|고맙|감사|알겠|좋아|오케이|확인|됐어|됐다|아니야|아니요|아뇨|아냐|맞아|뭐|왜|진짜|정말|그럼|그리고|근데|하지만)/; +// 「아니 서울」「서울은?」「부산으로」처럼 장소만 고쳐 말하는 짧은 응답 +const CORRECTION_RE = /^(?:아니|아냐|아니요|그게\s*아니라|아니\s*그게)?\s*([가-힣]{2,8}?)(?:은|는|으로|로|이|가|요|말야|말이야)?\s*[??.!]?$/; + export function weatherFollowUpHint( message: string, history: ReadonlyArray<{ role: string; content?: any }>, ): string | null { const msg = String(message || '').trim(); - if (!msg || msg.length > MAX_FOLLOWUP_CHARS || !WEATHER_RE.test(msg)) return null; + if (!msg || msg.length > MAX_FOLLOWUP_CHARS) return null; + if (!WEATHER_RE.test(msg)) return placeCorrectionHint(msg, history); const notes: string[] = []; if (TIME_BEFORE_GAJI.test(msg)) { @@ -37,3 +42,14 @@ export function weatherFollowUpHint( } return notes.length ? notes.join(' ') : null; } + +/** 직전 사용자 질문이 날씨였고 이번이 장소만 말하는 짧은 응답이면, 그 장소로 같은 날씨 조회를 다시 하게 한다. */ +function placeCorrectionHint(msg: string, history: ReadonlyArray<{ role: string; content?: any }>): string | null { + if (msg.length > 14 || SHORT_NON_PLACE.test(msg)) return null; + const m = CORRECTION_RE.exec(msg); + if (!m) return null; + const prevUser = [...history].reverse().find(h => h.role === 'user'); + const prevQ = String(prevUser?.content || '').trim(); + if (!prevQ || !WEATHER_RE.test(prevQ)) return null; + return `The user's short message "${msg}" is most likely a correction of the PLACE in their previous weather question ("${prevQ.slice(0, 80)}"): the place is "${m[1]}". Re-run the same kind of weather lookup (weather_kma for Korea) for that place and answer the previous question for it — do NOT switch to web search and do NOT ask which place they mean.`; +} diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 8e072ce..94aa923 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -2154,7 +2154,7 @@ async function handleChat( messages.push({ role: 'assistant', content: candidateText }); messages.push({ role: 'user', - content: `You opened by saying the search found nothing, but ${_abandon.substantiveResults} of this turn's results have real content in them. Result #1 being generic, off-topic, or a site's cookie/browser-settings boilerplate does not mean the search failed — read results #2, #3, #4 and onward before concluding. Answer from whatever those actually contain. If after reading ALL of them nothing addresses the question, say so — but say what you did find, rather than reporting the search as empty.`, + content: `You opened by saying the search found nothing, but ${_abandon.substantiveResults} of this turn's results have real content in them. Result #1 being generic, off-topic, or a site's cookie/browser-settings boilerplate does not mean the search failed — read results #2, #3, #4 and onward before concluding. Answer from whatever those actually contain. If after reading ALL of them nothing addresses the question, say so — but say what you did find, rather than reporting the search as empty. The user never saw your previous draft: do not mention this correction or that you first said nothing was found — write the answer as if it were your first.`, }); continue; } diff --git a/src/tools/claude-search.ts b/src/tools/claude-search.ts index c7b6f9f..0a15efa 100644 --- a/src/tools/claude-search.ts +++ b/src/tools/claude-search.ts @@ -120,7 +120,7 @@ export async function claudeWebSearch(query: string): Promise 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, + model: cfg.model, max_tokens: 3500, system: SYSTEM, messages, tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: cfg.max_uses, allowed_callers: ['direct'] }], }), signal: AbortSignal.timeout(60_000), @@ -132,7 +132,11 @@ export async function claudeWebSearch(query: string): Promise 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; } + if (!p.text) { + // 검색은 이미 돌았으니 수수료·토큰은 청구된다 — 기록은 남긴다(2026-10-18: max_tokens로 빈 답 → 비용만 샘) + logUsage(cfg.model, p.inputTokens, p.outputTokens, p.searches * SEARCH_FEE_USD); + addClaudeSearchUsage(p.searches); + 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); diff --git a/tests/followup-hints.test.ts b/tests/followup-hints.test.ts index 7630fb4..71a0188 100644 --- a/tests/followup-hints.test.ts +++ b/tests/followup-hints.test.ts @@ -22,3 +22,9 @@ test('"가지"가 채소면 오타로 보지 않음', () => assert.equal(weather test('"내일까지 강수량"은 누적 힌트', () => assert.match(weatherFollowUpHint('내일까지 현풍 강수량은?', [])!, /CUMULATIVE/)); test('오타 "내일 가지 강수량"도 누적 힌트', () => assert.match(weatherFollowUpHint('내일 가지 예상 강수량은?', [])!, /CUMULATIVE/)); test('"내일 강수량"(까지 없음)은 누적 힌트 없음', () => assert.equal(weatherFollowUpHint('내일 강수량은?', []), null)); + +const HW = [{ role: 'user', content: '오늘 세월에 비가 많이 왔나?' }, { role: 'assistant', content: '찾지 못했습니다' }]; +test('"아니 서울" → 장소 정정 힌트', () => { const h = weatherFollowUpHint('아니 서울', HW)!; assert.match(h, /"서울"/); assert.match(h, /weather_kma/); }); +test('"부산으로" / "서울은?" → 정정 힌트', () => { assert.match(weatherFollowUpHint('부산으로', HW)!, /"부산"/); assert.match(weatherFollowUpHint('서울은?', HW)!, /"서울"/); }); +test('날씨 맥락 없으면 정정 힌트 없음', () => assert.equal(weatherFollowUpHint('아니 서울', [{ role: 'user', content: '파스타 맛집' }]), null)); +test('"고마워" 같은 짧은 응답은 제외', () => { assert.equal(weatherFollowUpHint('고마워', HW), null); assert.equal(weatherFollowUpHint('알겠어요', HW), null); });