File size: 4,401 Bytes
9713441 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | 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<T = any>(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<LLMCompletionResult | null> {
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<string, string> = {
'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<string, any> = {
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;
}
|