d3ro-voice/packages/core/src/suggestion-confidence.ts

72 lines
3.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// packages/core/src/suggestion-confidence.ts
//
// 모델 제안을 토큰 로그 확률로 거르고 자른다 (Gmail Smart Compose 의 신뢰도 게이팅과 같은 생각).
//
// 재생 평가(2026-10-24, gemma4:e4b, 120건): 그대로 보여 주면 첫 어절 적중이 3% 였다. 첫 어절 확률이
// 낮은 후보를 숨기고, 확률이 꺾이는 토큰에서 자르면 노출은 4~6% 로 줄지만 적중은 20~29% 로 오른다.
// 틀린 제안은 맞는 제안보다 읽는 비용이 5배 이상 크다(arXiv 2403.15502) — 덜 보여 주는 편이 낫다.
export interface TokenLogprob {
token: string
logprob: number
}
export interface ConfidenceSettings {
/** 첫 어절을 이루는 토큰 로그 확률 합의 하한 — 못 넘으면 후보를 버린다 */
firstWordMin: number
/** 토큰 하나의 로그 확률 하한 — 처음 못 넘는 토큰 앞에서 자른다 */
tokenMin: number
}
// 첫 어절 −0.5 로 시작했다가 실사용(2026-10-25)에서 거의 안 떠 −1.0 으로 풀었다(시뮬레이션: 노출 ~15%, 적중 ~11%).
export const SUGGESTION_CONFIDENCE: ConfidenceSettings = { firstWordMin: -1.0, tokenMin: -1.0 }
/**
* 후보가 화면·앞 글에 이미 있는 글을 그대로 베꼈는가.
* 베낀 글은 모델이 높은 확률을 주므로 확신 검사로 걸러지지 않는다(실측 2026-10-25: 앞 대화의 문장이 그대로 제안됨).
* 후보 앞 12자(짧으면 전체, 8자 이상일 때만)가 문맥에 그대로 있으면 베낀 것으로 본다.
*/
export function copiesContext(candidate: string, context: string): boolean {
const squash = (text: string) => text.replace(/\s+/gu, ' ').trim()
const text = squash(candidate)
if (text.length < 8) return false
return squash(context).includes(text.slice(0, 12))
}
export interface ConfidenceCut {
/** 원문(토큰을 이은 글)에서 남길 글자 수 */
keepChars: number
firstWordLogprob: number
}
const SENTENCE_END = /[.!?。!?…\n]/u
/**
* 남길 길이를 정한다. 첫 어절이 자신 없거나 남는 글이 없으면 null.
* 어절 중간에서 끊기면 그 어절은 통째로 뺀다 — 반쪽 단어를 제안하지 않는다.
*/
export function cutByConfidence(
tokens: TokenLogprob[],
settings: ConfidenceSettings = SUGGESTION_CONFIDENCE
): ConfidenceCut | null {
let text = ''
let firstWordLogprob = 0
let firstWordDone = false
for (const { token, logprob } of tokens) {
const startsWord = /^\s/u.test(token)
if (text.trim().length > 0 && startsWord) firstWordDone = true
if (logprob < settings.tokenMin) {
if (!startsWord && !/\s$/u.test(text)) {
// 어절 중간에서 멈췄다 — 그 어절을 뺀다(첫 어절이었다면 남는 게 없다).
const lastSpace = text.trimEnd().search(/\s\S*$/u)
text = lastSpace >= 0 ? text.slice(0, lastSpace) : ''
}
break
}
text += token
if (!firstWordDone && text.trim().length > 0) firstWordLogprob += logprob
if (SENTENCE_END.test(token)) break
}
if (text.trim().length === 0 || firstWordLogprob < settings.firstWordMin) return null
return { keepChars: text.length, firstWordLogprob }
}