Anthropic 프롬프트 캐싱(도구 끝·시스템 끝·자동) + 캐시 토큰 기록, 한국어 메모를 넛지 전부에 붙여 라운드 간 앞부분 고정(2라운드 캐시 읽기 3.9K→9.7K). 프롬프트: 🦞 이모지 금지 문구 삭제, NEVER/ALWAYS…no exceptions 강조를 보통 문장으로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
48fc855e1f
commit
32557bcd1c
6 files changed
+36
-16
No files matched your search
@@ -29,7 +29,7 @@ export function isClaudeModel(model: string): boolean {
|
||||
|
||||
/**
|
||||
* @param userMsgIndex 이번 턴 사용자 메시지의 messages 인덱스. 그 뒤에 들어온 user 메시지만 넛지로 본다.
|
||||
* @param userMessage 사용자 원문 — 한글이 있으면 마지막 넛지에 한국어로 답하라는 메모를 붙인다.
|
||||
* @param userMessage 사용자 원문 — 한글이 있으면 넛지마다 한국어로 답하라는 메모를 붙인다.
|
||||
*/
|
||||
export function adaptNudgesForClaude<T extends { role: string; content?: any }>(
|
||||
messages: T[], userMsgIndex: number, userMessage: string,
|
||||
@@ -41,12 +41,16 @@ export function adaptNudgesForClaude<T extends { role: string; content?: any }>(
|
||||
&& 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}` };
|
||||
// 한국어 메모는 사용자 메시지 뒤의 넛지 전부에 붙인다. 마지막 넛지에만 붙이면 다음 라운드에 메모 위치가 옮겨 가
|
||||
// 앞부분이 달라지고, 프롬프트 캐시가 거기서 끊긴다(2026-10-23 실측: 2라운드 캐시 읽기가 도구 부분 3.9K뿐).
|
||||
// 맞장구는 사용자 메시지 뒤에서만 뺐으므로 사용자 메시지의 위치는 out에서도 userMsgIndex 그대로다.
|
||||
if (/[가-힣]/.test(String(userMessage || ''))) {
|
||||
for (let i = userMsgIndex + 1; i < out.length; i++) {
|
||||
const m = out[i];
|
||||
if (m.role === 'user' && typeof m.content === 'string' && !m.content.includes(KOREAN_REPLY_NOTE)) {
|
||||
out[i] = { ...m, content: `${m.content}\n\n${KOREAN_REPLY_NOTE}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -128,7 +128,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
const meteo = has('weather_openmeteo');
|
||||
if (!kma && !meteo) return '';
|
||||
if (kma && meteo) {
|
||||
return 'Pick the source by location: for anywhere in Korea ALWAYS call weather_kma first, no exceptions (the Korea Meteorological Administration is the authority domestically; observation-backed, includes precipitation chance), and add weather_openmeteo only when you need UV/long hourly detail (weather_kma already returns days 4-10 from the official KMA mid-range forecast, so "이번 주" needs no second tool); outside Korea use weather_openmeteo. If the tool you called did not return precipitation chance, do NOT invent one and do NOT quietly skip it — call one that provides it. ';
|
||||
return 'Pick the source by location: for places in Korea call weather_kma first (the Korea Meteorological Administration is the authority domestically; observation-backed, includes precipitation chance), and add weather_openmeteo only when you need UV/long hourly detail (weather_kma already returns days 4-10 from the official KMA mid-range forecast, so "이번 주" needs no second tool); outside Korea use weather_openmeteo. If the tool you called did not return precipitation chance, do NOT invent one and do NOT quietly skip it — call one that provides it. ';
|
||||
}
|
||||
if (kma) return 'Use weather_kma (Korea only, observation-backed, includes precipitation chance). If it cannot cover the location or range, say so rather than estimating. ';
|
||||
return 'Use weather_openmeteo — it carries precipitation probability and hourly detail. If it did not return a precipitation chance, do NOT invent one. ';
|
||||
@@ -217,7 +217,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
// 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.'
|
||||
? '\nCHEMISTRY NOTATION: Do not 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.'
|
||||
: '';
|
||||
// MAPS: same message-gated exception as CHEMISTRY NOTATION — it constrains output FORMAT
|
||||
// (emit a Google Maps URL on its own line so markdown.js renders it as an inline map iframe,
|
||||
@@ -260,7 +260,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
? ' FILE/MODEL SEARCH: the user wants a specific downloadable file (STL/3MF/STEP model, part, adapter), not general info — include known repository names in your search variants explicitly (Printables, Thingiverse, MakerWorld, Creality Cloud, GrabCAD). Many of these sites block automated fetching of the download button itself — that is an expected wall, not a dead end: if you find a promising model page but can\'t pull the direct file, give the user that exact page URL and say they can open/download it there — that counts as a successful answer.'
|
||||
: '';
|
||||
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.'
|
||||
? '\nIMAGE EDITING RULE: Do not 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.'
|
||||
: '';
|
||||
const mediaGenRuleBlock = (toolNames.has('image_generate') || toolNames.has('video_generate'))
|
||||
? '\nIMAGE/VIDEO GENERATION: When a user asks to create/draw/generate a NEW image from a description (no existing photo involved), call image_generate (local SDXL, 10-20 seconds by default). If the user explicitly asks for higher quality/detail/photorealism (e.g. "고품질로", "디테일 살려서"), pass quality="high" instead — this uses FLUX.1-schnell, noticeably better detail but 40-60 seconds total, so tell the user it\'ll take a bit before calling it. When they ask for a short video/clip/animation from a description, call video_generate (local LTX-Video, 30–90 seconds — tell the user it\'ll take a bit before calling it). All run entirely on local GPU hardware, no external API or cost. Do not confuse these with image_edit, which only modifies an existing uploaded/generated image.'
|
||||
@@ -269,9 +269,9 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
? '\nCODE OUTPUT: When writing code in a fenced code block, start with a filename comment on line 1: `# filename: snake_game.py` (Python), `// filename: app.js` (JS/C), `<!-- filename: index.html -->` (HTML). Never repeat code already written in this conversation. For modifications to existing files, use coder_overwrite_lines or coder_insert_lines (not coder_write_file — it only works for NEW files). All code changes are presented as diffs for the user to review before being applied. Write code directly — do not ask for permission.'
|
||||
: '';
|
||||
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.'
|
||||
? '\nPACKAGE INSTALL: Do not 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. 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) informational answers you researched with a tool (news, weather, factual explanations, comparisons) are not held to 2-4 sentences, but size them to the question: lead with the answer, and leave out background, caveats and closing offers ("더 필요하시면…") the user did not ask for. (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.\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) informational answers you researched with a tool (news, weather, factual explanations, comparisons) are not held to 2-4 sentences, but size them to the question: lead with the answer, and leave out background, caveats and closing offers ("더 필요하시면…") the user did not ask for. (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}`;
|
||||
|
||||
@@ -73,12 +73,18 @@ export class AnthropicAdapter implements LLMProvider {
|
||||
max_tokens: options?.max_tokens ?? 8192,
|
||||
messages: toAnthropicMessages(rest),
|
||||
};
|
||||
if (system) body.system = system;
|
||||
// 시스템 프롬프트 끝에도 캐시 지점 — 같은 분(시각 줄) 안의 다음 턴이 도구+시스템을 캐시에서 읽는다
|
||||
if (system) body.system = [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }];
|
||||
if (options?.temperature !== undefined && acceptsTemperature(model)) body.temperature = options.temperature;
|
||||
if (shouldDisableThinking(model, (options as any)?.think)) body.thinking = { type: 'disabled' };
|
||||
if (Array.isArray(options?.tools) && options!.tools!.length) {
|
||||
body.tools = toAnthropicTools(options!.tools!);
|
||||
// 도구 설명(수천 토큰)은 시스템 프롬프트 앞이라 분 단위 시각이 바뀌어도 캐시가 산다 — 끝 도구에 캐시 지점
|
||||
if (body.tools.length) body.tools[body.tools.length - 1].cache_control = { type: 'ephemeral' };
|
||||
}
|
||||
// 프롬프트 캐싱(2026-10-23): 이전엔 매 호출 ~9K 토큰을 새로 처리했다. 한 턴 안의 도구 라운드는 앞부분이 같으므로
|
||||
// 자동 캐시(마지막 블록까지)로 다음 라운드가 캐시에서 읽는다 — 비용보다 첫 글자 지연이 줄어드는 게 목적.
|
||||
body.cache_control = { type: 'ephemeral' };
|
||||
|
||||
const data = await this.post('/v1/messages', body);
|
||||
const result = fromAnthropicResponse(data);
|
||||
@@ -88,7 +94,7 @@ export class AnthropicAdapter implements LLMProvider {
|
||||
if (u) {
|
||||
const promptTokens = (Number(u.input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0);
|
||||
const completionTokens = Number(u.output_tokens) || 0;
|
||||
logUsage(model, promptTokens, completionTokens);
|
||||
logUsage(model, promptTokens, completionTokens, 0, { cacheRead: Number(u.cache_read_input_tokens) || 0, cacheWrite: Number(u.cache_creation_input_tokens) || 0 });
|
||||
return { ...result, usage: { promptTokens, completionTokens, ctxWindow: Number(options?.num_ctx) || 0 } } as ChatResult;
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -19,13 +19,15 @@ const USAGE_LOG_PATH = (() => {
|
||||
catch { return null; }
|
||||
})();
|
||||
|
||||
export function logUsage(model: string, promptTokens: number, completionTokens: number, extraUsd = 0): void {
|
||||
export function logUsage(model: string, promptTokens: number, completionTokens: number, extraUsd = 0,
|
||||
cache?: { cacheRead: number; cacheWrite: number }): void {
|
||||
if (!USAGE_LOG_PATH || (!promptTokens && !completionTokens && !extraUsd)) return;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(USAGE_LOG_PATH), { recursive: true });
|
||||
fs.appendFileSync(USAGE_LOG_PATH, JSON.stringify({
|
||||
ts: new Date().toISOString(), model, promptTokens, completionTokens,
|
||||
...(extraUsd ? { extraUsd } : {}), // 토큰 외 과금(예: Claude 웹 검색 수수료)
|
||||
...(cache && (cache.cacheRead || cache.cacheWrite) ? cache : {}), // Anthropic 프롬프트 캐시(promptTokens에 포함됨)
|
||||
}) + '\n');
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
@@ -17,6 +17,14 @@ test('사용자 메시지 뒤 가짜 맞장구는 빼고 마지막 넛지에 한
|
||||
assert.equal(msgs[4].content, 'Reminder: call a tool first.', '원본 배열은 그대로');
|
||||
});
|
||||
|
||||
test('넛지 전부에 메모가 붙어 라운드가 바뀌어도 앞부분이 같다(프롬프트 캐시)', () => {
|
||||
const r1 = [...base, { role: 'user', content: 'Reminder: call a tool first.' }];
|
||||
const r2 = [...r1, { role: 'assistant', content: '', tool_calls: [{}] } as any, { role: 'tool', content: 'r' }];
|
||||
const a = adaptNudgesForClaude(r1, 2, '주말에 현풍 비오나?');
|
||||
const b = adaptNudgesForClaude(r2, 2, '주말에 현풍 비오나?');
|
||||
assert.deepEqual(b.slice(0, a.length), a);
|
||||
});
|
||||
|
||||
test('진짜 초안(candidateText)과 도구 라운드는 그대로', () => {
|
||||
const msgs = [...base, { role: 'assistant', content: '초안 답변입니다.' }, { role: 'user', content: 'Re-check the figures.' }];
|
||||
const out = adaptNudgesForClaude(msgs, 2, '주말에 현풍 비오나?');
|
||||
|
||||
@@ -154,7 +154,7 @@ describe('도구 게이팅 — 도구가 있을 때만 규칙이 붙는다', ()
|
||||
// 사용자 문구로 게이팅했다면 정규식이 놓친 표현에서 이 규칙이 사라졌을 것.
|
||||
const p = build({ toolNames: ['image_edit'] });
|
||||
assert.ok(p.includes('IMAGE EDITING RULE'));
|
||||
assert.ok(/NEVER call image_edit/i.test(p));
|
||||
assert.ok(/Do not call image_edit/i.test(p));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user