import { nanoid } from 'nanoid'; import { agent } from './agent.ts'; import { ai } from './ai.ts'; import { logger } from './logger.ts'; /** * 清除文本中的@信息 * @param text */ const clearAtInfo = (text: string = '') => { const newText = text.replace(/@[\u4e00-\u9fa5\w]+/g, '').replace(/#.*?#/g, ''); return newText.trim(); }; /** * 从文本中提取标签信息, 如 #标签 * @param text */ export const pickTagsInfo = (text: string = '') => { if (!text) { return { tags: [], text: '', }; } const _tags = text.match(/#([\u4e00-\u9fa5\w]+)/g) || []; const validTags = _tags.map((tag) => tag.replace(/#/g, '')).filter((tag) => tag.trim() !== ''); const noTagsText = text.replace(/#([\u4e00-\u9fa5\w]+)/g, '').trim(); return { tags: validTags, text: noTagsText, }; }; agent .route({ path: 'xhs', }) .define(async (ctx) => { const { text = '', note = '', hasNote } = ctx.query || {}; const id = nanoid(); const no_at_text = clearAtInfo(text); const pickNote = pickTagsInfo(note); const no_tags_text = pickNote.text; const some_text = no_at_text.length > 20 ? no_at_text.slice(0, 20) : no_at_text; const hasCmd = some_text.includes('指令'); if (hasCmd) { const analyzeRes = await agent.call({ path: 'analyze', key: 'cmd', payload: { text: no_at_text, }, }); if (analyzeRes.code === 200) { const cmd = analyzeRes.body?.cmd; if (cmd) { const res = await agent.call({ ...cmd.action, payload: { text: no_at_text, note: no_tags_text, hasNote: hasNote || false, }, }); ctx.body = res.body || ''; return; } } else { logger.error('指令分析错误:', analyzeRes.message); } } const resFix = await agent.call({ path: 'fix', key: 'xhs', payload: { text: no_at_text, }, }); if (resFix.code !== 200) { ctx.throw(500, 'AI 小红书prompt优化错误: ' + resFix.message); return; } else { console.log('小红书优化的文本', resFix.body); } const prompt_text = resFix.body || ''; const res = await ai .chat( [ { role: 'user', content: prompt_text, }, ], { // @ts-ignore enable_thinking: false, }, ) .catch((error) => { ctx.throw(500, 'AI 服务错误: ' + error.status); return error; }); ctx.body = res.choices?.[0]?.message?.content || ''; }) .addTo(agent);