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

134 lines
3.7 KiB
JavaScript
Raw Normal View History

const { OpenAiEmbedder } = require("../../EmbeddingEngines/openAi");
class OpenAiLLM extends OpenAiEmbedder {
2023-06-03 19:28:07 -07:00
constructor() {
super();
const { Configuration, OpenAIApi } = require("openai");
if (!process.env.OPEN_AI_KEY) throw new Error("No OpenAI API key was set.");
2023-06-07 21:31:35 -07:00
const config = new Configuration({
apiKey: process.env.OPEN_AI_KEY,
});
this.openai = new OpenAIApi(config);
2023-06-03 19:28:07 -07:00
}
async isValidChatCompletionModel(modelName = "") {
2023-06-07 21:31:35 -07:00
const validModels = ["gpt-4", "gpt-3.5-turbo"];
const isPreset = validModels.some((model) => modelName === model);
if (isPreset) return true;
const model = await this.openai
.retrieveModel(modelName)
.then((res) => res.data)
.catch(() => null);
return !!model;
2023-06-03 19:28:07 -07:00
}
constructPrompt({
systemPrompt = "",
contextTexts = [],
chatHistory = [],
userPrompt = "",
}) {
const prompt = {
role: "system",
content: `${systemPrompt}
Context:
${contextTexts
.map((text, i) => {
return `[CONTEXT ${i}]:\n${text}\n[END CONTEXT ${i}]\n\n`;
})
.join("")}`,
};
return [prompt, ...chatHistory, { role: "user", content: userPrompt }];
}
2023-06-07 21:31:35 -07:00
async isSafe(input = "") {
const { flagged = false, categories = {} } = await this.openai
.createModeration({ input })
2023-06-03 19:28:07 -07:00
.then((json) => {
const res = json.data;
2023-06-07 21:31:35 -07: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];
})
.catch((error) => {
throw new Error(
`OpenAI::CreateModeration failed with: ${error.message}`
);
2023-06-07 21:31:35 -07:00
});
2023-06-03 19:28:07 -07:00
if (!flagged) return { safe: true, reasons: [] };
2023-06-07 21:31:35 -07: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-03 19:28:07 -07:00
2023-06-07 21:31:35 -07:00
return { safe: false, reasons };
2023-06-03 19:28:07 -07:00
}
async sendChat(chatHistory = [], prompt, workspace = {}) {
2023-06-07 21:31:35 -07:00
const model = process.env.OPEN_MODEL_PREF;
if (!(await this.isValidChatCompletionModel(model)))
2023-06-07 21:31:35 -07:00
throw new Error(
`OpenAI chat: ${model} is not valid for chat completion!`
);
2023-06-03 19:28:07 -07:00
2023-06-07 21:31:35 -07:00
const textResponse = await this.openai
.createChatCompletion({
model,
temperature: Number(workspace?.openAiTemp ?? 0.7),
2023-06-07 21:31:35 -07:00
n: 1,
messages: [
{ role: "system", content: "" },
...chatHistory,
{ role: "user", content: prompt },
],
2023-06-03 19:28:07 -07:00
})
2023-06-07 21:31:35 -07: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;
})
.catch((error) => {
throw new Error(
`OpenAI::createChatCompletion failed with: ${error.message}`
);
2023-06-07 21:31:35 -07:00
});
2023-06-03 19:28:07 -07:00
2023-06-07 21:31:35 -07:00
return textResponse;
2023-06-03 19:28:07 -07:00
}
async getChatCompletion(messages = null, { temperature = 0.7 }) {
const model = process.env.OPEN_MODEL_PREF || "gpt-3.5-turbo";
if (!(await this.isValidChatCompletionModel(model)))
throw new Error(
`OpenAI chat: ${model} is not valid for chat completion!`
);
const { data } = await this.openai.createChatCompletion({
model,
messages,
temperature,
});
if (!data.hasOwnProperty("choices")) return null;
return data.choices[0].message.content;
}
2023-06-03 19:28:07 -07:00
}
module.exports = {
OpenAiLLM,
2023-06-03 19:28:07 -07:00
};