198 lines
14 KiB
TypeScript
198 lines
14 KiB
TypeScript
/**
|
|
* separateThinkingFromContent — glm-5.3-flash 영어 셀프토크 접두사 분리
|
|
*
|
|
* 2026-09-22 실측: glm-5.3-flash:cloud(당시 primary)가 날씨 답변 앞에 영어로 내부 계획을 붙였다가
|
|
* 마지막 단락에서 한글 답변과 무공백 융합("No emoji habit.아쉽게도…")해 통째로 노출됨.
|
|
* 키워드 휴리스틱이 이 패턴을 못 잡아 구조 기반 stripEnglishScratchPrefix를 추가.
|
|
* 표본 2건은 그날의 실제 세션 텍스트(09175258 세션)다.
|
|
*/
|
|
|
|
import { test, describe } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { separateThinkingFromContent } from '../src/gateway/chat/thinking-separation';
|
|
|
|
// ── 실측 표본 1: "추석에 비소식 없나?" 응답 ──
|
|
const SAMPLE_1 = `Also note discrepancy: Open-Meteo showed Sep 24 as mostly clear/dry (0% precip prob through 22:00), while KMA says 30% for Sep 24. KMA is observation-backed and preferred for Korea. I'll lead with KMA numbers. The openmeteo hourly for Sep 24 showed 0% precip probability — slight disagreement, but KMA is the authoritative source for Korea. I'll present KMA as main, and can mention the trend.
|
|
|
|
Answer format: weather answers should be natural sentences, not forced tables. But a small table for the holiday period could help... The rules say for weather do NOT force a table — explain in natural fuller sentences. I'll write in Korean, conversational but informative.
|
|
|
|
Key message: 아쉽게도 비 소식이 있습니다. 추석 당일(9/25 금) 강수확률 60%, 비 예보. 전날(9/24 목)은 흐림 30%. 토요일(9/26)도 60% 비. 일요일(9/27)부터는 개어서 4%. 서울 기준이며, 지역 알려주면 다시 확인해주겠다고.
|
|
|
|
Also mention: 발표 시각 2026-09-22 23:00 KST 기준 단기예보라, 3일 뒤 예보라 변동 가능성 있음 — 추석 당일까지는 예보가 바뀔 수 있으니 며칠 뒤 다시 확인 권장.
|
|
|
|
Keep it reasonably concise but full sentences. No emoji habit.아쉽게도 비 소식이 있습니다. 기상청 단기예보(오늘 밤 11시 발표, 서울 기준)에 따르면 추석 연휴 후반부에 비가 예보돼요.
|
|
|
|
- **9/24 (목, 추석 전날)**: 흐림, 19~28°C, 강수확률 30% — 아직 비 예보는 아니고 흐려지는 날
|
|
- **9/25 (금, 추석 당일)**: **비, 강수확률 60%**, 19~28°C — 당일은 비 소식 확실하게 잡혀 있음
|
|
|
|
즉 귀성길인 목요일까지는 큰 문제가 없지만, 추석 당일과 토요일 귀경길에 비를 만날 가능성이 높습니다.
|
|
|
|
서울 기준으로 봤는데, 다른 지역(고향)이 궁금하면 알려주세요.`;
|
|
|
|
// ── 실측 표본 2: "남부 지방은 어때?" 응답 ──
|
|
const SAMPLE_2 = `Actually the rule: "When comparing several cities (e.g. '오늘 유럽 대도시 최고 기온'), a table is fine for the numbers themselves, but always follow it with a few sentences of actual commentary." So table + commentary is fine here.
|
|
|
|
Key points:
|
|
- 남부 3대 도시(부산·대구·광주) 모두 비슷한 패턴
|
|
- 추석 당일(9/25 금): 세 도시 모두 흐림, 강수확률 30% — 서울(비 60%)보다 하루 늦게 비가 옴
|
|
|
|
Keep it focused and natural. Korean language.남부 지방은 서울보다 비가 하루 늦게 옵니다. 부산·대구·광주 세 도시를 기상청 단기예보(오늘 밤 11시 발표)로 확인했는데, 패턴이 거의 같아요.
|
|
|
|
| 날짜 | 부산 | 대구 | 광주 |
|
|
|------|------|------|------|
|
|
| 9/26 (토) | **비 60%** | **비 60%** | **비 60%** |
|
|
|
|
역시 3일 뒤까지의 예보라 변동 가능성은 있으니, 토요일 출발 전에 다시 확인하시는 게 좋습니다.`;
|
|
|
|
describe('glm 영어 셀프토크 접두사 분리', () => {
|
|
test('실측 표본 1 — 영어 계획 노출분을 thinking으로 떼어낸다', () => {
|
|
const { reply, thinking } = separateThinkingFromContent(SAMPLE_1);
|
|
assert.ok(!/Also note|Answer format|Also mention|Keep it reasonably/.test(reply),
|
|
`reply에 영어 계획 잔여물이 남음: ${reply.slice(0, 120)}`);
|
|
assert.ok(reply.startsWith('아쉽게도 비 소식이 있습니다'), `reply 시작이 한글 답변이 아님: ${reply.slice(0, 60)}`);
|
|
assert.ok(/귀성길인 목요일/.test(reply), '답변 본문이 잘리면 안 됨');
|
|
assert.ok(/Open-Meteo/.test(thinking), '분리된 thinking에 계획이 있어야 함');
|
|
});
|
|
|
|
test('실측 표본 2 — "Korean language."뒤 무공백 융합을 끊는다', () => {
|
|
const { reply, thinking } = separateThinkingFromContent(SAMPLE_2);
|
|
assert.ok(!/Actually the rule|Keep it focused/.test(reply),
|
|
`reply에 영어 계획 잔여물이 남음: ${reply.slice(0, 120)}`);
|
|
assert.ok(reply.startsWith('남부 지방은 서울보다'), `reply 시작이 한글 답변이 아님: ${reply.slice(0, 60)}`);
|
|
assert.ok(/부산·대구·광주 세 도시를 기상청/.test(reply), '융합 단락의 한글 본문이 보존돼야 함');
|
|
assert.ok(/9\/26 \(토\)/.test(reply), '마크다운 표가 잘리면 안 됨');
|
|
assert.ok(/Actually the rule/.test(thinking), '분리된 thinking에 계획이 있어야 함');
|
|
});
|
|
|
|
test('정상 한글 답변은 건드리지 않는다', () => {
|
|
const normal = '오늘 서울 날씨는 맑습니다. 최고 기온은 24도예요.\n\n- 아침 16도\n- 낮 24도\n\n즐거운 하루 보내세요.';
|
|
const { reply, thinking } = separateThinkingFromContent(normal);
|
|
assert.equal(thinking, '');
|
|
assert.equal(reply, normal);
|
|
});
|
|
|
|
test('영어 단어 뒤 바로 한글 오는 정상 혼합문은 보존된다', () => {
|
|
const mixed = 'Open-Meteo 모델은 목요일을 맑은 날로 보고 있습니다.\n\n기상청 기준으로 정리하면 다음과 같습니다.\n\n- 9/24: 흐림 30%\n- 9/25: 비 60%\n\n출발 전에 다시 확인하세요.';
|
|
const { reply, thinking } = separateThinkingFromContent(mixed);
|
|
assert.equal(thinking, '');
|
|
assert.ok(reply.startsWith('Open-Meteo'), '영어 단어로 시작하는 정상 답변이 잘리면 안 됨');
|
|
});
|
|
|
|
test('짧은 영어 접두는 기존 키워드 휴리스틱이 걸러낸다', () => {
|
|
const short = 'Let me summarize the forecast for you.\n\n답변입니다. 추석 당일 비 예보 60%입니다.\n\n추가로 토요일도 비 60%예요.\n\n일요일부터는 개어서 맑습니다.';
|
|
const { reply, thinking } = separateThinkingFromContent(short);
|
|
// "Let me" 단락은 starterRE/reasoningRE에 걸려 thinking으로 간다 — reply는 한글 답변만 남는다
|
|
assert.ok(/Let me/.test(thinking), '영어 접두 단락이 thinking으로 가야 함');
|
|
assert.ok(reply.startsWith('답변입니다'), `reply가 한글 답변이어야 함: ${reply.slice(0, 60)}`);
|
|
});
|
|
|
|
test('기존 <think> 태그 방식은 그대로 작동한다', () => {
|
|
const tagged = '<think>사용자가 추석 비를 물었다. KMA를 보자.</think>아쉽게도 추석 당일 비 예보가 있습니다. 강수확률 60%예요.';
|
|
const { reply, thinking } = separateThinkingFromContent(tagged);
|
|
assert.ok(reply.startsWith('아쉽게도'), `<think> 태그가 안 떼어짐: ${reply.slice(0, 60)}`);
|
|
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) =>
|
|
`The user asked me to check changes. I need to look at file ${i} and the rules say I should not guess, so let me check the tools carefully.`).join('\n\n');
|
|
|
|
test('여러 문단·목록으로 된 한글 답변이 통째로 남는다(마지막 문장만 남지 않음)', () => {
|
|
const answer = '프로젝트 변경사항을 확인했습니다.\n\n**오늘 바뀐 것**\n- 이름이 astra로 바뀌었습니다.\n- 부품 3종이 추가되었습니다.\n\n설계 정밀도가 필요하면 다시 확인해야 합니다.';
|
|
const { reply, thinking } = separateThinkingFromContent(reasoning + '\n\n' + answer, GLM);
|
|
assert.equal(reply, answer);
|
|
assert.ok(thinking.startsWith('The user asked'));
|
|
assert.ok(!/프로젝트 변경사항/.test(thinking));
|
|
});
|
|
|
|
test('답변이 중간에서 끊겨도(문장 부호 없이 끝남) 앞의 문단까지 보존한다 — 작업실 채팅 사건', () => {
|
|
const answer = '확인 결과입니다.\n\n- 이름이 바뀌었습니다.\n\n개인 테스트 프로젝트 참고용은 괜찮지만 설계';
|
|
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, GLM);
|
|
assert.equal(reply, answer);
|
|
});
|
|
|
|
test('답변이 영어이면(꼬리가 한글이 아님) 기존 동작을 유지한다', () => {
|
|
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, GLM).reply, answer);
|
|
});
|
|
});
|
|
|
|
// ── 2026-10-01 실사례 2: 짧은 응답 — 영어 혼잣말 뒤에 공백 없이 한글 답이 붙음 ──
|
|
describe('짧은 영어 혼잣말 + 공백 없이 붙은 한글 답', () => {
|
|
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, 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, 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, /^메모에 정확도/);
|
|
});
|
|
});
|
|
});
|
|
|
|
|
|
// ── 2026-10-03 실측: 논문 목록 표가 통째로 추론으로 분류돼 "|" 한 글자만 답으로 남은 사고 ──
|
|
// 표 첫 행 제목 "A Review of the Current Literature"가 reasoningRE의 `the current`에 걸렸다.
|
|
describe('markdown table is never classified as reasoning', () => {
|
|
const TABLE = `전체 146건의 검색 결과 중 벌크필 관련 논문 3건을 추출하여 정리해 드립니다.
|
|
|
|
| 번호 | PMID | 저널 | 연도 | 제목 |
|
|
| :--- | :--- | :--- | :--- | :--- |
|
|
| 1 | 28443833 | J Adhes Dent | 2017 | Bulk-Fill Composites: A Review of the Current Literature. |
|
|
| 2 | 32030379 | J Adhes Dent | 2020 | Structural/Chemical Characterization and Bond Strength of a New Self-Adhesive Bulk-fill Restorative. |
|
|
| 3 | 29178706 | Am J Dent | 2017 | Stress distribution of bulk-fill resin composite in class II restorations. |`;
|
|
|
|
test('표 전체가 답변으로 남는다', () => {
|
|
const r = separateThinkingFromContent(TABLE, { model: 'gemma4:31b-cloud' });
|
|
assert.equal(r.thinking, '');
|
|
assert.equal(r.reply, TABLE);
|
|
});
|
|
|
|
test('표 뒤에 짧은 맺음말이 있어도 표를 지우지 않는다', () => {
|
|
const r = separateThinkingFromContent(TABLE + '\n\nDone!', { model: 'gemma4:31b-cloud' });
|
|
assert.ok(r.reply.includes('| 3 | 29178706 |'));
|
|
assert.ok(r.reply.includes('A Review of the Current Literature'));
|
|
});
|
|
|
|
test('실제 추론 문단은 여전히 분리된다', () => {
|
|
const t = 'The user wants a list. Let me check the tools first.\n\n핵심만 말씀드리면 3편입니다. 첫 번째 논문이 가장 최신입니다.';
|
|
const r = separateThinkingFromContent(t, { model: 'gemma4:31b-cloud' });
|
|
assert.ok(r.thinking.includes('The user wants'));
|
|
assert.ok(r.reply.startsWith('핵심만'));
|
|
});
|
|
});
|