| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- "use strict";
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- const router_1 = __importDefault(require("@koa/router"));
- const axios_1 = __importDefault(require("axios"));
- const config_1 = require("../../config");
- const router = new router_1.default();
- // 获取可用文本模型列表
- function getAvailableModels() {
- return config_1.config.models.getModelsByType('text').filter((m) => m.enabled !== false);
- }
- // 随机选择模型
- function getRandomModel() {
- const models = getAvailableModels();
- if (models.length === 0) {
- throw new Error('没有可用的文本模型');
- }
- return models[Math.floor(Math.random() * models.length)].id;
- }
- // AI 生成文本
- router.post('/generate', async (ctx) => {
- const { prompt, model } = ctx.request.body;
- if (!prompt || prompt.trim().length === 0) {
- ctx.status = 400;
- ctx.body = { code: 400, message: '请输入提示词' };
- return;
- }
- try {
- // 获取模型配置
- const modelId = model || getRandomModel();
- const modelConfig = config_1.config.models.getModel(modelId);
- if (!modelConfig) {
- ctx.status = 400;
- ctx.body = { code: 400, message: `模型 ${modelId} 不存在` };
- return;
- }
- const { apiKey, baseUrl } = modelConfig;
- if (!apiKey || !baseUrl) {
- ctx.status = 500;
- ctx.body = { code: 500, message: `模型 ${modelId} 缺少 API 配置` };
- return;
- }
- console.log(`🤖 使用模型: ${modelId}, baseUrl: ${baseUrl}`);
- // 调用 OpenAI-compatible API
- const response = await axios_1.default.post(`${baseUrl}/chat/completions`, {
- model: modelId,
- messages: [{ role: 'user', content: prompt }],
- }, {
- headers: {
- 'Authorization': `Bearer ${apiKey}`,
- 'Content-Type': 'application/json',
- },
- timeout: 120000,
- });
- const data = response.data;
- // 提取生成的文本
- const generatedText = data.choices?.[0]?.message?.content || '';
- ctx.body = {
- code: 0,
- message: 'success',
- data: {
- text: generatedText,
- model: modelId,
- },
- };
- }
- catch (error) {
- console.error('❌ AI 生成失败:', error.response?.data || error.message);
- ctx.status = 500;
- ctx.body = {
- code: 500,
- message: error.message || 'AI 生成失败,请稍后重试',
- };
- }
- });
- // 获取可用模型列表
- router.get('/models', async (ctx) => {
- const models = getAvailableModels();
- ctx.body = {
- code: 0,
- message: 'success',
- data: {
- models: models.map((m) => ({ id: m.id, name: m.name })),
- default: config_1.config.models.textGeneration.defaultModel,
- },
- };
- });
- exports.default = router;
|