Add site OpenAI key and model picker
This commit is contained in:
@@ -17,7 +17,7 @@ const PUBLIC_BASE_URL = (process.env.PUBLIC_BASE_URL || `http://localhost:${PORT
|
||||
const AUTH_SECRET = process.env.AUTH_SECRET || "dev-secret-change-me";
|
||||
const COOKIE_NAME = "mf_session";
|
||||
const OPENAI_API_KEY = process.env.OPENAI_API_KEY || "";
|
||||
const OPENAI_TRANSLATION_MODEL = process.env.OPENAI_TRANSLATION_MODEL || "gpt-5.6-luna";
|
||||
const OPENAI_TRANSLATION_MODEL = process.env.OPENAI_TRANSLATION_MODEL || "gpt-5-mini";
|
||||
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"]);
|
||||
const ALLOWED_IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif"]);
|
||||
const MAX_ATTACHMENT_BYTES = 3_000_000;
|
||||
@@ -85,6 +85,7 @@ async function adminApi(req, res, url) {
|
||||
if (url.pathname === "/api/admin/bootstrap" && req.method === "GET") return adminBootstrap(res);
|
||||
if (url.pathname === "/api/admin/events" && req.method === "GET") return eventStream(req, res, url, "admin");
|
||||
if (url.pathname === "/api/admin/site" && req.method === "PATCH") return updateSite(req, res);
|
||||
if (url.pathname === "/api/admin/ai/models" && req.method === "GET") return adminAiModels(res);
|
||||
if (url.pathname === "/api/admin/conversations" && req.method === "GET") return adminConversations(res);
|
||||
if (url.pathname === "/api/admin/visitors" && req.method === "GET") return adminVisitors(res);
|
||||
if (url.pathname.match(/^\/api\/admin\/visitors\/[^/]+$/) && req.method === "PATCH") return updateVisitorProfile(req, res, url);
|
||||
@@ -296,7 +297,8 @@ function defaultSettings() {
|
||||
translations: {
|
||||
enabled: false,
|
||||
operatorLanguage: "cs",
|
||||
model: OPENAI_TRANSLATION_MODEL
|
||||
model: OPENAI_TRANSLATION_MODEL,
|
||||
openaiApiKey: ""
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -435,7 +437,9 @@ function adminConversation(res, url) {
|
||||
async function updateSite(req, res) {
|
||||
const body = await readJson(req);
|
||||
const site = getDefaultSite();
|
||||
const settings = { ...JSON.parse(site.settings_json), ...(body.settings || {}) };
|
||||
const currentSettings = parseJson(site.settings_json, defaultSettings());
|
||||
const incomingSettings = body.settings || {};
|
||||
const settings = mergeSiteSettings(currentSettings, incomingSettings);
|
||||
db.prepare(`
|
||||
UPDATE sites
|
||||
SET is_online = ?, settings_json = ?, updated_at = CURRENT_TIMESTAMP
|
||||
@@ -446,6 +450,27 @@ async function updateSite(req, res) {
|
||||
return json(res, 200, { site: formatSite(updated), snippet: snippetFor(updated) });
|
||||
}
|
||||
|
||||
async function adminAiModels(res) {
|
||||
const settings = getTranslationSettings();
|
||||
const apiKey = settings.openaiApiKey;
|
||||
if (!apiKey) return json(res, 400, { error: "missing_openai_api_key", models: fallbackTranslationModels() });
|
||||
try {
|
||||
const response = await fetch("https://api.openai.com/v1/models", {
|
||||
headers: { "Authorization": `Bearer ${apiKey}` }
|
||||
});
|
||||
if (!response.ok) throw new Error(`OpenAI HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
const models = (data.data || [])
|
||||
.map((item) => item.id)
|
||||
.filter(isUsableTextModel)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
return json(res, 200, { models: models.length ? models : fallbackTranslationModels() });
|
||||
} catch (error) {
|
||||
console.error("openai_models_failed", error.message);
|
||||
return json(res, 502, { error: "openai_models_failed", models: fallbackTranslationModels() });
|
||||
}
|
||||
}
|
||||
|
||||
async function updateConversationStatus(req, res, url) {
|
||||
const body = await readJson(req);
|
||||
const status = ["new", "open", "resolved", "spam"].includes(body.status) ? body.status : null;
|
||||
@@ -742,7 +767,7 @@ async function translateStoredMessage(conversationId, messageId, senderType, bod
|
||||
if (!targetLanguage) return markMessageTranslation(messageId, null, null, null, "skipped");
|
||||
|
||||
try {
|
||||
const result = await translateText(message.body, targetLanguage, settings.model);
|
||||
const result = await translateText(message.body, targetLanguage, settings.model, settings.openaiApiKey);
|
||||
const sourceLanguage = normalizeLanguage(result.sourceLanguage);
|
||||
const translatedText = String(result.translatedText || "").trim();
|
||||
const translatedLanguage = normalizeLanguage(result.translatedLanguage || targetLanguage);
|
||||
@@ -773,11 +798,11 @@ function markMessageTranslation(messageId, sourceLanguage, translatedBody, trans
|
||||
`).run(sourceLanguage, translatedBody, translatedLanguage, status, messageId);
|
||||
}
|
||||
|
||||
async function translateText(text, targetLanguage, model) {
|
||||
async function translateText(text, targetLanguage, model, apiKey) {
|
||||
const response = await fetch("https://api.openai.com/v1/responses", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${OPENAI_API_KEY}`,
|
||||
"Authorization": `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
@@ -828,6 +853,26 @@ function outputTextFromResponse(data) {
|
||||
return chunks.join("");
|
||||
}
|
||||
|
||||
function mergeSiteSettings(currentSettings, incomingSettings) {
|
||||
const settings = { ...currentSettings, ...incomingSettings };
|
||||
const currentTranslations = currentSettings.translations || {};
|
||||
const incomingTranslations = incomingSettings.translations || {};
|
||||
settings.translations = {
|
||||
...currentTranslations,
|
||||
...incomingTranslations
|
||||
};
|
||||
if (!incomingTranslations.openaiApiKey) {
|
||||
settings.translations.openaiApiKey = currentTranslations.openaiApiKey || "";
|
||||
}
|
||||
if (isMaskedApiKey(incomingTranslations.openaiApiKey)) {
|
||||
settings.translations.openaiApiKey = currentTranslations.openaiApiKey || "";
|
||||
}
|
||||
settings.translations.openaiApiKey = normalizeOpenAiApiKey(settings.translations.openaiApiKey);
|
||||
delete settings.translations.hasOpenaiApiKey;
|
||||
delete settings.translations.openaiApiKeyMasked;
|
||||
return settings;
|
||||
}
|
||||
|
||||
function getTranslationSettings() {
|
||||
const site = getDefaultSite();
|
||||
const settings = parseJson(site.settings_json, defaultSettings());
|
||||
@@ -835,10 +880,43 @@ function getTranslationSettings() {
|
||||
return {
|
||||
enabled: Boolean(translations.enabled),
|
||||
operatorLanguage: normalizeLanguage(translations.operatorLanguage) || "cs",
|
||||
model: String(translations.model || OPENAI_TRANSLATION_MODEL).trim() || OPENAI_TRANSLATION_MODEL
|
||||
model: String(translations.model || OPENAI_TRANSLATION_MODEL).trim() || OPENAI_TRANSLATION_MODEL,
|
||||
openaiApiKey: normalizeOpenAiApiKey(translations.openaiApiKey) || OPENAI_API_KEY
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeOpenAiApiKey(value) {
|
||||
const text = String(value || "").trim();
|
||||
if (!text || isMaskedApiKey(text)) return "";
|
||||
return text;
|
||||
}
|
||||
|
||||
function isMaskedApiKey(value) {
|
||||
return String(value || "").includes("...");
|
||||
}
|
||||
|
||||
function maskApiKey(value) {
|
||||
const text = normalizeOpenAiApiKey(value);
|
||||
if (!text) return "";
|
||||
return `${text.slice(0, 7)}...${text.slice(-4)}`;
|
||||
}
|
||||
|
||||
function fallbackTranslationModels() {
|
||||
return [
|
||||
OPENAI_TRANSLATION_MODEL,
|
||||
"gpt-5.1",
|
||||
"gpt-5-mini",
|
||||
"gpt-5-nano",
|
||||
"gpt-4.1-mini",
|
||||
"gpt-4.1-nano"
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
function isUsableTextModel(id) {
|
||||
return /^(gpt-|o[134])/.test(id)
|
||||
&& !/audio|realtime|transcribe|tts|image|search|embedding|moderation|codex/i.test(id);
|
||||
}
|
||||
|
||||
function normalizeLanguage(value) {
|
||||
const text = String(value || "").trim().toLowerCase().replace("_", "-");
|
||||
if (!text) return "";
|
||||
@@ -1036,6 +1114,10 @@ function formatSite(site) {
|
||||
settings.notifications = { ...defaultSettings().notifications, ...(settings.notifications || {}) };
|
||||
settings.launcherEffects = { ...defaultSettings().launcherEffects, ...(settings.launcherEffects || {}) };
|
||||
settings.translations = { ...defaultSettings().translations, ...(settings.translations || {}) };
|
||||
const storedOpenAiKey = settings.translations.openaiApiKey || OPENAI_API_KEY;
|
||||
settings.translations.hasOpenaiApiKey = Boolean(storedOpenAiKey);
|
||||
settings.translations.openaiApiKeyMasked = maskApiKey(storedOpenAiKey);
|
||||
settings.translations.openaiApiKey = "";
|
||||
return {
|
||||
id: site.id,
|
||||
siteKey: site.site_key,
|
||||
|
||||
Reference in New Issue
Block a user