/** * 统一调用后端 /api/aimodelapp/chat(提示词由前端 ai-prompts.js 组装) */ (function (global) { global.AiChat = { /** * @param {{ role: string, content: string }[]} messages * @param {{ provider?: string, model?: string }} [opts] * @returns {Promise} 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);