d3ro-voice/packages/core/src/chat-template.ts
Yun Chan 3cac14f668
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled
feat(desktop): typo auto-correct and context-aware sentence prediction
Typo auto-correct (INPUT-19)
- TypoCorrectionService + core typo-correction: 2-set Korean layout
  mistypes both ways, always-wrong spellings, near-misses of the user's
  frequent words, optional model check re-validated in core; applied by
  backspace N + paste and cancelled on new keys or window change.

Prediction quality (INPUT-20/21)
- gemma models are sent raw with the user's unfinished sentence pre-filled
  into the model turn, so the model truly continues the text (mid-word
  joins and spacing exact). Other models keep the instruction prompt.
- Context: text before the caret (opening lines and a fact list of names,
  dates, amounts outside the 400-char window), messages just sent in the
  same chat window (memory only, 30 min), personal-graph follow-ups and
  IDF-ranked related sentences with Korean stemming.
- Guards: first sentence only, restated-prefix stripping (also fixes the
  instruction path), repeat drop, no invented dates/names/numbers
  (one retry), plain -다 register, no emoji unless the user uses them,
  search-box keywords. Fill loop mixes instruction prompts for variety.
- Opt-in real-model probe: tests/integration/suggestion-quality.ollama.test.ts

Suggestions now actually show up
- Terminal (Claude Code): caret trust from the input line, not the whole
  screen (status line below the box blocked every keystroke); Korean
  composition counts as typing at the end; a grey placeholder filling the
  empty box at once is not user text.
- Chrome: UIA focus flicker while typing no longer resets "edited".
- KakaoTalk/RichEdit: trailing paragraph mark ignored for edit position
  and stripped so accepted text keeps its separating space.
- While the overlay is visible the suggestion shortcuts are captured so
  Ctrl+Alt+Enter no longer also types a newline; released when hidden.
- nut-js preloaded after boot (first accept waited 4.8 s).
2026-10-03 21:48:28 +09:00

52 lines
2.6 KiB
TypeScript

// packages/core — 원형(raw) 채팅 템플릿.
//
// 왜 필요한가: 인라인 제안은 "사용자 글을 그대로 이어 쓰기" 다. 모델 차례 앞에 사용자가 쓰던
// 문장을 미리 넣어 두면(prefill) 모델은 그 글자 바로 뒤부터 쓴다 — 단어 중간("회의실"+"에서")과
// 띄어쓰기까지 정확히 이어진다. Ollama 의 채팅 API 는 이어 쓸 때 응답 앞 공백을 지우고 일부
// 렌더러는 차례를 닫아 버려(실측: "검토해 보시" → "부탁드립니다.") 이 용도로 쓸 수 없다.
// 그래서 템플릿을 아는 모델 계열만 직접 그려 `raw` 로 보낸다. 모르는 계열은 null — 호출자는
// 기존(지시형) 경로를 쓴다.
export type RawChatFamily = 'gemma4' | 'gemma'
export interface RawChatInput {
system: string
user: string
/** 모델 차례 앞에 미리 넣을 텍스트 (모델이 이어 쓴다) */
assistantPrefix: string
}
/** 모델 이름(Ollama 태그)으로 원형 템플릿 계열을 판별한다. */
export function detectRawChatFamily(model: string): RawChatFamily | null {
const name = model.trim().toLowerCase().split('/').pop() ?? ''
if (/^gemma-?4/u.test(name)) return 'gemma4'
if (/^gemma-?[23]?(?:[:.-]|$)/u.test(name)) return 'gemma'
return null
}
/** 사용자 텍스트에 섞인 차례 구분 토큰을 지운다 — 문맥 텍스트가 대화 구조를 바꾸지 못하게. */
function stripTurnMarkers(text: string): string {
return text.replace(/<\|?\/?(?:turn|start_of_turn|end_of_turn|bos|eos)\|?>|<(?:turn|end_of_turn)\|>/gu, '')
}
/** 원형 프롬프트를 그린다. 템플릿을 모르는 모델이면 null. */
export function renderRawChatPrompt(model: string, input: RawChatInput): string | null {
const family = detectRawChatFamily(model)
if (!family) return null
const system = stripTurnMarkers(input.system)
const user = stripTurnMarkers(input.user)
const prefix = stripTurnMarkers(input.assistantPrefix)
if (family === 'gemma4') {
return `<|turn>system\n${system}<turn|>\n<|turn>user\n${user}<turn|>\n<|turn>model\n${prefix}`
}
// gemma 2/3 에는 system 차례가 없다 — 첫 user 차례 앞에 붙인다(공식 템플릿과 같음).
return `<start_of_turn>user\n${system}\n\n${user}<end_of_turn>\n<start_of_turn>model\n${prefix}`
}
/** 원형 요청의 정지 문자열 — 차례 종료 토큰이 텍스트로 새어 나와도 거기서 멈춘다. */
export function rawChatStopSequences(model: string): string[] {
const family = detectRawChatFamily(model)
if (family === 'gemma4') return ['<turn|>', '<|turn>']
if (family === 'gemma') return ['<end_of_turn>', '<start_of_turn>']
return []
}