feat(parameter): Add summary by ChatGPT (#13611)

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* feat: 添加使用 ChatGPT 进行总结的功能

* style: camelCase

---------
This commit is contained in:
zzturn
2023-11-06 22:36:24 +08:00
committed by GitHub
parent f421736df4
commit e594309e7e
10 changed files with 187 additions and 0 deletions

View File

@@ -4,6 +4,10 @@ const { simplecc } = require('simplecc-wasm');
const got = require('@/utils/got');
const config = require('@/config').value;
const { RE2JS } = require('re2js');
const md = require('markdown-it')({
html: true,
});
const htmlToText = require('html-to-text');
let mercury_parser;
@@ -23,6 +27,26 @@ const resolveRelativeLink = ($, elem, attr, baseUrl) => {
}
};
const summarizeArticle = async (articleText) => {
const apiUrl = `${config.openai.endpoint}/chat/completions`;
const response = await got.post(apiUrl, {
json: {
model: config.openai.model,
max_tokens: config.openai.maxTokens,
messages: [
{ role: 'system', content: config.openai.prompt },
{ role: 'user', content: articleText },
],
temperature: config.openai.temperature,
},
headers: {
Authorization: `Bearer ${config.openai.apiKey}`,
},
});
return response.data.choices[0].message.content;
};
module.exports = async (ctx, next) => {
await next();
@@ -286,6 +310,33 @@ module.exports = async (ctx, next) => {
await Promise.all(tasks);
}
// openai
if (ctx.query.chatgpt && config.openai.apiKey) {
ctx.state.data.item = await Promise.all(
ctx.state.data.item.map(async (item) => {
if (item.description) {
try {
const summary = await ctx.cache.tryGet(`openai:${item.link}`, async () => {
const text = htmlToText.htmlToText(item.description);
if (text.length < 300) {
return '';
}
const summary_md = await summarizeArticle(text);
return md.render(summary_md);
});
// 将总结结果添加到文章数据中
if (summary !== '') {
item.description = summary + '<hr/><br/>' + item.description;
}
} catch (e) {
// when openai failed, return default description and not write cache
}
}
return item;
})
);
}
// scihub
if (ctx.query.scihub) {
ctx.state.data.item.map((item) => {