| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import Router from '@koa/router';
- import { Context } from 'koa';
- import axios from 'axios';
- import { config } from '../../config';
- const router = new Router();
- // AI 生成文本
- router.post('/generate', async (ctx: Context) => {
- const { prompt } = ctx.request.body as {
- prompt: string;
- };
- if (!prompt || prompt.trim().length === 0) {
- ctx.status = 400;
- ctx.body = { code: 400, message: '请输入提示词' };
- return;
- }
- try {
- // 使用阿里云 DashScope API 调用 Qwen 大模型
- const apiKey = config.dashscope.apiKey;
-
- if (!apiKey) {
- ctx.status = 500;
- ctx.body = { code: 500, message: '未配置 AI API Key' };
- return;
- }
- // 调用阿里云百炼文本生成 API
- const response = await axios.post(
- 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
- {
- model: 'qwen-turbo',
- input: {
- prompt: prompt,
- },
- parameters: {
- result_format: 'message',
- },
- },
- {
- headers: {
- 'Authorization': `Bearer ${apiKey}`,
- 'Content-Type': 'application/json',
- },
- timeout: 60000,
- }
- );
- const data = response.data;
- console.log('🤖 AI 响应:', JSON.stringify(data));
-
- if (data.code) {
- throw new Error(data.message || `AI 调用失败: ${data.code}`);
- }
- // 提取生成的文本
- const generatedText = data.output?.choices?.[0]?.message?.content || '';
-
- ctx.body = {
- code: 0,
- message: 'success',
- data: {
- text: generatedText,
- },
- };
- } catch (error: any) {
- console.error('❌ AI 生成失败:', error.response?.data || error.message);
- ctx.status = 500;
- ctx.body = {
- code: 500,
- message: error.message || 'AI 生成失败,请稍后重试',
- };
- }
- });
- export default router;
|