'use client' // apps/admin/src/app/(admin)/models/page.tsx // D3RO Voice — Dynamic AI Models & Cloud STT Transcription Provider Manager (Midnight Glass v2) import React, { useState, useEffect, useRef } from 'react' import { Box, Typography, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, MenuItem, Select, FormControl, InputLabel, Tabs, Tab, Alert, CircularProgress, } from '@mui/material' import { C, FONT_SANS, FONT_MONO, panelSx, tableSx, statusBadgeSx, primaryButtonSx } from '@/lib/console-theme' import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds' import type { ModelEndpoint, SttProviderEndpoint, STTProviderCategory, } from '@/lib/api-server' import { createModelEndpointClient, createSttEndpointClient, deleteModelEndpointClient, deleteSttEndpointClient, fetchModelEndpointsClient, fetchSttEndpointsClient, setDefaultSttEndpointClient, testSttEndpointClient, updateSttEndpointClient, } from '@/lib/backend-admin-client' const PRESET_LLM_MODELS = [ { modelId: 'whisper-large-v3-turbo', modelName: 'Faster-Whisper Large-v3 Turbo (Local)', provider: 'Local Sidecar', endpointUrl: 'http://localhost:8971/stt/transcribe', promptCost: '0.000000', completionCost: '0.000000' }, { modelId: 'ollama-gemma4-e4b', modelName: 'Ollama Gemma-4 E4B (Bundled Local)', provider: 'Ollama Local', endpointUrl: 'http://localhost:11434/api/generate', promptCost: '0.000000', completionCost: '0.000000' }, { modelId: 'gpt-realtime-2.1', modelName: 'OpenAI GPT-Realtime 2.1 (Live Voice)', provider: 'OpenAI', endpointUrl: 'wss://api.openai.com/v1/realtime', promptCost: '0.005000', completionCost: '0.020000' }, { modelId: 'gpt-4o-mini', modelName: 'GPT-4o Mini (Cloud Synthesis & Meeting)', provider: 'OpenAI', endpointUrl: 'https://api.openai.com/v1/chat/completions', promptCost: '0.000150', completionCost: '0.000600' }, { modelId: 'claude-3-5-sonnet', modelName: 'Claude 3.5 Sonnet (Action Planner)', provider: 'Anthropic', endpointUrl: 'https://api.anthropic.com/v1/messages', promptCost: '0.003000', completionCost: '0.015000' }, ] const PRESET_STT_PROVIDERS: Array<{ name: string providerType: STTProviderCategory endpointUrl: string modelId: string method: 'multipart' | 'binary-stream' | 'json-base64' | 'custom-rest' costPerMinute: number language: string prompt?: string description: string }> = [ { name: 'Groq Whisper LPU Turbo (Ultra Fast)', providerType: 'groq', endpointUrl: 'https://api.groq.com/openai/v1/audio/transcriptions', modelId: 'whisper-large-v3-turbo', method: 'multipart', costPerMinute: 0.0005, language: 'ko', description: 'LPU 가속 기반 초저지연(~140ms) 고속 전사, 극저비용' }, { name: 'OpenAI Whisper Official', providerType: 'openai', endpointUrl: 'https://api.openai.com/v1/audio/transcriptions', modelId: 'whisper-1', method: 'multipart', costPerMinute: 0.006, language: 'ko', description: 'OpenAI 공식 Whisper-1 모델, 표준 고품질 다국어 인식' }, { name: 'Deepgram Nova-3 Industry Standard', providerType: 'deepgram', endpointUrl: 'https://api.deepgram.com/v1/listen', modelId: 'nova-3', method: 'binary-stream', costPerMinute: 0.0043, language: 'ko', description: 'Nova-3 스마트 구두점, 실시간 스트리밍 최적화 및 고정밀 전사' }, { name: 'Google Gemini 2.0 Flash / Cloud STT', providerType: 'google', endpointUrl: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent', modelId: 'gemini-2.0-flash', method: 'json-base64', costPerMinute: 0.001, language: 'ko', description: 'Gemini 2.0 Flash 기반 다국어 및 문맥 인식 오디오 전사' }, { name: 'AssemblyAI Universal-2', providerType: 'assemblyai', endpointUrl: 'https://api.assemblyai.com/v2/transcript', modelId: 'best', method: 'multipart', costPerMinute: 0.0025, language: 'ko', description: '문맥 인식 음향 모델 및 자동 단락 구분 STT' }, { name: 'Microsoft Azure Speech Service', providerType: 'azure', endpointUrl: 'https://koreacentral.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1', modelId: 'azure-speech', method: 'binary-stream', costPerMinute: 0.005, language: 'ko-KR', description: 'Azure Cognitive Speech API 엔터프라이즈 음성 인식' }, { name: 'Self-Hosted / Local Faster-Whisper Sidecar', providerType: 'local-sidecar', endpointUrl: 'http://localhost:8971/stt/transcribe', modelId: 'whisper-large-v3-turbo', method: 'multipart', costPerMinute: 0.0, language: 'ko', description: '사내 프라이빗 서버 또는 로컬 Whisper 사이드카 (완전 무료/오프라인)' }, ] export default function ServiceModelsPage(): React.ReactElement { const [activeTab, setActiveTab] = useState<'stt' | 'llm'>('stt') // STT Endpoints State const [sttEndpoints, setSttEndpoints] = useState([]) const [sttModalOpen, setSttModalOpen] = useState(false) const [sttEditingId, setSttEditingId] = useState(null) const [sttLoading, setSttLoading] = useState(false) const [sttPingStatus, setSttPingStatus] = useState>({}) const [sttTestModalResult, setSttTestModalResult] = useState<{ success: boolean; message: string; ms: number } | null>(null) const [testingInModal, setTestingInModal] = useState(false) // STT Form State const [sttName, setSttName] = useState('') const [sttProviderType, setSttProviderType] = useState('custom') const [sttEndpointUrl, setSttEndpointUrl] = useState('') const [sttApiKey, setSttApiKey] = useState('') const [sttModelId, setSttModelId] = useState('') const [sttMethod, setSttMethod] = useState<'multipart' | 'binary-stream' | 'json-base64' | 'custom-rest'>('multipart') const [sttLanguage, setSttLanguage] = useState('ko') const [sttPrompt, setSttPrompt] = useState('') const [sttCostPerMinute, setSttCostPerMinute] = useState('0') const [sttFallbackPriority, setSttFallbackPriority] = useState(1) const [sttIsDefault, setSttIsDefault] = useState(false) const [sttMemo, setSttMemo] = useState('') // LLM Endpoints State const [llmEndpoints, setLlmEndpoints] = useState([]) const [llmModalOpen, setLlmModalOpen] = useState(false) const [llmLoading, setLlmLoading] = useState(false) const [dataError, setDataError] = useState(null) // LLM Form State const [llmModelId, setLlmModelId] = useState('') const [llmModelName, setLlmModelName] = useState('') const [llmProvider, setLlmProvider] = useState('Custom') const [llmEndpointUrl, setLlmEndpointUrl] = useState('') const [llmApiKey, setLlmApiKey] = useState('') const [llmPromptCost, setLlmPromptCost] = useState('0') const [llmCompletionCost, setLlmCompletionCost] = useState('0') const [llmMemo, setLlmMemo] = useState('') const mountedRef = useRef(true) const loadSeqRef = useRef(0) const loadData = async () => { const seq = ++loadSeqRef.current setDataError(null) try { const [sttData, llmData] = await Promise.all([fetchSttEndpointsClient(), fetchModelEndpointsClient()]) if (!mountedRef.current || loadSeqRef.current !== seq) return setSttEndpoints(sttData) setLlmEndpoints(llmData) } catch (error) { if (!mountedRef.current || loadSeqRef.current !== seq) return setDataError(error instanceof Error ? error.message : '관리자 백엔드에서 엔드포인트를 불러오지 못했습니다.') } } useEffect(() => { mountedRef.current = true void loadData() return () => { mountedRef.current = false } }, []) // ── STT Handlers ────────────────────────────────────────────────────────── const openAddSttModal = () => { setSttEditingId(null) setSttName('') setSttProviderType('custom') setSttEndpointUrl('') setSttApiKey('') setSttModelId('') setSttMethod('multipart') setSttLanguage('ko') setSttPrompt('') setSttCostPerMinute('0') setSttFallbackPriority(sttEndpoints.length + 1) setSttIsDefault(sttEndpoints.length === 0) setSttTestModalResult(null) setSttMemo('') setSttModalOpen(true) } const openEditSttModal = (ep: SttProviderEndpoint) => { setSttEditingId(ep.id) setSttName(ep.name) setSttProviderType(ep.providerType) setSttEndpointUrl(ep.endpointUrl) setSttApiKey('') setSttModelId(ep.modelId) setSttMethod(ep.method) setSttLanguage(ep.language) setSttPrompt(ep.prompt || '') setSttCostPerMinute(ep.costPerMinute.toFixed(6)) setSttFallbackPriority(ep.fallbackPriority) setSttIsDefault(ep.isDefault) setSttTestModalResult(null) setSttMemo('') setSttModalOpen(true) } const handleSaveSttEndpoint = async (e: React.FormEvent) => { e.preventDefault() const parsedCostPerMinute = parseFloat(sttCostPerMinute) if (!Number.isFinite(parsedCostPerMinute) || parsedCostPerMinute < 0) { alert('분당 비용은 0 이상의 유효한 숫자여야 합니다.') return } setSttLoading(true) try { const payload = { name: sttName, providerType: sttProviderType, endpointUrl: sttEndpointUrl, apiKey: sttApiKey ? sttApiKey : undefined, modelId: sttModelId, method: sttMethod, language: sttLanguage, prompt: sttPrompt ? sttPrompt : undefined, temperature: 0.0, costPerMinute: parsedCostPerMinute, costPerSecond: parsedCostPerMinute / 60, isDefault: sttIsDefault, isActive: true, fallbackPriority: sttFallbackPriority, memo: sttMemo.trim(), } if (sttEditingId) { await updateSttEndpointClient(sttEditingId, payload) } else { await createSttEndpointClient(payload) } await loadData() if (mountedRef.current) setSttModalOpen(false) } catch (err) { if (mountedRef.current) { alert('Error saving STT endpoint: ' + (err instanceof Error ? err.message : String(err))) } } finally { if (mountedRef.current) setSttLoading(false) } } const handleSetDefaultStt = async (id: number) => { const memo = prompt('기본 STT 공급자 변경 사유를 입력하세요.')?.trim() ?? '' if (memo.length < 3) return try { await setDefaultSttEndpointClient(id, memo) if (!mountedRef.current) return setSttEndpoints((prev) => prev.map((ep) => ({ ...ep, isDefault: ep.id === id, })) ) } catch (err) { if (mountedRef.current) { alert('Error: ' + (err instanceof Error ? err.message : String(err))) } } } const handlePingStt = async (id: number) => { setSttPingStatus((prev) => ({ ...prev, [id]: 'Testing...' })) try { const result = await testSttEndpointClient(id) if (!mountedRef.current) return setSttPingStatus((prev) => ({ ...prev, [id]: result.success ? `⚡ OK • ${result.latencyMs}ms` : `❌ ${result.message}` })) } catch (error) { if (!mountedRef.current) return setSttPingStatus((prev) => ({ ...prev, [id]: `❌ ${error instanceof Error ? error.message : 'Test failed'}` })) } } const handleTestInModal = async () => { setTestingInModal(true) setSttTestModalResult(null) try { const result = await testSttEndpointClient(sttEditingId ?? 0, sttApiKey, sttEndpointUrl) if (!mountedRef.current) return setSttTestModalResult({ success: result.success, message: result.message, ms: result.latencyMs, }) } catch (err) { if (!mountedRef.current) return setSttTestModalResult({ success: false, message: err instanceof Error ? err.message : 'Test failed', ms: 0, }) } finally { if (mountedRef.current) setTestingInModal(false) } } const handleDeleteStt = async (id: number) => { if (!confirm('이 STT 프로바이더 엔드포인트를 삭제하시겠습니까?')) return const memo = prompt('삭제 사유를 입력하세요.')?.trim() ?? '' if (memo.length < 3) return try { await deleteSttEndpointClient(id, memo) if (mountedRef.current) { setSttEndpoints((prev) => prev.filter((ep) => ep.id !== id)) } } catch (err) { if (mountedRef.current) { alert('Error: ' + (err instanceof Error ? err.message : String(err))) } } } // ── LLM Handlers ────────────────────────────────────────────────────────── const openAddLlmModal = () => { setLlmModelId('') setLlmModelName('') setLlmProvider('Custom') setLlmEndpointUrl('') setLlmApiKey('') setLlmPromptCost('0') setLlmCompletionCost('0') setLlmMemo('') setLlmModalOpen(true) } const handleAddLlmEndpoint = async (e: React.FormEvent) => { e.preventDefault() const parsedPromptCost = parseFloat(llmPromptCost) const parsedCompletionCost = parseFloat(llmCompletionCost) if ( !Number.isFinite(parsedPromptCost) || parsedPromptCost < 0 || !Number.isFinite(parsedCompletionCost) || parsedCompletionCost < 0 ) { alert('토큰 비용은 0 이상의 유효한 숫자여야 합니다.') return } setLlmLoading(true) try { await createModelEndpointClient({ modelId: llmModelId, modelName: llmModelName, provider: llmProvider, endpointUrl: llmEndpointUrl, apiKey: llmApiKey, costPer1kPromptTokens: parsedPromptCost, costPer1kCompletionTokens: parsedCompletionCost, memo: llmMemo.trim(), }) await loadData() if (!mountedRef.current) return setLlmModalOpen(false) setLlmModelId('') setLlmModelName('') setLlmEndpointUrl('') setLlmApiKey('') setLlmMemo('') } catch (err) { if (mountedRef.current) { alert('Error: ' + (err instanceof Error ? err.message : String(err))) } } finally { if (mountedRef.current) setLlmLoading(false) } } const handleDeleteLlm = async (id: number) => { if (!confirm('이 LLM 엔드포인트를 삭제하시겠습니까?')) return const memo = prompt('삭제 사유를 입력하세요.')?.trim() ?? '' if (memo.length < 3) return try { await deleteModelEndpointClient(id, memo) if (mountedRef.current) { setLlmEndpoints((current) => current.filter((endpoint) => endpoint.id !== id)) } } catch (error) { if (mountedRef.current) { alert('Error: ' + (error instanceof Error ? error.message : String(error))) } } } const defaultStt = sttEndpoints.find((e) => e.isDefault) || sttEndpoints[0] return ( <> {/* Header Bar */} AI Engines & Cloud STT Orchestrator {sttEndpoints.length} STT • {llmEndpoints.length} LLM CONFIGURED Dynamic routing, auto failover, token and per-minute billing, instant default switch {activeTab === 'stt' ? ( ) : ( )} {dataError && ( {dataError} )} {/* Tabs Navigation */} setActiveTab(val)} sx={{ '& .MuiTabs-indicator': { backgroundColor: C.accentLight, height: '3px', borderRadius: '3px', }, }} > {/* ── TAB 1: STT Transcription Providers ── */} {activeTab === 'stt' && ( {/* Active Cloud STT Summary Card */} {defaultStt && ( ⚡ Active Default Cloud STT: {defaultStt.name} DEFAULT ACTIVE Model: {defaultStt.modelId} • Method: {defaultStt.method} • Rate: ${defaultStt.costPerMinute.toFixed(4)}/min • Lang: {defaultStt.language} 🛡️ Auto Failover Route: {sttEndpoints.map((e) => e.providerType).join(' ➔ ')} )} {/* STT Endpoints Table */} Configured Cloud Transcription Providers 클라우드 사용자는 별도 설정 없이 관리자가 지정한 기본 프로바이더로 즉시 전사 시스템을 사용합니다. PRIORITY ORDER BASED FALLBACK PRIORITY PROVIDER NAME PROVIDER TYPE MODEL ID METHOD COST ($/MIN) STATUS / DEFAULT ACTIONS {sttEndpoints.length === 0 ? ( NO STT PROVIDER ENDPOINTS CONFIGURED ) : ( sttEndpoints.map((ep) => ( #{ep.fallbackPriority} {ep.name} {ep.endpointUrl} {ep.providerType.toUpperCase()} {ep.modelId} {ep.method} ${ep.costPerMinute.toFixed(4)}/m {ep.isDefault ? ( ⭐ DEFAULT ) : ( {ep.isActive ? 'STANDBY' : 'DISABLED'} )} {!ep.isDefault && ( )} )) )} )} {/* ── TAB 2: LLM Models ── */} {activeTab === 'llm' && ( Active AI Reasoning & Action Endpoints AUTO FAILOVER: CLOUD → LOCAL OLLAMA MODEL ID MODEL NAME PROVIDER ENDPOINT URL PROMPT ($/1K) COMPLETION ($/1K) STATUS ACTIONS {llmEndpoints.length === 0 ? ( NO MODEL ENDPOINTS CONFIGURED ) : ( llmEndpoints.map((ep) => ( {ep.modelId} {ep.isDefault && ( DEFAULT )} {ep.modelName} {ep.provider} {ep.endpointUrl} ${ep.costPer1kPromptTokens.toFixed(6)} ${ep.costPer1kCompletionTokens.toFixed(6)} {ep.isActive ? 'ACTIVE' : 'DISABLED'} )) )} )} {/* ── STT Provider Add/Edit Modal ── */} setSttModalOpen(false)} maxWidth="md" fullWidth PaperProps={{ sx: { bgcolor: C.card, border: `1px solid ${C.borderHl}`, borderRadius: '20px', boxShadow: '0 24px 60px var(--d3-scrim)', }, }} > {sttEditingId ? 'Edit STT Provider Endpoint' : 'Add Cloud STT Provider Endpoint'} {sttEditingId === null && ( ⚡ Load Preset Template (optional) )} setSttName(e.target.value)} required fullWidth size="small" placeholder="e.g. Groq Whisper LPU Fast" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px' }, '& .MuiInputLabel-root': { color: C.dim }, }} /> Provider Type setSttEndpointUrl(e.target.value)} required fullWidth size="small" placeholder="https://api.groq.com/openai/v1/audio/transcriptions" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttApiKey(e.target.value)} fullWidth size="small" placeholder={sttEditingId ? '•••••••• (변경 시 입력)' : 'gsk_... or sk-... or token'} sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttModelId(e.target.value)} required fullWidth size="small" placeholder="e.g. whisper-large-v3-turbo, nova-3" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> Dispatch Method setSttLanguage(e.target.value)} required size="small" placeholder="ko, en, auto" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttCostPerMinute(e.target.value)} required size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttFallbackPriority(parseInt(e.target.value) || 1)} required size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttPrompt(e.target.value)} size="small" placeholder="e.g. D3RO, Kubernetes, React, LLM" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px' }, '& .MuiInputLabel-root': { color: C.dim }, }} /> setSttMemo(event.target.value)} required helperText="변경 사유를 3자 이상 입력하세요." size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px' } }} /> {/* Test Connection Inside Modal */} Live Connection Test (Synthetic Audio Ping) {sttTestModalResult && ( {sttTestModalResult.message} )} {/* ── LLM Model Add Modal ── */} setLlmModalOpen(false)} maxWidth="sm" fullWidth PaperProps={{ sx: { bgcolor: C.card, border: `1px solid ${C.borderHl}`, borderRadius: '20px', boxShadow: '0 24px 60px var(--d3-scrim)', }, }} > Add Reasoning Model Endpoint ⚡ Load Preset Template (optional) setLlmModelId(e.target.value)} required fullWidth size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO } }} /> setLlmModelName(e.target.value)} required fullWidth size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px' } }} /> Provider Category setLlmEndpointUrl(e.target.value)} required fullWidth size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO } }} /> setLlmApiKey(e.target.value)} fullWidth size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO } }} /> setLlmPromptCost(e.target.value)} required size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO } }} /> setLlmCompletionCost(e.target.value)} required size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px', fontFamily: FONT_MONO } }} /> setLlmMemo(event.target.value)} required helperText="생성 사유를 3자 이상 입력하세요." size="small" sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'var(--d3-bg-inset-soft)', color: C.bright, borderRadius: '10px' } }} /> ) }