Next-sentence suggestions now arrive one at a time up to twelve, shown three per page with Ctrl+Alt+Up/Down to move, Left/Right to page, Enter to accept and Esc to close; old default bindings migrate and the panel guide follows the live bindings. The overlay is redesigned, stays put while candidates stream and sits outside the input box when no caret is reported. The personal phrase memory stops learning from terminals, code editors and the coding-agent hub, ignores symbol-heavy lines and empty-field placeholders, and prunes existing entries that break those rules. Fixes suggestion keys starting dictation, installs stuck on a pre-1.5.0 speech engine without the focus endpoint, Ollama runner windows flashing while typing, the speech engine starting twice, and cold-model timeouts. Live captions can be dragged to a remembered position and show a waiting notice until the first line arrives. Bumps the product version to 1.6.0 (Android/iOS build 1060000).
255 lines
10 KiB
TypeScript
255 lines
10 KiB
TypeScript
// src/main/services/llm-prompts.ts
|
|
// LLM 시스템 프롬프트 SSOT — PremiumLLMService 공용.
|
|
|
|
import { getLogger } from './LoggerService'
|
|
import type { LLMAction } from '@d3ro/core/types'
|
|
|
|
const logger = getLogger('llm-prompts')
|
|
|
|
/**
|
|
* 기본 시스템 프롬프트 (NO_THINK prefix 없음).
|
|
* PremiumLLMService는 NO_THINK prefix 없이 바로 사용.
|
|
*/
|
|
const BASE_SYSTEM_PROMPTS: Record<string, string> = {
|
|
refine: `다음 음성 전사 텍스트를 자연스럽고 격식 있는 문어체로 다듬어주세요.
|
|
원래 의미를 유지하면서 문법 오류를 수정하고, 불필요한 반복이나 필러를 제거하세요.
|
|
다듬어진 텍스트만 출력하세요. 설명이나 부가 문구를 붙이지 마세요.`,
|
|
|
|
translate: `다음 텍스트를 {{targetLanguage}}로 번역해주세요.
|
|
자연스럽고 정확한 번역만 출력하세요. 원문이나 설명을 붙이지 마세요.`,
|
|
|
|
summarize: `다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.
|
|
요약문만 출력하세요.`,
|
|
|
|
grammar: `다음 텍스트의 문법 오류만 수정해주세요.
|
|
원래 의미와 톤을 유지하면서 문법 오류만 수정하세요.
|
|
수정된 텍스트만 출력하세요.`,
|
|
|
|
expand: `다음 텍스트를 더 자세하고 풍부하게 확장해주세요.
|
|
확장된 텍스트만 출력하세요.`,
|
|
}
|
|
|
|
/**
|
|
* 번역 대상 언어 기본값.
|
|
* `AppConfig`에는 번역 대상 언어 키가 없다 (`language`는 UI 로케일,
|
|
* `sttLanguage`는 입력 언어라 둘 다 대상 언어가 아니다).
|
|
*/
|
|
export const DEFAULT_TARGET_LANGUAGE = 'English'
|
|
|
|
/**
|
|
* 번역 대상 언어를 해석한다. LLM을 호출하는 모든 경로가 이 함수를 쓴다.
|
|
*
|
|
* `AppConfig`에는 번역 대상 언어 키가 없다 — `language`는 UI 로케일이고
|
|
* `sttLanguage`는 입력(원문) 언어라 어느 쪽도 대상 언어로 쓸 수 없다.
|
|
* (입력 언어로 번역하면 원문 그대로가 되고, UI 로케일은 `'ko'` 같은 코드라
|
|
* 프롬프트에 그대로 넣으면 문장이 깨진다.)
|
|
*
|
|
* 따라서 현재는 {@link DEFAULT_TARGET_LANGUAGE} 고정이다. 사용자가 대상 언어를
|
|
* 고를 수 있으려면 설정 키가 필요하다.
|
|
*/
|
|
export function resolveTargetLanguage(): string {
|
|
return DEFAULT_TARGET_LANGUAGE
|
|
}
|
|
|
|
/**
|
|
* `action: 'custom'`인데 시스템 프롬프트가 주어지지 않았을 때 쓰는 액션.
|
|
* 지시문이 `{{text}}`로 사용자 텍스트 위치를 직접 지정한 하위 호환 경로에서 발생한다.
|
|
*/
|
|
const CUSTOM_FALLBACK_ACTION = 'refine'
|
|
|
|
/** 지시문이 사용자 텍스트 위치를 직접 지정할 때 쓰는 플레이스홀더. */
|
|
const TEXT_PLACEHOLDER = /\{\{text\}\}/g
|
|
|
|
/** 치환 후에도 남아 있는 플레이스홀더 탐지용. */
|
|
const ANY_PLACEHOLDER = /\{\{([^{}]+)\}\}/g
|
|
|
|
export interface InstructionVars {
|
|
/** 사용자 음성 텍스트 (스크린 컨텍스트 프리픽스 포함). */
|
|
text: string
|
|
/** 번역 대상 언어. 생략 시 {@link DEFAULT_TARGET_LANGUAGE}. */
|
|
targetLanguage?: string
|
|
}
|
|
|
|
/**
|
|
* 사용자 정의 지시문의 플레이스홀더를 치환한다.
|
|
* 치환되지 않고 남은 `{{...}}`는 그대로 두되 경고를 남긴다 —
|
|
* 조용히 새어나간 플레이스홀더가 LLM에 그대로 전달되는 사고가 있었다.
|
|
*/
|
|
export function renderInstructionPrompt(prompt: string, vars: InstructionVars): string {
|
|
const rendered = prompt
|
|
.replace(TEXT_PLACEHOLDER, vars.text)
|
|
.replace(/\{\{userPrompt\}\}/g, vars.text)
|
|
.replace(/\{\{targetLanguage\}\}/g, vars.targetLanguage ?? DEFAULT_TARGET_LANGUAGE)
|
|
|
|
const leftovers = [...rendered.matchAll(ANY_PLACEHOLDER)].map((m) => m[1])
|
|
if (leftovers.length > 0) {
|
|
logger.warn(
|
|
`Unresolved instruction placeholders passed to the LLM: ${[...new Set(leftovers)].join(', ')}`,
|
|
)
|
|
}
|
|
|
|
return rendered
|
|
}
|
|
|
|
/**
|
|
* 지시문과 사용자 텍스트로 `processText(text, action, targetLanguage, customPrompt)` 인자를 만든다.
|
|
*
|
|
* - 기본: 지시문은 **시스템 프롬프트**, 사용자 텍스트는 **처리 대상 텍스트**.
|
|
* - 하위 호환: 지시문에 `{{text}}`가 있으면 사용자가 텍스트 위치를 직접 지정한 것이므로
|
|
* 치환된 지시문을 처리 대상 텍스트로 넘기고 시스템 프롬프트는 비워 기본 동작을 따른다.
|
|
*/
|
|
export function buildInstructionInvocation(
|
|
instructionPrompt: string,
|
|
userText: string,
|
|
targetLanguage?: string,
|
|
): { text: string; systemPrompt?: string } {
|
|
const rendered = renderInstructionPrompt(instructionPrompt, { text: userText, targetLanguage })
|
|
|
|
if (instructionPrompt.includes('{{text}}')) {
|
|
return { text: rendered }
|
|
}
|
|
return { text: userText, systemPrompt: rendered }
|
|
}
|
|
|
|
/**
|
|
* 액션 + 옵션으로 시스템 프롬프트를 해석한다.
|
|
* translate 액션은 targetLanguage 치환, custom 액션은 customPrompt 사용.
|
|
*/
|
|
export function resolveSystemPrompt(
|
|
action: LLMAction,
|
|
targetLanguage?: string,
|
|
customPrompt?: string,
|
|
): string {
|
|
if (action === 'custom') {
|
|
if (customPrompt && customPrompt.trim().length > 0) {
|
|
return customPrompt
|
|
}
|
|
// BASE_SYSTEM_PROMPTS에 'custom' 키가 없어 조용히 refine으로 떨어지던 자리.
|
|
// 하위 호환({{text}}) 경로에서는 정상이지만, 지시문을 시스템 프롬프트로
|
|
// 넘기지 못한 버그도 같은 모양이라 반드시 드러나야 한다.
|
|
logger.warn(
|
|
`resolveSystemPrompt: action 'custom' without a custom prompt — ` +
|
|
`falling back to the '${CUSTOM_FALLBACK_ACTION}' system prompt`,
|
|
)
|
|
return BASE_SYSTEM_PROMPTS[CUSTOM_FALLBACK_ACTION]
|
|
}
|
|
if (action === 'translate') {
|
|
return BASE_SYSTEM_PROMPTS.translate.replace(
|
|
'{{targetLanguage}}',
|
|
targetLanguage ?? DEFAULT_TARGET_LANGUAGE,
|
|
)
|
|
}
|
|
return BASE_SYSTEM_PROMPTS[action] ?? BASE_SYSTEM_PROMPTS[CUSTOM_FALLBACK_ACTION]
|
|
}
|
|
|
|
export { BASE_SYSTEM_PROMPTS }
|
|
|
|
// ============================================================
|
|
// 다음 문장 제안 (ghost text) — 프롬프트 정본
|
|
// ============================================================
|
|
|
|
/**
|
|
* 추론 모델이 `thinking` 블록을 지 않게 하는 prefix.
|
|
*
|
|
* `LocalLLMService.processText` 가 같은 목적으로 쓰는 값과 같다. 제안 경로는
|
|
* `streamGenerate` 를 직접 부르므로 여기서 직접 붙인다.
|
|
*/
|
|
export const SUGGESTION_NO_THINK_PREFIX = '/no_think'
|
|
|
|
/**
|
|
* 제안 시스템 프롬프트.
|
|
*
|
|
* 지시문은 **시스템 프롬프트에만** 둔다. 지시문이 처리 대상 텍스트 자리에 들어가
|
|
* 지시문 자체를 다듬어 돌려주던 회귀(밋 9c2b4d4)와 같은 부류의 사고를 막는다.
|
|
*/
|
|
const SUGGESTION_SYSTEM_PROMPT = `사용자가 지금 입력창에 글을 쓰는 중입니다. 사용자가 마지막으로 쓴 글 뒤에 이어질 다음 문장을 제안하세요.
|
|
|
|
규칙:
|
|
- 당신은 사용자와 대화하는 비서가 아닙니다. 사용자 본인이 다음에 직접 칠 문장만, 사용자 자신의 목소리로 쓰세요.
|
|
- 사용자에게 질문하지 말고, 도와주겠다고 제안하지 말고, 사용자를 부르듯 말하지 마세요. ("궁금한 점이 있으신가요?", "도와드릴까요?" 같은 응답 금지)
|
|
- 입력이 검색어나 폼 입력처럼 보이면(문장이 아니라 키워드 나열 등), 같은 종류의 텍스트로 짧게 이어 쓰세요.
|
|
- 사용자가 언어와 같은 언어로 쓰세요.
|
|
- 사용자의 말투와 문체를 유지하세요. 존댓말/반말, 격식/비격식을 바꾸지 마세요.
|
|
- 이미 나온 단어를 되풀이하지 말고 이어지는 내용만 쓰세요.
|
|
- 후보를 한 줄에 하나씩, 번호나 따옴표, 설명 없이 출력하세요.
|
|
- 각 후보는 한 문장, 최대 {{maxChars}}자입니다.
|
|
- 확신이 없으면 짧게 쓰세요. 리말, 요약, 빈 줄을 출력하지 마세요.`
|
|
|
|
export interface SuggestionPromptInput {
|
|
/** 어렛 앞까지의 텍스트 */
|
|
prefix: string
|
|
/** 활성 앱/창 (맥락 트) */
|
|
appName?: string | null
|
|
windowTitle?: string | null
|
|
/** 사용자가 자주 쓰는 표현 (개인화 힌트) */
|
|
phraseHints?: readonly string[]
|
|
/**
|
|
* 과거에 같은 꼬리 뒤에 실제로 이어 쓴 문장 (개인 기억).
|
|
*
|
|
* 자주 쓰는 표현보다 훨씬 강한 문맥 신호다 — 사용자 자신의 실제 이어쓰기다.
|
|
*/
|
|
continuationHints?: readonly string[]
|
|
/**
|
|
* 이미 이 세션에서 제안한 문장들 — 채우기 루프가 중복을 피하려고 넘긴다.
|
|
* 지시문이 아니라 데이터 섹션으로만 들어간다(기존 continuationHints 와 같은 방식).
|
|
*/
|
|
avoidCandidates?: readonly string[]
|
|
/** 후보 개수 */
|
|
candidates?: number
|
|
/** 후보당 최대 길이 */
|
|
maxChars?: number
|
|
}
|
|
|
|
/**
|
|
* 제안 요청용 (systemPrompt, text) 를 만든다.
|
|
*
|
|
* 시스템 프롬프트에 지시문, 사용자 메시지에는 **지금까지 쓴 텍스트와 맥락**만 는다.
|
|
*/
|
|
export function buildSuggestionPrompt(input: SuggestionPromptInput): {
|
|
systemPrompt: string
|
|
text: string
|
|
} {
|
|
const candidates = Math.max(1, Math.min(input.candidates ?? 3, 5))
|
|
const maxChars = Math.max(20, Math.min(input.maxChars ?? 160, 400))
|
|
|
|
const sections: string[] = ['[지금까지 텍스트]', input.prefix]
|
|
|
|
if (input.phraseHints && input.phraseHints.length > 0) {
|
|
sections.push('', '[자주 쓰는 표현]')
|
|
for (const hint of input.phraseHints.slice(0, 5)) {
|
|
sections.push(`- ${hint}`)
|
|
}
|
|
}
|
|
|
|
if (input.appName || input.windowTitle) {
|
|
sections.push('', '[현재 앱]')
|
|
const app = [input.appName, input.windowTitle].filter(Boolean).join(' — ')
|
|
sections.push(app)
|
|
}
|
|
|
|
if (input.continuationHints && input.continuationHints.length > 0) {
|
|
sections.push('', '[과거에 사용자가 비슷한 문장 뒤에 실제로 이어 쓴 내용]')
|
|
for (const hint of input.continuationHints.slice(0, 3)) {
|
|
sections.push(`- ${hint}`)
|
|
}
|
|
sections.push('위 내용은 문체와 맥락 참고용입니다. 그대로 복사하지 말고 이어질 문장을 새로 쓰세요.')
|
|
}
|
|
|
|
if (input.avoidCandidates && input.avoidCandidates.length > 0) {
|
|
sections.push('', '[이미 제안한 문장 — 아래와 겹치지 않는 다른 문장을 쓰세요]')
|
|
for (const avoid of input.avoidCandidates.slice(0, 12)) {
|
|
sections.push(`- ${avoid}`)
|
|
}
|
|
}
|
|
|
|
sections.push('', `이어질 다음 문장 ${candidates}개를 한 줄씩 출력하세요.`)
|
|
|
|
const systemPrompt = `${SUGGESTION_NO_THINK_PREFIX}\n${SUGGESTION_SYSTEM_PROMPT.replace(
|
|
'{{maxChars}}',
|
|
String(maxChars)
|
|
)}`
|
|
|
|
return { systemPrompt, text: sections.join('\n') }
|
|
}
|
|
|
|
export { SUGGESTION_SYSTEM_PROMPT }
|