2024-04-23 22:06:07 +02:00
|
|
|
const { NativeEmbedder } = require("../../EmbeddingEngines/native");
|
2024-04-30 21:33:42 +02:00
|
|
|
const {
|
|
|
|
handleDefaultStreamResponseV2,
|
|
|
|
} = require("../../helpers/chat/responses");
|
2024-05-18 06:44:55 +02:00
|
|
|
const { toValidNumber } = require("../../http");
|
2024-04-23 22:06:07 +02:00
|
|
|
|
|
|
|
class GenericOpenAiLLM {
|
|
|
|
constructor(embedder = null, modelPreference = null) {
|
2024-04-30 21:33:42 +02:00
|
|
|
const { OpenAI: OpenAIApi } = require("openai");
|
2024-04-23 22:06:07 +02:00
|
|
|
if (!process.env.GENERIC_OPEN_AI_BASE_PATH)
|
|
|
|
throw new Error(
|
|
|
|
"GenericOpenAI must have a valid base path to use for the api."
|
|
|
|
);
|
|
|
|
|
|
|
|
this.basePath = process.env.GENERIC_OPEN_AI_BASE_PATH;
|
2024-04-30 21:33:42 +02:00
|
|
|
this.openai = new OpenAIApi({
|
|
|
|
baseURL: this.basePath,
|
2024-04-23 22:06:07 +02:00
|
|
|
apiKey: process.env.GENERIC_OPEN_AI_API_KEY ?? null,
|
|
|
|
});
|
|
|
|
this.model =
|
|
|
|
modelPreference ?? process.env.GENERIC_OPEN_AI_MODEL_PREF ?? null;
|
2024-05-18 06:44:55 +02:00
|
|
|
this.maxTokens = process.env.GENERIC_OPEN_AI_MAX_TOKENS
|
|
|
|
? toValidNumber(process.env.GENERIC_OPEN_AI_MAX_TOKENS, 1024)
|
|
|
|
: 1024;
|
2024-04-23 22:06:07 +02:00
|
|
|
if (!this.model)
|
|
|
|
throw new Error("GenericOpenAI must have a valid model set.");
|
|
|
|
this.limits = {
|
|
|
|
history: this.promptWindowLimit() * 0.15,
|
|
|
|
system: this.promptWindowLimit() * 0.15,
|
|
|
|
user: this.promptWindowLimit() * 0.7,
|
|
|
|
};
|
|
|
|
|
2024-05-17 02:25:05 +02:00
|
|
|
this.embedder = embedder ?? new NativeEmbedder();
|
2024-04-23 22:06:07 +02:00
|
|
|
this.defaultTemp = 0.7;
|
|
|
|
this.log(`Inference API: ${this.basePath} Model: ${this.model}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
log(text, ...args) {
|
|
|
|
console.log(`\x1b[36m[${this.constructor.name}]\x1b[0m ${text}`, ...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
#appendContext(contextTexts = []) {
|
|
|
|
if (!contextTexts || !contextTexts.length) return "";
|
|
|
|
return (
|
|
|
|
"\nContext:\n" +
|
|
|
|
contextTexts
|
|
|
|
.map((text, i) => {
|
|
|
|
return `[CONTEXT ${i}]:\n${text}\n[END CONTEXT ${i}]\n\n`;
|
|
|
|
})
|
|
|
|
.join("")
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
streamingEnabled() {
|
2024-05-02 01:52:28 +02:00
|
|
|
return "streamGetChatCompletion" in this;
|
2024-04-23 22:06:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure the user set a value for the token limit
|
|
|
|
// and if undefined - assume 4096 window.
|
|
|
|
promptWindowLimit() {
|
|
|
|
const limit = process.env.GENERIC_OPEN_AI_MODEL_TOKEN_LIMIT || 4096;
|
|
|
|
if (!limit || isNaN(Number(limit)))
|
|
|
|
throw new Error("No token context limit was set.");
|
|
|
|
return Number(limit);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Short circuit since we have no idea if the model is valid or not
|
|
|
|
// in pre-flight for generic endpoints
|
|
|
|
isValidChatCompletionModel(_modelName = "") {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
constructPrompt({
|
|
|
|
systemPrompt = "",
|
|
|
|
contextTexts = [],
|
|
|
|
chatHistory = [],
|
|
|
|
userPrompt = "",
|
|
|
|
}) {
|
|
|
|
const prompt = {
|
|
|
|
role: "system",
|
|
|
|
content: `${systemPrompt}${this.#appendContext(contextTexts)}`,
|
|
|
|
};
|
|
|
|
return [prompt, ...chatHistory, { role: "user", content: userPrompt }];
|
|
|
|
}
|
|
|
|
|
|
|
|
async isSafe(_input = "") {
|
|
|
|
// Not implemented so must be stubbed
|
|
|
|
return { safe: true, reasons: [] };
|
|
|
|
}
|
|
|
|
|
|
|
|
async getChatCompletion(messages = null, { temperature = 0.7 }) {
|
2024-04-30 21:33:42 +02:00
|
|
|
const result = await this.openai.chat.completions
|
|
|
|
.create({
|
2024-04-23 22:06:07 +02:00
|
|
|
model: this.model,
|
|
|
|
messages,
|
|
|
|
temperature,
|
2024-05-10 23:49:02 +02:00
|
|
|
max_tokens: this.maxTokens,
|
2024-04-23 22:06:07 +02:00
|
|
|
})
|
|
|
|
.catch((e) => {
|
|
|
|
throw new Error(e.response.data.error.message);
|
|
|
|
});
|
|
|
|
|
2024-04-30 21:33:42 +02:00
|
|
|
if (!result.hasOwnProperty("choices") || result.choices.length === 0)
|
|
|
|
return null;
|
|
|
|
return result.choices[0].message.content;
|
2024-04-23 22:06:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async streamGetChatCompletion(messages = null, { temperature = 0.7 }) {
|
2024-04-30 21:33:42 +02:00
|
|
|
const streamRequest = await this.openai.chat.completions.create({
|
|
|
|
model: this.model,
|
|
|
|
stream: true,
|
|
|
|
messages,
|
|
|
|
temperature,
|
2024-05-10 23:49:02 +02:00
|
|
|
max_tokens: this.maxTokens,
|
2024-04-30 21:33:42 +02:00
|
|
|
});
|
2024-04-23 22:06:07 +02:00
|
|
|
return streamRequest;
|
|
|
|
}
|
|
|
|
|
|
|
|
handleStream(response, stream, responseProps) {
|
2024-04-30 21:33:42 +02:00
|
|
|
return handleDefaultStreamResponseV2(response, stream, responseProps);
|
2024-04-23 22:06:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Simple wrapper for dynamic embedder & normalize interface for all LLM implementations
|
|
|
|
async embedTextInput(textInput) {
|
|
|
|
return await this.embedder.embedTextInput(textInput);
|
|
|
|
}
|
|
|
|
async embedChunks(textChunks = []) {
|
|
|
|
return await this.embedder.embedChunks(textChunks);
|
|
|
|
}
|
|
|
|
|
|
|
|
async compressMessages(promptArgs = {}, rawHistory = []) {
|
|
|
|
const { messageArrayCompressor } = require("../../helpers/chat");
|
|
|
|
const messageArray = this.constructPrompt(promptArgs);
|
|
|
|
return await messageArrayCompressor(this, messageArray, rawHistory);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
GenericOpenAiLLM,
|
|
|
|
};
|