anything-llm/server/utils/openAi/index.js

77 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-06-08 06:31:35 +02:00
const { Configuration, OpenAIApi } = require("openai");
2023-06-04 04:28:07 +02:00
class OpenAi {
constructor() {
2023-06-08 06:31:35 +02:00
const config = new Configuration({
apiKey: process.env.OPEN_AI_KEY,
2023-06-09 17:58:07 +02:00
// organization: "org-123xyz", // Optional
2023-06-08 06:31:35 +02:00
});
2023-06-04 04:28:07 +02:00
const openai = new OpenAIApi(config);
2023-06-08 06:31:35 +02:00
this.openai = openai;
2023-06-04 04:28:07 +02:00
}
2023-06-08 06:31:35 +02:00
isValidChatModel(modelName = "") {
const validModels = ["gpt-4", "gpt-3.5-turbo"];
return validModels.includes(modelName);
2023-06-04 04:28:07 +02:00
}
2023-06-08 06:31:35 +02:00
async isSafe(input = "") {
const { flagged = false, categories = {} } = await this.openai
.createModeration({ input })
2023-06-04 04:28:07 +02:00
.then((json) => {
const res = json.data;
2023-06-08 06:31:35 +02:00
if (!res.hasOwnProperty("results"))
throw new Error("OpenAI moderation: No results!");
if (res.results.length === 0)
throw new Error("OpenAI moderation: No results length!");
return res.results[0];
});
2023-06-04 04:28:07 +02:00
if (!flagged) return { safe: true, reasons: [] };
2023-06-08 06:31:35 +02:00
const reasons = Object.keys(categories)
.map((category) => {
const value = categories[category];
if (value === true) {
return category.replace("/", " or ");
} else {
return null;
}
})
.filter((reason) => !!reason);
2023-06-04 04:28:07 +02:00
2023-06-08 06:31:35 +02:00
return { safe: false, reasons };
2023-06-04 04:28:07 +02:00
}
async sendChat(chatHistory = [], prompt, workspace = {}) {
2023-06-08 06:31:35 +02:00
const model = process.env.OPEN_MODEL_PREF;
if (!this.isValidChatModel(model))
throw new Error(
`OpenAI chat: ${model} is not valid for chat completion!`
);
2023-06-04 04:28:07 +02:00
2023-06-08 06:31:35 +02:00
const textResponse = await this.openai
.createChatCompletion({
model,
temperature: Number(workspace?.openAiTemp ?? 0.7),
2023-06-08 06:31:35 +02:00
n: 1,
messages: [
{ role: "system", content: "" },
...chatHistory,
{ role: "user", content: prompt },
],
2023-06-04 04:28:07 +02:00
})
2023-06-08 06:31:35 +02:00
.then((json) => {
const res = json.data;
if (!res.hasOwnProperty("choices"))
throw new Error("OpenAI chat: No results!");
if (res.choices.length === 0)
throw new Error("OpenAI chat: No results length!");
return res.choices[0].message.content;
});
2023-06-04 04:28:07 +02:00
2023-06-08 06:31:35 +02:00
return textResponse;
2023-06-04 04:28:07 +02:00
}
}
module.exports = {
OpenAi,
};