/** * AI 文本生成 - API 路由 * 简单的 AI 文本生成,用户输入主题,直接调用 AI 生成内容 */ import Router from '@koa/router'; import { Context } from 'koa'; import { callLLM } from '../../services/llm'; const router = new Router(); /** * POST /api/book-generator/ai-generate * AI 生成文本内容 */ router.post('/ai-generate', async (ctx: Context) => { try { const body = ctx.request.body as { topic: string; type?: string; // 'article' | 'story' | 'summary' length?: 'short' | 'medium' | 'long'; // 'short' ~500字, 'medium' ~1000字, 'long' ~2000字 }; if (!body.topic || body.topic.trim().length === 0) { ctx.status = 400; ctx.body = { code: 1, message: '请输入主题' }; return; } const topic = body.topic.trim(); const length = body.length || 'medium'; // 根据长度设置字数要求 const lengthConfig = { short: { words: '500-800', desc: '简短精炼' }, medium: { words: '1000-1500', desc: '中等长度' }, long: { words: '2000-3000', desc: '详细深入' }, }; const config = lengthConfig[length as keyof typeof lengthConfig]; // 构建 prompt const prompt = `请为"${topic}"主题写一篇${config.desc}的文章。 要求: 1. 字数:约${config.words}字 2. 内容要有深度,逻辑清晰 3. 语言流畅自然 4. 直接输出正文,不要有标题和额外说明 请直接输出文章内容:`; console.log(`[AI Generate] 主题: ${topic}, 长度: ${length}`); // 异步调用 AI const generateContent = async () => { try { const content = await callLLM(prompt); console.log(`[AI Generate] 生成完成,字数: ${content.length}`); return { success: true, content, wordCount: content.length }; } catch (error: any) { console.error('[AI Generate] 生成失败:', error); return { success: false, error: error.message || '生成失败' }; } }; // 异步执行,不阻塞 const resultPromise = generateContent(); // 先返回任务ID const taskId = `ai_${Date.now()}`; // 异步处理结果(不等待) resultPromise.then(result => { // 可以在这里存储结果或发送通知 console.log(`[AI Generate] 任务 ${taskId} 完成:`, result.success ? '成功' : '失败'); }); ctx.body = { code: 0, message: 'AI 生成任务已启动', data: { taskId, topic, status: 'started', }, }; } catch (error) { console.error('[AI Generate] 启动失败:', error); ctx.status = 500; ctx.body = { code: 1, message: error instanceof Error ? error.message : '启动失败', }; } }); /** * POST /api/book-generator/ai-generate/sync * AI 同步生成文本内容(等待结果) */ router.post('/ai-generate/sync', async (ctx: Context) => { try { const body = ctx.request.body as { topic: string; }; if (!body.topic || body.topic.trim().length === 0) { ctx.status = 400; ctx.body = { code: 1, message: '请输入主题' }; return; } const topic = body.topic.trim(); // 构建 prompt - 根据用户输入生成内容 const prompt = `${topic} 请根据上面的要求生成内容,要求: 1. 内容要有深度,逻辑清晰,论述完整 2. 语言流畅自然 3. 直接输出正文,不要有标题和其他说明 请直接输出内容:`; console.log(`[AI Generate Sync] 主题: ${topic}`); // 同步调用 AI const content = await callLLM(prompt); console.log(`[AI Generate Sync] 生成完成,字数: ${content.length}`); ctx.body = { code: 0, message: '生成成功', data: { topic, content, wordCount: content.length, }, }; } catch (error: any) { console.error('[AI Generate Sync] 生成失败:', error); ctx.status = 500; ctx.body = { code: 1, message: error.message || '生成失败,请稍后重试', }; } }); export default router;