import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js'; import { logUsage } from '../db/database.js'; import type { AIRoleKey } from '@olokaflow/shared'; export interface LLMChatMessage { role: 'system' | 'user' | 'assistant'; content: string | Array<{ type: string; text?: string; image_url?: { url: string } }>; } export interface LLMCompletionResult { content: string; usedProfileId: string; usedModelId: string; promptTokens: number; completionTokens: number; durationMs: number; fromFallback: boolean; } export function extractCleanJson(rawText: string, fallback: T): T { if (!rawText || !rawText.trim()) return fallback; let cleaned = rawText.trim(); cleaned = cleaned.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '').trim(); try { return JSON.parse(cleaned) as T; } catch { const firstObj = cleaned.indexOf('{'); const lastObj = cleaned.lastIndexOf('}'); if (firstObj !== -1 && lastObj > firstObj) { try { return JSON.parse(cleaned.slice(firstObj, lastObj + 1)) as T; } catch {} } const firstArr = cleaned.indexOf('['); const lastArr = cleaned.lastIndexOf(']'); if (firstArr !== -1 && lastArr > firstArr) { try { return JSON.parse(cleaned.slice(firstArr, lastArr + 1)) as T; } catch {} } return fallback; } } export function extractCleanHtml(rawText: string): string { if (!rawText) return ''; let cleaned = rawText.trim(); cleaned = cleaned.replace(/^```(?:html)?\s*/i, '').replace(/\s*```$/, '').trim(); return cleaned; } export async function callLLMForRole(params: { role: AIRoleKey; messages: LLMChatMessage[]; projectId?: string; overrideProfileId?: string; overrideModelId?: string; maxTokens?: number; temperature?: number; signal?: AbortSignal; }): Promise { const targets = resolveTargetsForRole( params.role, params.overrideProfileId, params.overrideModelId ); for (const target of targets) { const { profile, modelId, isFallback } = target; if (!profile.baseUrl || !profile.apiKey) { continue; } const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol); const startTime = Date.now(); try { const headers: Record = { 'Content-Type': 'application/json', ...profile.customHeaders, }; if (profile.protocol === 'anthropic') { headers['x-api-key'] = profile.apiKey; headers['anthropic-version'] = '2023-06-01'; } else { headers['Authorization'] = `Bearer ${profile.apiKey}`; } const url = profile.protocol === 'anthropic' ? `${baseUrl}/messages` : `${baseUrl}/chat/completions`; const bodyObj: Record = { model: modelId, messages: params.messages, max_tokens: params.maxTokens || 4096, temperature: params.temperature ?? 0.4, }; const resp = await fetch(url, { method: 'POST', headers, body: JSON.stringify(bodyObj), signal: params.signal || AbortSignal.timeout(profile.timeoutMs || 180000), }); 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 content = json.choices?.[0]?.message?.content || json.content?.[0]?.text || ''; const promptTokens = Number(json.usage?.prompt_tokens || json.usage?.input_tokens || 250); const completionTokens = Number(json.usage?.completion_tokens || json.usage?.output_tokens || 350); const durationMs = Date.now() - startTime; logUsage({ projectId: params.projectId, profileId: profile.id, modelId, role: params.role, promptTokens, completionTokens, durationMs, }); return { content, usedProfileId: profile.id, usedModelId: modelId, promptTokens, completionTokens, durationMs, fromFallback: isFallback, }; } catch (err: any) { console.warn( `[LLMService] Role "${params.role}" failed on profile "${profile.name}" (${modelId}): ${err.message}. Trying next target...` ); } } return null; }