mirror of
https://github.com/Jerryplusy/crystelf-plugin.git
synced 2026-01-29 09:17:27 +00:00
103 lines
2.7 KiB
JavaScript
103 lines
2.7 KiB
JavaScript
import OpenAI from 'openai';
|
|
|
|
class OpenaiChat {
|
|
constructor() {
|
|
this.openai = null;
|
|
}
|
|
|
|
/**
|
|
* @param apiKey 密钥
|
|
* @param baseUrl openaiAPI地址
|
|
*/
|
|
init(apiKey, baseUrl) {
|
|
this.openai = new OpenAI({
|
|
apiKey: apiKey,
|
|
baseURL: baseUrl,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param prompt 用户说的话
|
|
* @param chatHistory 聊天历史记录
|
|
* @param model 模型
|
|
* @param temperature 温度
|
|
* @param customPrompt 提示词
|
|
* @param messages 多模态消息数组
|
|
* @returns {Promise<{success: boolean, aiResponse: string}|{}>}
|
|
*/
|
|
async callAi({ prompt, chatHistory = [], model, temperature, customPrompt, messages = [] }) {
|
|
if (!this.openai) {
|
|
logger.error('[crystelf-ai] ai未初始化..');
|
|
return { success: false };
|
|
}
|
|
let finalMessages;
|
|
if (messages.length > 0) {
|
|
finalMessages = messages;
|
|
} else {
|
|
let systemMessage = {
|
|
role: 'system',
|
|
content: customPrompt || '',
|
|
};
|
|
finalMessages = [
|
|
systemMessage,
|
|
...chatHistory,
|
|
{
|
|
role: 'user',
|
|
content: prompt,
|
|
},
|
|
];
|
|
}
|
|
|
|
try {
|
|
// logger.info("[DEBUG] 请求体:", {
|
|
//model: model,
|
|
// messages: finalMessages,
|
|
//});
|
|
|
|
const completion = await this.openai.chat.completions.create({
|
|
messages: finalMessages,
|
|
model: model,
|
|
temperature: temperature,
|
|
frequency_penalty: 0.2,
|
|
presence_penalty: 0.2,
|
|
stream:false
|
|
});
|
|
let parsedCompletion = completion;
|
|
if (typeof completion === 'string') {
|
|
try {
|
|
parsedCompletion = JSON.parse(completion);
|
|
} catch (parseError) {
|
|
logger.error('[crystelf-ai] 响应JSON解析失败:', parseError);
|
|
return { success: false };
|
|
}
|
|
}
|
|
|
|
//logger.info("[DEBUG] 解析后的响应:", JSON.stringify(parsedCompletion));
|
|
let aiResponse = null;
|
|
|
|
if (parsedCompletion && parsedCompletion.choices && Array.isArray(parsedCompletion.choices) && parsedCompletion.choices.length > 0) {
|
|
const choice = parsedCompletion.choices[0];
|
|
if (choice && choice.message && choice.message.content) {
|
|
aiResponse = choice.message.content;
|
|
}
|
|
}
|
|
|
|
if (!aiResponse) {
|
|
logger.error('[crystelf-ai] 无法从响应中提取AI回复内容:', parsedCompletion);
|
|
return { success: false };
|
|
}
|
|
|
|
logger.info("[DEBUG] AI响应内容:", aiResponse);
|
|
return {
|
|
success: true,
|
|
aiResponse: aiResponse,
|
|
};
|
|
} catch (err) {
|
|
logger.error(err);
|
|
return { success: false };
|
|
}
|
|
}
|
|
}
|
|
|
|
export default OpenaiChat;
|