2024-05-17 02:25:05 +02:00
|
|
|
const { NativeEmbedder } = require("../../EmbeddingEngines/native");
|
2024-03-12 23:21:27 +01:00
|
|
|
const {
|
|
|
|
writeResponseChunk,
|
|
|
|
clientAbortedHandler,
|
|
|
|
} = require("../../helpers/chat/responses");
|
2023-08-22 19:23:29 +02:00
|
|
|
|
2023-11-17 00:19:49 +01:00
|
|
|
class AzureOpenAiLLM {
|
2024-10-16 00:24:44 +02:00
|
|
|
constructor(embedder = null, modelPreference = null) {
|
2023-08-04 23:56:27 +02:00
|
|
|
const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
|
2023-10-30 23:44:03 +01:00
|
|
|
if (!process.env.AZURE_OPENAI_ENDPOINT)
|
|
|
|
throw new Error("No Azure API endpoint was set.");
|
|
|
|
if (!process.env.AZURE_OPENAI_KEY)
|
|
|
|
throw new Error("No Azure API key was set.");
|
|
|
|
|
|
|
|
this.openai = new OpenAIClient(
|
2023-08-04 23:56:27 +02:00
|
|
|
process.env.AZURE_OPENAI_ENDPOINT,
|
|
|
|
new AzureKeyCredential(process.env.AZURE_OPENAI_KEY)
|
|
|
|
);
|
2024-10-16 00:24:44 +02:00
|
|
|
this.model = modelPreference ?? process.env.OPEN_MODEL_PREF;
|
2023-11-06 22:13:53 +01:00
|
|
|
this.limits = {
|
|
|
|
history: this.promptWindowLimit() * 0.15,
|
|
|
|
system: this.promptWindowLimit() * 0.15,
|
|
|
|
user: this.promptWindowLimit() * 0.7,
|
|
|
|
};
|
2023-11-17 00:19:49 +01:00
|
|
|
|
2024-05-17 02:25:05 +02:00
|
|
|
this.embedder = embedder ?? new NativeEmbedder();
|
2024-01-17 23:42:05 +01:00
|
|
|
this.defaultTemp = 0.7;
|
2023-11-06 22:13:53 +01:00
|
|
|
}
|
|
|
|
|
2023-12-28 23:42:34 +01:00
|
|
|
#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("")
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-11-14 00:07:30 +01:00
|
|
|
streamingEnabled() {
|
2024-05-02 01:52:28 +02:00
|
|
|
return "streamGetChatCompletion" in this;
|
2023-11-14 00:07:30 +01:00
|
|
|
}
|
|
|
|
|
2024-08-15 21:13:28 +02:00
|
|
|
static promptWindowLimit(_modelName) {
|
|
|
|
return !!process.env.AZURE_OPENAI_TOKEN_LIMIT
|
|
|
|
? Number(process.env.AZURE_OPENAI_TOKEN_LIMIT)
|
|
|
|
: 4096;
|
|
|
|
}
|
|
|
|
|
2023-11-06 22:13:53 +01:00
|
|
|
// Sure the user selected a proper value for the token limit
|
|
|
|
// could be any of these https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models#gpt-4-models
|
|
|
|
// and if undefined - assume it is the lowest end.
|
|
|
|
promptWindowLimit() {
|
|
|
|
return !!process.env.AZURE_OPENAI_TOKEN_LIMIT
|
|
|
|
? Number(process.env.AZURE_OPENAI_TOKEN_LIMIT)
|
|
|
|
: 4096;
|
2023-08-04 23:56:27 +02:00
|
|
|
}
|
|
|
|
|
2023-11-06 22:13:53 +01:00
|
|
|
isValidChatCompletionModel(_modelName = "") {
|
2023-08-04 23:56:27 +02:00
|
|
|
// The Azure user names their "models" as deployments and they can be any name
|
|
|
|
// so we rely on the user to put in the correct deployment as only they would
|
|
|
|
// know it.
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-08-26 23:35:42 +02:00
|
|
|
/**
|
|
|
|
* Generates appropriate content array for a message + attachments.
|
|
|
|
* @param {{userPrompt:string, attachments: import("../../helpers").Attachment[]}}
|
|
|
|
* @returns {string|object[]}
|
|
|
|
*/
|
|
|
|
#generateContent({ userPrompt, attachments = [] }) {
|
|
|
|
if (!attachments.length) {
|
|
|
|
return userPrompt;
|
|
|
|
}
|
|
|
|
|
|
|
|
const content = [{ type: "text", text: userPrompt }];
|
|
|
|
for (let attachment of attachments) {
|
|
|
|
content.push({
|
|
|
|
type: "image_url",
|
|
|
|
imageUrl: {
|
|
|
|
url: attachment.contentString,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return content.flat();
|
|
|
|
}
|
|
|
|
|
2023-10-30 23:44:03 +01:00
|
|
|
constructPrompt({
|
|
|
|
systemPrompt = "",
|
|
|
|
contextTexts = [],
|
|
|
|
chatHistory = [],
|
|
|
|
userPrompt = "",
|
2024-08-26 23:35:42 +02:00
|
|
|
attachments = [], // This is the specific attachment for only this prompt
|
2023-10-30 23:44:03 +01:00
|
|
|
}) {
|
|
|
|
const prompt = {
|
|
|
|
role: "system",
|
2023-12-28 23:42:34 +01:00
|
|
|
content: `${systemPrompt}${this.#appendContext(contextTexts)}`,
|
2023-10-30 23:44:03 +01:00
|
|
|
};
|
2024-08-26 23:35:42 +02:00
|
|
|
return [
|
|
|
|
prompt,
|
|
|
|
...chatHistory,
|
|
|
|
{
|
|
|
|
role: "user",
|
|
|
|
content: this.#generateContent({ userPrompt, attachments }),
|
|
|
|
},
|
|
|
|
];
|
2023-10-30 23:44:03 +01:00
|
|
|
}
|
|
|
|
|
2023-08-04 23:56:27 +02:00
|
|
|
async getChatCompletion(messages = [], { temperature = 0.7 }) {
|
2023-11-06 22:13:53 +01:00
|
|
|
if (!this.model)
|
2023-08-04 23:56:27 +02:00
|
|
|
throw new Error(
|
|
|
|
"No OPEN_MODEL_PREF ENV defined. This must the name of a deployment on your Azure account for an LLM chat model like GPT-3.5."
|
|
|
|
);
|
|
|
|
|
2023-11-06 22:13:53 +01:00
|
|
|
const data = await this.openai.getChatCompletions(this.model, messages, {
|
2023-08-04 23:56:27 +02:00
|
|
|
temperature,
|
|
|
|
});
|
|
|
|
if (!data.hasOwnProperty("choices")) return null;
|
|
|
|
return data.choices[0].message.content;
|
|
|
|
}
|
2023-11-06 22:13:53 +01:00
|
|
|
|
2024-01-04 01:25:39 +01:00
|
|
|
async streamGetChatCompletion(messages = [], { temperature = 0.7 }) {
|
|
|
|
if (!this.model)
|
|
|
|
throw new Error(
|
|
|
|
"No OPEN_MODEL_PREF ENV defined. This must the name of a deployment on your Azure account for an LLM chat model like GPT-3.5."
|
|
|
|
);
|
|
|
|
|
|
|
|
const stream = await this.openai.streamChatCompletions(
|
|
|
|
this.model,
|
|
|
|
messages,
|
|
|
|
{
|
|
|
|
temperature,
|
|
|
|
n: 1,
|
|
|
|
}
|
|
|
|
);
|
2024-02-07 17:15:14 +01:00
|
|
|
return stream;
|
|
|
|
}
|
|
|
|
|
|
|
|
handleStream(response, stream, responseProps) {
|
|
|
|
const { uuid = uuidv4(), sources = [] } = responseProps;
|
|
|
|
|
|
|
|
return new Promise(async (resolve) => {
|
|
|
|
let fullText = "";
|
2024-03-12 23:21:27 +01:00
|
|
|
|
|
|
|
// Establish listener to early-abort a streaming response
|
|
|
|
// in case things go sideways or the user does not like the response.
|
|
|
|
// We preserve the generated text but continue as if chat was completed
|
|
|
|
// to preserve previously generated content.
|
|
|
|
const handleAbort = () => clientAbortedHandler(resolve, fullText);
|
|
|
|
response.on("close", handleAbort);
|
|
|
|
|
2024-02-07 17:15:14 +01:00
|
|
|
for await (const event of stream) {
|
|
|
|
for (const choice of event.choices) {
|
|
|
|
const delta = choice.delta?.content;
|
|
|
|
if (!delta) continue;
|
|
|
|
fullText += delta;
|
|
|
|
writeResponseChunk(response, {
|
|
|
|
uuid,
|
|
|
|
sources: [],
|
|
|
|
type: "textResponseChunk",
|
|
|
|
textResponse: delta,
|
|
|
|
close: false,
|
|
|
|
error: false,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
writeResponseChunk(response, {
|
|
|
|
uuid,
|
|
|
|
sources,
|
|
|
|
type: "textResponseChunk",
|
|
|
|
textResponse: "",
|
|
|
|
close: true,
|
|
|
|
error: false,
|
|
|
|
});
|
2024-03-12 23:21:27 +01:00
|
|
|
response.removeListener("close", handleAbort);
|
2024-02-07 17:15:14 +01:00
|
|
|
resolve(fullText);
|
|
|
|
});
|
2024-01-04 01:25:39 +01:00
|
|
|
}
|
|
|
|
|
2023-11-17 00:19:49 +01: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);
|
|
|
|
}
|
|
|
|
|
2023-11-06 22:13:53 +01:00
|
|
|
async compressMessages(promptArgs = {}, rawHistory = []) {
|
|
|
|
const { messageArrayCompressor } = require("../../helpers/chat");
|
|
|
|
const messageArray = this.constructPrompt(promptArgs);
|
|
|
|
return await messageArrayCompressor(this, messageArray, rawHistory);
|
|
|
|
}
|
2023-08-04 23:56:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2023-10-30 23:44:03 +01:00
|
|
|
AzureOpenAiLLM,
|
2023-08-04 23:56:27 +02:00
|
|
|
};
|