v4.3.32: 수치 대조 가드에 날짜 검증 추가, 순위는 의도적으로 제외

단위 없는 주장(날짜·순위)이 numeric-grounding의 사각지대로 남아 있어 확장.

날짜 — 추가함. 단 형식 관용이 필수:
출처는 "Nov 10th, 2015" / "November 2015" / "2015-11-10" / "2015년 11월"을
제각각 쓰는데 답변은 한국어로 나온다. 실제로 모델이 영문 스펙 페이지를 보고
"2015년 11월 10일"이라 답했으므로, 단순 문자열 대조를 넣었다면 정답이 오탐으로
걸렸을 것. 연도 일치 + 월을 영문명/약어/ISO/한글 중 어떤 형태로든 연도 근처에서
찾는 방식으로 구현. 연도만 맞고 월이 다르면 걸린다.
날짜를 묻지 않은 질문에서는 답변에 연월이 섞여 있어도 판정하지 않음.

순위 — 넣지 않기로 결정. 근거:
순위표는 위치를 선행 맨숫자로 적는다("40 경상북도 구미시 402,726"). "위" 인접을
요구하면 정답인 답변이 오탐으로 걸리고(나무위키 실제 표로 확인), 단위를 떼고
맨숫자 "40"만 찾으면 어떤 문서에나 있어 검증이 무의미해진다. 오탐 아니면 무동작
둘 중 하나이므로 추가할 가치가 없음. 이 판단 근거를 테스트로 고정해 나중에
누가 다시 넣으려 할 때 이유가 보이도록 함.

배포 후 확인(둘 다 정답, 가드 미발동 = 오탐 없음):
- "Tesla M40 몇 년 몇 월 출시" → 2015년 11월
- "구미시 인구 전국 몇 위" → 402,726명 40위 (나무위키 원본 표와 정확히 일치,
  모델이 web_fetch 후 python_eval로 직접 스크래핑해 산출)

테스트 142개 통과(날짜 4개, 순위 제외 근거 1개 신규).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-07-29 20:26:00 +09:00
1 parent ca7e6e49af
commit f2ae455458
3 files changed
+127 -3

No files matched your search

