const Router = require('@koa/router'); const ai = require('../controller/ai.controller'); const router = new Router({ prefix: '/ai' }); const request = require('../utils/request'); const util = require('../utils/util'); const qs = require('qs'); const bodyParser = require('koa-bodyparser'); const { chatStream } = require('../controller/ai.controller'); /** * 接口代理和大模型接入API接口 */ // 流式chat router.post('/stream', bodyParser(), chatStream); // 接口转发(get) router.get('/proxy', async (ctx) => handleProxy(ctx, 'get')); // 接口转发(post) router.post('/proxy', async (ctx) => handleProxy(ctx, 'post')); // 接口转发(put) router.put('/proxy', async (ctx) => handleProxy(ctx, 'put')); // 接口转发(patch) router.patch('/proxy', async (ctx) => handleProxy(ctx, 'patch')); // 接口转发(delete) router.delete('/proxy', async (ctx) => handleProxy(ctx, 'delete')); const handleProxy = async (ctx, method) => { try { const { query, body, headers: { host, origin, proxyapi, ...headers }, } = ctx.request; if (!proxyapi) { return util.fail(ctx, '接口请求地址不存在', 404); } let params = method === 'get' || method === 'delete' ? query : body; if (headers['content-type'] === 'application/x-www-form-urlencoded') { params = qs.stringify(params); } else { params = method === 'get' || method === 'delete' ? query : JSON.stringify(params || {}); } let response = null; if (method === 'get' || method === 'delete') { response = await request[method](proxyapi, { params, headers, }); } else { response = await request[method](proxyapi, params, { headers, }); } const { status, statusText, data } = response; for (let key in response.headers) { ctx.set(key, response.headers[key]); } if (status === 200) { ctx.body = data; } else { if (status === 401 || status === 405) { return util.fail(ctx, '接口请求方法错误', status); } if (status === 404) { return util.fail(ctx, '接口请求地址不存在', status); } util.fail(ctx, data || statusText, 500); } } catch (error) { // 根据错误类型设置状态码和错误信息 if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') { // 服务地址不存在或无法连接 ctx.status = 502; // Bad Gateway ctx.body = { message: '服务不可用或地址不存在', error: error.message, }; } else if (error.response) { // 如果错误是来自后端接口的响应 const { status, data } = error.response; ctx.status = status; // 设置状态码 ctx.body = data; // 设置响应体 } else if (error.request) { // 请求已发出,但没有收到响应 ctx.status = 504; // Gateway Timeout ctx.body = { message: '请求超时,未收到响应', error: error.message, }; } else { // 其他未知错误 ctx.status = 500; // Internal Server Error ctx.body = { message: '服务器内部错误', error: error.message, }; } } }; module.exports = router;