tmaiplugin
Version:
TrainingMaster AIGC Component
78 lines (75 loc) • 3.55 kB
text/typescript
import { CommentResult } from "./declare";
import { fixedJsonString } from "./util/stringutil";
import PluginBase from './aipluginbase'
const ROLE_DEFINE = ['你是一名专业的知识评论专家,擅长对知识问答提供非常有见底的分析,并给出结论',
'你是一位程序设计专家,特别擅长数据分析,内容组织并进行结构化设计,形成Json格式的数据']
const PROMPT: any = [
`根据以下知识提问内容以及回答结果进行分析,对回答结果内容进行的点评,给出一段不超过200字的评语,并按照100分制给出回答结果得分:
知识提问内容如下:"
{{QUESTION}}"
----
回答结果如下:"
{{ANSWER}}
"`,
`请将内容按照{"comment":"点评内容","score":"得分"}的标准Json结构输出。
内容如下:"
{{CONTENT}}
"`
]
/**
* 问答内容点评提插件
*/
export class CommentPlugin extends PluginBase {
/**
* 从指定的文本内容中生成相关的问答
* @param {*} content
* @param {*} count
* @param {*} axiosOption
* @returns
*///并在答案末尾处必须给出答案内容中的关键词
async execute(params: any): Promise<CommentResult> {
let { question, answer, axios } = params;
if (!this.gptInstance) return {successed:false};
if (!question || !answer) return { successed: false, error: { errcode: 2, errmsg: '缺失参数' } }
let message = [
{ role: 'system', content: ROLE_DEFINE[0] },
{ role: 'user', content: PROMPT[0].replace('{{QUESTION}}', question).replace('{{ANSWER}}',answer) },
]
console.log('Comment Message', message)
let result:any = await this.gptInstance.chatRequest(message, {}, axios);
///如果请求发生了网络错误(不是内容合规问题),则再重试一次,如果任然有错则放弃
if (!result.successed && result.error != 'content_filter') {
console.log('network error,retry onemore time')
result = await this.gptInstance.chatRequest(message, {}, axios);
}
if (result.successed && result.message) {
let answerString = result.message[0].message.content.trim().replace(/\t|\n|\v|\r|\f/g, '');
let orgJsonPrompt = [
{ role: 'system', content: ROLE_DEFINE[1] },
{ role: 'user', content: PROMPT[1].replace('{{CONTENT}}', answerString) }
]
console.log('orgJsonPrompt', orgJsonPrompt)
let fixedJsonResult: any = await this.gptInstance.chatRequest(orgJsonPrompt, { replyCounts: 1 }, {})
if (fixedJsonResult.successed) {
answerString = fixedJsonResult.message[0].message.content.trim().replace(/\t|\n|\v|\r|\f/g, '');
}
let jsonObj = fixedJsonResult.successed ? fixedJsonString(answerString) : [];
///能够提取到内容
if (jsonObj.length) return { successed: true, ...jsonObj[0] }
///回答的内容非JSON格式,自己来提取算了
console.log('自己组装')
let matched = answerString.match(/\d+分/g), score = 0;
if (matched && matched.length) {
score = Number(matched[0].replace('分', ''));
}
return { successed: true, comment: answerString, score }
}
return { successed: false };
}
}
/**
* 点评问题回答的评价
* @param question
* @param answer
* @param axiosOption
*/