+5 -2
View File
@@ -1691,12 +1691,15 @@ async function handleChat(
&& numericGroundingForcedRetries < MAX_NUMERIC_GROUNDING_FORCED_RETRIES;
if (shouldForceNumericRetry) {
numericGroundingForcedRetries++;
console.log(`[v2] NUMERIC-GROUNDING POST-CHECK (${numericGroundingForcedRetries}/${MAX_NUMERIC_GROUNDING_FORCED_RETRIES}): ${_numeric.unsupported.length} figure(s) not found in tool output [${_numeric.unsupported.map((c) => c.text).join(', ')}]. Re-prompting...`);
const _badFigures = _numeric.dateUnsupported && _numeric.primaryDate
? [_numeric.primaryDate.text]
: _numeric.unsupported.map((c) => c.text);
console.log(`[v2] NUMERIC-GROUNDING POST-CHECK (${numericGroundingForcedRetries}/${MAX_NUMERIC_GROUNDING_FORCED_RETRIES}): ${_badFigures.length} figure(s) not found in tool output [${_badFigures.join(', ')}]. Re-prompting...`);
sendSSE('info', { message: 'Re-prompting model: stated figures were not in the search results...' });
messages.push({ role: 'assistant', content: candidateText });
messages.push({
role: 'user',
content: `None of the figures you just gave (${_numeric.unsupported.map((c) => c.text).join(', ')}) appear anywhere in the tool results from this turn — you produced them from memory, not from what you found. Rewrite the answer using ONLY numbers the tools actually returned. If the specific figure the user asked for is not in those results, say plainly that you could not find it and explain what IS known qualitatively, WITHOUT substituting an estimate. A stated range like "약 2~5" reads as a measurement to the user; do not offer one you cannot source.`,
content: `None of the figures you just gave (${_badFigures.join(', ')}) appear anywhere in the tool results from this turn — you produced them from memory, not from what you found. Rewrite the answer using ONLY numbers the tools actually returned. If the specific figure the user asked for is not in those results, say plainly that you could not find it and explain what IS known qualitatively, WITHOUT substituting an estimate. A stated range like "약 2~5" reads as a measurement to the user; do not offer one you cannot source.`,
});
continue;
}
+72 -1
View File
@@ -55,6 +55,10 @@ export interface NumericGroundingResult {
unsupported: NumericClaim[];
/** The claim judged as the direct answer — first one in scope. */
primaryClaim: NumericClaim | null;
/** The date judged as the direct answer, when the question asked for one. */
primaryDate: DateClaim | null;
/** True when that date does not appear in the sources in any recognised format. */
dateUnsupported: boolean;
/** The unit the question asked about, when it named one. */
askedUnit: string | null;
/** True when every claim in scope is unsupported — the caller's retry trigger. */
@@ -69,6 +73,64 @@ const ASKED_UNIT_PATTERNS: Array<[RegExp, string[]]> = [
[/몇\s*퍼센트|비율|성능\s*(차이|손실|향상)|percent/i, ['%']],
];
/**
* Dates are checked separately from unit-bearing figures because sources write them in whatever
* format they like — "Nov 10th, 2015", "2015-11-10", "2015년 11월" all state the same fact — so
* proximity-to-a-unit matching does not apply. Verified 2026-07-29: the model answered
* "2015년 11월 10일" from an English spec page, which a naive check would have called invented.
*
* RANK IS DELIBERATELY NOT CHECKED. Ranking tables write the position as a bare leading number
* ("40 경상북도 구미시 402,726") with no "위" anywhere near it, so requiring the unit would flag a
* correct answer — observed on exactly that page. Dropping the unit and matching a bare small
* integer is meaningless, since "40" occurs in almost any document. Either way the check would
* be false positives or a no-op, so rank claims stay unverified.
*/
const MONTH_NAMES = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
const DATE_CLAIM = /(\d{4})\s*년\s*(\d{1,2})\s*월|(\d{4})[-/](\d{1,2})(?:[-/]\d{1,2})?/g;
const ASKS_FOR_DATE = /몇\s*년|언제|출시\s*(일|날짜|시기)|며칠|when (was|did).*(release|launch|announce)|release date/i;
export interface DateClaim { year: string; month: string; text: string; }
export function extractDateClaims(text: string): DateClaim[] {
const out: DateClaim[] = [];
const re = new RegExp(DATE_CLAIM.source, 'g');
let m: RegExpExecArray | null;
while ((m = re.exec(withoutCode(text))) !== null) {
const year = m[1] || m[3];
const month = m[2] || m[4];
if (year && month) out.push({ year, month, text: m[0].trim() });
}
return out;
}
/** Does the source state this year+month in ANY common format? */
export function isDateSupported(claim: DateClaim, source: string): boolean {
const src = source.toLowerCase();
if (!src.includes(claim.year)) return false;
const monthNum = Number(claim.month);
const forms = [
`${claim.year}-${String(monthNum).padStart(2, '0')}`,
`${claim.year}/${String(monthNum).padStart(2, '0')}`,
`${claim.year}년 ${monthNum}월`,
`${claim.year}년${monthNum}월`,
`${monthNum}월`,
];
const name = MONTH_NAMES[monthNum - 1];
if (name) forms.push(name, name.slice(0, 3));
// The month form has to sit near the year, so an unrelated mention elsewhere does not count.
for (const form of forms) {
let from = 0;
for (;;) {
const idx = src.indexOf(form, from);
if (idx === -1) break;
const window = src.slice(Math.max(0, idx - 60), idx + form.length + 60);
if (window.includes(claim.year)) return true;
from = idx + 1;
}
}
return false;
}
/** Which claim units would answer this question, or null when it named none. */
export function detectAskedUnits(userMessage: string): string[] | null {
const m = String(userMessage || '');
@@ -138,13 +200,22 @@ export function checkNumericGrounding(
const unsupported = claims.filter(c => !isClaimSupported(c, source));
// The reply leads with its answer; later figures are comparisons and derivations.
const primaryClaim = claims[0] || null;
// Date questions are judged on their own terms (format-tolerant, no unit proximity).
const dateClaims = ASKS_FOR_DATE.test(String(userMessage || '')) ? extractDateClaims(answer) : [];
const askedDates = new Set(extractDateClaims(String(userMessage || '')).map(d => d.text));
const primaryDate = dateClaims.filter(d => !askedDates.has(d.text))[0] || null;
const dateUnsupported = !!primaryDate && source.trim().length > 0 && !isDateSupported(primaryDate, source);
return {
claims,
unsupported,
primaryClaim,
primaryDate,
dateUnsupported,
askedUnit: askedUnits ? askedUnits[0] : null,
// No claims at all → nothing to verify. Sources empty is handled upstream by the
// empty-grounding check, so treat it as "cannot verify" rather than "all fabricated".
allUnsupported: !!primaryClaim && source.trim().length > 0 && unsupported.includes(primaryClaim),
allUnsupported: (!!primaryClaim && source.trim().length > 0 && unsupported.includes(primaryClaim)) || dateUnsupported,
};
}
+50
View File
@@ -128,3 +128,53 @@ describe('보수적 임계값 — 오탐 방지가 우선', () => {
assert.equal(checkNumericGrounding('32GB입니다.', [' ']).allUnsupported, false);
});
});
describe('날짜 검증 — 출처마다 표기가 다르므로 형식 관용이 필수', () => {
const q = 'Tesla M40은 정확히 몇 년 몇 월에 출시됐어?';
const a = 'NVIDIA Tesla M40은 2015년 11월 10일에 출시되었습니다.';
test('영문·ISO·한글 어떤 표기든 근거로 인정한다', () => {
// 한국어 답변 + 영문 출처는 정상 조합이다. 이걸 못 맞추면 정답이 오탐으로 걸린다.
for (const src of [
'NVIDIA Tesla M40 ... Release Date: Nov 10th, 2015 ... Maxwell',
'Launched November 2015 alongside the M4',
'release_date: 2015-11-10, arch: Maxwell',
'테슬라 M40은 2015년 11월 출시',
]) {
assert.equal(checkNumericGrounding(a, [src], q).dateUnsupported, false, `표기 인식 실패: ${src}`);
}
});
test('연도만 맞고 월이 다르면 걸린다', () => {
const r = checkNumericGrounding(a, ['Released in 2015. In March 2015 NVIDIA announced ...'], q);
assert.equal(r.dateUnsupported, true);
assert.equal(r.primaryDate?.year, '2015');
});
test('출처가 무관하면 걸린다', () => {
assert.equal(
checkNumericGrounding(a, ['Nvidia Corporation is an American company headquartered in Santa Clara'], q).dateUnsupported,
true,
);
});
test('날짜를 묻지 않은 질문에서는 답변의 연월을 판정하지 않는다', () => {
// 날씨 답변에 "2026년 7월 기준" 같은 표현이 섞여도 검증 대상이 아니다.
const r = checkNumericGrounding('내일 구미는 23~33°C입니다. 2026년 7월 기준 평년보다 높습니다.', ['기온: 23.0~33.0°C'], '내일 구미 날씨');
assert.equal(r.allUnsupported, false);
assert.equal(r.primaryDate, null);
});
});
describe('순위는 의도적으로 검증하지 않는다', () => {
test('순위표는 "40 구미시" 처럼 단위 없이 쓰므로 정답이 오탐되면 안 된다', () => {
// 이 케이스가 순위 검증을 넣지 않기로 한 근거다. "위" 인접을 요구하면 정답이 걸리고,
// 맨숫자 "40"만 찾으면 어떤 문서에나 있어 검증이 무의미해진다.
const r = checkNumericGrounding(
'구미시의 인구는 402,726명으로 전국 기초자치단체 중 40위입니다.',
['순위 지역 인구(명) ... 39 대구광역시 북구 407,548 40 경상북도 구미시 402,726'],
'구미시 인구는 전국 시 단위에서 몇 위야?',
);
assert.equal(r.allUnsupported, false);
});
});