2023-12-28 02:21:47 +01:00
|
|
|
const { chatPrompt } = require("../../chats");
|
2023-12-28 22:59:47 +01:00
|
|
|
const { StringOutputParser } = require("langchain/schema/output_parser");
|
2023-12-28 02:21:47 +01:00
|
|
|
|
|
|
|
// Docs: https://github.com/jmorganca/ollama/blob/main/docs/api.md
|
|
|
|
class OllamaAILLM {
|
2024-01-17 21:59:25 +01:00
|
|
|
constructor(embedder = null, modelPreference = null) {
|
2023-12-28 02:21:47 +01:00
|
|
|
if (!process.env.OLLAMA_BASE_PATH)
|
|
|
|
throw new Error("No Ollama Base Path was set.");
|
|
|
|
|
|
|
|
this.basePath = process.env.OLLAMA_BASE_PATH;
|
2024-01-17 21:59:25 +01:00
|
|
|
this.model = modelPreference || process.env.OLLAMA_MODEL_PREF;
|
2023-12-28 02:21:47 +01:00
|
|
|
this.limits = {
|
|
|
|
history: this.promptWindowLimit() * 0.15,
|
|
|
|
system: this.promptWindowLimit() * 0.15,
|
|
|
|
user: this.promptWindowLimit() * 0.7,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!embedder)
|
|
|
|
throw new Error(
|
|
|
|
"INVALID OLLAMA SETUP. No embedding engine has been set. Go to instance settings and set up an embedding interface to use Ollama as your LLM."
|
|
|
|
);
|
|
|
|
this.embedder = embedder;
|
2024-01-17 23:42:05 +01:00
|
|
|
this.defaultTemp = 0.7;
|
2023-12-28 02:21:47 +01:00
|
|
|
}
|
|
|
|
|
2023-12-28 22:59:47 +01:00
|
|
|
#ollamaClient({ temperature = 0.07 }) {
|
|
|
|
const { ChatOllama } = require("langchain/chat_models/ollama");
|
|
|
|
return new ChatOllama({
|
|
|
|
baseUrl: this.basePath,
|
|
|
|
model: this.model,
|
|
|
|
temperature,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// For streaming we use Langchain's wrapper to handle weird chunks
|
|
|
|
// or otherwise absorb headaches that can arise from Ollama models
|
|
|
|
#convertToLangchainPrototypes(chats = []) {
|
|
|
|
const {
|
|
|
|
HumanMessage,
|
|
|
|
SystemMessage,
|
|
|
|
AIMessage,
|
|
|
|
} = require("langchain/schema");
|
|
|
|
const langchainChats = [];
|
2023-12-28 23:42:34 +01:00
|
|
|
const roleToMessageMap = {
|
|
|
|
system: SystemMessage,
|
|
|
|
user: HumanMessage,
|
|
|
|
assistant: AIMessage,
|
|
|
|
};
|
|
|
|
|
2023-12-28 22:59:47 +01:00
|
|
|
for (const chat of chats) {
|
2023-12-28 23:42:34 +01:00
|
|
|
if (!roleToMessageMap.hasOwnProperty(chat.role)) continue;
|
|
|
|
const MessageClass = roleToMessageMap[chat.role];
|
|
|
|
langchainChats.push(new MessageClass({ content: chat.content }));
|
2023-12-28 22:59:47 +01:00
|
|
|
}
|
2023-12-28 23:42:34 +01:00
|
|
|
|
2023-12-28 22:59:47 +01:00
|
|
|
return langchainChats;
|
|
|
|
}
|
|
|
|
|
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-12-28 02:21:47 +01:00
|
|
|
streamingEnabled() {
|
|
|
|
return "streamChat" in this && "streamGetChatCompletion" in this;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure the user set a value for the token limit
|
|
|
|
// and if undefined - assume 4096 window.
|
|
|
|
promptWindowLimit() {
|
|
|
|
const limit = process.env.OLLAMA_MODEL_TOKEN_LIMIT || 4096;
|
|
|
|
if (!limit || isNaN(Number(limit)))
|
|
|
|
throw new Error("No Ollama token context limit was set.");
|
|
|
|
return Number(limit);
|
|
|
|
}
|
|
|
|
|
|
|
|
async isValidChatCompletionModel(_ = "") {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
constructPrompt({
|
|
|
|
systemPrompt = "",
|
|
|
|
contextTexts = [],
|
|
|
|
chatHistory = [],
|
|
|
|
userPrompt = "",
|
|
|
|
}) {
|
|
|
|
const prompt = {
|
|
|
|
role: "system",
|
2023-12-28 23:42:34 +01:00
|
|
|
content: `${systemPrompt}${this.#appendContext(contextTexts)}`,
|
2023-12-28 02:21:47 +01:00
|
|
|
};
|
|
|
|
return [prompt, ...chatHistory, { role: "user", content: userPrompt }];
|
|
|
|
}
|
|
|
|
|
|
|
|
async isSafe(_input = "") {
|
|
|
|
// Not implemented so must be stubbed
|
|
|
|
return { safe: true, reasons: [] };
|
|
|
|
}
|
|
|
|
|
|
|
|
async sendChat(chatHistory = [], prompt, workspace = {}, rawHistory = []) {
|
2023-12-28 22:59:47 +01:00
|
|
|
const messages = await this.compressMessages(
|
|
|
|
{
|
|
|
|
systemPrompt: chatPrompt(workspace),
|
|
|
|
userPrompt: prompt,
|
|
|
|
chatHistory,
|
2023-12-28 02:21:47 +01:00
|
|
|
},
|
2023-12-28 22:59:47 +01:00
|
|
|
rawHistory
|
|
|
|
);
|
|
|
|
|
|
|
|
const model = this.#ollamaClient({
|
2024-01-17 23:42:05 +01:00
|
|
|
temperature: Number(workspace?.openAiTemp ?? this.defaultTemp),
|
2023-12-28 22:59:47 +01:00
|
|
|
});
|
|
|
|
const textResponse = await model
|
|
|
|
.pipe(new StringOutputParser())
|
|
|
|
.invoke(this.#convertToLangchainPrototypes(messages));
|
2023-12-28 02:21:47 +01:00
|
|
|
|
|
|
|
if (!textResponse.length)
|
|
|
|
throw new Error(`Ollama::sendChat text response was empty.`);
|
|
|
|
|
|
|
|
return textResponse;
|
|
|
|
}
|
|
|
|
|
|
|
|
async streamChat(chatHistory = [], prompt, workspace = {}, rawHistory = []) {
|
2023-12-28 22:59:47 +01:00
|
|
|
const messages = await this.compressMessages(
|
|
|
|
{
|
|
|
|
systemPrompt: chatPrompt(workspace),
|
|
|
|
userPrompt: prompt,
|
|
|
|
chatHistory,
|
2023-12-28 02:21:47 +01:00
|
|
|
},
|
2023-12-28 22:59:47 +01:00
|
|
|
rawHistory
|
|
|
|
);
|
2023-12-28 02:21:47 +01:00
|
|
|
|
2023-12-28 22:59:47 +01:00
|
|
|
const model = this.#ollamaClient({
|
2024-01-17 23:42:05 +01:00
|
|
|
temperature: Number(workspace?.openAiTemp ?? this.defaultTemp),
|
2023-12-28 22:59:47 +01:00
|
|
|
});
|
|
|
|
const stream = await model
|
|
|
|
.pipe(new StringOutputParser())
|
|
|
|
.stream(this.#convertToLangchainPrototypes(messages));
|
|
|
|
return stream;
|
2023-12-28 02:21:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async getChatCompletion(messages = null, { temperature = 0.7 }) {
|
2023-12-28 22:59:47 +01:00
|
|
|
const model = this.#ollamaClient({ temperature });
|
|
|
|
const textResponse = await model
|
|
|
|
.pipe(new StringOutputParser())
|
|
|
|
.invoke(this.#convertToLangchainPrototypes(messages));
|
2023-12-28 02:21:47 +01:00
|
|
|
|
|
|
|
if (!textResponse.length)
|
|
|
|
throw new Error(`Ollama::getChatCompletion text response was empty.`);
|
|
|
|
|
|
|
|
return textResponse;
|
|
|
|
}
|
|
|
|
|
|
|
|
async streamGetChatCompletion(messages = null, { temperature = 0.7 }) {
|
2023-12-28 22:59:47 +01:00
|
|
|
const model = this.#ollamaClient({ temperature });
|
|
|
|
const stream = await model
|
|
|
|
.pipe(new StringOutputParser())
|
|
|
|
.stream(this.#convertToLangchainPrototypes(messages));
|
|
|
|
return stream;
|
2023-12-28 02:21:47 +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);
|
|
|
|
}
|
|
|
|
|
|
|
|
async compressMessages(promptArgs = {}, rawHistory = []) {
|
|
|
|
const { messageArrayCompressor } = require("../../helpers/chat");
|
|
|
|
const messageArray = this.constructPrompt(promptArgs);
|
|
|
|
return await messageArrayCompressor(this, messageArray, rawHistory);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
OllamaAILLM,
|
|
|
|
};
|