2025.11.27.17.50

This commit is contained in:
RUI
2025-11-27 17:50:44 +08:00
commit 5dbb30b32c
111 changed files with 18320 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { SystemConfig } from '@/models';
import withDatabase from '@/lib/withDatabase';
import { requireAdmin } from '@/lib/auth';
async function handler(req: NextApiRequest, res: NextApiResponse, user: any) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}
const { endpoint, apiKey, assistantId } = req.body;
if (!endpoint) {
return res.status(400).json({ message: 'Endpoint is required' });
}
try {
let finalApiKey = apiKey;
// 如果没有提供 Key 但提供了 ID尝试从数据库获取
if (!finalApiKey && assistantId) {
const config = await SystemConfig.findOne().select('+AI配置列表.API密钥').lean();
if (config && config.AI配置列表) {
const assistant = config.AI配置列表.find((a: any) => a._id.toString() === assistantId);
if (assistant) {
finalApiKey = assistant.API密钥;
}
}
}
if (!finalApiKey) {
return res.status(400).json({ message: 'API Key is required' });
}
// 处理 Endpoint确保指向 /models
// 假设用户填写的 endpoint 是 base url (e.g. https://api.openai.com/v1)
// 或者完整的 chat url (e.g. https://api.openai.com/v1/chat/completions)
let baseUrl = endpoint.replace(/\/+$/, '');
if (baseUrl.endsWith('/chat/completions')) {
baseUrl = baseUrl.replace('/chat/completions', '');
}
const url = `${baseUrl}/models`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${finalApiKey}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorText = await response.text();
console.error('Fetch Models Error:', errorText);
return res.status(response.status).json({ message: `Provider Error: ${response.statusText}` });
}
const data = await response.json();
// OpenAI 格式返回 { data: [{ id: 'model-name', ... }] }
const models = data.data ? data.data.map((m: any) => m.id) : [];
return res.status(200).json({ models });
} catch (error) {
console.error('Fetch Models Internal Error:', error);
return res.status(500).json({ message: 'Internal Server Error' });
}
}
export default withDatabase(requireAdmin(handler));