// src/main/services/OnlineLLMService.ts // C# .NET Backend API Server 연결 서비스. // 온라인 모드 사용 시 필수 인증(JWT Bearer)을 통해 서버로 AI 요청 전달. import { EventEmitter } from 'events' import { configGet, configSet } from './ConfigService' import { normalizeLoopbackUrl } from '../utils/loopback' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import type { LLMAction } from '@d3ro/core/types' import { redactPII, redactPIIMessages, rehydrateText } from '@d3ro/core/utils/pii-redactor' import { resolveSystemPrompt } from './llm-prompts' interface OnlineGenerateResponse { text: string model: string promptTokens: number completionTokens: number totalDurationMs: number cost: number } class OnlineLLMService extends EventEmitter { private _abortController: AbortController | null = null private _disposed = false isAvailable(): boolean { const token = configGet('authToken') return Boolean(token && token.length > 0) } private _ensureAuth(): string { if (this._disposed) { throw new D3ROError(ErrorCode.LLMProcessingFailed, 'OnlineLLMService disposed') } const token = configGet('authToken') if (!token || token.length === 0) { throw new D3ROError( ErrorCode.LLMServerUnreachable, '온라인 모드를 이용하기 위해서는 로그인이 꼭 필요합니다.' ) } return token } private async _postOnlineRequest( endpoint: string, payload: Record, externalSignal?: AbortSignal ): Promise { const token = this._ensureAuth() const apiUrl = normalizeLoopbackUrl(configGet('onlineApiUrl') ?? 'http://127.0.0.1:5000') // cancelGeneration() 이 실제로 이 요청을 끊도록 컨트롤러를 등록한다(예전엔 한 번도 할당되지 않아 no-op). this._abortController?.abort() const controller = new AbortController() this._abortController = controller const onExternalAbort = (): void => { controller.abort() } if (externalSignal) { if (externalSignal.aborted) { controller.abort() } else { externalSignal.addEventListener('abort', onExternalAbort, { once: true }) } } try { const response = await fetch(`${apiUrl}${endpoint}`, { signal: controller.signal, method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, body: JSON.stringify(payload) }) if (response.status === 401) { configSet('authToken', null) throw new D3ROError( ErrorCode.LLMServerUnreachable, '인증 토큰이 만료되었습니다. 다시 로그인해주세요.' ) } if (!response.ok) { throw new D3ROError( ErrorCode.LLMProcessingFailed, `API Server responded with status ${response.status}` ) } const data = (await response.json()) as Partial | null if (typeof data?.text !== 'string' || data.text.trim().length === 0) { throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Online LLM returned empty text') } return data.text } catch (err) { if (err instanceof D3ROError) throw err if (controller.signal.aborted) { throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'Online LLM request cancelled') } throw new D3ROError( ErrorCode.LLMProcessingFailed, `온라인 API 서버 연결 실패: ${err instanceof Error ? err.message : String(err)}` ) } finally { externalSignal?.removeEventListener('abort', onExternalAbort) if (this._abortController === controller) this._abortController = null } } async processText( text: string, action: LLMAction, targetLanguage?: string, customPrompt?: string ): Promise { this._ensureAuth() const systemPrompt = resolveSystemPrompt(action, targetLanguage, customPrompt) const redaction = redactPII(text, 'tokenize') const rawText = await this._postOnlineRequest('/api/llm/generate', { prompt: redaction.redactedText, systemPrompt, model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini', temperature: 0.7, maxTokens: 2048 }) return rehydrateText(rawText.trim(), redaction.tokens) } async *chatStream( messages: Array<{ role: string; content: string }>, options?: { model?: string; temperature?: number; signal?: AbortSignal } ): AsyncGenerator { this._ensureAuth() const redactedBatch = redactPIIMessages(messages) const rawText = await this._postOnlineRequest( '/api/llm/chat', { messages: redactedBatch.messages.map((m) => ({ role: m.role, content: m.content })), model: options?.model ?? configGet('llmModelId') ?? 'd3ro-gpt4o-mini', temperature: options?.temperature ?? 0.7 }, options?.signal ) const restored = rehydrateText(rawText, redactedBatch.tokens) yield restored return restored } cancelGeneration(): void { if (this._abortController) { this._abortController.abort() this._abortController = null } } dispose(): void { this._disposed = true this.cancelGeneration() this.removeAllListeners() } } let instance: OnlineLLMService | null = null export function resetOnlineLLMServiceForTests(): void { if (instance) instance.dispose() instance = null } export function getOnlineLLMService(): OnlineLLMService { if (!instance) { instance = new OnlineLLMService() } return instance }