code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async embedTextInput(textInput) {
return await this.embedder.embedTextInput(textInput);
} | Construct the user prompt for this model.
@param {{attachments: import("../../helpers").Attachment[]}} param0
@returns | embedTextInput | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/xai/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/xai/index.js | MIT |
async embedChunks(textChunks = []) {
return await this.embedder.embedChunks(textChunks);
} | Construct the user prompt for this model.
@param {{attachments: import("../../helpers").Attachment[]}} param0
@returns | embedChunks | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/xai/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/xai/index.js | MIT |
async compressMessages(promptArgs = {}, rawHistory = []) {
const { messageArrayCompressor } = require("../../helpers/chat");
const messageArray = this.constructPrompt(promptArgs);
return await messageArrayCompressor(this, messageArray, rawHistory);
} | Construct the user prompt for this model.
@param {{attachments: import("../../helpers").Attachment[]}} param0
@returns | compressMessages | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/xai/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/xai/index.js | MIT |
jobs() {
return [
// Job for auto-sync of documents
// https://github.com/breejs/bree
{
name: "sync-watched-documents",
interval: "1hr",
},
];
} | @returns {import("@mintplex-labs/bree").Job[]} | jobs | javascript | Mintplex-Labs/anything-llm | server/utils/BackgroundWorkers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/BackgroundWorkers/index.js | MIT |
onError(error, _workerMetadata) {
this.logger.error(`${error.message}`, {
service: "bg-worker",
origin: error.name,
});
} | @returns {import("@mintplex-labs/bree").Job[]} | onError | javascript | Mintplex-Labs/anything-llm | server/utils/BackgroundWorkers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/BackgroundWorkers/index.js | MIT |
onWorkerMessageHandler(message, _workerMetadata) {
this.logger.info(`${message.message}`, {
service: "bg-worker",
origin: message.name,
});
} | @returns {import("@mintplex-labs/bree").Job[]} | onWorkerMessageHandler | javascript | Mintplex-Labs/anything-llm | server/utils/BackgroundWorkers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/BackgroundWorkers/index.js | MIT |
clearConfig() {
this.#customConfig = null;
} | Clears the current config so it can be refetched on the server for next render. | clearConfig | javascript | Mintplex-Labs/anything-llm | server/utils/boot/MetaGenerator.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/boot/MetaGenerator.js | MIT |
async generate(response, code = 200) {
if (this.#customConfig === null) await this.#fetchConfg();
response.status(code).send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /... | @param {import('express').Response} response
@param {number} code | generate | javascript | Mintplex-Labs/anything-llm | server/utils/boot/MetaGenerator.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/boot/MetaGenerator.js | MIT |
async function chatSync({
workspace,
message = null,
mode = "chat",
user = null,
thread = null,
sessionId = null,
attachments = [],
reset = false,
}) {
const uuid = uuidv4();
const chatMode = mode ?? "chat";
// If the user wants to reset the chat history we do so pre-flight
// and continue exec... | Handle synchronous chats with your workspace via the developer API endpoint
@param {{
workspace: import("@prisma/client").workspaces,
message:string,
mode: "chat"|"query",
user: import("@prisma/client").users|null,
thread: import("@prisma/client").workspace_threads|null,
sessionId: string|null,
attachments: { na... | chatSync | javascript | Mintplex-Labs/anything-llm | server/utils/chats/apiChatHandler.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/apiChatHandler.js | MIT |
async function streamChat({
response,
workspace,
message = null,
mode = "chat",
user = null,
thread = null,
sessionId = null,
attachments = [],
reset = false,
}) {
const uuid = uuidv4();
const chatMode = mode ?? "chat";
// If the user wants to reset the chat history we do so pre-flight
// and... | Handle streamable HTTP chunks for chats with your workspace via the developer API endpoint
@param {{
response: import("express").Response,
workspace: import("@prisma/client").workspaces,
message:string,
mode: "chat"|"query",
user: import("@prisma/client").users|null,
thread: import("@prisma/client").workspace_thre... | streamChat | javascript | Mintplex-Labs/anything-llm | server/utils/chats/apiChatHandler.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/apiChatHandler.js | MIT |
async function grepAllSlashCommands(message) {
const allPresets = await SlashCommandPresets.where({});
// Replace all preset commands with their corresponding prompts
// Allows multiple commands in one message
let updatedMessage = message;
for (const preset of allPresets) {
const regex = new RegExp(
... | @description This function will do recursive replacement of all slash commands with their corresponding prompts.
@notice This function is used for API calls and is not user-scoped. THIS FUNCTION DOES NOT SUPPORT PRESET COMMANDS.
@returns {Promise<string>} | grepAllSlashCommands | javascript | Mintplex-Labs/anything-llm | server/utils/chats/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/index.js | MIT |
async function recentChatHistory({
user = null,
workspace,
thread = null,
messageLimit = 20,
apiSessionId = null,
}) {
const rawHistory = (
await WorkspaceChats.where(
{
workspaceId: workspace.id,
user_id: user?.id || null,
thread_id: thread?.id || null,
api_session... | @description This function will do recursive replacement of all slash commands with their corresponding prompts.
@notice This function is used for API calls and is not user-scoped. THIS FUNCTION DOES NOT SUPPORT PRESET COMMANDS.
@returns {Promise<string>} | recentChatHistory | javascript | Mintplex-Labs/anything-llm | server/utils/chats/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/index.js | MIT |
async function chatPrompt(workspace, user = null) {
const basePrompt =
workspace?.openAiPrompt ??
"Given the following conversation, relevant context, and a follow up question, reply with an answer to the current question the user is asking. Return only your response to the question given the above informatio... | Returns the base prompt for the chat. This method will also do variable
substitution on the prompt if there are any defined variables in the prompt.
@param {Object|null} workspace - the workspace object
@param {Object|null} user - the user object
@returns {Promise<string>} - the base prompt | chatPrompt | javascript | Mintplex-Labs/anything-llm | server/utils/chats/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/index.js | MIT |
function sourceIdentifier(sourceDocument) {
if (!sourceDocument?.title || !sourceDocument?.published) return uuidv4();
return `title:${sourceDocument.title}-timestamp:${sourceDocument.published}`;
} | Returns the base prompt for the chat. This method will also do variable
substitution on the prompt if there are any defined variables in the prompt.
@param {Object|null} workspace - the workspace object
@param {Object|null} user - the user object
@returns {Promise<string>} - the base prompt | sourceIdentifier | javascript | Mintplex-Labs/anything-llm | server/utils/chats/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/chats/index.js | MIT |
constructor() {
const { CommunicationKey } = require("../comKey");
this.comkey = new CommunicationKey();
this.endpoint = `http://0.0.0.0:${process.env.COLLECTOR_PORT || 8888}`;
} | @typedef {Object} CollectorOptions
@property {string} whisperProvider - The provider to use for whisper, defaults to "local"
@property {string} WhisperModelPref - The model to use for whisper if set.
@property {string} openAiKey - The API key to use for OpenAI interfacing, mostly passed to OAI Whisper provider.
@proper... | constructor | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
log(text, ...args) {
console.log(`\x1b[36m[CollectorApi]\x1b[0m ${text}`, ...args);
} | @typedef {Object} CollectorOptions
@property {string} whisperProvider - The provider to use for whisper, defaults to "local"
@property {string} WhisperModelPref - The model to use for whisper if set.
@property {string} openAiKey - The API key to use for OpenAI interfacing, mostly passed to OAI Whisper provider.
@proper... | log | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async online() {
return await fetch(this.endpoint)
.then((res) => res.ok)
.catch(() => false);
} | Attach options to the request passed to the collector API
@returns {CollectorOptions} | online | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async acceptedFileTypes() {
return await fetch(`${this.endpoint}/accepts`)
.then((res) => {
if (!res.ok) throw new Error("failed to GET /accepts");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return null;
});
} | Attach options to the request passed to the collector API
@returns {CollectorOptions} | acceptedFileTypes | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async processDocument(filename = "") {
if (!filename) return false;
const data = JSON.stringify({
filename,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/process`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Int... | Process a document
- Will append the options to the request body
@param {string} filename - The filename of the document to process
@returns {Promise<Object>} - The response from the collector API | processDocument | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async processLink(link = "", scraperHeaders = {}) {
if (!link) return false;
const data = JSON.stringify({
link,
scraperHeaders,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/process-link`, {
method: "POST",
headers: {
"Content-Type": "a... | Process a link
- Will append the options to the request body
@param {string} link - The link to process
@param {{[key: string]: string}} scraperHeaders - Custom headers to apply to the web-scraping request URL
@returns {Promise<Object>} - The response from the collector API | processLink | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async processRawText(textContent = "", metadata = {}) {
const data = JSON.stringify({
textContent,
metadata,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/process-raw-text`, {
method: "POST",
headers: {
"Content-Type": "application/json",
... | Process raw text as a document for the collector
- Will append the options to the request body
@param {string} textContent - The text to process
@param {Object} metadata - The metadata to process
@returns {Promise<Object>} - The response from the collector API | processRawText | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async forwardExtensionRequest({ endpoint, method, body }) {
return await fetch(`${this.endpoint}${endpoint}`, {
method,
body, // Stringified JSON!
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(body),
"X-Payload-Signer": this.comkey.encrypt(
... | Process raw text as a document for the collector
- Will append the options to the request body
@param {string} textContent - The text to process
@param {Object} metadata - The metadata to process
@returns {Promise<Object>} - The response from the collector API | forwardExtensionRequest | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async getLinkContent(link = "", captureAs = "text") {
if (!link) return false;
const data = JSON.stringify({
link,
captureAs,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/util/get-link`, {
method: "POST",
headers: {
"Content-Type": "appl... | Get the content of a link only in a specific format
- Will append the options to the request body
@param {string} link - The link to get the content of
@param {"text"|"html"} captureAs - The format to capture the content as
@returns {Promise<Object>} - The response from the collector API | getLinkContent | javascript | Mintplex-Labs/anything-llm | server/utils/collectorApi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/collectorApi/index.js | MIT |
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
} | Embeds a single text input
@param {string|string[]} textInput - The text to embed
@returns {Promise<Array<number>>} The embedding values | embedTextInput | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/gemini/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/gemini/index.js | MIT |
async embedChunks(textChunks = []) {
this.log(`Embedding ${textChunks.length} chunks...`);
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for mor... | Embeds a list of text inputs
@param {string[]} textChunks - The list of text to embed
@returns {Promise<Array<Array<number>>>} The embedding values | embedChunks | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/gemini/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/gemini/index.js | MIT |
get maxConcurrentChunks() {
if (!process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS)
return 500;
if (
isNaN(Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS))
)
return 500;
return Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS);
} | returns the `GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS` env variable as a number
or 500 if the env variable is not set or is not a number.
@returns {number} | maxConcurrentChunks | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/genericOpenAi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/genericOpenAi/index.js | MIT |
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
} | returns the `GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS` env variable as a number
or 500 if the env variable is not set or is not a number.
@returns {number} | embedTextInput | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/genericOpenAi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/genericOpenAi/index.js | MIT |
async embedChunks(textChunks = []) {
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const embeddingRequests = [];
for (const ch... | returns the `GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS` env variable as a number
or 500 if the env variable is not set or is not a number.
@returns {number} | embedChunks | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/genericOpenAi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/genericOpenAi/index.js | MIT |
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
} | Checks if the Ollama service is alive by pinging the base path.
@returns {Promise<boolean>} - A promise that resolves to true if the service is alive, false otherwise. | embedTextInput | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/ollama/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/ollama/index.js | MIT |
async embedChunks(textChunks = []) {
if (!(await this.#isAlive()))
throw new Error(
`Ollama service could not be reached. Is Ollama running?`
);
this.log(
`Embedding ${textChunks.length} chunks of text with ${this.model}.`
);
let data = [];
let error = null;
for (cons... | This function takes an array of text chunks and embeds them using the Ollama API.
chunks are processed sequentially to avoid overwhelming the API with too many requests
or running out of resources on the endpoint running the ollama instance.
We will use the num_ctx option to set the maximum context window to the max c... | embedChunks | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingEngines/ollama/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingEngines/ollama/index.js | MIT |
get host() {
if (!NativeEmbeddingReranker.#transformers) return "https://huggingface.co";
try {
return new URL(NativeEmbeddingReranker.#transformers.env.remoteHost).host;
} catch (e) {
return this.#fallbackHost;
}
} | This function will return the host of the current reranker suite.
If the reranker suite is not initialized, it will return the default HF host.
@returns {string} The host of the current reranker suite. | host | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingRerankers/native/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingRerankers/native/index.js | MIT |
async preload() {
try {
this.log(`Preloading reranker suite...`);
await this.initClient();
this.log(
`Preloaded reranker suite. Reranking is available as a service now.`
);
return;
} catch (e) {
console.error(e);
this.log(
`Failed to preload reranker sui... | This function will preload the reranker suite and tokenizer.
This is useful for reducing the latency of the first rerank call and pre-downloading the models and such
to avoid having to wait for the models to download on the first rerank call. | preload | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingRerankers/native/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingRerankers/native/index.js | MIT |
async initClient() {
if (NativeEmbeddingReranker.#transformers) {
this.log(`Reranker suite already initialized - reusing.`);
return;
}
await import("@xenova/transformers").then(
async ({ AutoModelForSequenceClassification, AutoTokenizer, env }) => {
this.log(`Loading reranker suit... | This function will preload the reranker suite and tokenizer.
This is useful for reducing the latency of the first rerank call and pre-downloading the models and such
to avoid having to wait for the models to download on the first rerank call. | initClient | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingRerankers/native/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingRerankers/native/index.js | MIT |
async rerank(query, documents, options = { topK: 4 }) {
await this.initClient();
const model = NativeEmbeddingReranker.#model;
const tokenizer = NativeEmbeddingReranker.#tokenizer;
const start = Date.now();
this.log(`Reranking ${documents.length} documents...`);
const inputs = tokenizer(new Arr... | Reranks a list of documents based on the query.
@param {string} query - The query to rerank the documents against.
@param {{text: string}[]} documents - The list of document text snippets to rerank. Should be output from a vector search.
@param {Object} options - The options for the reranking.
@param {number} options.t... | rerank | javascript | Mintplex-Labs/anything-llm | server/utils/EmbeddingRerankers/native/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/EmbeddingRerankers/native/index.js | MIT |
async function cachedVectorInformation(filename = null, checkOnly = false) {
if (!filename) return checkOnly ? false : { exists: false, chunks: [] };
const digest = uuidv5(filename, uuidv5.URL);
const file = path.resolve(vectorCachePath, `${digest}.json`);
const exists = fs.existsSync(file);
if (checkOnly) ... | Searches the vector-cache folder for existing information so we dont have to re-embed a
document and can instead push directly to vector db.
@param {string} filename - the filename to check for cached vector information
@param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data
@... | cachedVectorInformation | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function storeVectorResult(vectorData = [], filename = null) {
if (!filename) return;
console.log(
`Caching vectorized results of ${filename} to prevent duplicated embedding.`
);
if (!fs.existsSync(vectorCachePath)) fs.mkdirSync(vectorCachePath);
const digest = uuidv5(filename, uuidv5.URL);
const... | Searches the vector-cache folder for existing information so we dont have to re-embed a
document and can instead push directly to vector db.
@param {string} filename - the filename to check for cached vector information
@param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data
@... | storeVectorResult | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function purgeSourceDocument(filename = null) {
if (!filename) return;
const filePath = path.resolve(documentsPath, normalizePath(filename));
if (
!fs.existsSync(filePath) ||
!isWithin(documentsPath, filePath) ||
!fs.lstatSync(filePath).isFile()
)
return;
console.log(`Purging source do... | Searches the vector-cache folder for existing information so we dont have to re-embed a
document and can instead push directly to vector db.
@param {string} filename - the filename to check for cached vector information
@param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data
@... | purgeSourceDocument | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function purgeVectorCache(filename = null) {
if (!filename) return;
const digest = uuidv5(filename, uuidv5.URL);
const filePath = path.resolve(vectorCachePath, `${digest}.json`);
if (!fs.existsSync(filePath) || !fs.lstatSync(filePath).isFile()) return;
console.log(`Purging vector-cache of ${filename}.`... | Searches the vector-cache folder for existing information so we dont have to re-embed a
document and can instead push directly to vector db.
@param {string} filename - the filename to check for cached vector information
@param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data
@... | purgeVectorCache | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function findDocumentInDocuments(documentName = null) {
if (!documentName) return null;
for (const folder of fs.readdirSync(documentsPath)) {
const isFolder = fs
.lstatSync(path.join(documentsPath, folder))
.isDirectory();
if (!isFolder) continue;
const targetFilename = normalizePath(... | Searches the vector-cache folder for existing information so we dont have to re-embed a
document and can instead push directly to vector db.
@param {string} filename - the filename to check for cached vector information
@param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data
@... | findDocumentInDocuments | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function isWithin(outer, inner) {
if (outer === inner) return false;
const rel = path.relative(outer, inner);
return !rel.startsWith("../") && rel !== "..";
} | Checks if a given path is within another path.
@param {string} outer - The outer path (should be resolved).
@param {string} inner - The inner path (should be resolved).
@returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. | isWithin | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function normalizePath(filepath = "") {
const result = path
.normalize(filepath.trim())
.replace(/^(\.\.(\/|\\|$))+/, "")
.trim();
if (["..", ".", "/"].includes(result)) throw new Error("Invalid path.");
return result;
} | Checks if a given path is within another path.
@param {string} outer - The outer path (should be resolved).
@param {string} inner - The inner path (should be resolved).
@returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. | normalizePath | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function hasVectorCachedFiles() {
try {
return (
fs.readdirSync(vectorCachePath)?.filter((name) => name.endsWith(".json"))
.length !== 0
);
} catch {}
return false;
} | Checks if a given path is within another path.
@param {string} outer - The outer path (should be resolved).
@param {string} inner - The inner path (should be resolved).
@returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. | hasVectorCachedFiles | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function getPinnedWorkspacesByDocument(filenames = []) {
return (
await Document.where(
{
docpath: {
in: Object.keys(filenames),
},
pinned: true,
},
null,
null,
null,
{
workspaceId: true,
docpath: true,
}
)
).r... | @param {string[]} filenames - array of filenames to check for pinned workspaces
@returns {Promise<Record<string, string[]>>} - a record of filenames and their corresponding workspaceIds | getPinnedWorkspacesByDocument | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function getWatchedDocumentFilenames(filenames = []) {
return (
await Document.where(
{
docpath: { in: Object.keys(filenames) },
watched: true,
},
null,
null,
null,
{ workspaceId: true, docpath: true }
)
).reduce((result, { workspaceId, docpath }) =>... | Get a record of filenames and their corresponding workspaceIds that have watched a document
that will be used to determine if a document should be displayed in the watched documents sidebar
@param {string[]} filenames - array of filenames to check for watched workspaces
@returns {Promise<Record<string, string[]>>} - a ... | getWatchedDocumentFilenames | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function purgeEntireVectorCache() {
fs.rmSync(vectorCachePath, { recursive: true, force: true });
fs.mkdirSync(vectorCachePath);
return;
} | Purges the entire vector-cache folder and recreates it.
@returns {void} | purgeEntireVectorCache | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
async function fileToPickerData({
pathToFile,
liveSyncAvailable = false,
cachefilename = null,
}) {
let metadata = {};
const filename = path.basename(pathToFile);
const fileStats = fs.statSync(pathToFile);
const cachedStatus = await cachedVectorInformation(cachefilename, true);
if (fileStats.size < FIL... | Converts a file to picker data
@param {string} pathToFile - The path to the file to convert
@param {boolean} liveSyncAvailable - Whether live sync is available
@returns {Promise<{name: string, type: string, [string]: any, cached: boolean, canWatch: boolean}>} - The picker data | fileToPickerData | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function hasRequiredMetadata(metadata = {}) {
return REQUIRED_FILE_OBJECT_FIELDS.every((field) =>
metadata.hasOwnProperty(field)
);
} | Checks if a given metadata object has all the required fields
@param {{name: string, type: string, url: string, title: string, docAuthor: string, description: string, docSource: string, chunkSource: string, published: string, wordCount: number, token_count_estimate: number}} metadata - The metadata object to check (fil... | hasRequiredMetadata | javascript | Mintplex-Labs/anything-llm | server/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/index.js | MIT |
function isDefaultFilename(filename) {
return [LOGO_FILENAME, LOGO_FILENAME_DARK].includes(filename);
} | Checks if the filename is the default logo filename for dark or light mode.
@param {string} filename - The filename to check.
@returns {boolean} Whether the filename is the default logo filename. | isDefaultFilename | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
function validFilename(newFilename = "") {
return !isDefaultFilename(newFilename);
} | Checks if the filename is the default logo filename for dark or light mode.
@param {string} filename - The filename to check.
@returns {boolean} Whether the filename is the default logo filename. | validFilename | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
function getDefaultFilename(darkMode = true) {
return darkMode ? LOGO_FILENAME : LOGO_FILENAME_DARK;
} | Shows the logo for the current theme. In dark mode, it shows the light logo
and vice versa.
@param {boolean} darkMode - Whether the logo should be for dark mode.
@returns {string} The filename of the logo. | getDefaultFilename | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
async function determineLogoFilepath(defaultFilename = LOGO_FILENAME) {
const currentLogoFilename = await SystemSettings.currentLogoFilename();
const basePath = process.env.STORAGE_DIR
? path.join(process.env.STORAGE_DIR, "assets")
: path.join(__dirname, "../../storage/assets");
const defaultFilepath = pa... | Shows the logo for the current theme. In dark mode, it shows the light logo
and vice versa.
@param {boolean} darkMode - Whether the logo should be for dark mode.
@returns {string} The filename of the logo. | determineLogoFilepath | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
function fetchLogo(logoPath) {
if (!fs.existsSync(logoPath)) {
return {
found: false,
buffer: null,
size: 0,
mime: "none/none",
};
}
const mime = getType(logoPath);
const buffer = fs.readFileSync(logoPath);
return {
found: true,
buffer,
size: buffer.length,
mim... | Shows the logo for the current theme. In dark mode, it shows the light logo
and vice versa.
@param {boolean} darkMode - Whether the logo should be for dark mode.
@returns {string} The filename of the logo. | fetchLogo | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
async function renameLogoFile(originalFilename = null) {
const extname = path.extname(originalFilename) || ".png";
const newFilename = `${v4()}${extname}`;
const assetsDirectory = process.env.STORAGE_DIR
? path.join(process.env.STORAGE_DIR, "assets")
: path.join(__dirname, `../../storage/assets`);
const... | Shows the logo for the current theme. In dark mode, it shows the light logo
and vice versa.
@param {boolean} darkMode - Whether the logo should be for dark mode.
@returns {string} The filename of the logo. | renameLogoFile | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
async function removeCustomLogo(logoFilename = LOGO_FILENAME) {
if (!logoFilename || !validFilename(logoFilename)) return false;
const assetsDirectory = process.env.STORAGE_DIR
? path.join(process.env.STORAGE_DIR, "assets")
: path.join(__dirname, `../../storage/assets`);
const logoPath = path.join(assets... | Shows the logo for the current theme. In dark mode, it shows the light logo
and vice versa.
@param {boolean} darkMode - Whether the logo should be for dark mode.
@returns {string} The filename of the logo. | removeCustomLogo | javascript | Mintplex-Labs/anything-llm | server/utils/files/logo.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/logo.js | MIT |
function handleFileUpload(request, response, next) {
const upload = multer({ storage: fileUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
... | Handle Generic file upload as documents from the GUI
@param {Request} request
@param {Response} response
@param {NextFunction} next | handleFileUpload | javascript | Mintplex-Labs/anything-llm | server/utils/files/multer.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/multer.js | MIT |
function handleAPIFileUpload(request, response, next) {
const upload = multer({ storage: fileAPIUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.messag... | Handle API file upload as documents - this does not manipulate the filename
at all for encoding/charset reasons.
@param {Request} request
@param {Response} response
@param {NextFunction} next | handleAPIFileUpload | javascript | Mintplex-Labs/anything-llm | server/utils/files/multer.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/multer.js | MIT |
function handlePfpUpload(request, response, next) {
const upload = multer({ storage: pfpUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
... | Handle PFP file upload as logos | handlePfpUpload | javascript | Mintplex-Labs/anything-llm | server/utils/files/multer.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/multer.js | MIT |
async function purgeFolder(folderName = null) {
if (!folderName) return;
const subFolder = normalizePath(folderName);
const subFolderPath = path.resolve(documentsPath, subFolder);
const validRemovableSubFolders = fs
.readdirSync(documentsPath)
.map((folder) => {
// Filter out any results which are... | Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations
for the documents within the folder.
@notice This function is not recursive. It only purges the contents of the specified folder.
@notice You cannot purge the `custom-documents` folder.
@param {string} ... | purgeFolder | javascript | Mintplex-Labs/anything-llm | server/utils/files/purgeDocument.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/purgeDocument.js | MIT |
rmVectorCache = () =>
new Promise((resolve) =>
purgeVectorCache(filename).then(() => resolve(true))
) | Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations
for the documents within the folder.
@notice This function is not recursive. It only purges the contents of the specified folder.
@notice You cannot purge the `custom-documents` folder.
@param {string} ... | rmVectorCache | javascript | Mintplex-Labs/anything-llm | server/utils/files/purgeDocument.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/purgeDocument.js | MIT |
rmVectorCache = () =>
new Promise((resolve) =>
purgeVectorCache(filename).then(() => resolve(true))
) | Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations
for the documents within the folder.
@notice This function is not recursive. It only purges the contents of the specified folder.
@notice You cannot purge the `custom-documents` folder.
@param {string} ... | rmVectorCache | javascript | Mintplex-Labs/anything-llm | server/utils/files/purgeDocument.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/purgeDocument.js | MIT |
rmWorkspaceDoc = () =>
new Promise((resolve) =>
Document.removeDocuments(workspace, filenames).then(() => resolve(true))
) | Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations
for the documents within the folder.
@notice This function is not recursive. It only purges the contents of the specified folder.
@notice You cannot purge the `custom-documents` folder.
@param {string} ... | rmWorkspaceDoc | javascript | Mintplex-Labs/anything-llm | server/utils/files/purgeDocument.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/purgeDocument.js | MIT |
rmWorkspaceDoc = () =>
new Promise((resolve) =>
Document.removeDocuments(workspace, filenames).then(() => resolve(true))
) | Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations
for the documents within the folder.
@notice This function is not recursive. It only purges the contents of the specified folder.
@notice You cannot purge the `custom-documents` folder.
@param {string} ... | rmWorkspaceDoc | javascript | Mintplex-Labs/anything-llm | server/utils/files/purgeDocument.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/files/purgeDocument.js | MIT |
function getVectorDbClass(getExactly = null) {
const vectorSelection = getExactly ?? process.env.VECTOR_DB ?? "lancedb";
switch (vectorSelection) {
case "pinecone":
const { Pinecone } = require("../vectorDbProviders/pinecone");
return Pinecone;
case "chroma":
const { Chroma } = require("..... | Gets the systems current vector database provider.
@param {('pinecone' | 'chroma' | 'lancedb' | 'weaviate' | 'qdrant' | 'milvus' | 'zilliz' | 'astra') | null} getExactly - If provided, this will return an explit provider.
@returns { BaseVectorDatabaseProvider} | getVectorDbClass | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function getLLMProvider({ provider = null, model = null } = {}) {
const LLMSelection = provider ?? process.env.LLM_PROVIDER ?? "openai";
const embedder = getEmbeddingEngineSelection();
switch (LLMSelection) {
case "openai":
const { OpenAiLLM } = require("../AiProviders/openAi");
return new OpenAi... | Returns the LLMProvider with its embedder attached via system or via defined provider.
@param {{provider: string | null, model: string | null} | null} params - Initialize params for LLMs provider
@returns {BaseLLMProvider} | getLLMProvider | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function getEmbeddingEngineSelection() {
const { NativeEmbedder } = require("../EmbeddingEngines/native");
const engineSelection = process.env.EMBEDDING_ENGINE;
switch (engineSelection) {
case "openai":
const { OpenAiEmbedder } = require("../EmbeddingEngines/openAi");
return new OpenAiEmbedder();
... | Returns the EmbedderProvider by itself to whatever is currently in the system settings.
@returns {BaseEmbedderProvider} | getEmbeddingEngineSelection | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function getLLMProviderClass({ provider = null } = {}) {
switch (provider) {
case "openai":
const { OpenAiLLM } = require("../AiProviders/openAi");
return OpenAiLLM;
case "azure":
const { AzureOpenAiLLM } = require("../AiProviders/azureOpenAi");
return AzureOpenAiLLM;
case "anthrop... | Returns the LLMProviderClass - this is a helper method to access static methods on a class
@param {{provider: string | null} | null} params - Initialize params for LLMs provider
@returns {BaseLLMProviderClass} | getLLMProviderClass | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function getBaseLLMProviderModel({ provider = null } = {}) {
switch (provider) {
case "openai":
return process.env.OPEN_MODEL_PREF;
case "azure":
return process.env.OPEN_MODEL_PREF;
case "anthropic":
return process.env.ANTHROPIC_MODEL_PREF;
case "gemini":
return process.env.GEM... | Returns the defined model (if available) for the given provider.
@param {{provider: string | null} | null} params - Initialize params for LLMs provider
@returns {string | null} | getBaseLLMProviderModel | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function maximumChunkLength() {
if (
!!process.env.EMBEDDING_MODEL_MAX_CHUNK_LENGTH &&
!isNaN(process.env.EMBEDDING_MODEL_MAX_CHUNK_LENGTH) &&
Number(process.env.EMBEDDING_MODEL_MAX_CHUNK_LENGTH) > 1
)
return Number(process.env.EMBEDDING_MODEL_MAX_CHUNK_LENGTH);
return 1_000;
} | Returns the defined model (if available) for the given provider.
@param {{provider: string | null} | null} params - Initialize params for LLMs provider
@returns {string | null} | maximumChunkLength | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
function toChunks(arr, size) {
return Array.from({ length: Math.ceil(arr.length / size) }, (_v, i) =>
arr.slice(i * size, i * size + size)
);
} | Returns the defined model (if available) for the given provider.
@param {{provider: string | null} | null} params - Initialize params for LLMs provider
@returns {string | null} | toChunks | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/index.js | MIT |
constructor(model = "gpt-3.5-turbo") {
if (TokenManager.instance && TokenManager.currentModel === model) {
this.log("Returning existing instance for model:", model);
return TokenManager.instance;
}
this.model = model;
this.encoderName = this.#getEncodingFromModel(model);
this.encoder = ... | @class TokenManager
@notice
We cannot do estimation of tokens here like we do in the collector
because we need to know the model to do it.
Other issues are we also do reverse tokenization here for the chat history during cannonballing.
So here we are stuck doing the actual tokenization and encoding until we figure out... | constructor | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
log(text, ...args) {
console.log(`\x1b[35m[TokenManager]\x1b[0m ${text}`, ...args);
} | @class TokenManager
@notice
We cannot do estimation of tokens here like we do in the collector
because we need to know the model to do it.
Other issues are we also do reverse tokenization here for the chat history during cannonballing.
So here we are stuck doing the actual tokenization and encoding until we figure out... | log | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
tokensFromString(input = "") {
try {
const tokens = this.encoder.encode(String(input), undefined, []);
return tokens;
} catch (e) {
console.error(e);
return [];
}
} | Pass in an empty array of disallowedSpecials to handle all tokens as text and to be tokenized.
@param {string} input
@returns {number[]} | tokensFromString | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
bytesFromTokens(tokens = []) {
const bytes = this.encoder.decode(tokens);
return bytes;
} | Converts an array of tokens back to a string.
@param {number[]} tokens
@returns {string} | bytesFromTokens | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
countFromString(input = "") {
const tokens = this.tokensFromString(input);
return tokens.length;
} | Counts the number of tokens in a string.
@param {string} input
@returns {number} | countFromString | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
statsFrom(input) {
if (typeof input === "string") return this.countFromString(input);
// What is going on here?
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb Item 6.
// The only option is to estimate. From repeated testing using the static value... | Estimates the number of tokens in a string or array of strings.
@param {string | string[]} input
@returns {number} | statsFrom | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/tiktoken.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/tiktoken.js | MIT |
async function looksLikePostgresConnectionString(connectionString = null) {
if (!connectionString || !connectionString.startsWith("postgresql://"))
return "Invalid Postgres connection string. Must start with postgresql://";
if (connectionString.includes(" "))
return "Invalid Postgres connection string. Must... | Validates the Postgres connection string for the PGVector options.
@param {string} input - The Postgres connection string to validate.
@returns {string} - An error message if the connection string is invalid, otherwise null. | looksLikePostgresConnectionString | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
async function validatePGVectorConnectionString(key, prevValue, nextValue) {
const envKey = KEY_MAPPING[key].envKey;
if (prevValue === nextValue) return; // If the value is the same as the previous value, don't validate it.
if (!nextValue) return; // If the value is not set, don't validate it.
if (nextValue ==... | Validates the Postgres connection string for the PGVector options.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the connection string is invalid, otherwise nu... | validatePGVectorConnectionString | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
async function validatePGVectorTableName(key, prevValue, nextValue) {
const envKey = KEY_MAPPING[key].envKey;
if (prevValue === nextValue) return; // If the value is the same as the previous value, don't validate it.
if (!nextValue) return; // If the value is not set, don't validate it.
if (nextValue === proce... | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | validatePGVectorTableName | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
async function updateENV(newENVs = {}, force = false, userId = null) {
let error = "";
const validKeys = Object.keys(KEY_MAPPING);
const ENV_KEYS = Object.keys(newENVs).filter(
(key) => validKeys.includes(key) && !newENVs[key].includes("******") // strip out answers where the value is all asterisks
);
con... | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | updateENV | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
async function executeValidationChecks(checks, value, force) {
const results = await Promise.all(
checks.map((validator) => validator(value, force))
);
return results.filter((err) => typeof err === "string");
} | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | executeValidationChecks | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
async function logChangesToEventLog(newValues = {}, userId = null) {
const { EventLogs } = require("../../models/eventLogs");
const eventMapping = {
LLMProvider: "update_llm_provider",
EmbeddingEngine: "update_embedding_engine",
VectorDB: "update_vector_db",
};
for (const [key, eventName] of Object... | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | logChangesToEventLog | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
function dumpENV() {
const fs = require("fs");
const path = require("path");
const frozenEnvs = {};
const protectedKeys = [
...Object.values(KEY_MAPPING).map((values) => values.envKey),
// Manually Add Keys here which are not already defined in KEY_MAPPING
// and are either managed or manually set ... | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | dumpENV | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
function sanitizeValue(value) {
const offendingChars =
/[\n\r\t\v\f\u0085\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000"'`#]/;
const firstOffendingCharIndex = value.search(offendingChars);
if (firstOffendingCharIndex === -1) return value;
return value.substring(0, firstOffendingCha... | Validates the Postgres table name for the PGVector options.
- Table should not already exist in the database.
@param {string} key - The ENV key we are validating.
@param {string} prevValue - The previous value of the key.
@param {string} nextValue - The next value of the key.
@returns {string} - An error message if the... | sanitizeValue | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/updateENV.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/updateENV.js | MIT |
function fillSourceWindow({
nDocs = 4, // Number of documents
searchResults = [], // Sources from similarity search
history = [], // Raw history
filterIdentifiers = [], // pinned document sources
} = config) {
const sources = [...searchResults];
if (sources.length >= nDocs || history.length === 0) {
re... | Fill the sources window with the priority of
1. Pinned documents (handled prior to function)
2. VectorSearch results
3. prevSources in chat history - starting from most recent.
Ensuring the window always has the desired amount of sources so that followup questions
in any chat mode have relevant sources, but not infini... | fillSourceWindow | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/index.js | MIT |
log = (text, ...args) => {
console.log(`\x1b[36m[fillSourceWindow]\x1b[0m ${text}`, ...args);
} | Fill the sources window with the priority of
1. Pinned documents (handled prior to function)
2. VectorSearch results
3. prevSources in chat history - starting from most recent.
Ensuring the window always has the desired amount of sources so that followup questions
in any chat mode have relevant sources, but not infini... | log | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/index.js | MIT |
log = (text, ...args) => {
console.log(`\x1b[36m[fillSourceWindow]\x1b[0m ${text}`, ...args);
} | Fill the sources window with the priority of
1. Pinned documents (handled prior to function)
2. VectorSearch results
3. prevSources in chat history - starting from most recent.
Ensuring the window always has the desired amount of sources so that followup questions
in any chat mode have relevant sources, but not infini... | log | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/index.js | MIT |
static countTokens(messages = []) {
try {
return this.tokenManager.statsFrom(messages);
} catch (e) {
return 0;
}
} | Counts the tokens in the messages.
@param {Array<{content: string}>} messages - the messages sent to the LLM so we can calculate the prompt tokens since most providers do not return this on stream
@returns {number} | countTokens | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/LLMPerformanceMonitor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/LLMPerformanceMonitor.js | MIT |
static measureAsyncFunction(func) {
return (async () => {
const start = Date.now();
const output = await func; // is a promise
const end = Date.now();
return { output, duration: (end - start) / 1000 };
})();
} | Wraps a function and logs the duration (in seconds) of the function call.
@param {Function} func
@returns {Promise<{output: any, duration: number}>} | measureAsyncFunction | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/LLMPerformanceMonitor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/LLMPerformanceMonitor.js | MIT |
static async measureStream(
func,
messages = [],
runPromptTokenCalculation = true
) {
const stream = await func;
stream.start = Date.now();
stream.duration = 0;
stream.metrics = {
completion_tokens: 0,
prompt_tokens: runPromptTokenCalculation ? this.countTokens(messages) : 0,
... | Wraps a completion stream and and attaches a start time and duration property to the stream.
Also attaches an `endMeasurement` method to the stream that will calculate the duration of the stream and metrics.
@param {Promise<OpenAICompatibleStream>} func
@param {Messages} messages - the messages sent to the LLM so we ca... | measureStream | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/LLMPerformanceMonitor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/LLMPerformanceMonitor.js | MIT |
function handleDefaultStreamResponseV2(response, stream, responseProps) {
const { uuid = uuidv4(), sources = [] } = responseProps;
// Why are we doing this?
// OpenAI do enable the usage metrics in the stream response but:
// 1. This parameter is not available in our current API version (TODO: update)
// 2. ... | Handles the default stream response for a chat.
@param {import("express").Response} response
@param {import('./LLMPerformanceMonitor').MonitoredStream} stream
@param {Object} responseProps
@returns {Promise<string>} | handleDefaultStreamResponseV2 | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
handleAbort = () => {
stream?.endMeasurement(usage);
clientAbortedHandler(resolve, fullText);
} | Handles the default stream response for a chat.
@param {import("express").Response} response
@param {import('./LLMPerformanceMonitor').MonitoredStream} stream
@param {Object} responseProps
@returns {Promise<string>} | handleAbort | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
handleAbort = () => {
stream?.endMeasurement(usage);
clientAbortedHandler(resolve, fullText);
} | Handles the default stream response for a chat.
@param {import("express").Response} response
@param {import('./LLMPerformanceMonitor').MonitoredStream} stream
@param {Object} responseProps
@returns {Promise<string>} | handleAbort | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
function convertToChatHistory(history = []) {
const formattedHistory = [];
for (const record of history) {
const { prompt, response, createdAt, feedbackScore = null, id } = record;
const data = JSON.parse(response);
// In the event that a bad response was stored - we should skip its entire record
/... | Handles the default stream response for a chat.
@param {import("express").Response} response
@param {import('./LLMPerformanceMonitor').MonitoredStream} stream
@param {Object} responseProps
@returns {Promise<string>} | convertToChatHistory | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
function convertToPromptHistory(history = []) {
const formattedHistory = [];
for (const record of history) {
const { prompt, response } = record;
const data = JSON.parse(response);
// In the event that a bad response was stored - we should skip its entire record
// because it was likely an error an... | Converts a chat history to a prompt history.
@param {Object[]} history - The chat history to convert
@returns {{role: string, content: string, attachments?: import("..").Attachment}[]} | convertToPromptHistory | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
function writeResponseChunk(response, data) {
response.write(`data: ${JSON.stringify(data)}\n\n`);
return;
} | Converts a chat history to a prompt history.
@param {Object[]} history - The chat history to convert
@returns {{role: string, content: string, attachments?: import("..").Attachment}[]} | writeResponseChunk | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
function formatChatHistory(
chatHistory = [],
formatterFunction,
mode = "asProperty"
) {
return chatHistory.map((historicalMessage) => {
if (
historicalMessage?.role !== "user" || // Only user messages can have attachments
!historicalMessage?.attachments || // If there are no attachments, we can... | Formats the chat history to re-use attachments in the chat history
that might have existed in the conversation earlier.
@param {{role:string, content:string, attachments?: Object[]}[]} chatHistory
@param {function} formatterFunction - The function to format the chat history from the llm provider
@param {('asProperty'|'... | formatChatHistory | javascript | Mintplex-Labs/anything-llm | server/utils/helpers/chat/responses.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/helpers/chat/responses.js | MIT |
function setLogger() {
return new Logger().logger;
} | Sets and overrides Console methods for logging when called.
This is a singleton method and will not create multiple loggers.
@returns {winston.Logger | console} - instantiated logger interface. | setLogger | javascript | Mintplex-Labs/anything-llm | server/utils/logger/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/logger/index.js | MIT |
async activeMCPServers() {
await this.bootMCPServers();
return Object.keys(this.mcps).flatMap((name) => `@@mcp_${name}`);
} | Get all of the active MCP servers as plugins we can load into agents.
This will also boot all MCP servers if they have not been started yet.
@returns {Promise<string[]>} Array of flow names in @@mcp_{name} format | activeMCPServers | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/index.js | MIT |
async convertServerToolsToPlugins(name, _aibitat = null) {
const mcp = this.mcps[name];
if (!mcp) return null;
const tools = (await mcp.listTools()).tools;
if (!tools.length) return null;
const plugins = [];
for (const tool of tools) {
plugins.push({
name: `${name}-${tool.name}`,... | Convert an MCP server name to an AnythingLLM Agent plugin
@param {string} name - The base name of the MCP server to convert - not the tool name. eg: `docker-mcp` not `docker-mcp:list-containers`
@param {Object} aibitat - The aibitat object to pass to the plugin
@returns {Promise<{name: string, description: string, plug... | convertServerToolsToPlugins | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/index.js | MIT |
async servers() {
await this.bootMCPServers();
const servers = [];
for (const [name, result] of Object.entries(this.mcpLoadingResults)) {
const config = this.mcpServerConfigs.find((s) => s.name === name);
if (result.status === "failed") {
servers.push({
name,
config:... | Returns the MCP servers that were loaded or attempted to be loaded
so that we can display them in the frontend for review or error logging.
@returns {Promise<{
name: string,
running: boolean,
tools: {name: string, description: string, inputSchema: Object}[],
process: {pid: number, cmd: string}|null,
error: st... | servers | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/index.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.