한국어 질문에 영어로 답하면 light 모델로 한국어 번역해 되돌리는 보정 + 시스템 프롬프트에 사용자 언어 규칙
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1610ff938c
commit
1cd5a83f9a
4 files changed
+52
-1
No files matched your search
@@ -85,6 +85,8 @@ import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool
|
||||
import { buildChatSystemPrompt, groundingResultReadingRule } from './system-prompt';
|
||||
import { decideRoute } from './model-routing';
|
||||
import { weatherFabricationReplacement } from './tool-failure-backstop';
|
||||
import { replyIsWrongLanguage, TRANSLATE_TO_KOREAN_SYSTEM } from './language-backstop';
|
||||
import { lightChat } from '../../providers/light-chat';
|
||||
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';
|
||||
@@ -2507,6 +2509,16 @@ async function handleChat(
|
||||
finalText = finalText.split(/\n+/)[0].slice(0, 220).trim();
|
||||
}
|
||||
finalText = sanitizeFinalReply(finalText, { preflightReason: preflightReasonForTurn }) || 'Hey! How can I help?';
|
||||
if (replyIsWrongLanguage(message || '', finalText)) {
|
||||
const ko = await lightChat([
|
||||
{ role: 'system', content: TRANSLATE_TO_KOREAN_SYSTEM },
|
||||
{ role: 'user', content: finalText },
|
||||
], { max_tokens: 3000, temperature: 0.1, timeoutMs: 40_000 });
|
||||
if (ko && !replyIsWrongLanguage(message || '', ko)) {
|
||||
console.log('[v2] LANGUAGE BACKSTOP: Korean question answered in English — translated reply to Korean.');
|
||||
finalText = ko;
|
||||
}
|
||||
}
|
||||
finalText = appendDroppedSearchImages(finalText, allToolResults);
|
||||
finalText = appendGeneratedChartImages(finalText, allToolResults);
|
||||
{
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 한국어 질문에 영어로 답한 경우 보정 (2026-10-17: Haiku 5.5가 검색 결과에 영어 자료가 섞이면
|
||||
* "Here's what I found…"로 시작해 영어로 답함 — 6문항 중 2건).
|
||||
* 판정은 순수 함수, 되돌리기는 호출자가 light 모델로 번역한다.
|
||||
*/
|
||||
|
||||
const HANGUL = /[가-힣]/g;
|
||||
const LATIN = /[A-Za-z]/g;
|
||||
|
||||
/** 사용자가 한국어로 물었는데 답의 본문(코드·링크·표 구분선 제외)이 영어 위주인가. */
|
||||
export function replyIsWrongLanguage(userMessage: string, reply: string): boolean {
|
||||
const msg = String(userMessage || '');
|
||||
const hangulInMsg = (msg.match(HANGUL) || []).length;
|
||||
const latinInMsg = (msg.match(LATIN) || []).length;
|
||||
if (hangulInMsg < 2 || hangulInMsg < latinInMsg) return false; // 한국어 질문이 아님
|
||||
const body = String(reply || '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`[^`]*`/g, ' ')
|
||||
.replace(/!?\[[^\]]*\]\([^)]*\)/g, ' ')
|
||||
.replace(/https?:\/\/\S+/g, ' ');
|
||||
const h = (body.match(HANGUL) || []).length;
|
||||
const l = (body.match(LATIN) || []).length;
|
||||
if (l < 60) return false; // 짧은 답·고유명사 위주는 건드리지 않음
|
||||
return h < l * 0.25;
|
||||
}
|
||||
|
||||
export const TRANSLATE_TO_KOREAN_SYSTEM =
|
||||
'Translate the assistant reply into natural Korean. Keep all markdown (tables, bold, lists, headings), numbers, URLs, ' +
|
||||
'image links, code and proper nouns exactly as they are. Output ONLY the translation, no commentary.';
|
||||
@@ -269,7 +269,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
const packageInstallRuleBlock = (toolNames.has('shell') || toolNames.has('run_command'))
|
||||
? '\nPACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.'
|
||||
: '';
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. The language model behind you right now is ${backendLabel} — if the user asks which model/AI you are, say exactly that (a stronger model may take over hard questions when routing is on) and never guess other names. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. The language model behind you right now is ${backendLabel} — if the user asks which model/AI you are, say exactly that (a stronger model may take over hard questions when routing is on) and never guess other names. Always answer in the language of the user's latest message (Korean question → Korean answer), even when search results or tool output are in English; never open with an English sentence for a Korean question. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.${verifyFactsRule}
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${routeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph.${newsFormatRule}${weatherFormatRule}${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { replyIsWrongLanguage } from '../src/gateway/chat/language-backstop';
|
||||
|
||||
const EN = "Here's what I found for the restaurants. The Kakao Map search and the web search returned different sets, so I grouped them separately below.";
|
||||
test('한국어 질문 + 영어 답 → 보정 대상', () => assert.equal(replyIsWrongLanguage('구미 맛집 추천해줘', EN), true));
|
||||
test('한국어 질문 + 한국어 답 → 통과', () => assert.equal(replyIsWrongLanguage('맛집', '인동 맛집은 곤들레, 천생산제면소가 있습니다. 전화번호와 거리는 아래 표를 참고하세요. ' + 'Kakao'), false));
|
||||
test('영어 질문 + 영어 답 → 통과', () => assert.equal(replyIsWrongLanguage('recommend restaurants', EN), false));
|
||||
test('짧은 영어(고유명사) → 통과', () => assert.equal(replyIsWrongLanguage('이거 뭐야', 'GPU'), false));
|
||||
test('영어 혼용 한국어 답 → 통과', () => assert.equal(replyIsWrongLanguage('날씨', '오늘은 맑고 최고 25도, 최저 11도입니다. 출처는 기상청과 오픈메테오이며 Weather data from KMA and Open-Meteo 로 확인했습니다.'), false));
|
||||
Reference in new issue
Block a user