diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 94aa923..98e11e0 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -86,6 +86,7 @@ import { buildChatSystemPrompt, groundingResultReadingRule } from './system-prom import { decideRoute } from './model-routing'; import { weatherFabricationReplacement } from './tool-failure-backstop'; import { weatherFollowUpHint } from './followup-hints'; +import { suspectSoundAlikePlace } from './voice-place-check'; import { replyIsWrongLanguage, TRANSLATE_TO_KOREAN_SYSTEM } from './language-backstop'; import { lightChat } from '../../providers/light-chat'; import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content'; @@ -2628,6 +2629,24 @@ async function handleChat( const rawToolArgs = normalizeToolArgs(call.function?.arguments); const toolArgs = correctNewsCategoryForBreadth2(toolName, rawToolArgs, recentUserText, message); + // 음성 입력인데 날씨 지명이 주요 도시와 소리만 다른 말(세월↔서울)이면 조회 전에 한 줄로 확인한다(voice-place-check.ts, 2026-10-18). + // 직전 답변에서 이미 같은 지명으로 확인을 물었으면 다시 묻지 않는다(사용자가 "맞다"고 한 경우). + if (/^weather_(kma|openmeteo|airkorea)$/.test(String(toolName)) && /VOICE INPUT:/.test(String(callerContext || ''))) { + const _loc = String((toolArgs as any)?.location || '').trim(); + const _alt = _loc ? suspectSoundAlikePlace(_loc) : null; + const _lastAsst = String([...history].reverse().find(h => h.role === 'assistant')?.content || ''); + if (_alt && !(_lastAsst.includes(_loc) && /말씀|맞으|맞나/.test(_lastAsst))) { + const askMsg = `PLACE CONFIRMATION NEEDED: "${_loc}" sounds like "${_alt}" and may be a speech-recognition error. The weather lookup was NOT run. Reply with ONE short speakable question only — e.g. "${_loc}이 ${_alt} 말씀이세요?" — and nothing else; do not call any tool. If the user confirms "${_loc}" is correct, look it up as written.`; + console.log(`[v2] VOICE PLACE CHECK: "${_loc}" ~ "${_alt}" — asking for confirmation instead of ${toolName}`); + const askResult: ToolResult = { name: toolName, args: toolArgs, result: askMsg, error: false }; + allToolResults.push(askResult); + sendSSE('tool_call', { action: toolName, args: toolArgs, stepNum: allToolResults.length }); + sendSSE('tool_result', { action: toolName, result: askMsg.slice(0, 300), error: false, stepNum: allToolResults.length }); + messages.push({ role: 'tool', name: toolName, tool_name: toolName, tool_call_id: toolCallId || undefined, content: askMsg }); + continue; + } + } + // Block PageDown / browser_scroll on interactive pages when the model hasn't // filled or clicked anything yet. This is the #1 cause of the scroll loop bug // where the AI scrolls past the X.com composer instead of filling it. diff --git a/src/gateway/chat/voice-place-check.ts b/src/gateway/chat/voice-place-check.ts new file mode 100644 index 0000000..6ca6e30 --- /dev/null +++ b/src/gateway/chat/voice-place-check.ts @@ -0,0 +1,41 @@ +/** + * 음성 입력에서 소리가 비슷한 다른 지명으로 오인식된 것 같은 날씨 지명을 찾아낸다 (2026-10-18). + * + * 실사고: 「오늘 서울에 비가 많이 왔나」가 「세월」로 인식됐고, 지오코더가 "세월"이라는 실제 지명을 찾아 + * 엉뚱한 지점의 강수량이 답으로 나갔다. 도구가 실패했다면 모델이 되물었을 텐데 성공해서 문제가 안 보였다. + * 그래서 도구를 부르기 전에, 주요 도시와 소리(자모)가 거의 같은데 정확히 같지는 않은 지명이면 확인을 먼저 받는다. + * 지점표에 이미 있는 지명(현풍·화원 등)과 주요 도시 정확 일치는 건드리지 않는다. + */ +import { toJamo, jamoDistance } from '../../tools/stt-correct'; +import { KR_CITY_COORDS, lookupKoreanPlace } from '../../tools/weather'; + +export const MAJOR_CITIES = [ + '서울', '부산', '대구', '인천', '광주', '대전', '울산', '세종', '수원', '창원', '구미', '제주', '포항', + '전주', '청주', '춘천', '강릉', '목포', '여수', '안동', '천안', '김해', '진주', '원주', '순천', '경주', '성남', '고양', '용인', +]; + +// 소리는 비슷해도 실제로 자주 쓰이는 다른 지명 — 되묻지 않는다 +const REAL_OTHER_PLACES = new Set(['마산', '진해', '청도', '청두', '광저', '대구', '구리', '군포', '서산', '부안', '부여']); + +const CHO = 'ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ'; +function initials(s: string): string { + return [...s].map(ch => { const c = ch.charCodeAt(0); return c >= 0xac00 && c <= 0xd7a3 ? CHO[Math.floor((c - 0xac00) / 588)] : ch; }).join(''); +} + +/** 확인이 필요한 경우 소리가 비슷한 주요 도시를, 아니면 null. */ +export function suspectSoundAlikePlace(location: string): string | null { + const loc = String(location || '').trim(); + if (!/^[가-힣]{2,4}$/.test(loc)) return null; // 한글 2~4자 단일 지명만 + if (MAJOR_CITIES.includes(loc) || REAL_OTHER_PLACES.has(loc)) return null; + if (KR_CITY_COORDS[loc.toLowerCase()]) return null; + try { if (lookupKoreanPlace(loc)) return null; } catch { /* 지점표 없음 */ } + const j = toJamo(loc); + let best: { city: string; d: number } | null = null; + for (const c of MAJOR_CITIES) { + const d = jamoDistance(j, toJamo(c)); + // 거리 1이거나, 거리 2라도 모든 초성이 같을 때만(세월↔서울: 모음만 다름). 마산↔부산처럼 초성이 다르면 다른 곳이다. + const ok = d === 1 || (d === 2 && initials(loc) === initials(c)); + if (ok && (!best || d < best.d)) best = { city: c, d }; + } + return best ? best.city : null; +} diff --git a/tests/voice-place-check.test.ts b/tests/voice-place-check.test.ts new file mode 100644 index 0000000..2c36882 --- /dev/null +++ b/tests/voice-place-check.test.ts @@ -0,0 +1,9 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { suspectSoundAlikePlace } from '../src/gateway/chat/voice-place-check'; + +test('세월 → 서울 의심', () => assert.equal(suspectSoundAlikePlace('세월'), '서울')); +test('주요 도시 정확 일치는 통과', () => { for (const c of ['서울', '부산', '구미', '대구']) assert.equal(suspectSoundAlikePlace(c), null); }); +test('지점표에 있는 지명은 통과', () => { for (const c of ['현풍', '화원', '다사']) assert.equal(suspectSoundAlikePlace(c), null); }); +test('소리가 많이 다르면 통과', () => assert.equal(suspectSoundAlikePlace('안양'), null)); +test('영문·다단어는 통과', () => { assert.equal(suspectSoundAlikePlace('Seoul'), null); assert.equal(suspectSoundAlikePlace('서울 강남'), null); });