hexo-ai-summary-liushen
Version:
Hexo 插件:使用 AI(如 ChatGPT 或腾讯混元)自动为 Markdown 博文生成摘要,并将摘要写入 front-matter,可控制并发请求。
63 lines (50 loc) • 1.74 kB
JavaScript
const fetch = require('node-fetch')
module.exports = async function ai(token, api, model, content, prompt) {
const url = api || 'https://api.openai.com/v1/chat/completions'
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
const body = {
model: model || 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: "所有摘要内容均不要换行,不要分段,不要分点,写在一段文本内即可!" + prompt },
{ role: 'user', content: content}
],
max_tokens: 300
}
try {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body)
})
if (!res.ok) {
const errText = await res.text()
throw new Error(`AI 请求失败 (${res.status}): ${errText}`)
}
const json = await res.json()
// 如果返回格式不正确,抛出错误
const reply = json.choices?.[0]?.message?.content?.trim()
if (!reply) {
throw new Error('OpenAI 返回的响应格式不正确')
}
// 后处理与校验
const cleaned = reply
.replace(/[\r\n]+/g, ' ') // 去换行
.replace(/\s+/g, ' ') // 合并多空格
.trim()
// 校验非法字符和最大长度
const illegalChars = /[#`]/g
if (cleaned.length > 500) {
console.info('[Hexo-AI-Summary-LiuShen] AI 返回摘要不符合格式要求(长度超限)')
}
if (cleaned.match(illegalChars)) {
console.info('[Hexo-AI-Summary-LiuShen] AI 返回摘要不符合格式要求(包含非法字符)')
}
return cleaned
} catch (error) {
// 捕获并抛出请求中的任何错误
throw new Error(`AI 请求失败: ${error.message}`)
}
}