fix: đã sửa lỗi AI gửi prompt

This commit is contained in:
2026-07-22 08:52:34 +07:00
parent 09bb431a2b
commit e0b849fdf2
6 changed files with 375 additions and 97 deletions
+39 -7
View File
@@ -63,8 +63,26 @@ const AIGateway = (function() {
}
}];
function parseOrigin(urlStr) {
try { const u = new URL(urlStr); return `${u.protocol}//${u.hostname}${u.port ? ':'+u.port : ''}`; } catch (_) { return null; }
}
function isLocalhost(urlStr) {
try {
const u = new URL(urlStr);
return u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0' || u.hostname === '::1';
} catch (_) { return false; }
}
async function callLLM({ provider, model, apiKey, baseUrl, messages, tools, toolChoice }) {
const url = `${baseUrl.replace(/\/$/, '')}/chat/completions`;
const base = baseUrl.replace(/\/$/, '');
const url = `${base}/chat/completions`;
const origin = window.location.origin;
const urlOrigin = parseOrigin(url);
const appOrigin = parseOrigin(origin);
const sameOrigin = urlOrigin === appOrigin;
const targetIsLocal = isLocalhost(url);
const headers = {
'Content-Type': 'application/json',
...(apiKey ? { 'Authorization': `Bearer ${apiKey}` } : {})
@@ -77,15 +95,29 @@ const AIGateway = (function() {
...(toolChoice ? { tool_choice: toolChoice } : {})
};
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body)
});
let response;
if (sameOrigin) {
response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body)
});
} else if (targetIsLocal && !isLocalhost(origin)) {
throw new Error(`AI provider local (${url}) không khả dụng từ domain từ xa (${origin}).\nHãy dùng provider từ xa (OpenAI, Anthropic...) hoặc dùng CORS plugin trình duyệt.`);
} else {
response = await fetch(`${origin}/api/v1/ai/proxy`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, headers, body })
});
}
if (!response.ok) {
const errText = await response.text();
throw new Error(`LLM API error ${response.status}: ${errText}`);
let detail = errText;
try { const j = JSON.parse(errText); if (j.detail) detail = j.detail; } catch (_) {}
throw new Error(detail);
}
return await response.json();