refactor(thinking): GLM 전용 분리 규칙 — 긴 영어 추론 뒤 한글 꼬리 찾기와 혼잣말 봉합 규칙은 모델명에 glm이 들어갈 때만 적용, 다른 모델은 예전 동작. INLINE REASONING 로그에 모델 이름 추가
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a25b63e20e
commit
45e14b595e
3 files changed
+42
-18
No files matched your search
@@ -132,7 +132,7 @@ export interface HandleChatDeps {
|
||||
getModelProfileFixedNumCtx: (modelName: string) => number | undefined;
|
||||
getModelProfileThink: (modelName: string) => boolean | 'high' | 'medium' | 'low' | undefined;
|
||||
stripExplicitThinkTags: (text: string) => { cleaned: string; thinking: string };
|
||||
separateThinkingFromContent: (text: string) => { reply: string; thinking: string };
|
||||
separateThinkingFromContent: (text: string, opts?: { model?: string }) => { reply: string; thinking: string };
|
||||
isOrchestrationSkillEnabled: () => boolean;
|
||||
isBrowserHeavyResearchPage: (input: { url?: string; pageType?: string; snapshotElements?: number; feedCount?: number; goal?: string }) => boolean;
|
||||
incrementPreemptSessionCount: (sessionId: string) => number;
|
||||
@@ -1877,9 +1877,9 @@ async function handleChat(
|
||||
}
|
||||
|
||||
if (!toolCalls || toolCalls.length === 0) {
|
||||
const { reply, thinking: inlineThinking } = separateThinkingFromContent(response.content || '');
|
||||
const { reply, thinking: inlineThinking } = separateThinkingFromContent(response.content || '', { model: resolvedModelThisRound });
|
||||
if (inlineThinking) {
|
||||
console.log(`[v2] INLINE REASONING (${inlineThinking.length} chars): ${inlineThinking.slice(0, 100)}...`);
|
||||
console.log(`[v2] INLINE REASONING [${resolvedModelThisRound || '?'}] (${inlineThinking.length} chars): ${inlineThinking.slice(0, 100)}...`);
|
||||
allThinking += (allThinking ? '\n\n' : '') + inlineThinking;
|
||||
sendSSE('thinking', { thinking: inlineThinking });
|
||||
}
|
||||
|
||||
@@ -2,7 +2,13 @@
|
||||
// 2026-09-22 server.ts에서 추출(단위 테스트를 위해). 실측 데이터: tests/thinking-separation.test.ts
|
||||
|
||||
|
||||
function separateThinkingFromContent(text: string): { reply: string; thinking: string } {
|
||||
// opts.model — 응답을 낸 모델 이름. 2026-10-01부터 GLM 계열에서만 나타나는 패턴(긴 영어 추론 뒤 한글 답, 짧은 혼잣말과
|
||||
// 한글의 무공백 융합)에 대한 공격적 규칙은 이름에 "glm"이 들어간 모델에만 적용한다. 다른 모델은 예전 규칙 그대로라
|
||||
// 정상 응답이 오탐으로 잘릴 위험이 없다. 모델을 모르면(undefined) GLM 전용 규칙은 꺼진다.
|
||||
export interface SeparationOptions { model?: string }
|
||||
const isGlm = (opts?: SeparationOptions) => /glm/i.test(opts?.model || '');
|
||||
|
||||
function separateThinkingFromContent(text: string, opts?: SeparationOptions): { reply: string; thinking: string } {
|
||||
if (!text) return { reply: '', thinking: '' };
|
||||
|
||||
// think 태그 안의 내용은 버리지 않고 thinking으로 보존한다(기존엔 그냥 삭제돼 손실).
|
||||
@@ -13,21 +19,21 @@ function separateThinkingFromContent(text: string): { reply: string; thinking: s
|
||||
.replace(/<\/think>/gi, '')
|
||||
.trim();
|
||||
const captured = thinkParts.join('\n\n').trim();
|
||||
const base = classify(cleaned);
|
||||
const base = classify(cleaned, opts);
|
||||
return {
|
||||
reply: base.reply,
|
||||
thinking: [captured, base.thinking].filter(Boolean).join('\n\n'),
|
||||
};
|
||||
}
|
||||
|
||||
function classify(cleaned: string): { reply: string; thinking: string } {
|
||||
function classify(cleaned: string, opts?: SeparationOptions): { reply: string; thinking: string } {
|
||||
if (!cleaned) return { reply: '', thinking: '' };
|
||||
|
||||
// glm-5.3-flash 영어 셀프토크 접두사(구조 기반) 먼저 시도 — 키워드 휴리스틱에 안 잡히는 패턴
|
||||
const scratch = stripEnglishScratchPrefix(cleaned);
|
||||
const scratch = stripEnglishScratchPrefix(cleaned, isGlm(opts));
|
||||
if (scratch) {
|
||||
// 접두사 제거 후 남은 답변에 대해 기존 키워드 휴리스틱을 한 번 더 돌려 중첩 셀프토크도 처리
|
||||
const inner = separateThinkingFromContent(scratch.reply);
|
||||
const inner = separateThinkingFromContent(scratch.reply, opts);
|
||||
return {
|
||||
reply: inner.reply,
|
||||
thinking: [scratch.thinking, inner.thinking].filter(Boolean).join('\n\n'),
|
||||
@@ -40,7 +46,7 @@ function classify(cleaned: string): { reply: string; thinking: string } {
|
||||
// 영어 추론이 끝나고 한글 답변이 시작되는 지점부터 끝까지를 답으로 쓴다(2026-10-01). 예전에는 아래처럼
|
||||
// "마지막 문장 하나"만 남겨서, 멀쩡히 끝난 여러 문단의 한글 답변도 한 줄로 줄어들었다
|
||||
// (작업실 채팅 실사례: 답변이 "…참고용은 괜찮지만 설계" 한 조각만 남음).
|
||||
const tail = koreanAnswerTail(cleaned);
|
||||
const tail = isGlm(opts) ? koreanAnswerTail(cleaned) : null;
|
||||
if (tail) return tail;
|
||||
// Try to find the last sentence that looks like a real reply
|
||||
const sentences = cleaned.split(/(?<=[.!?])\s+/);
|
||||
@@ -132,7 +138,7 @@ const SCRATCH_LABEL_RE = /^(Also note|Also mention|Answer format|Key message|Key
|
||||
// 봉합점 앞 영어가 "내 할 일을 중얼거리는" 말투인지(키워드는 보조 증거일 뿐 — 한글 없음 + 봉합점이 핵심 구조 신호).
|
||||
const INNER_MONOLOGUE_RE = /^(The (user|note|answer|tool|file|result|search|response|rules?)\b|I (need|should|will|have|can|am)\b|Let me\b|Now,? |Okay|Ok,|Hmm|Wait|So,? |First,? |Done\b|Good\b|Alright)/i;
|
||||
|
||||
function stripEnglishScratchPrefix(text: string): { reply: string; thinking: string } | null {
|
||||
function stripEnglishScratchPrefix(text: string, glm = false): { reply: string; thinking: string } | null {
|
||||
if (!text) return null;
|
||||
const HANGUL = /[가-힣]/;
|
||||
// 답변 언어가 한국어인 경우에만 적용한다(마지막 500자에 한글이 있어야 함).
|
||||
@@ -148,7 +154,7 @@ function stripEnglishScratchPrefix(text: string): { reply: string; thinking: str
|
||||
// 단락 수 증거가 없어도, 봉합점 앞이 전부 영어이고 추론 말투로 시작하면 셀프토크로 본다.
|
||||
// before는 봉합점의 영어 런(m[1]) 앞까지라서, 런 자체를 합쳐서 본다.
|
||||
const beforeAll = (before + m[1]).trim();
|
||||
const strongSolo = !HANGUL.test(beforeAll) && INNER_MONOLOGUE_RE.test(beforeAll);
|
||||
const strongSolo = glm && !HANGUL.test(beforeAll) && INNER_MONOLOGUE_RE.test(beforeAll);
|
||||
const hasEvidence =
|
||||
strongSolo ||
|
||||
prior.some(p => SCRATCH_LABEL_RE.test(p)) ||
|
||||
|
||||
@@ -93,6 +93,9 @@ describe('glm 영어 셀프토크 접두사 분리', () => {
|
||||
assert.ok(/추석 비를 물었다/.test(thinking), 'think 내용이 thinking으로 가야 함');
|
||||
});
|
||||
|
||||
// GLM 계열에서만 켜지는 규칙 — 모델 이름에 glm이 들어갈 때만 적용(2026-10-01).
|
||||
const GLM = { model: 'glm-5.3:cloud' };
|
||||
|
||||
// ── 2026-10-01 실사례: 긴 영어 추론 뒤의 한글 답변이 "마지막 문장 하나"로 줄어들던 문제 ──
|
||||
describe('긴 영어 추론 뒤 한글 답변 — 한글이 시작되는 지점부터 끝까지가 답', () => {
|
||||
const reasoning = Array.from({ length: 40 }, (_, i) =>
|
||||
@@ -100,7 +103,7 @@ describe('glm 영어 셀프토크 접두사 분리', () => {
|
||||
|
||||
test('여러 문단·목록으로 된 한글 답변이 통째로 남는다(마지막 문장만 남지 않음)', () => {
|
||||
const answer = '프로젝트 변경사항을 확인했습니다.\n\n**오늘 바뀐 것**\n- 이름이 astra로 바뀌었습니다.\n- 부품 3종이 추가되었습니다.\n\n설계 정밀도가 필요하면 다시 확인해야 합니다.';
|
||||
const { reply, thinking } = separateThinkingFromContent(reasoning + '\n\n' + answer);
|
||||
const { reply, thinking } = separateThinkingFromContent(reasoning + '\n\n' + answer, GLM);
|
||||
assert.equal(reply, answer);
|
||||
assert.ok(thinking.startsWith('The user asked'));
|
||||
assert.ok(!/프로젝트 변경사항/.test(thinking));
|
||||
@@ -108,25 +111,25 @@ describe('glm 영어 셀프토크 접두사 분리', () => {
|
||||
|
||||
test('답변이 중간에서 끊겨도(문장 부호 없이 끝남) 앞의 문단까지 보존한다 — 작업실 채팅 사건', () => {
|
||||
const answer = '확인 결과입니다.\n\n- 이름이 바뀌었습니다.\n\n개인 테스트 프로젝트 참고용은 괜찮지만 설계';
|
||||
const { reply } = separateThinkingFromContent(reasoning + '\n\n' + answer);
|
||||
const { reply } = separateThinkingFromContent(reasoning + '\n\n' + answer, GLM);
|
||||
assert.equal(reply, answer);
|
||||
});
|
||||
|
||||
test('추론 문단 안의 한글 인용은 답변으로 오인하지 않는다', () => {
|
||||
const withQuote = reasoning + '\n\nThe user wrote "변경사항 있나 확인" so I should list what changed in the project and answer in Korean.';
|
||||
const answer = '바뀐 것은 이름 변경과 부품 추가입니다.';
|
||||
const { reply } = separateThinkingFromContent(withQuote + '\n\n' + answer);
|
||||
const { reply } = separateThinkingFromContent(withQuote + '\n\n' + answer, GLM);
|
||||
assert.equal(reply, answer);
|
||||
});
|
||||
|
||||
test('답변이 영어이면(꼬리가 한글이 아님) 기존 동작을 유지한다', () => {
|
||||
const { reply } = separateThinkingFromContent(reasoning + '\n\nThere are no changes in the project today.');
|
||||
const { reply } = separateThinkingFromContent(reasoning + '\n\nThere are no changes in the project today.', GLM);
|
||||
assert.ok(reply.length > 0 && !/The user asked/.test(reply));
|
||||
});
|
||||
|
||||
test('답변이 한 단락이어도 여러 문장이 모두 남는다', () => {
|
||||
const answer = '이름이 바뀌었습니다. 부품이 추가되었습니다. 센서 마운트도 만들었습니다.';
|
||||
assert.equal(separateThinkingFromContent(reasoning + '\n\n' + answer).reply, answer);
|
||||
assert.equal(separateThinkingFromContent(reasoning + '\n\n' + answer, GLM).reply, answer);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -135,14 +138,29 @@ describe('glm 영어 셀프토크 접두사 분리', () => {
|
||||
const FUSED = 'The note was added successfully. The answer is complete. Let me give a brief closing confirmation.메모에 정확도 스펙을 저장했습니다. 공식 정확도는 약 0.4°입니다. 조립 시 AGC 레지스터 값이 중간에 오도록 맞추는 것만 기억하시면 됩니다.';
|
||||
|
||||
test('한글 답 전체가 남고 영어 혼잣말은 생각으로 간다(마지막 문장 하나만 남지 않음)', () => {
|
||||
const { reply, thinking } = separateThinkingFromContent(FUSED);
|
||||
const { reply, thinking } = separateThinkingFromContent(FUSED, GLM);
|
||||
assert.equal(reply, '메모에 정확도 스펙을 저장했습니다. 공식 정확도는 약 0.4°입니다. 조립 시 AGC 레지스터 값이 중간에 오도록 맞추는 것만 기억하시면 됩니다.');
|
||||
assert.match(thinking, /^The note was added/);
|
||||
});
|
||||
|
||||
test('정상 응답의 "영어 문장.한글" 붙임(혼잣말 말투 아님)은 건드리지 않는다', () => {
|
||||
const normal = 'Open-Meteo and KMA are both fine sources for this kind of daily forecast request.아쉽게도 내일은 비가 옵니다.';
|
||||
assert.equal(separateThinkingFromContent(normal).reply, normal);
|
||||
assert.equal(separateThinkingFromContent(normal, GLM).reply, normal);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GLM이 아닌 모델에는 GLM 전용 규칙이 적용되지 않는다', () => {
|
||||
const FUSED = 'The note was added successfully. The answer is complete. Let me give a brief closing confirmation.메모에 정확도 스펙을 저장했습니다. 공식 정확도는 약 0.4°입니다. 조립 시 AGC 레지스터 값이 중간에 오도록 맞추는 것만 기억하시면 됩니다.';
|
||||
|
||||
test('모델이 gemma4이거나 모르면 예전 동작(마지막 문장)이 그대로다 — 새 규칙은 GLM 전용', () => {
|
||||
const old = '조립 시 AGC 레지스터 값이 중간에 오도록 맞추는 것만 기억하시면 됩니다.';
|
||||
assert.equal(separateThinkingFromContent(FUSED, { model: 'gemma4:31b-cloud' }).reply, old);
|
||||
assert.equal(separateThinkingFromContent(FUSED).reply, old);
|
||||
});
|
||||
|
||||
test('모델 이름의 대소문자·접미사와 무관하게 glm이면 켜진다', () => {
|
||||
assert.match(separateThinkingFromContent(FUSED, { model: 'GLM-5.3-Flash:cloud' }).reply, /^메모에 정확도/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user