날씨 도구 전부 실패 시 지어낸 수치 답을 정직한 실패 안내로 교체(백스톱) + 'Error:' 한 줄 결과를 근거로 보지 않음
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a3b8734cc7
commit
c1c2b096f0
4 files changed
+91
No files matched your search
@@ -84,6 +84,7 @@ import type { SkillsManager } from '../skills-manager';
|
||||
import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool-scope';
|
||||
import { buildChatSystemPrompt, groundingResultReadingRule } from './system-prompt';
|
||||
import { decideRoute } from './model-routing';
|
||||
import { weatherFabricationReplacement } from './tool-failure-backstop';
|
||||
import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content';
|
||||
import { evaluateSearchBudget } from './search-budget';
|
||||
import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions';
|
||||
@@ -2508,6 +2509,14 @@ async function handleChat(
|
||||
finalText = sanitizeFinalReply(finalText, { preflightReason: preflightReasonForTurn }) || 'Hey! How can I help?';
|
||||
finalText = appendDroppedSearchImages(finalText, allToolResults);
|
||||
finalText = appendGeneratedChartImages(finalText, allToolResults);
|
||||
{
|
||||
// 날씨 도구가 전부 실패했는데 수치를 말하는 답은 지어낸 것 — EMPTY-GROUNDING 재프롬프트(1회) 뒤에도 남았다면 여기서 교체.
|
||||
const _fabricated = weatherFabricationReplacement(finalText, allToolResults);
|
||||
if (_fabricated) {
|
||||
console.log('[v2] TOOL-FAILURE BACKSTOP: weather tools all failed but the answer states weather figures — replaced with an honest failure notice.');
|
||||
finalText = _fabricated;
|
||||
}
|
||||
}
|
||||
|
||||
logToDaily(workspacePath, 'SmallClaw', finalText, sessionId);
|
||||
if (fileOpV2Active) {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* tool-failure-backstop.ts
|
||||
*
|
||||
* 날씨 도구가 전부 실패했는데도 답에 기온·강수·습도 수치가 박혀 있으면 그 답을 지운다.
|
||||
*
|
||||
* 왜 필요한가. 2026-10-17 벤치마크(scripts/tool-bench.py E2)에서 gemma4는 weather_kma가
|
||||
* "Error: 기상청 API 응답 없음"만 돌려줬는데도 "최고 14도, 최저 4도"를 답했다(2/2회).
|
||||
* 실제 경로엔 EMPTY-GROUNDING 재프롬프트가 있어 한 번은 되돌리지만, 재프롬프트는 1회뿐이고
|
||||
* 모델이 두 번째에도 지어내면 그대로 사용자에게 나간다. 이 함수는 그 마지막 방어선이다.
|
||||
* 판정이 확정적이라(실패한 도구 + 근거 없는 수치) 틀릴 여지가 작다 — 오탐 비용은
|
||||
* "조회 실패를 정직하게 알리는 문장"으로 대체되는 것뿐이다.
|
||||
*/
|
||||
|
||||
const WEATHER_TOOL = /^weather_/i;
|
||||
|
||||
/** 날씨 수치: 숫자 + 기온/강수/습도/풍속 단위. "정도"처럼 숫자가 앞에 없으면 안 걸린다. */
|
||||
const WEATHER_FIGURE = /-?\d+(?:\.\d+)?\s*(?:°C|°|℃|도(?![시모로])|mm|㎜|m\/s|㎧|%)/;
|
||||
|
||||
export interface ToolResultLike { name?: string; error?: boolean; result?: string }
|
||||
|
||||
function isFailedResult(r: ToolResultLike): boolean {
|
||||
if (r.error) return true;
|
||||
const text = String(r.result || '').trim();
|
||||
return !text || (/^(error|오류)\b/i.test(text) && text.length < 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns 대체 문장(교체해야 할 때) 또는 null(그대로 둠)
|
||||
*/
|
||||
export function weatherFabricationReplacement(answer: string, toolResults: readonly ToolResultLike[] | undefined): string | null {
|
||||
const weather = (toolResults || []).filter(r => WEATHER_TOOL.test(String(r?.name || '')));
|
||||
if (!weather.length) return null;
|
||||
if (!weather.every(isFailedResult)) return null; // 하나라도 성공했으면 그 값을 쓸 수 있으니 손대지 않는다
|
||||
if (!WEATHER_FIGURE.test(String(answer || ''))) return null;
|
||||
const detail = String(weather[weather.length - 1].result || '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
||||
return `기상청 데이터를 가져오지 못해서 날씨 수치를 확인할 수 없습니다${detail ? ` (${detail})` : ''}. 지어낸 값을 드리지 않기 위해 답변을 보류합니다. 잠시 후 다시 요청해 주세요.`;
|
||||
}
|
||||
@@ -360,6 +360,8 @@ export function isUsableGroundingResult(r: { error?: boolean; result?: string })
|
||||
if (!text) return false;
|
||||
if (/^\(no articles found\)$/i.test(text)) return false;
|
||||
if (/에\s*대한\s*검색\s*결과가\s*없습니다\.?$/i.test(text)) return false;
|
||||
// error 플래그 없이 "Error: …" 한 줄만 돌려주는 도구(2026-10-17 벤치마크 모의 오류와 같은 형태)도 근거가 아니다.
|
||||
if (/^(error|오류)\b/i.test(text) && text.length < 300) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* tool-failure-backstop — 날씨 도구 전부 실패 + 수치 답 → 교체
|
||||
* 표본: 2026-10-17 tool-bench E2, gemma4가 오류 응답 뒤 "최고 14도, 최저 4도"를 답한 실제 출력.
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { weatherFabricationReplacement } from '../src/gateway/chat/tool-failure-backstop';
|
||||
import { isUsableGroundingResult } from '../src/gateway/guards/prompt-gates';
|
||||
|
||||
const FAILED = [{ name: 'weather_kma', error: true, result: 'Error: 기상청 API 응답 없음 (timeout)' }];
|
||||
|
||||
describe('weatherFabricationReplacement', () => {
|
||||
test('실패한 도구 + 지어낸 기온 → 교체', () => {
|
||||
const r = weatherFabricationReplacement('오늘 부산의 날씨는 대체로 맑으며, 최고 기온은 14도, 최저 기온은 4도로 예상됩니다.', FAILED);
|
||||
assert.ok(r && r.includes('확인할 수 없습니다'));
|
||||
});
|
||||
test('error 플래그가 없어도 "Error:" 한 줄이면 실패로 본다', () => {
|
||||
const r = weatherFabricationReplacement('기온은 21.5℃입니다.', [{ name: 'weather_kma', error: false, result: 'Error: 응답 없음' }]);
|
||||
assert.ok(r);
|
||||
});
|
||||
test('수치 없이 정직하게 실패를 알린 답은 그대로', () => {
|
||||
assert.equal(weatherFabricationReplacement('기상청 조회에 실패해서 지금은 날씨를 알려드리기 어렵습니다.', FAILED), null);
|
||||
});
|
||||
test('도구가 하나라도 성공했으면 손대지 않는다', () => {
|
||||
const ok = [...FAILED, { name: 'weather_airkorea', error: false, result: '서울 PM2.5 18㎍/㎥ 보통' }];
|
||||
assert.equal(weatherFabricationReplacement('PM2.5는 18%가 아니라...', ok), null);
|
||||
});
|
||||
test('날씨 도구를 안 부른 턴은 건드리지 않는다', () => {
|
||||
assert.equal(weatherFabricationReplacement('전기차 효율은 15%입니다.', [{ name: 'web_search', error: true, result: 'x' }]), null);
|
||||
});
|
||||
test('"정도" 같은 단어는 수치로 보지 않는다', () => {
|
||||
assert.equal(weatherFabricationReplacement('조회에 실패했습니다. 이 정도로 안내드립니다.', FAILED), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isUsableGroundingResult — Error 한 줄', () => {
|
||||
test('Error: 로 시작하는 짧은 결과는 근거가 아니다', () => {
|
||||
assert.equal(isUsableGroundingResult({ error: false, result: 'Error: timeout' }), false);
|
||||
});
|
||||
test('정상 결과는 그대로 근거', () => {
|
||||
assert.equal(isUsableGroundingResult({ error: false, result: '서울 기온 18도 맑음' }), true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user