Spaces:
Sleeping

olokaflow / apps /server /src /services /aiProfileService.ts
phucsd's picture
Fix HF connection tester + Dual-Key Decrypt + Full Vault Hydration
3ec3c9b verified
Raw History Blame Contribute Delete
36.5 kB
import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { db, AUDIO_CACHE_DIR, UPLOADS_DIR } from '../db/database.js'; import { encryptSecret, decryptSecret, maskSecret, isMaskedOrEmptySecret, } from '../db/crypto.js'; import type { AIProviderProfile, AIModelRecord, AIRoleRoutingEntry, AIRoleKey, AIConnectionTestResult, AIProviderProtocol, AIModelCapability, } from '@olokaflow/shared'; export function normalizeBaseUrl(baseUrl: string, protocol?: AIProviderProtocol): string { let clean = String(baseUrl || '').trim(); if (!clean) return ''; try { const parsed = new URL(clean); parsed.hash = ''; parsed.search = ''; clean = parsed.toString(); } catch { // keep raw string if partial } clean = clean.replace(/\/+$/, ''); const suffixes = [ '/chat/completions', '/completions', '/responses', '/embeddings', '/models', '/messages', '/audio/speech', '/audio/transcriptions', '/images/generations', ]; const lower = clean.toLowerCase(); for (const suffix of suffixes) { if (lower.endsWith(suffix)) { clean = clean.slice(0, -suffix.length).replace(/\/+$/, ''); break; } } try { const parsed = new URL(clean); if ( (protocol === 'gemini' || parsed.hostname === 'generativelanguage.googleapis.com') && !parsed.pathname.includes('/openai') ) { clean = 'https://generativelanguage.googleapis.com/v1beta/openai'; } } catch { // ignore } return clean; } function rowToProfile(row: any, includePlainKey = false): AIProviderProfile { const plainKey = decryptSecret(row.encrypted_api_key || ''); let customHeaders: Record<string, string> = {}; let models: AIModelRecord[] = []; try { customHeaders = JSON.parse(row.custom_headers_json || '{}'); } catch {} try { models = JSON.parse(row.models_json || '[]'); } catch {} return { id: row.id, name: row.name, protocol: row.protocol as AIProviderProtocol, baseUrl: row.base_url, apiKey: includePlainKey ? plainKey : '', hasApiKey: Boolean(plainKey), maskedApiKey: maskSecret(row.encrypted_api_key || ''), customHeaders, timeoutMs: Number(row.timeout_ms || 180000), maxConcurrency: Number(row.max_concurrency || 4), enabled: Boolean(row.enabled), notes: row.notes || '', healthStatus: row.health_status || 'untested', lastTestedAt: row.last_tested_at || null, lastLatencyMs: row.last_latency_ms ?? null, lastTestMessage: row.last_test_message || '', models, createdAt: row.created_at, updatedAt: row.updated_at, }; } export function listAIProfiles(includePlainKey = false): AIProviderProfile[] { const rows = db.prepare('SELECT * FROM ai_provider_profiles ORDER BY created_at ASC').all(); return rows.map((r) => rowToProfile(r, includePlainKey)); } export function getAIProfileById(id: string, includePlainKey = false): AIProviderProfile | null { const row = db.prepare('SELECT * FROM ai_provider_profiles WHERE id = ?').get(id); if (!row) return null; return rowToProfile(row, includePlainKey); } export function saveAIProfile(input: Partial<AIProviderProfile> & { name: string; baseUrl: string; protocol: AIProviderProtocol }): AIProviderProfile { const now = new Date().toISOString(); const existingRow = input.id ? (db.prepare('SELECT * FROM ai_provider_profiles WHERE id = ?').get(input.id) as any) : null; const id = existingRow ? existingRow.id : input.id || `prof-${crypto.randomUUID().slice(0, 8)}`; const cleanUrl = normalizeBaseUrl(input.baseUrl, input.protocol); let encryptedKey = existingRow ? existingRow.encrypted_api_key : ''; if (input.apiKey !== undefined && !isMaskedOrEmptySecret(input.apiKey)) { encryptedKey = encryptSecret(input.apiKey.trim()); } else if (input.apiKey === '' && !existingRow) { encryptedKey = ''; } const customHeaders = input.customHeaders ?? (existingRow ? JSON.parse(existingRow.custom_headers_json || '{}') : {}); const models = input.models ?? (existingRow ? JSON.parse(existingRow.models_json || '[]') : []); if (existingRow) { db.prepare(` UPDATE ai_provider_profiles SET name = ?, protocol = ?, base_url = ?, encrypted_api_key = ?, custom_headers_json = ?, timeout_ms = ?, max_concurrency = ?, enabled = ?, notes = ?, models_json = ?, updated_at = ? WHERE id = ? `).run( input.name, input.protocol, cleanUrl, encryptedKey, JSON.stringify(customHeaders), input.timeoutMs ?? existingRow.timeout_ms ?? 180000, input.maxConcurrency ?? existingRow.max_concurrency ?? 4, input.enabled === undefined ? existingRow.enabled : input.enabled ? 1 : 0, input.notes ?? existingRow.notes ?? '', JSON.stringify(models), now, id ); } else { db.prepare(` INSERT INTO ai_provider_profiles ( id, name, protocol, base_url, encrypted_api_key, custom_headers_json, timeout_ms, max_concurrency, enabled, notes, health_status, last_tested_at, last_latency_ms, last_test_message, models_json, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run( id, input.name, input.protocol, cleanUrl, encryptedKey, JSON.stringify(customHeaders), input.timeoutMs ?? 180000, input.maxConcurrency ?? 4, input.enabled === false ? 0 : 1, input.notes ?? '', 'untested', null, null, 'Chưa kiểm tra kết nối', JSON.stringify(models), now, now ); } return getAIProfileById(id, false)!; } export function deleteAIProfile(id: string): boolean { const res = db.prepare('DELETE FROM ai_provider_profiles WHERE id = ?').run(id); return res.changes > 0; } export function duplicateAIProfile(id: string): AIProviderProfile | null { const source = getAIProfileById(id, true); if (!source) return null; return saveAIProfile({ ...source, id: `prof-${crypto.randomUUID().slice(0, 8)}`, name: `${source.name} (Bản sao)`, }); } function inferModelCapabilities(modelId: string, raw: any): AIModelCapability[] { const lower = modelId.toLowerCase(); const caps = new Set<AIModelCapability>(); if (lower.includes('embed') || lower.includes('bge')) { caps.add('embedding'); return Array.from(caps); } if (lower.includes('tts') || lower.includes('speech') || lower.includes('omnivoice')) { caps.add('tts'); return Array.from(caps); } if (lower.includes('whisper') || lower.includes('asr') || lower.includes('transcribe')) { caps.add('asr'); return Array.from(caps); } if (lower.includes('flux') || lower.includes('dall-e') || lower.includes('sdxl') || lower.includes('imagen')) { caps.add('image_gen'); return Array.from(caps); } caps.add('chat'); caps.add('coding'); caps.add('json_mode'); if ( lower.includes('vl') || lower.includes('vision') || lower.includes('4o') || lower.includes('gemini') || lower.includes('claude-3') || lower.includes('omni') || lower.includes('pixtral') ) { caps.add('vision'); } if ( lower.includes('r1') || lower.includes('reasoner') || lower.includes('o1') || lower.includes('o3') || lower.includes('thinking') || lower.includes('gemini-2.5') || raw?.reasoning === true ) { caps.add('reasoning'); } return Array.from(caps); } function getFallbackProviderCatalog(baseUrl: string, protocol: AIProviderProtocol): AIModelRecord[] { const lowerUrl = baseUrl.toLowerCase(); const createRec = (modelId: string, name: string, caps: AIModelCapability[], thinking = false): AIModelRecord => ({ id: `mdl-${modelId.replace(/[^a-zA-Z0-9_-]/g, '-')}`, modelId, name, ownedBy: protocol, capabilities: caps, supportsThinking: thinking, reasoningEffort: thinking ? 'medium' : 'none', maxTokens: 8192, healthStatus: 'untested', lastTestedAt: null, ttftMs: null, durationMs: null, lastTestMessage: '', }); if (protocol === 'gemini' || lowerUrl.includes('googleapis.com')) { return [ createRec('gemini-2.5-flash', 'Gemini 2.5 Flash (Vision + Fast Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true), createRec('gemini-2.5-pro', 'Gemini 2.5 Pro (Director + Deep Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true), createRec('gemini-2.0-flash', 'Gemini 2.0 Flash', ['chat', 'coding', 'vision', 'json_mode'], false), ]; } if (protocol === 'anthropic' || lowerUrl.includes('anthropic.com')) { return [ createRec('claude-3-7-sonnet-20250219', 'Claude 3.7 Sonnet (Motion & Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true), createRec('claude-3-5-sonnet-20241022', 'Claude 3.5 Sonnet', ['chat', 'coding', 'vision', 'json_mode'], false), createRec('claude-3-5-haiku-20241022', 'Claude 3.5 Haiku (Fast Edit)', ['chat', 'coding', 'json_mode'], false), ]; } if (lowerUrl.includes('xiaomimimo.com')) { return [ createRec('mimo-v2.5-pro', 'MiMo-V2.5-Pro', ['chat', 'coding', 'reasoning', 'json_mode'], true), createRec('mimo-v2.5-pro-ultraspeed', 'MiMo-V2.5-Pro-UltraSpeed', ['chat', 'coding', 'reasoning', 'json_mode'], true), createRec('mimo-v2-omni', 'MiMo-V2-Omni (Vision)', ['chat', 'coding', 'vision', 'json_mode'], true), ]; } if (lowerUrl.includes('deepseek.com')) { return [ createRec('deepseek-chat', 'DeepSeek V3 Chat', ['chat', 'coding', 'json_mode'], false), createRec('deepseek-reasoner', 'DeepSeek R1 Reasoner', ['chat', 'coding', 'reasoning', 'json_mode'], true), ]; } if (protocol === 'huggingface') { return [ createRec('black-forest-labs/FLUX.1-schnell', 'FLUX.1 Schnell (Fast Image Gen)', ['image_gen'], false), createRec('black-forest-labs/FLUX.1-dev', 'FLUX.1 Dev (HD Image Gen)', ['image_gen'], false), ]; } if (protocol === 'openai-voice') { return [ createRec('tts-1-hd', 'OpenAI TTS-1-HD', ['tts'], false), createRec('tts-1', 'OpenAI TTS-1 Standard', ['tts'], false), createRec('whisper-1', 'Whisper-1 Word Timestamps', ['asr'], false), ]; } return []; } /** * Fetches available models from an endpoint (`/models`) or merges with known catalog fallback. */ export async function fetchModelsFromEndpoint(params: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: AIProviderProtocol; customHeaders?: Record<string, string>; }): Promise<{ success: boolean; models: AIModelRecord[]; source: 'endpoint' | 'fallback'; message: string; }> { const existing = params.profileId ? getAIProfileById(params.profileId, true) : null; const protocol = params.protocol || existing?.protocol || 'openai-compatible'; const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol); const apiKey = params.apiKey && !isMaskedOrEmptySecret(params.apiKey) ? params.apiKey.trim() : existing?.apiKey || ''; const customHeaders = params.customHeaders || existing?.customHeaders || {}; if (!baseUrl) { throw new Error('Chưa nhập API Base URL.'); } const candidateUrls = [`${baseUrl}/models`]; try { const u = new URL(baseUrl); if (!u.pathname.match(/\/v\d+/)) { candidateUrls.push(`${u.origin}/v1/models`); } } catch {} const errors: string[] = []; for (const url of candidateUrls) { try { const headers: Record<string, string> = { Accept: 'application/json', ...customHeaders, }; if (apiKey) { if (protocol === 'anthropic' || url.includes('anthropic.com')) { headers['x-api-key'] = apiKey; headers['anthropic-version'] = '2023-06-01'; } else { headers['Authorization'] = `Bearer ${apiKey}`; } } const resp = await fetch(url, { method: 'GET', headers, signal: AbortSignal.timeout(10000), }); if (!resp.ok) { errors.push(`${url} -> HTTP ${resp.status}`); continue; } const payload = (await resp.json()) as any; const rawList = Array.isArray(payload?.data) ? payload.data : Array.isArray(payload?.models) ? payload.models : Array.isArray(payload) ? payload : []; if (rawList.length > 0) { const models: AIModelRecord[] = rawList .map((item: any) => { const modelId = typeof item === 'string' ? item : item.id || item.name || item.model || ''; if (!modelId) return null; const caps = inferModelCapabilities(modelId, item); const supportsThinking = caps.includes('reasoning'); return { id: `mdl-${modelId.replace(/[^a-zA-Z0-9_-]/g, '-')}`, modelId, name: item.display_name || item.name || modelId, ownedBy: item.owned_by || item.provider || protocol, capabilities: caps, supportsThinking, reasoningEffort: supportsThinking ? 'medium' : 'none', maxTokens: Number(item.context_length || item.max_tokens || 8192), healthStatus: 'untested', lastTestedAt: null, ttftMs: null, durationMs: null, lastTestMessage: '', } as AIModelRecord; }) .filter(Boolean) as AIModelRecord[]; if (existing) { saveAIProfile({ ...existing, models }); } return { success: true, models, source: 'endpoint', message: `Đã quét thành công ${models.length} model trực tiếp từ ${url}.`, }; } } catch (err: any) { errors.push(`${url}: ${err.message}`); } } const fallbackModels = getFallbackProviderCatalog(baseUrl, protocol); if (fallbackModels.length > 0) { if (existing) { saveAIProfile({ ...existing, models: fallbackModels }); } return { success: true, models: fallbackModels, source: 'fallback', message: `Endpoint không mở /models (${errors.join('; ')}); đã nạp ${fallbackModels.length} model chuẩn cho ${protocol}.`, }; } throw new Error(`Không thể lấy danh sách model từ ${baseUrl}. Chi tiết: ${errors.join(' | ')}`); } /** * TEST 1: Ping & Authentication Connection Test */ export async function testProfileConnection(params: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: AIProviderProtocol; modelId?: string; customHeaders?: Record<string, string>; }): Promise<AIConnectionTestResult> { const existing = params.profileId ? getAIProfileById(params.profileId, true) : null; const protocol = params.protocol || existing?.protocol || 'openai-compatible'; const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol); const apiKey = params.apiKey && !isMaskedOrEmptySecret(params.apiKey) ? params.apiKey.trim() : existing?.apiKey || ''; const customHeaders = params.customHeaders || existing?.customHeaders || {}; const testedAt = new Date().toISOString(); const startTime = Date.now(); if (!baseUrl) { return { success: false, testType: 'connection', durationMs: 0, message: 'Chưa nhập API Base URL.', error: 'Missing baseUrl', testedAt, }; } try { const headers: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'application/json', ...customHeaders, }; if (apiKey) { if (protocol === 'anthropic') { headers['x-api-key'] = apiKey; headers['anthropic-version'] = '2023-06-01'; } else { headers['Authorization'] = `Bearer ${apiKey}`; } } let testUrl = `${baseUrl}/models`; let method = 'GET'; let body: string | undefined; if (protocol === 'modal-render') { testUrl = `${baseUrl.replace(/\/api\/render$/i, '')}/health`; method = 'GET'; } else if (protocol === 'huggingface' || baseUrl.includes('huggingface.co')) { testUrl = 'https://huggingface.co/api/whoami-v2'; method = 'GET'; } else if (baseUrl.includes('tts.oloka.net')) { testUrl = `${baseUrl.replace(/\/v1$/i, '')}/v1/voices`; method = 'GET'; } else if (protocol === 'anthropic') { testUrl = `${baseUrl}/messages`; method = 'POST'; body = JSON.stringify({ model: params.modelId || existing?.models?.[0]?.modelId || 'claude-3-5-haiku-20241022', messages: [{ role: 'user', content: 'ping' }], max_tokens: 8, }); } let resp = await fetch(testUrl, { method, headers, body, signal: AbortSignal.timeout(10000), }); // If GET /models is 404 on a custom OpenAI gateway, fallback to POST /chat/completions ping if (!resp.ok && resp.status === 404 && protocol === 'openai-compatible') { const modelToPing = params.modelId || existing?.models?.[0]?.modelId || 'gpt-4o'; resp = await fetch(`${baseUrl}/chat/completions`, { method: 'POST', headers, body: JSON.stringify({ model: modelToPing, messages: [{ role: 'user', content: 'ping' }], max_tokens: 5, }), signal: AbortSignal.timeout(10000), }); } const durationMs = Date.now() - startTime; const text = await resp.text(); if (text.trim().startsWith('<!DOCTYPE html') || text.trim().startsWith('<html')) { throw new Error('Server trả về trang HTML (có thể bị chặn bởi Cloudflare hoặc sai đường dẫn API).'); } if (!resp.ok) { let errMsg = `HTTP ${resp.status}`; try { const json = JSON.parse(text); errMsg = json.error?.message || json.message || errMsg; } catch {} throw new Error(errMsg); } const message = `Kết nối thành công tới ${baseUrl} (${durationMs}ms, HTTP ${resp.status}).`; if (existing) { db.prepare(` UPDATE ai_provider_profiles SET health_status = 'healthy', last_tested_at = ?, last_latency_ms = ?, last_test_message = ? WHERE id = ? `).run(testedAt, durationMs, message, existing.id); } return { success: true, testType: 'connection', profileId: existing?.id, protocol, statusCode: resp.status, durationMs, message, testedAt, }; } catch (err: any) { const durationMs = Date.now() - startTime; const errMsg = `Kết nối thất bại: ${err.message}`; if (existing) { db.prepare(` UPDATE ai_provider_profiles SET health_status = 'failed', last_tested_at = ?, last_latency_ms = ?, last_test_message = ? WHERE id = ? `).run(testedAt, durationMs, errMsg, existing.id); } return { success: false, testType: 'connection', profileId: existing?.id, protocol, durationMs, message: errMsg, error: err.message, testedAt, }; } } /** * TEST 2: Deep Model Preflight Benchmark (TTFT ms, SSE Stream, JSON Validation, Sample Output) */ export async function testModelPreflight(params: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: AIProviderProtocol; modelId: string; reasoningEffort?: string; customHeaders?: Record<string, string>; }): Promise<AIConnectionTestResult> { const existing = params.profileId ? getAIProfileById(params.profileId, true) : null; const protocol = params.protocol || existing?.protocol || 'openai-compatible'; const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol); const apiKey = params.apiKey && !isMaskedOrEmptySecret(params.apiKey) ? params.apiKey.trim() : existing?.apiKey || ''; const customHeaders = params.customHeaders || existing?.customHeaders || {}; const modelId = (params.modelId || '').trim(); const testedAt = new Date().toISOString(); if (!baseUrl || !modelId) { return { success: false, testType: 'model_preflight', durationMs: 0, message: 'Thiếu Base URL hoặc Model ID cần kiểm tra.', testedAt, }; } const startTime = Date.now(); let ttftMs: number | null = null; let streamMode = 'non-stream'; try { const headers: Record<string, string> = { 'Content-Type': 'application/json', ...customHeaders, }; if (apiKey) { if (protocol === 'anthropic') { headers['x-api-key'] = apiKey; headers['anthropic-version'] = '2023-06-01'; } else { headers['Authorization'] = `Bearer ${apiKey}`; } } const targetUrl = protocol === 'anthropic' ? `${baseUrl}/messages` : `${baseUrl}/chat/completions`; const messages = [ { role: 'system', content: 'You are OlokaFlow HyperFrames preflight checker. Reply ONLY with a valid JSON object: {"ready": true, "engine": "hyperframes", "model": "<your_model>", "greeting_vi": "Sẵn sàng dựng video chuyên nghiệp!"}', }, { role: 'user', content: 'Run preflight JSON & responsiveness check.', }, ]; const bodyObj: Record<string, any> = { model: modelId, messages, max_tokens: 160, stream: protocol !== 'anthropic', }; if (params.reasoningEffort && params.reasoningEffort !== 'none') { bodyObj.reasoning_effort = params.reasoningEffort; } const resp = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(bodyObj), signal: AbortSignal.timeout(25000), }); if (!resp.ok) { const errText = await resp.text(); throw new Error(`HTTP ${resp.status}: ${errText.slice(0, 240)}`); } const contentType = resp.headers.get('content-type') || ''; let fullContent = ''; if (contentType.includes('text/event-stream') && resp.body) { streamMode = 'sse-stream'; const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; if (ttftMs === null) { ttftMs = Date.now() - startTime; } buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { const trimmed = line.trim(); if (!trimmed.startsWith('data:')) continue; const dataStr = trimmed.slice(5).trim(); if (dataStr === '[DONE]') continue; try { const parsed = JSON.parse(dataStr); const delta = parsed.choices?.[0]?.delta?.content || ''; fullContent += delta; } catch {} } } } else { const json = (await resp.json()) as any; ttftMs = Date.now() - startTime; fullContent = json.choices?.[0]?.message?.content || json.content?.[0]?.text || JSON.stringify(json); } const durationMs = Date.now() - startTime; let isJson = false; try { const cleaned = fullContent .trim() .replace(/^```(?:json)?\s*/i, '') .replace(/\s*```$/, '') .trim(); JSON.parse(cleaned); isJson = true; } catch {} const msg = `Model "${modelId}" hoạt động tốt! TTFT: ${ttftMs || durationMs}ms | Tổng: ${(durationMs / 1000).toFixed(2)}s | Chế độ: ${streamMode} | Output: ${isJson ? 'JSON Chuẩn ✓' : 'Text'}`; if (existing) { const updatedModels = existing.models.map((m) => m.modelId === modelId ? { ...m, healthStatus: (durationMs < 12000 ? 'healthy' : 'degraded') as any, lastTestedAt: testedAt, ttftMs: ttftMs || durationMs, durationMs, lastTestMessage: msg, } : m ); saveAIProfile({ ...existing, healthStatus: 'healthy', lastTestedAt: testedAt, lastLatencyMs: ttftMs || durationMs, lastTestMessage: msg, models: updatedModels, }); } return { success: true, testType: 'model_preflight', profileId: existing?.id, modelId, protocol, durationMs, ttftMs: ttftMs || durationMs, streamMode, isJson, sampleOutput: fullContent.slice(0, 300), message: msg, testedAt, }; } catch (err: any) { const durationMs = Date.now() - startTime; const errMsg = `Lỗi test model "${modelId}": ${err.message}`; if (existing) { const updatedModels = existing.models.map((m) => m.modelId === modelId ? { ...m, healthStatus: 'failed' as const, lastTestedAt: testedAt, durationMs, lastTestMessage: errMsg, } : m ); saveAIProfile({ ...existing, models: updatedModels }); } return { success: false, testType: 'model_preflight', profileId: existing?.id, modelId, protocol, durationMs, message: errMsg, error: err.message, testedAt, }; } } /** * TEST 3: Vision Capability Test (Base64 PNG inspection) */ export async function testModelVision(params: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: AIProviderProtocol; modelId: string; }): Promise<AIConnectionTestResult> { const existing = params.profileId ? getAIProfileById(params.profileId, true) : null; const protocol = params.protocol || existing?.protocol || 'openai-compatible'; const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol); const apiKey = params.apiKey && !isMaskedOrEmptySecret(params.apiKey) ? params.apiKey.trim() : existing?.apiKey || ''; const testedAt = new Date().toISOString(); const startTime = Date.now(); // 1x1 cobalt blue PNG in base64 const samplePngDataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPj/HwADBwIAMCbHYQAAAABJRU5ErkJggg=='; try { const resp = await fetch(`${baseUrl}/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...(existing?.customHeaders || {}), }, body: JSON.stringify({ model: params.modelId, messages: [ { role: 'user', content: [ { type: 'text', text: 'Describe this image briefly in 5 words.' }, { type: 'image_url', image_url: { url: samplePngDataUri } }, ], }, ], max_tokens: 60, }), signal: AbortSignal.timeout(20000), }); const durationMs = Date.now() - startTime; if (!resp.ok) { const errText = await resp.text(); throw new Error(`HTTP ${resp.status}: ${errText.slice(0, 200)}`); } const json = (await resp.json()) as any; const reply = json.choices?.[0]?.message?.content || ''; return { success: true, testType: 'vision', profileId: existing?.id, modelId: params.modelId, durationMs, sampleOutput: reply.slice(0, 200), message: `Model "${params.modelId}" đọc ảnh Vision thành công trong ${durationMs}ms! Phản hồi: "${reply.slice(0, 80)}"`, testedAt, }; } catch (err: any) { return { success: false, testType: 'vision', profileId: existing?.id, modelId: params.modelId, durationMs: Date.now() - startTime, message: `Model "${params.modelId}" không hỗ trợ Vision hoặc lỗi: ${err.message}`, error: err.message, testedAt, }; } } /** * TEST 4: Voice TTS / Image Gen / Modal Render Live Test */ export async function testVoiceOrMediaEndpoint(params: { profileId?: string; testKind: 'voice' | 'image_gen' | 'modal_render'; modelId?: string; voiceId?: string; }): Promise<AIConnectionTestResult> { const existing = params.profileId ? getAIProfileById(params.profileId, true) : null; if (!existing) { throw new Error('Không tìm thấy Profile cần kiểm tra.'); } const testedAt = new Date().toISOString(); const startTime = Date.now(); const baseUrl = normalizeBaseUrl(existing.baseUrl, existing.protocol); const apiKey = existing.apiKey; try { if (params.testKind === 'voice') { const isOloka = baseUrl.includes('tts.oloka.net'); const ttsModel = params.modelId || existing.models[0]?.modelId || (isOloka ? 'olokatts-v3-turbo' : 'tts-1'); const voice = params.voiceId || (isOloka ? 'Hải Đăng' : 'alloy'); const speechUrl = isOloka ? `${baseUrl.replace(/\/v1$/i, '')}/v1/audio/speech` : `${baseUrl}/audio/speech`; const resp = await fetch(speechUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...(isOloka ? { Accept: 'audio/wav' } : {}), ...existing.customHeaders, }, body: JSON.stringify( isOloka ? { model: ttsModel, voice, input: 'Xin chào, hệ thống giọng nói OlokaFlow đã kết nối thành công!', speed: 1.0, } : { model: ttsModel, voice, input: 'Xin chào, hệ thống giọng nói OlokaFlow đã kết nối thành công!', response_format: 'mp3', } ), signal: AbortSignal.timeout(40000), }); if (!resp.ok) { const errText = await resp.text(); throw new Error(`TTS HTTP ${resp.status}: ${errText.slice(0, 200)}`); } const buf = Buffer.from(await resp.arrayBuffer()); const ext = isOloka ? 'wav' : 'mp3'; const fileName = `test-voice-${Date.now()}.${ext}`; const filePath = path.join(AUDIO_CACHE_DIR, fileName); fs.writeFileSync(filePath, buf); const durationMs = Date.now() - startTime; return { success: true, testType: 'voice', profileId: existing.id, modelId: ttsModel, durationMs, audioPreviewUrl: `/media/audio_cache/${fileName}`, message: `Sinh giọng nói TTS thành công (${(buf.length / 1024).toFixed(1)} KB trong ${durationMs}ms). Bấm Play để nghe thử!`, testedAt, }; } if (params.testKind === 'image_gen') { const imgModel = params.modelId || existing.models[0]?.modelId || 'black-forest-labs/FLUX.1-schnell'; let imgBuffer: Buffer; if (existing.protocol === 'huggingface' || baseUrl.includes('huggingface.co')) { const hfUrl = baseUrl.endsWith(imgModel) ? baseUrl : `${baseUrl}/${imgModel}`; const resp = await fetch(hfUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), }, body: JSON.stringify({ inputs: 'Futuristic neon studio camera icon, minimal 3d render, dark obsidian background', }), signal: AbortSignal.timeout(30000), }); if (!resp.ok) { throw new Error(`HF Image API HTTP ${resp.status}: ${(await resp.text()).slice(0, 200)}`); } imgBuffer = Buffer.from(await resp.arrayBuffer()); } else { const resp = await fetch(`${baseUrl}/images/generations`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), }, body: JSON.stringify({ model: imgModel, prompt: 'Minimal 3d studio camera icon on dark background', n: 1, size: '1024x1024', }), signal: AbortSignal.timeout(30000), }); if (!resp.ok) { throw new Error(`OpenAI Image API HTTP ${resp.status}: ${(await resp.text()).slice(0, 200)}`); } const data = (await resp.json()) as any; const b64 = data.data?.[0]?.b64_json; const url = data.data?.[0]?.url; if (b64) { imgBuffer = Buffer.from(b64, 'base64'); } else if (url) { const r2 = await fetch(url); imgBuffer = Buffer.from(await r2.arrayBuffer()); } else { throw new Error('API không trả về url hoặc b64_json.'); } } const fileName = `test-img-${Date.now()}.png`; fs.writeFileSync(path.join(UPLOADS_DIR, fileName), imgBuffer); const durationMs = Date.now() - startTime; return { success: true, testType: 'image_gen', profileId: existing.id, modelId: imgModel, durationMs, imagePreviewUrl: `/media/uploads/${fileName}`, message: `Tạo ảnh thử nghiệm thành công bằng "${imgModel}" trong ${(durationMs / 1000).toFixed(1)}s!`, testedAt, }; } // Modal Render endpoint test return await testProfileConnection({ profileId: existing.id }); } catch (err: any) { return { success: false, testType: params.testKind, profileId: existing.id, durationMs: Date.now() - startTime, message: `Lỗi kiểm tra ${params.testKind}: ${err.message}`, error: err.message, testedAt, }; } } // ============================================================================ // ROLE ROUTING MATRIX & ENDPOINT RESOLUTION WITH AUTO-FAILOVER // ============================================================================ export function getRoleRoutings(): AIRoleRoutingEntry[] { const rows = db.prepare('SELECT * FROM ai_role_routings ORDER BY role ASC').all() as any[]; return rows.map((r) => ({ role: r.role as AIRoleKey, label: r.label, description: r.description, primaryProfileId: r.primary_profile_id || '', primaryModelId: r.primary_model_id || '', fallbackProfileId: r.fallback_profile_id || '', fallbackModelId: r.fallback_model_id || '', })); } export function saveRoleRoutings(entries: AIRoleRoutingEntry[]): AIRoleRoutingEntry[] { const now = new Date().toISOString(); const stmt = db.prepare(` UPDATE ai_role_routings SET primary_profile_id = ?, primary_model_id = ?, fallback_profile_id = ?, fallback_model_id = ?, updated_at = ? WHERE role = ? `); for (const e of entries) { stmt.run( e.primaryProfileId || '', e.primaryModelId || '', e.fallbackProfileId || '', e.fallbackModelId || '', now, e.role ); } return getRoleRoutings(); } export interface ResolvedModelTarget { profile: AIProviderProfile; modelId: string; isFallback: boolean; } export function resolveTargetsForRole( role: AIRoleKey, overrideProfileId?: string, overrideModelId?: string ): ResolvedModelTarget[] { const allProfiles = listAIProfiles(true).filter((p) => p.enabled); const targets: ResolvedModelTarget[] = []; if (overrideProfileId) { const p = allProfiles.find((x) => x.id === overrideProfileId); if (p) { targets.push({ profile: p, modelId: overrideModelId || p.models[0]?.modelId || 'gpt-4o', isFallback: false, }); } } const routing = getRoleRoutings().find((r) => r.role === role); if (routing) { const primaryProf = allProfiles.find((x) => x.id === routing.primaryProfileId); if (primaryProf) { targets.push({ profile: primaryProf, modelId: routing.primaryModelId || primaryProf.models[0]?.modelId || 'gpt-4o', isFallback: false, }); } const fallbackProf = allProfiles.find((x) => x.id === routing.fallbackProfileId); if (fallbackProf) { targets.push({ profile: fallbackProf, modelId: routing.fallbackModelId || fallbackProf.models[0]?.modelId || 'gpt-4o', isFallback: true, }); } } return targets; }
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { db, AUDIO_CACHE_DIR, UPLOADS_DIR } from '../db/database.js';
import {
encryptSecret,
decryptSecret,
maskSecret,
isMaskedOrEmptySecret,
} from '../db/crypto.js';
import type {
AIProviderProfile,
AIModelRecord,
AIRoleRoutingEntry,
AIRoleKey,
AIConnectionTestResult,
AIProviderProtocol,
AIModelCapability,
} from '@olokaflow/shared';
export function normalizeBaseUrl(baseUrl: string, protocol?: AIProviderProtocol): string {
let clean = String(baseUrl || '').trim();
if (!clean) return '';
try {
const parsed = new URL(clean);
parsed.hash = '';
parsed.search = '';
clean = parsed.toString();
} catch {
// keep raw string if partial
}
clean = clean.replace(/\/+$/, '');
const suffixes = [
'/chat/completions',
'/completions',
'/responses',
'/embeddings',
'/models',
'/messages',
'/audio/speech',
'/audio/transcriptions',
'/images/generations',
];
const lower = clean.toLowerCase();
for (const suffix of suffixes) {
if (lower.endsWith(suffix)) {
clean = clean.slice(0, -suffix.length).replace(/\/+$/, '');
break;
}
}
try {
const parsed = new URL(clean);
if (
(protocol === 'gemini' || parsed.hostname === 'generativelanguage.googleapis.com') &&
!parsed.pathname.includes('/openai')
) {
clean = 'https://generativelanguage.googleapis.com/v1beta/openai';
}
} catch {
// ignore
}
return clean;
}
function rowToProfile(row: any, includePlainKey = false): AIProviderProfile {
const plainKey = decryptSecret(row.encrypted_api_key || '');
let customHeaders: Record<string, string> = {};
let models: AIModelRecord[] = [];
try {
customHeaders = JSON.parse(row.custom_headers_json || '{}');
} catch {}
try {
models = JSON.parse(row.models_json || '[]');
} catch {}
return {
id: row.id,
name: row.name,
protocol: row.protocol as AIProviderProtocol,
baseUrl: row.base_url,
apiKey: includePlainKey ? plainKey : '',
hasApiKey: Boolean(plainKey),
maskedApiKey: maskSecret(row.encrypted_api_key || ''),
customHeaders,
timeoutMs: Number(row.timeout_ms || 180000),
maxConcurrency: Number(row.max_concurrency || 4),
enabled: Boolean(row.enabled),
notes: row.notes || '',
healthStatus: row.health_status || 'untested',
lastTestedAt: row.last_tested_at || null,
lastLatencyMs: row.last_latency_ms ?? null,
lastTestMessage: row.last_test_message || '',
models,
createdAt: row.created_at,
updatedAt: row.updated_at,