Files
SupportBot/Events/Models/openai.js
T
2026-05-16 15:10:27 +01:00

67 lines
1.6 KiB
JavaScript

// Emerald Services | SupportBot
// Open AI integration for SupportBot AI
const fs = require("fs");
const yaml = require("js-yaml");
const OpenAI = require("openai");
const supportbotai = require("../../Structures/ConfigStore").supportbotAi;
const client = new OpenAI({
apiKey: supportbotai.General.Model_API_Key,
});
function extractTextFromMessage(message) {
if (!message) return "";
if (typeof message.content === "string") {
return message.content.trim();
}
if (Array.isArray(message.content)) {
return message.content
.map((part) => {
if (typeof part === "string") return part;
if (part?.type === "text" && typeof part.text === "string")
return part.text;
if (typeof part?.text?.value === "string") return part.text.value;
return "";
})
.join("")
.trim();
}
return "";
}
async function chat({ messages, temperature, maxTokens }) {
const model = supportbotai.General.Model;
const response = await client.chat.completions.create({
model,
messages,
temperature: temperature || supportbotai.General.Temperature || 0.4,
max_completion_tokens: maxTokens || supportbotai.General.Tokens || 800,
});
const choice = response?.choices?.[0];
const message = choice?.message;
const content = extractTextFromMessage(message);
if (!content) {
console.error("OpenAI raw response:", JSON.stringify(response, null, 2));
throw new Error(
`OpenAI returned empty response. finish_reason=${choice?.finish_reason || "unknown"}`,
);
}
return {
content,
raw: response,
};
}
module.exports = {
chat,
};