AUTO-RECOVER 오발동 수정 + Claude용 넛지 정리 — 장소·길찾기·모델 검색을 근거 도구로 인정('인동 맛집' 재검색 강제 5회), '도구는 쓰지 말고' 보조 호출·'지금 어떤 모델이야' 자기소개 제외. Claude 모델엔 가짜 맞장구를 빼고 마지막 영어 넛지에 '한국어로 답하라' 메모를 붙인 사본을 보냄(영어 답·영어 혼잣말 원인)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ebd4ee903b
commit
f42a51e3df
5 files changed
+126
-2
No files matched your search
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* claude-nudge-adapt.ts — 가드 넛지를 Claude 모델에 맞게 손보기(2026-10-22).
|
||||
*
|
||||
* 가드들은 재생성시킬 때 가짜 assistant 맞장구("Got it — checking now.", "Understood.")를 넣고 그 뒤에
|
||||
* 영어 user 지시("Yes, use web_search right now…")를 붙인다. gemma 시절, 대화가 user/assistant로 번갈아야
|
||||
* 따라오던 버릇에 맞춘 것이다. Claude에서는 둘 다 해롭다:
|
||||
* · 시스템 프롬프트의 "사용자의 마지막 메시지 언어로 답하라"를 Claude는 정확히 지킨다 → 마지막 메시지가
|
||||
* 영어 넛지라 영어로 답한다(Haiku 전환 후 로그: 영어 혼잣말 12건, LANGUAGE BACKSTOP 4건, "인동 맛집" 영어 답).
|
||||
* · 가짜 맞장구는 모델이 한 적 없는 말을 입에 넣는다. Anthropic API는 연속된 user 메시지를 합쳐 주므로 필요 없다.
|
||||
* 원본 messages 배열은 건드리지 않고(가드들이 그 배열을 계속 읽는다), 이번 호출에 보낼 사본만 만든다.
|
||||
*/
|
||||
|
||||
/** 가드들이 넣는 가짜 assistant 맞장구 — 정확히 이 문자열일 때만 뺀다(진짜 초안은 남긴다). */
|
||||
export const SYNTHETIC_ACKS: ReadonlySet<string> = new Set([
|
||||
'Got it — checking now.',
|
||||
'Got it — let me verify that first.',
|
||||
'Understood.',
|
||||
'Understood. Acting immediately.',
|
||||
'Let me check that now.',
|
||||
'Understood. Executing browser automation now.',
|
||||
'Understood. Checking desktop state now.',
|
||||
]);
|
||||
|
||||
export const KOREAN_REPLY_NOTE = '(위 지시는 시스템 메모입니다. 사용자에게는 반드시 한국어로 답하세요.)';
|
||||
|
||||
export function isClaudeModel(model: string): boolean {
|
||||
return /claude|haiku|sonnet|opus/i.test(String(model || ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param userMsgIndex 이번 턴 사용자 메시지의 messages 인덱스. 그 뒤에 들어온 user 메시지만 넛지로 본다.
|
||||
* @param userMessage 사용자 원문 — 한글이 있으면 마지막 넛지에 한국어로 답하라는 메모를 붙인다.
|
||||
*/
|
||||
export function adaptNudgesForClaude<T extends { role: string; content?: any }>(
|
||||
messages: T[], userMsgIndex: number, userMessage: string,
|
||||
): T[] {
|
||||
if (userMsgIndex < 0 || userMsgIndex >= messages.length) return messages;
|
||||
const out: T[] = [];
|
||||
messages.forEach((m, i) => {
|
||||
if (i > userMsgIndex && m.role === 'assistant' && typeof m.content === 'string'
|
||||
&& SYNTHETIC_ACKS.has(m.content.trim()) && !(m as any).tool_calls?.length) return;
|
||||
out.push(m);
|
||||
});
|
||||
const last = out[out.length - 1];
|
||||
// 맞장구는 사용자 메시지 뒤에서만 뺐으므로 사용자 메시지의 위치는 out에서도 userMsgIndex 그대로다
|
||||
if (last && last.role === 'user' && out.length - 1 > userMsgIndex
|
||||
&& typeof last.content === 'string'
|
||||
&& /[가-힣]/.test(String(userMessage || '')) && !last.content.includes(KOREAN_REPLY_NOTE)) {
|
||||
out[out.length - 1] = { ...last, content: `${last.content}\n\n${KOREAN_REPLY_NOTE}` };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -93,6 +93,7 @@ import { replyIsWrongLanguage, TRANSLATE_TO_KOREAN_SYSTEM } from './language-bac
|
||||
import { lightChat } from '../../providers/light-chat';
|
||||
import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content';
|
||||
import { evaluateSearchBudget } from './search-budget';
|
||||
import { adaptNudgesForClaude, isClaudeModel } from './claude-nudge-adapt';
|
||||
import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions';
|
||||
import { logToolSkip } from './tool-skip-log';
|
||||
import { checkNumericGrounding } from './numeric-grounding';
|
||||
@@ -909,6 +910,7 @@ async function handleChat(
|
||||
const content = role === 'user' ? resolveImageContent(foldedContent, workspacePath) : msg.content;
|
||||
messages.push({ role, content });
|
||||
}
|
||||
const userMsgIndex = messages.length; // adaptNudgesForClaude: 이 뒤의 user 메시지는 가드 넛지
|
||||
messages.push({ role: 'user', content: resolveImageContent(message, workspacePath) });
|
||||
|
||||
// News/weather/prices/etc. must come from a live tool call, never training data — and
|
||||
@@ -1538,7 +1540,11 @@ async function handleChat(
|
||||
if (round > 0 && messages.length && (messages[messages.length - 1] as any)?.role === 'user') {
|
||||
try { sendSSE('draft_reset', {}); } catch {}
|
||||
}
|
||||
const generationPromise = ollama.chatWithThinkingStream(messages, 'executor', (token: string) => {
|
||||
// Claude: 가짜 맞장구 빼고 마지막 넛지에 '한국어로 답하라'를 붙인 사본을 보낸다(claude-nudge-adapt.ts)
|
||||
const _messagesForModel = isClaudeModel(resolvedModelThisRound || getModelForRole('executor'))
|
||||
? adaptNudgesForClaude(messages, userMsgIndex, message)
|
||||
: messages;
|
||||
const generationPromise = ollama.chatWithThinkingStream(_messagesForModel, 'executor', (token: string) => {
|
||||
try { sendSSE('token', { text: token }); } catch {}
|
||||
}, {
|
||||
// Empty (not omitted) once toolsDisabledForRestOfTurn trips — a model with no
|
||||
|
||||
@@ -68,7 +68,7 @@ import {
|
||||
// verify a local file's dimensions, so the model just searched generic news instead and tacked a
|
||||
// non-sequitur onto an already-correct answer.
|
||||
/** Tools that can actually ground a factual/live-data answer. Anything else does not count. */
|
||||
export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|weather_|ollama_web_|news_search|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query|cms_hospital_compare|stl_cad|scad_to_stl)/i;
|
||||
export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|place_search|route_search|model_search|weather_|ollama_web_|news_search|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query|cms_hospital_compare|stl_cad|scad_to_stl)/i;
|
||||
|
||||
export interface AutoRecoverInput {
|
||||
/** The user's message this turn. */
|
||||
@@ -114,6 +114,17 @@ export function decideAutoRecover(input: AutoRecoverInput): AutoRecoverDecision
|
||||
return { shouldRetry: false, kind: 'search', reason: '' };
|
||||
}
|
||||
|
||||
// 앱의 보조 호출(논문 검색어 만들기·저널 분류·PPTX 계획)은 "도구는 쓰지 말고 JSON 한 줄로"처럼 도구를 금지한다.
|
||||
// 여기에 검색을 강제하면 지시가 서로 부딪쳐 9번 헛재생성했다(2026-10-22, Haiku 전환 후 로그).
|
||||
if (/도구(는|를)?\s*(쓰지|사용하지|호출하지)\s*(말|마)|(?:without|don'?t|do not)\s+(?:using|use|call(?:ing)?)\s+(?:any\s+)?tools?/i.test(message)) {
|
||||
return { shouldRetry: false, kind: 'search', reason: '' };
|
||||
}
|
||||
// "지금 어떤 모델이야?" — 자기 자신(답하는 모델)을 묻는 질문. '지금' 때문에 실시간 조회로 잡혀 재검색을 강제당했다.
|
||||
if (/(무슨|어떤|어느)\s*모델(이야|이니|이냐|야|이에요|예요|인가요|인가|이세요|써|쓰|돌아)/.test(message)
|
||||
&& !/(최신|출시|나온|신형|추천|비교|좋은)/.test(message)) {
|
||||
return { shouldRetry: false, kind: 'search', reason: '' };
|
||||
}
|
||||
|
||||
const looksLikeReasoning = content.length > 300
|
||||
&& (/\b(let me|I need to|I should|the user|first,|wait,|hmm|the rules say)\b/i.test(content));
|
||||
const queryNeedsTools = /\b(search|find|look up|latest|news|info|open|browse|navigate|visit|click|type|fill|what happened|desktop|screen|window|vscode|vs code|codex|clipboard)\b/i.test(message)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { adaptNudgesForClaude, isClaudeModel, KOREAN_REPLY_NOTE } from '../src/gateway/chat/claude-nudge-adapt';
|
||||
|
||||
const base = [
|
||||
{ role: 'system', content: 'sys' },
|
||||
{ role: 'assistant', content: 'Understood.' }, // 이전 대화 기록 — 손대지 않음
|
||||
{ role: 'user', content: '주말에 현풍 비오나?' },
|
||||
];
|
||||
|
||||
test('사용자 메시지 뒤 가짜 맞장구는 빼고 마지막 넛지에 한국어 메모를 붙인다', () => {
|
||||
const msgs = [...base, { role: 'assistant', content: 'Got it — checking now.' }, { role: 'user', content: 'Reminder: call a tool first.' }];
|
||||
const out = adaptNudgesForClaude(msgs, 2, '주말에 현풍 비오나?');
|
||||
assert.deepEqual(out.map(m => m.role), ['system', 'assistant', 'user', 'user']);
|
||||
assert.equal(out[1].content, 'Understood.');
|
||||
assert.ok(out[3].content.endsWith(KOREAN_REPLY_NOTE));
|
||||
assert.equal(msgs[4].content, 'Reminder: call a tool first.', '원본 배열은 그대로');
|
||||
});
|
||||
|
||||
test('진짜 초안(candidateText)과 도구 라운드는 그대로', () => {
|
||||
const msgs = [...base, { role: 'assistant', content: '초안 답변입니다.' }, { role: 'user', content: 'Re-check the figures.' }];
|
||||
const out = adaptNudgesForClaude(msgs, 2, '주말에 현풍 비오나?');
|
||||
assert.equal(out.length, 5);
|
||||
const tool = [...base, { role: 'assistant', content: '', tool_calls: [{}] } as any, { role: 'tool', content: 'r' }];
|
||||
assert.deepEqual(adaptNudgesForClaude(tool, 2, '비오나'), tool);
|
||||
});
|
||||
|
||||
test('넛지가 없으면 사용자 메시지에 메모를 붙이지 않고, 영어 질문엔 붙이지 않는다', () => {
|
||||
assert.equal(adaptNudgesForClaude(base, 2, '주말에 현풍 비오나?')[2].content, '주말에 현풍 비오나?');
|
||||
const msgs = [...base.slice(0, 2), { role: 'user', content: 'weather?' }, { role: 'user', content: 'Reminder' }];
|
||||
assert.equal(adaptNudgesForClaude(msgs, 2, 'weather?')[3].content, 'Reminder');
|
||||
});
|
||||
|
||||
test('isClaudeModel', () => {
|
||||
assert.ok(isClaudeModel('claude-haiku-5-5'));
|
||||
assert.ok(!isClaudeModel('gemma4:31b-cloud'));
|
||||
});
|
||||
@@ -498,3 +498,21 @@ describe('skillContext 길이 한도 — 모델 컨텍스트에 비례', () => {
|
||||
assert.equal(budgetFromNumCtx(1048576), SKILL_CTX_MAX_CHARS);
|
||||
});
|
||||
});
|
||||
|
||||
describe('decideAutoRecover — Haiku 전환 후 오발동(2026-10-22)', () => {
|
||||
const ans = '인동에는 한재촌, 미미관 마라탕 등이 있습니다. 카카오맵 기준 평점이 높은 곳 위주로 골랐습니다. '.repeat(3);
|
||||
test('place_search를 이미 불렀으면 맛집 질문에 web_search를 강제하지 않는다', () => {
|
||||
assert.equal(decideAutoRecover({ message: '구미 인동 맛집 추천해줘', content: ans, availableToolNames: ['web_search', 'place_search'], calledToolNames: ['place_search'] }).shouldRetry, false);
|
||||
});
|
||||
test('"도구는 쓰지 말고" 보조 호출에는 검색을 강제하지 않는다', () => {
|
||||
const msg = '아래 요청에 맞는 학술 논문을 PubMed·OpenAlex에서 찾으려 한다. 도구는 쓰지 말고, 검색어만 JSON 한 줄로 답하라.\n요청: 최신 복합레진 접착 RCT';
|
||||
assert.equal(decideAutoRecover({ message: msg, content: '{"pubmed":"composite adhesive RCT 2024"}', availableToolNames: ['web_search'], calledToolNames: [] }).shouldRetry, false);
|
||||
});
|
||||
test('"지금 어떤 모델이야?"는 자기소개라 재검색하지 않는다', () => {
|
||||
assert.equal(decideAutoRecover({ message: '안녕! 지금 어떤 모델이야?', content: '저는 SmallClaw이고 지금은 claude-haiku-5-5로 답하고 있습니다.', availableToolNames: ['web_search'], calledToolNames: [] }).shouldRetry, false);
|
||||
});
|
||||
test('최신 모델을 묻는 사실 질문은 여전히 대상', () => {
|
||||
const d = decideAutoRecover({ message: '지금 어떤 모델이 최신이야? 아이폰 최신 모델 알려줘', content: '최신 모델은 아이폰 15 Pro입니다. 가격은 155만원부터입니다.', availableToolNames: ['web_search'], calledToolNames: [] });
|
||||
assert.equal(d.shouldRetry, true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user