Files
InfoGenie/InfoGenie-frontend/public/aimodelapp/shared/ai-chat.js
2026-03-28 20:59:52 +08:00

49 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 统一调用后端 /api/aimodelapp/chat提示词由前端 ai-prompts.js 组装)
*/
(function (global) {
global.AiChat = {
/**
* @param {{ role: string, content: string }[]} messages
* @param {{ provider?: string, model?: string }} [opts]
* @returns {Promise<string>} assistant 文本
*/
async complete(messages, opts) {
opts = opts || {};
const token =
(global.AUTH_CONFIG && typeof global.AUTH_CONFIG.getToken === 'function'
? global.AUTH_CONFIG.getToken()
: null) || global.localStorage.getItem('token');
if (!token) {
throw new Error('未登录请先登录后使用AI功能');
}
const base = (global.API_CONFIG && global.API_CONFIG.baseUrl) || '';
const res = await fetch(base + '/api/aimodelapp/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({
messages,
provider: opts.provider || 'deepseek',
model: opts.model || 'deepseek-chat',
}),
});
if (!res.ok) {
let errMsg = res.statusText;
try {
const errData = await res.json();
errMsg = errData.error || errMsg;
} catch (e) { /* ignore */ }
throw new Error(errMsg || 'API 请求失败');
}
const data = await res.json();
if (data.success && data.content != null) {
return typeof data.content === 'string' ? data.content : String(data.content);
}
throw new Error(data.error || 'API 响应异常');
},
};
})(typeof window !== 'undefined' ? window : this);