Files
monkey-ai-web/src/helpers/api.js
T

407 lines
12 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.
import {
getUserIdFromLocalStorage,
redirectToExpiredLogin,
showError,
formatMessageForAPI,
isValidMessage,
stripHistoryAttachments,
} from './utils';
import axios from 'axios';
import i18next from 'i18next';
import { MESSAGE_ROLES } from '../constants/playground.constants';
import { getServerURL } from './config';
import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
import {
DEFAULT_READ_TIMEOUT_MS,
installRequestLifecycle,
} from './requestLifecycle';
function createAPIInstance() {
const serverURL = getServerURL();
return axios.create({
baseURL: serverURL,
withCredentials: serverURL !== '',
// Let the lifecycle apply a read default while preserving explicit timeouts.
timeout: null,
headers: {
'Cache-Control': 'no-store',
},
});
}
export let API;
let retireAPI;
function patchAPIInstance(instance) {
const originalGet = instance.get.bind(instance);
const inFlightGetRequests = new Map();
instance.get = (url, config = {}) => {
if (
config?.disableDuplicate ||
config?.signal ||
config?.cancelToken ||
config?.requestGroup
) {
return originalGet(url, config);
}
const fallbackOrgId =
url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
? localStorage.getItem('current_org_id') || ''
: '';
const requestKey = buildGetRequestKey(
url,
config,
fallbackOrgId,
getUserIdFromLocalStorage(),
);
const timeout =
config?.timeout ?? instance.defaults.timeout ?? DEFAULT_READ_TIMEOUT_MS;
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}#timeout=${timeout}`;
if (inFlightGetRequests.has(key)) {
return inFlightGetRequests.get(key);
}
const reqPromise = originalGet(url, config).finally(() => {
inFlightGetRequests.delete(key);
});
inFlightGetRequests.set(key, reqPromise);
return reqPromise;
};
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
function addOrgHeaderInterceptor(instance) {
instance.interceptors.request.use((config) => {
config.headers['New-API-User'] = getUserIdFromLocalStorage();
if (config.url && config.url.startsWith('/api/org/')) {
const explicitOrgId = getHeaderValue(config.headers, 'X-Org-Id');
const orgId = explicitOrgId || localStorage.getItem('current_org_id');
if (orgId && !explicitOrgId) {
config.headers['X-Org-Id'] = orgId;
}
}
return config;
});
}
export function updateAPI() {
const instance = createAPIInstance();
patchAPIInstance(instance);
addOrgHeaderInterceptor(instance);
const previous = retireAPI;
retireAPI = installRequestLifecycle(instance, {
onError: (error) => showError(error, { redirectOnUnauthorized: false }),
onSessionExpired: redirectToExpiredLogin,
});
API = instance;
previous?.();
}
updateAPI();
// playground
// 构建API请求负载
export const buildApiPayload = (
messages,
systemPrompt,
inputs,
parameterEnabled,
) => {
// 剥离历史轮的文件/图片附件:只把最后一条 user 消息的附件发给上游,
// 之前轮的文件已经在历史 assistant 回复里被"消化"过,再重发只是浪费 token,
// 还会因 COS 私有桶预签名 URL 过期导致上游报"failed to fetch file"。
const processedMessages = stripHistoryAttachments(
messages.filter(isValidMessage).map(formatMessageForAPI).filter(Boolean),
);
// 如果有系统提示,插入到消息开头
if (systemPrompt && systemPrompt.trim()) {
processedMessages.unshift({
role: MESSAGE_ROLES.SYSTEM,
content: systemPrompt.trim(),
});
}
const payload = {
model: inputs.model,
group: inputs.group,
messages: processedMessages,
stream: inputs.stream,
};
if (inputs.source) {
payload.source = inputs.source;
}
if (inputs.conversation_id) {
payload.conversation_id = inputs.conversation_id;
}
// 联网搜索
if (inputs.enableWebSearch) {
payload.enable_web_search = true;
}
// 添加启用的参数
const parameterMappings = {
temperature: 'temperature',
top_p: 'top_p',
max_tokens: 'max_tokens',
frequency_penalty: 'frequency_penalty',
presence_penalty: 'presence_penalty',
seed: 'seed',
};
Object.entries(parameterMappings).forEach(([key, param]) => {
const enabled = parameterEnabled[key];
const value = inputs[param];
const hasValue = value !== undefined && value !== null;
if (enabled && hasValue) {
payload[param] = value;
}
});
return payload;
};
// 从上游响应体里提取用户可读的错误文案。
// 后端 / 上游模型常以 OpenAI 兼容格式返回 `{"error":{"message":"..."}}`,
// 也可能是纯字符串、HTML、空。我们尽量把"模型 / 适配器写的人类可读 message"挖出来。
//
// 返回值约定:
// - 成功提取到 message 或拿到纯文本 → 返回该字符串
// - body 为空 / JSON 合法但找不到任何已知 message 字段 → 返回 ''
// 调用方应据此回退到 "HTTP {status} 请求失败" 之类的通用文案,
// 而不是把原 JSON 字符串展示给用户
export const extractErrorMessage = (body) => {
if (body == null) return '';
const str = typeof body === 'string' ? body : String(body);
const trimmed = str.trim();
if (trimmed === '') return '';
// 优先尝试 JSON:OpenAI 兼容格式 `{"error":{"message":"...","code":"..."}}`
const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');
if (looksLikeJson) {
try {
const parsed = JSON.parse(trimmed);
// 各种常见嵌套位置
const candidates = [
parsed?.error?.message,
parsed?.error?.error?.message,
parsed?.message,
typeof parsed?.error === 'string' ? parsed.error : null,
parsed?.error_msg,
];
for (const c of candidates) {
if (typeof c === 'string' && c.trim() !== '') return c.trim();
}
// JSON 合法但没有任何已知 message 字段 → 不向用户展示原 JSON
// (用户看不懂 `{"data":[]}` 这种东西,让调用方退回通用文案)
return '';
} catch {
// JSON 解析失败 — 不是合法 JSON 就当文本
}
}
// 纯文本(HTML / plain message):截断 500 字符直接返回
return trimmed.length > 500 ? trimmed.slice(0, 500) + '…' : trimmed;
};
// 处理API错误响应
export const handleApiError = (error, response = null) => {
const errorInfo = {
error: error.message || i18next.t('未知错误'),
timestamp: new Date().toISOString(),
stack: error.stack,
};
if (response) {
errorInfo.status = response.status;
errorInfo.statusText = response.statusText;
}
if (error.message.includes('HTTP error')) {
errorInfo.details = i18next.t('服务器返回了错误状态码');
} else if (error.message.includes('Failed to fetch')) {
errorInfo.details = i18next.t('网络连接失败或服务器无响应');
}
return errorInfo;
};
// 处理模型数据
export const processModelsData = (data, currentModel, levelStates = {}) => {
// levelStates(§6.2):后端已剔除 hidden,仅 visible 需锁定(不可选中提交)。
const modelOptions = data.map((model) => {
const locked = levelStates?.[model] === 'visible';
return {
label: model,
value: model,
disabled: locked,
level_locked: locked,
};
});
const hasCurrentModel = modelOptions.some(
(option) => option.value === currentModel && !option.level_locked,
);
// 自动选中首个「可调用」模型,避免默认落在锁定模型上
const firstCallable = modelOptions.find((o) => !o.level_locked);
const selectedModel = hasCurrentModel
? currentModel
: firstCallable?.value || '';
return { modelOptions, selectedModel };
};
// 处理分组数据
export const processGroupsData = (data, userGroup) => {
let groupOptions = Object.entries(data).map(([group, info]) => {
const desc = info?.desc || '';
return {
label: group,
value: group,
ratio: info?.ratio,
description: desc.length > 20 ? desc.substring(0, 20) + '...' : desc,
fullLabel: desc,
};
});
if (groupOptions.length === 0) {
groupOptions = [
{
label: i18next.t('用户分组'),
value: '',
ratio: 1,
},
];
} else if (userGroup) {
const userGroupIndex = groupOptions.findIndex((g) => g.value === userGroup);
if (userGroupIndex > -1) {
const userGroupOption = groupOptions.splice(userGroupIndex, 1)[0];
groupOptions.unshift(userGroupOption);
}
}
return groupOptions;
};
export async function getOAuthState() {
let path = '/api/oauth/state';
let affCode = localStorage.getItem('aff');
if (affCode && affCode.length > 0) {
path += `?aff=${affCode}`;
}
const res = await API.get(path);
const { success, message, data } = res.data;
if (success) {
return data;
} else {
showError(message);
return '';
}
}
export async function onDiscordOAuthClicked(client_id) {
const state = await getOAuthState();
if (!state) return false;
const redirect_uri = `${window.location.origin}/oauth/discord`;
const response_type = 'code';
const scope = 'identify+openid';
window.open(
`https://discord.com/oauth2/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`,
);
return true;
}
export async function onOIDCClicked(auth_url, client_id, openInNewTab = false) {
const state = await getOAuthState();
if (!state) return false;
const url = new URL(auth_url);
url.searchParams.set('client_id', client_id);
url.searchParams.set('redirect_uri', `${window.location.origin}/oauth/oidc`);
url.searchParams.set('response_type', 'code');
url.searchParams.set('scope', 'openid profile email');
url.searchParams.set('state', state);
if (openInNewTab) {
window.open(url.toString(), '_blank');
} else {
window.location.href = url.toString();
}
return true;
}
export async function onGitHubOAuthClicked(github_client_id) {
const state = await getOAuthState();
if (!state) return false;
window.open(
`https://github.com/login/oauth/authorize?client_id=${github_client_id}&state=${state}&scope=user:email`,
);
return true;
}
export async function onLinuxDOOAuthClicked(linuxdo_client_id) {
const state = await getOAuthState();
if (!state) return false;
window.open(
`https://connect.linux.do/oauth2/authorize?response_type=code&client_id=${linuxdo_client_id}&state=${state}`,
);
return true;
}
export async function onWeChatOpenOAuthClicked(wechat_open_app_id) {
const state = await getOAuthState();
if (!state) return false;
const redirect_uri = encodeURIComponent(
`${window.location.origin}/oauth/wechat-open`,
);
window.location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=${wechat_open_app_id}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`;
return true;
}
// 微信公众号网页授权(移动端微信浏览器内直接授权登录,无需扫码)
export async function onWeChatMPOAuthClicked(wechat_mp_app_id) {
const state = await getOAuthState();
if (!state) return false;
const redirect_uri = encodeURIComponent(
`${window.location.origin}/oauth/wechat-mp`,
);
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechat_mp_app_id}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
return true;
}
let channelModels = undefined;
export async function loadChannelModels() {
const res = await API.get('/api/models');
const { success, data } = res.data;
if (!success) {
return;
}
channelModels = data;
localStorage.setItem('channel_models', JSON.stringify(data));
}
export function getChannelModels(type) {
if (channelModels !== undefined && type in channelModels) {
if (!channelModels[type]) {
return [];
}
return channelModels[type];
}
let models = localStorage.getItem('channel_models');
if (!models) {
return [];
}
channelModels = JSON.parse(models);
if (type in channelModels) {
return channelModels[type];
}
return [];
}