perf: CHEMISTRY NOTATION을 화학 맥락일 때만 붙도록 게이팅 (매 턴 -174토큰)

이 블록은 470토큰까지 커져 무조건 블록 중 두 번째로 큰 항목이었는데,
실제로 모델이 \ce{}나 ```smiles를 내보낸 건 로그 83일 중 3일(~4%)뿐이었다.
나머지 96%의 턴에 값을 치르는 쪽이 더 나쁜 거래다.

이 파일 규칙 1("도구로만 게이팅, 메시지 문구로는 절대 금지")에 대한 의도적
예외다. 출력 형식 제약이라 키로 삼을 도구가 애초에 없고, 무엇보다 대가의
크기가 다르다 — image_edit 규칙이 빠지면 위험한 도구 호출이 나가지만, 이건
놓쳐봐야 깨진 ASCII 다이어그램 하나다. 파일 헤더의 규칙 2도 "무조건 유지"에서
이 예외를 설명하는 쪽으로 고쳐 적었다.

키워드는 일부러 넓게 잡았다. 애초에 무조건 유지했던 이유가 "치과/의료 질문은
화학 키워드 없이도 구조를 그리게 될 수 있다"였고 그게 이 사용자의 실제
도메인이므로, 성분·약물·마취·불소·아말감·레진·모노머·resin·anesthe 등을
함께 넣었다.

실측: 비화학 턴 시스템 프롬프트 1708 → 1533 토큰.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-08-10 12:40:11 +09:00
1 parent 96989373f5
commit fe69cc0126
3 files changed
+37 -12

No files matched your search

+1
View File
@@ -633,6 +633,7 @@ async function handleChat(
content: buildChatSystemPrompt({
executionMode,
toolNames: tools.map((t: any) => String(t?.function?.name || '')),
message,
dateStr,
timeStr,
isTranslateSession,
+20 -9
View File
@@ -17,9 +17,10 @@
* an unusual paraphrase would drop the rule on exactly the turn that needed it. Contrast
* tool-scope.ts, where keyword gating is fine because the worst case is a missing tool.
*
* 2. CHEMISTRY NOTATION stays unconditional. It constrains output FORMAT rather than a tool,
* so there is no tool to key on, and dental/medical questions can lead the model into
* drawing structures with no chemistry keyword anywhere in the prompt.
* 2. CHEMISTRY NOTATION is the one deliberate exception to rule 1 — it is message-gated, because
* it constrains output FORMAT rather than a tool so there is nothing else to key on. That is
* only acceptable because a missed keyword costs one garbled diagram rather than an unguarded
* tool call; see the note at the block itself for the measurement that motivated gating it.
*
* Pure: no config reads, no clock, no I/O. The caller resolves date, model profile, personality
* and skill context and passes them in.
@@ -43,6 +44,8 @@ export interface SystemPromptInput {
personalityCtx?: string;
/** Skill context blob the caller resolved for this user/message. */
skillsCtx?: string;
/** The user's message this turn — only used to gate CHEMISTRY NOTATION (see below). */
message?: string;
}
export function buildChatSystemPrompt(input: SystemPromptInput): string {
@@ -121,10 +124,19 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
// that tool is callable, and message-regex gating would drop it on exactly the paraphrase the
// regex missed. Tool availability is the same condition that makes the rule matter at all.
//
// CHEMISTRY NOTATION (180) is deliberately left unconditional: it constrains output FORMAT,
// not a tool, so there is no tool to key on, and this user's dental/medical questions can lead
// the model into drawing structures without any chemistry keyword in the prompt — the ASCII-art
// garbling it prevents would come back on precisely those turns.
// CHEMISTRY NOTATION was left unconditional for the reason above (no tool to key on, and this
// user's dental/medical questions can reach structure-drawing without an obvious chemistry
// keyword). Measured 2026-08-10: it had grown to 470 tokens — the second-largest block — while
// production logs showed the model actually emitting \ce{}/```smiles on only 3 of 83 logged
// days (~4%). Paying it on the other ~96% of turns is the worse trade, so it is now gated on
// message wording. This IS the message-regex gating the note above warns against, and the risk
// is real but bounded: a missed keyword costs one garbled ASCII diagram, not a dangerous tool
// call. The keyword set therefore errs wide, deliberately including the dental/medical and
// materials/drug vocabulary that motivated leaving it unconditional in the first place.
const chemistryRuleBlock = /분자|화학|화합물|구조식|시성식|분자식|원소|원자|이온|산화|환원|촉매|용해도|pH\b|산성|염기|알칼리|성분|약물|약품|제제|마취|불소|플루오르|아말감|레진|모노머|폴리머|중합|접착제|계면활성|방부제|첨가물|비타민|호르몬|단백질|아미노산|지방산|당류|알코올|에탄올|카페인|니코틴|SMILES|benzene|molecul|chemi|compound|reagent|reaction|formula|drug|monomer|polymer|resin|fluorid|anesthe/i
.test(String(input.message || ''))
? '\nCHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\\\ce{C4H10}$, $\\\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a ```smiles``` code block containing the SMILES string (e.g. ```smiles\\nc1ccccc1\\n``` for benzene, ```smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n``` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.'
: '';
const imageEditRuleBlock = toolNames.has('image_edit')
? '\nIMAGE EDITING RULE: NEVER call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user\'s message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.'
: '';
@@ -139,7 +151,6 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
: '';
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. 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. VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you're confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don't present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user's own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.
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. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live. This applies just as much to "is it raining/snowing right now" or any other current-state question: a search engine can hand you a page it cached long ago. Before treating a search result as live, check whether it carries its own timestamp — a date in the URL (e.g. "tm=2024.12.13.20:00", "?date=..."), a dateline, or "as of ..." phrasing — and compare it to the current date above. If that timestamp is more than a day or two old, it is NOT "지금"/"현재": say plainly that you couldn't find live data and name the stale date you found instead of presenting old numbers as current. When a result is a data TABLE (observation/measurement tables are the common case), read every row by its own row label, not by position — misaligning one city's or one row's figures onto the next is worse than finding nothing, because it looks authoritative while being wrong. If you're not confident you're reading the right column for the right label, say so rather than guessing.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}
CHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\ce{C4H10}$, $\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a \`\`\`smiles\`\`\` code block containing the SMILES string (e.g. \`\`\`smiles\\nc1ccccc1\\n\`\`\` for benzene, \`\`\`smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n\`\`\` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.${codeOutputRuleBlock}${packageInstallRuleBlock}
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. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live. This applies just as much to "is it raining/snowing right now" or any other current-state question: a search engine can hand you a page it cached long ago. Before treating a search result as live, check whether it carries its own timestamp — a date in the URL (e.g. "tm=2024.12.13.20:00", "?date=..."), a dateline, or "as of ..." phrasing — and compare it to the current date above. If that timestamp is more than a day or two old, it is NOT "지금"/"현재": say plainly that you couldn't find live data and name the stale date you found instead of presenting old numbers as current. When a result is a data TABLE (observation/measurement tables are the common case), read every row by its own row label, not by position — misaligning one city's or one row's figures onto the next is worse than finding nothing, because it looks authoritative while being wrong. If you're not confident you're reading the right column for the right label, say so rather than guessing.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${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. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain conditions in natural, fuller sentences rather than bare numbers, and use everything the tool actually returned: the multi-day trend it gives you (is it warming, cooling, steady?), precipitation chance, and anything notable. ${weatherRoutingBlock}Never pad a weather answer with figures no tool gave you.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
}
+16 -3
View File
@@ -29,9 +29,22 @@ describe('무조건 들어가는 블록', () => {
}
});
test('CHEMISTRY NOTATION은 도구와 무관하게 항상 — 출력 형식 제약이라 키로 삼을 도구가 없다', () => {
assert.ok(build().includes('CHEMISTRY NOTATION'));
assert.ok(build({ toolNames: ['web_search'] }).includes('CHEMISTRY NOTATION'));
// [2026-08-10] 470토큰까지 커진 반면 실제 사용은 로그 83일 중 3일(~4%)뿐이라 메시지 게이팅으로
// 전환. 출력 형식 제약이라 키로 삼을 도구가 없어서, 이 파일의 "도구로만 게이팅" 원칙에 대한
// 유일한 의도적 예외다 — 키워드를 놓쳐도 대가가 깨진 다이어그램 하나뿐이라 허용된다.
test('CHEMISTRY NOTATION은 화학 맥락일 때만 붙는다', () => {
assert.ok(!build({ message: '안녕' }).includes('CHEMISTRY NOTATION'));
assert.ok(!build({ message: '이 코드 리팩터링해줘', toolNames: ['coder_read_file'] }).includes('CHEMISTRY NOTATION'));
assert.ok(build({ message: '벤젠 화학식이 뭐야' }).includes('CHEMISTRY NOTATION'));
assert.ok(build({ message: '아스피린 분자구조 그려줘' }).includes('CHEMISTRY NOTATION'));
});
// 게이팅을 무조건 유지에서 조건부로 바꾼 이유가 치과/의료 어휘였으므로, 그쪽이 빠지면
// 애초에 게이팅한 의미가 없다 — 이 사용자의 실제 도메인이다.
test('치과/의료 어휘도 CHEMISTRY NOTATION을 켠다', () => {
for (const m of ['치과 레진 성분이 뭐지', '국소마취제 리도카인 어떻게 작용해', '불소도포 효과 있나']) {
assert.ok(build({ message: m }).includes('CHEMISTRY NOTATION'), `"${m}"에서 누락`);
}
});
test('현재 날짜/시각이 주입된다 — TEMPORAL CONSISTENCY의 근거값', () => {