code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
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 ( darkMode = true ) | 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}`,
})
.end();
return;
}
next();
});
} | Handle Generic file upload as documents from the GUI
@param {Request} request
@param {Response} response
@param {NextFunction} next | handleFileUpload ( request , response , next ) | 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.message}`,
})
.end();
return;
}
next();
});
} | 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 ( request , response , next ) | 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 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 ( outer , inner ) | 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 getWatchedDocumentFilenames(filenames = []) {
return (
await Document.where(
{
docpath: { in: Object.keys(filenames) },
watched: true,
},
null,
null,
null,
{ workspaceId: true, docpath: true }
)
).reduce((result, { workspaceId, docpath }) => {
const filename = filenames[docpath];
result[filename] = workspaceId;
return result;
}, {});
}
/**
* Purges the entire vector-cache folder and recreates it.
* @returns {void}
*/
function purgeEntireVectorCache() {
fs.rmSync(vectorCachePath, { recursive: true, force: true });
fs.mkdirSync(vectorCachePath);
return;
}
module.exports = {
findDocumentInDocuments,
cachedVectorInformation,
viewLocalFiles,
purgeSourceDocument,
purgeVectorCache,
storeVectorResult,
fileData,
normalizePath,
isWithin,
documentsPath,
hasVectorCachedFiles,
purgeEntireVectorCache,
getDocumentsByFolder,
}; | 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 record of filenames and their corresponding workspaceIds | getWatchedDocumentFilenames ( filenames = [ ] ) | 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 |
static loadPluginByHubId(hubId) {
const configLocation = path.resolve(
pluginsPath,
normalizePath(hubId),
"plugin.json"
);
if (!this.isValidLocation(configLocation)) return;
const config = safeJsonParse(fs.readFileSync(configLocation, "utf8"));
return new ImportedPlugin(config);
} | Gets the imported plugin handler.
@param {string} hubId - The hub ID of the plugin.
@returns {ImportedPlugin} - The plugin handler. | loadPluginByHubId ( hubId ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static checkPluginFolderExists() {
const dir = path.resolve(pluginsPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
return;
} | Checks if the plugin folder exists and if it does not, creates the folder. | checkPluginFolderExists ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static activeImportedPlugins() {
const plugins = [];
this.checkPluginFolderExists();
const folders = fs.readdirSync(path.resolve(pluginsPath));
for (const folder of folders) {
const configLocation = path.resolve(
pluginsPath,
normalizePath(folder),
"plugin.json"
);
if (!this.isValidLocation(configLocation)) continue;
const config = safeJsonParse(fs.readFileSync(configLocation, "utf8"));
if (config.active) plugins.push(`@@${config.hubId}`);
}
return plugins;
} | Loads plugins from `plugins` folder in storage that are custom loaded and defined.
only loads plugins that are active: true.
@returns {string[]} - array of plugin names to be loaded later. | activeImportedPlugins ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static listImportedPlugins() {
const plugins = [];
this.checkPluginFolderExists();
if (!fs.existsSync(pluginsPath)) return plugins;
const folders = fs.readdirSync(path.resolve(pluginsPath));
for (const folder of folders) {
const configLocation = path.resolve(
pluginsPath,
normalizePath(folder),
"plugin.json"
);
if (!this.isValidLocation(configLocation)) continue;
const config = safeJsonParse(fs.readFileSync(configLocation, "utf8"));
plugins.push(config);
}
return plugins;
} | Lists all imported plugins.
@returns {Array} - array of plugin configurations (JSON). | listImportedPlugins ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static updateImportedPlugin(hubId, config) {
const configLocation = path.resolve(
pluginsPath,
normalizePath(hubId),
"plugin.json"
);
if (!this.isValidLocation(configLocation)) return;
const currentConfig = safeJsonParse(
fs.readFileSync(configLocation, "utf8"),
null
);
if (!currentConfig) return;
const updatedConfig = { ...currentConfig, ...config };
fs.writeFileSync(configLocation, JSON.stringify(updatedConfig, null, 2));
return updatedConfig;
} | Updates a plugin configuration.
@param {string} hubId - The hub ID of the plugin.
@param {object} config - The configuration to update.
@returns {object} - The updated configuration. | updateImportedPlugin ( hubId , config ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static deletePlugin(hubId) {
if (!hubId) throw new Error("No plugin hubID passed.");
const pluginFolder = path.resolve(pluginsPath, normalizePath(hubId));
if (!this.isValidLocation(pluginFolder)) return;
fs.rmSync(pluginFolder, { recursive: true });
return true;
} | Deletes a plugin. Removes the entire folder of the object.
@param {string} hubId - The hub ID of the plugin.
@returns {boolean} - True if the plugin was deleted, false otherwise. | deletePlugin ( hubId ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
static validateImportedPluginHandler(hubId) {
const handlerLocation = path.resolve(
pluginsPath,
normalizePath(hubId),
"handler.js"
);
return this.isValidLocation(handlerLocation);
} | Validates if the handler.js file exists for the given plugin.
@param {string} hubId - The hub ID of the plugin.
@returns {boolean} - True if the handler.js file exists, false otherwise. | validateImportedPluginHandler ( hubId ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/imported.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/imported.js | MIT |
async function agentSkillsFromSystemSettings() {
const systemFunctions = [];
// Load non-imported built-in skills that are configurable, but are default enabled.
const _disabledDefaultSkills = safeJsonParse(
await SystemSettings.getValueOrFallback(
{ label: "disabled_agent_skills" },
"[]"
),
[]
);
DEFAULT_SKILLS.forEach((skill) => {
if (!_disabledDefaultSkills.includes(skill))
systemFunctions.push(AgentPlugins[skill].name);
});
// Load non-imported built-in skills that are configurable.
const _setting = safeJsonParse(
await SystemSettings.getValueOrFallback(
{ label: "default_agent_skills" },
"[]"
),
[]
);
_setting.forEach((skillName) => {
if (!AgentPlugins.hasOwnProperty(skillName)) return;
// This is a plugin module with many sub-children plugins who
// need to be named via `${parent}#${child}` naming convention
if (Array.isArray(AgentPlugins[skillName].plugin)) {
for (const subPlugin of AgentPlugins[skillName].plugin) {
systemFunctions.push(
`${AgentPlugins[skillName].name}#${subPlugin.name}`
);
}
return;
}
// This is normal single-stage plugin
systemFunctions.push(AgentPlugins[skillName].name);
});
return systemFunctions;
} | Fetches and preloads the names/identifiers for plugins that will be dynamically
loaded later
@returns {Promise<string[]>} | agentSkillsFromSystemSettings ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/defaults.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/defaults.js | MIT |
constructor({
uuid,
workspace,
prompt,
userId = null,
threadId = null,
sessionId = null,
}) {
super({ uuid });
this.#invocationUUID = uuid;
this.#workspace = workspace;
this.#prompt = prompt;
this.#userId = userId;
this.#threadId = threadId;
this.#sessionId = sessionId;
} | @param {{
uuid: string,
workspace: import("@prisma/client").workspaces,
prompt: string,
userId: import("@prisma/client").users["id"]|null,
threadId: import("@prisma/client").workspace_threads["id"]|null,
sessionId: string|null
}} parameters | constructor ( { uuid , workspace , prompt , userId = null , threadId = null , sessionId = null , } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/ephemeral.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/ephemeral.js | MIT |
packMessages() {
const thoughts = [];
let textResponse = null;
for (let msg of this.messages) {
if (msg.type !== "statusResponse") {
textResponse = msg.content;
} else {
thoughts.push(msg.content);
}
}
return { thoughts, textResponse };
} | Compacts all messages in class and returns them in a condensed format.
@returns {{thoughts: string[], textResponse: string}} | packMessages ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/ephemeral.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/ephemeral.js | MIT |
async waitForClose() {
return new Promise((resolve) => {
this.once("closed", () => resolve(this.packMessages()));
});
} | Waits on the HTTP plugin to emit the 'closed' event from the agentHandler
so that we can compact and return all the messages in the current queue.
@returns {Promise<{thoughts: string[], textResponse: string}>} | waitForClose ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/ephemeral.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/ephemeral.js | MIT |
get chats() {
return this._chats;
} | Get the chat history between agents and channels. | chats ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
agent(name = "", config = {}) {
this.agents.set(name, config);
return this;
} | Add a new agent to the AIbitat.
@param name
@param config
@returns | agent ( name = "" , config = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
channel(name = "", members = [""], config = {}) {
this.channels.set(name, {
members,
...config,
});
return this;
} | Add a new channel to the AIbitat.
@param name
@param members
@param config
@returns | channel ( name = "" , members = [ "" ] , config = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
getAgentConfig(agent = "") {
const config = this.agents.get(agent);
if (!config) {
throw new Error(`Agent configuration "${agent}" not found`);
}
return {
role: "You are a helpful AI assistant.",
// role: `You are a helpful AI assistant.
// Solve tasks using your coding and language skills.
// In the following cases, suggest typescript code (in a typescript coding block) or shell script (in a sh coding block) for the user to execute.
// 1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself.
// 2. When you need to perform some task with code, use the code to perform the task and output the result. Finish the task smartly.
// Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.
// When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.
// If you want the user to save the code in a file before executing it, put # filename: <filename> inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.
// If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.
// When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.
// Reply "TERMINATE" when everything is done.`,
...config,
};
} | Get the specific agent configuration.
@param agent The name of the agent.
@throws When the agent configuration is not found.
@returns The agent configuration. | getAgentConfig ( agent = "" ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
getChannelConfig(channel = "") {
const config = this.channels.get(channel);
if (!config) {
throw new Error(`Channel configuration "${channel}" not found`);
}
return {
maxRounds: 10,
role: "",
...config,
};
} | Get the specific channel configuration.
@param channel The name of the channel.
@throws When the channel configuration is not found.
@returns The channel configuration. | getChannelConfig ( channel = "" ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
getGroupMembers(node = "") {
const group = this.getChannelConfig(node);
return group.members;
} | Get the members of a group.
@throws When the group is not defined as an array in the connections.
@param node The name of the group.
@returns The members of the group. | getGroupMembers ( node = "" ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
onAbort(listener = () => null) { | Triggered when a plugin, socket, or command is aborted.
@param listener
@returns | onAbort | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
onTerminate(listener = () => null) { | Triggered when a chat is terminated. After this, the chat can't be continued.
@param listener
@returns | listener | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
onInterrupt(listener = () => null) { | Triggered when a chat is interrupted by a node.
@param listener
@returns | listener | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
onMessage(listener = (chat) => null) { | Triggered when a message is added to the chat history.
This can either be the first message or a reply to a message.
@param listener
@returns | listener | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
function(functionConfig) {
this.functions.set(functionConfig.name, functionConfig);
return this;
} | Register a new function to be called by the AIbitat agents.
You are also required to specify the which node can call the function.
@param functionConfig The function configuration. | (anonymous) ( functionConfig ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/index.js | MIT |
reset(type = "runs") {
switch (type) {
case "runs":
this.#hashes = {};
break;
case "cooldowns":
this.#cooldowns = {};
break;
case "uniques":
this.#uniques = {};
break;
}
return;
} | Resets the object property for this instance of the Deduplicator class
@param {('runs'|'cooldowns'|'uniques')} type - The type of prop to reset | reset ( type = "runs" ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/utils/dedupe.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/utils/dedupe.js | MIT |
get authMethod() {
const method = process.env.AWS_BEDROCK_LLM_CONNECTION_METHOD || "iam";
if (!["iam", "sessionToken"].includes(method)) return "iam";
return method;
} | Get the authentication method for the AWS Bedrock LLM.
There are only two valid values for this setting - anything else will default to "iam".
@returns {"iam"|"sessionToken"} | authMethod ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/providers/bedrock.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/providers/bedrock.js | MIT |
getCost(_usage) {
return 0;
}
} | Get the cost of the completion.
@param _usage The completion to get the cost for.
@returns The cost of the completion.
Stubbed since KoboldCPP has no cost basis. | getCost ( _usage ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/providers/bedrock.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/providers/bedrock.js | MIT |
static LangChainChatModel(provider = "openai", config = {}) {
switch (provider) {
// Cloud models
case "openai":
return new ChatOpenAI({
apiKey: process.env.OPEN_AI_KEY,
...config,
});
case "anthropic":
return new ChatAnthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
...config,
});
case "groq":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.groq.com/openai/v1",
},
apiKey: process.env.GROQ_API_KEY,
...config,
});
case "mistral":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.mistral.ai/v1",
},
apiKey: process.env.MISTRAL_API_KEY ?? null,
...config,
});
case "openrouter":
return new ChatOpenAI({
configuration: {
baseURL: "https://openrouter.ai/api/v1",
defaultHeaders: {
"HTTP-Referer": "https://anythingllm.com",
"X-Title": "AnythingLLM",
},
},
apiKey: process.env.OPENROUTER_API_KEY ?? null,
...config,
});
case "perplexity":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.perplexity.ai",
},
apiKey: process.env.PERPLEXITY_API_KEY ?? null,
...config,
});
case "togetherai":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.together.xyz/v1",
},
apiKey: process.env.TOGETHER_AI_API_KEY ?? null,
...config,
});
case "generic-openai":
return new ChatOpenAI({
configuration: {
baseURL: process.env.GENERIC_OPEN_AI_BASE_PATH,
},
apiKey: process.env.GENERIC_OPEN_AI_API_KEY,
maxTokens: toValidNumber(
process.env.GENERIC_OPEN_AI_MAX_TOKENS,
1024
),
...config,
});
case "bedrock":
return new ChatBedrockConverse({
model: process.env.AWS_BEDROCK_LLM_MODEL_PREFERENCE,
region: process.env.AWS_BEDROCK_LLM_REGION,
credentials: {
accessKeyId: process.env.AWS_BEDROCK_LLM_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_BEDROCK_LLM_ACCESS_KEY,
},
...config,
});
case "fireworksai":
return new ChatOpenAI({
apiKey: process.env.FIREWORKS_AI_LLM_API_KEY,
...config,
});
case "apipie":
return new ChatOpenAI({
configuration: {
baseURL: "https://apipie.ai/v1",
},
apiKey: process.env.APIPIE_LLM_API_KEY ?? null,
...config,
});
case "deepseek":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.deepseek.com/v1",
},
apiKey: process.env.DEEPSEEK_API_KEY ?? null,
...config,
});
case "xai":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.x.ai/v1",
},
apiKey: process.env.XAI_LLM_API_KEY ?? null,
...config,
});
case "novita":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.novita.ai/v3/openai",
},
apiKey: process.env.NOVITA_LLM_API_KEY ?? null,
...config,
});
case "ppio":
return new ChatOpenAI({
configuration: {
baseURL: "https://api.ppinfra.com/v3/openai",
},
apiKey: process.env.PPIO_API_KEY ?? null,
...config,
});
// OSS Model Runners
// case "anythingllm_ollama":
// return new ChatOllama({
// baseUrl: process.env.PLACEHOLDER,
// ...config,
// });
case "ollama":
return new ChatOllama({
baseUrl: process.env.OLLAMA_BASE_PATH,
...config,
});
case "lmstudio":
return new ChatOpenAI({
configuration: {
baseURL: parseLMStudioBasePath(process.env.LMSTUDIO_BASE_PATH),
},
apiKey: "not-used", // Needs to be specified or else will assume OpenAI
...config,
});
case "koboldcpp":
return new ChatOpenAI({
configuration: {
baseURL: process.env.KOBOLD_CPP_BASE_PATH,
},
apiKey: "not-used",
...config,
});
case "localai":
return new ChatOpenAI({
configuration: {
baseURL: process.env.LOCAL_AI_BASE_PATH,
},
apiKey: process.env.LOCAL_AI_API_KEY ?? "not-used",
...config,
});
case "textgenwebui":
return new ChatOpenAI({
configuration: {
baseURL: process.env.TEXT_GEN_WEB_UI_BASE_PATH,
},
apiKey: process.env.TEXT_GEN_WEB_UI_API_KEY ?? "not-used",
...config,
});
case "litellm":
return new ChatOpenAI({
configuration: {
baseURL: process.env.LITE_LLM_BASE_PATH,
},
apiKey: process.env.LITE_LLM_API_KEY ?? null,
...config,
});
case "nvidia-nim":
return new ChatOpenAI({
configuration: {
baseURL: process.env.NVIDIA_NIM_LLM_BASE_PATH,
},
apiKey: null,
...config,
});
default:
throw new Error(`Unsupported provider ${provider} for this task.`);
}
} | @param {string} provider - the string key of the provider LLM being loaded.
@param {LangChainModelConfig} config - Config to be used to override default connection object.
@returns | LangChainChatModel ( provider = "openai" , config = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/providers/ai-provider.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/providers/ai-provider.js | MIT |
static contextLimit(provider = "openai", modelName) {
const llm = getLLMProviderClass({ provider });
if (!llm || !llm.hasOwnProperty("promptWindowLimit")) return 8_000;
return llm.promptWindowLimit(modelName);
} | Get the context limit for a provider/model combination using static method in AIProvider class.
@param {string} provider
@param {string} modelName
@returns {number} | contextLimit ( provider = "openai" , modelName ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/providers/ai-provider.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/providers/ai-provider.js | MIT |
scrape: async function (url) {
this.super.introspect(
`${this.caller}: Scraping the content of ${url}`
);
const { success, content } =
await new CollectorApi().getLinkContent(url);
if (!success) {
this.super.introspect(
`${this.caller}: could not scrape ${url}. I can't use this page's content.`
);
throw new Error(
`URL could not be scraped and no content was found.`
);
}
if (!content || content?.length === 0) {
throw new Error("There was no content to be collected or read.");
}
const { TokenManager } = require("../../../helpers/tiktoken");
if (
new TokenManager(this.super.model).countFromString(content) <
Provider.contextLimit(this.super.provider, this.super.model)
) {
return content;
}
this.super.introspect(
`${this.caller}: This page's content is way too long. I will summarize it right now.`
);
this.super.onAbort(() => {
this.super.handlerProps.log(
"Abort was triggered, exiting summarization early."
);
this.controller.abort();
});
return summarizeContent({
provider: this.super.provider,
model: this.super.model,
controllerSignal: this.controller.signal,
content,
});
}, | Scrape a website and summarize the content based on objective if the content is too large.
Objective is the original objective & task that user give to the agent, url is the url of the website to be scraped.
Here we can leverage the document collector to get raw website text quickly.
@param url
@returns | scrape ( url ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/web-scraping.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/web-scraping.js | MIT |
askForFeedback: function (node = {}) {
return input({
message: `Provide feedback to ${chalk.yellow(
node.to
)} as ${chalk.yellow(
node.from
)}. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: `,
});
}, | Ask for feedback to the user using the terminal
@param node //{ from: string; to: string }
@returns | askForFeedback ( node = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/cli.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/cli.js | MIT |
socket.askForFeedback = (socket, node) => {
socket.awaitResponse = (question = "waiting...") => {
socket.send(JSON.stringify({ type: "WAITING_ON_INPUT", question }));
return new Promise(function (resolve) {
let socketTimeout = null;
socket.handleFeedback = (message) => {
const data = JSON.parse(message);
if (data.type !== "awaitingFeedback") return;
delete socket.handleFeedback;
clearTimeout(socketTimeout);
resolve(data.feedback);
return;
};
socketTimeout = setTimeout(() => {
console.log(
chalk.red(
`Client took too long to respond, chat thread is dead after ${SOCKET_TIMEOUT_MS}ms`
)
);
resolve("exit");
return;
}, SOCKET_TIMEOUT_MS);
});
};
return socket.awaitResponse(`Provide feedback to ${chalk.yellow(
node.to
)} as ${chalk.yellow(node.from)}.
Press enter to skip and use auto-reply, or type 'exit' to end the conversation: \n`);
};
// console.log("🚀 WS plugin is complete.");
},
};
}, | Socket wait for feedback on socket
@param socket The content to summarize. // AIbitatWebSocket & { receive: any, echo: any }
@param node The chat node // { from: string; to: string }
@returns The summarized content. | socket.askForFeedback | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/websocket.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/websocket.js | MIT |
listDocuments: async function () {
try {
this.super.introspect(
`${this.caller}: Looking at the available documents.`
);
const documents = await Document.where({
workspaceId: this.super.handlerProps.invocation.workspace_id,
});
if (documents.length === 0)
return "No documents found - nothing can be done. Stop.";
this.super.introspect(
`${this.caller}: Found ${documents.length} documents`
);
const foundDocuments = documents.map((doc) => {
const metadata = safeJsonParse(doc.metadata, {});
return {
document_id: doc.docId,
filename: metadata?.title ?? "unknown.txt",
description: metadata?.description ?? "no description",
};
});
return JSON.stringify(foundDocuments);
} catch (error) {
this.super.handlerProps.log(
`document-summarizer.list raised an error. ${error.message}`
);
return `Let the user know this action was not successful. An error was raised while listing available files. ${error.message}`;
}
}, | List all documents available in a workspace
@returns List of files and their descriptions if available. | listDocuments ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/summarize.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/summarize.js | MIT |
search: async function (query) {
const provider =
(await SystemSettings.get({ label: "agent_search_provider" }))
?.value ?? "unknown";
let engine;
switch (provider) {
case "google-search-engine":
engine = "_googleSearchEngine";
break;
case "searchapi":
engine = "_searchApi";
break;
case "serper-dot-dev":
engine = "_serperDotDev";
break;
case "bing-search":
engine = "_bingWebSearch";
break;
case "serply-engine":
engine = "_serplyEngine";
break;
case "searxng-engine":
engine = "_searXNGEngine";
break;
case "tavily-search":
engine = "_tavilySearch";
break;
case "duckduckgo-engine":
engine = "_duckDuckGoEngine";
break;
default:
engine = "_googleSearchEngine";
}
return await this[engine](query);
}, | Use Google Custom Search Engines
Free to set up, easy to use, 100 calls/day!
https://programmablesearchengine.google.com/controlpanel/create | search ( query ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/web-browsing.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/web-browsing.js | MIT |
middleTruncate(str, length = 5) {
if (str.length <= length) return str;
return `${str.slice(0, length)}...${str.slice(-length)}`;
}, | Utility function to truncate a string to a given length for debugging
calls to the API while keeping the actual values mostly intact
@param {string} str - The string to truncate
@param {number} length - The length to truncate the string to
@returns {string} The truncated string | middleTruncate ( str , length = 5 ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/web-browsing.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/web-browsing.js | MIT |
constructor(options = {}) {
this.scheme =
(options && options.scheme) || ConnectionStringParser.DEFAULT_SCHEME;
} | @param {ConnectionStringParserOptions} options | constructor ( options = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | MIT |
format(connectionStringObject) {
if (!connectionStringObject) {
return this.scheme + "://localhost";
}
if (
this.scheme &&
connectionStringObject.scheme &&
this.scheme !== connectionStringObject.scheme
) {
throw new Error(`Scheme not supported: ${connectionStringObject.scheme}`);
}
let uri =
(this.scheme ||
connectionStringObject.scheme ||
ConnectionStringParser.DEFAULT_SCHEME) + "://";
if (connectionStringObject.username) {
uri += encodeURIComponent(connectionStringObject.username);
// Allow empty passwords
if (connectionStringObject.password) {
uri += ":" + encodeURIComponent(connectionStringObject.password);
}
uri += "@";
}
uri += this._formatAddress(connectionStringObject);
// Only put a slash when there is an endpoint
if (connectionStringObject.endpoint) {
uri += "/" + encodeURIComponent(connectionStringObject.endpoint);
}
if (
connectionStringObject.options &&
Object.keys(connectionStringObject.options).length > 0
) {
uri +=
"?" +
Object.keys(connectionStringObject.options)
.map(
(option) =>
encodeURIComponent(option) +
"=" +
encodeURIComponent(connectionStringObject.options[option])
)
.join("&");
}
return uri;
} | Takes a connection string object and returns a URI string of the form:
scheme://[username[:password]@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[endpoint]][?options]
@param {Object} connectionStringObject The object that describes connection string parameters | format ( connectionStringObject ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | MIT |
parse(uri) {
const connectionStringParser = new RegExp(
"^\\s*" + // Optional whitespace padding at the beginning of the line
"([^:]+)://" + // Scheme (Group 1)
"(?:([^:@,/?=&]+)(?::([^:@,/?=&]+))?@)?" + // User (Group 2) and Password (Group 3)
"([^@/?=&]+)" + // Host address(es) (Group 4)
"(?:/([^:@,/?=&]+)?)?" + // Endpoint (Group 5)
"(?:\\?([^:@,/?]+)?)?" + // Options (Group 6)
"\\s*$", // Optional whitespace padding at the end of the line
"gi"
);
const connectionStringObject = {};
if (!uri.includes("://")) {
throw new Error(`No scheme found in URI ${uri}`);
}
const tokens = connectionStringParser.exec(uri);
if (Array.isArray(tokens)) {
connectionStringObject.scheme = tokens[1];
if (this.scheme && this.scheme !== connectionStringObject.scheme) {
throw new Error(`URI must start with '${this.scheme}://'`);
}
connectionStringObject.username = tokens[2]
? decodeURIComponent(tokens[2])
: tokens[2];
connectionStringObject.password = tokens[3]
? decodeURIComponent(tokens[3])
: tokens[3];
connectionStringObject.hosts = this._parseAddress(tokens[4]);
connectionStringObject.endpoint = tokens[5]
? decodeURIComponent(tokens[5])
: tokens[5];
connectionStringObject.options = tokens[6]
? this._parseOptions(tokens[6])
: tokens[6];
}
return connectionStringObject;
} | Where scheme and hosts will always be present. Other fields will only be present in the result if they were
present in the input.
@param {string} uri The connection string URI
@returns {ConnectionStringObject} The connection string object | parse ( uri ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | MIT |
_parseOptions(options) {
const result = {};
options.split("&").forEach((option) => {
const i = option.indexOf("=");
if (i >= 0) {
result[decodeURIComponent(option.substring(0, i))] = decodeURIComponent(
option.substring(i + 1)
);
}
});
return result;
} | Parses options
@param {string} options The options to process | _parseOptions ( options ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js | MIT |
function getDBClient(identifier = "", connectionConfig = {}) {
switch (identifier) {
case "mysql":
const { MySQLConnector } = require("./MySQL");
return new MySQLConnector(connectionConfig);
case "postgresql":
const { PostgresSQLConnector } = require("./Postgresql");
return new PostgresSQLConnector(connectionConfig);
case "sql-server":
const { MSSQLConnector } = require("./MSSQL");
return new MSSQLConnector(connectionConfig);
default:
throw new Error(
`There is no supported database connector for ${identifier}`
);
}
} | @param {SQLEngine} identifier
@param {object} connectionConfig
@returns Database Connection Engine Class for SQLAgent or throws error | getDBClient ( identifier = "" , connectionConfig = { } ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js | MIT |
async function listSQLConnections() {
return safeJsonParse(
(await SystemSettings.get({ label: "agent_sql_connections" }))?.value,
[]
);
} | Lists all of the known database connection that can be used by the agent.
@returns {Promise<[SQLConnection]>} | listSQLConnections ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js | MIT |
function isNullOrNaN(value) {
if (value === null) return true;
return isNaN(value);
} | @typedef {object} DocumentMetadata
@property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
@property {string} url - eg; "file://example.com/index.html"
@property {string} title - eg; "example.com/index.html"
@property {string} docAuthor - eg; "no author found"
@property {string} description - eg; "No description found."
@property {string} docSource - eg; "URL link uploaded by the user."
@property {string} chunkSource - eg; link://https://example.com
@property {string} published - ISO 8601 date string
@property {number} wordCount - Number of words in the document
@property {string} pageContent - The raw text content of the document
@property {number} token_count_estimate - Number of tokens in the document | isNullOrNaN ( value ) | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js | MIT |
static determineMaxChunkSize(preferred = null, embedderLimit = 1000) {
const prefValue = isNullOrNaN(preferred)
? Number(embedderLimit)
: Number(preferred);
const limit = Number(embedderLimit);
if (prefValue > limit)
console.log(
`\x1b[43m[WARN]\x1b[0m Text splitter chunk length of ${prefValue} exceeds embedder model max of ${embedderLimit}. Will use ${embedderLimit}.`
);
return prefValue > limit ? limit : prefValue;
} | Does a quick check to determine the text chunk length limit.
Embedder models have hard-set limits that cannot be exceeded, just like an LLM context
so here we want to allow override of the default 1000, but up to the models maximum, which is
sometimes user defined. | determineMaxChunkSize ( preferred = null , embedderLimit = 1000 ) | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js | MIT |
stringifyHeader() {
if (!this.config.chunkHeaderMeta) return null;
let content = "";
Object.entries(this.config.chunkHeaderMeta).map(([key, value]) => {
if (!key || !value) return;
content += `${key}: ${value}\n`;
});
if (!content) return null;
return `<document_metadata>\n${content}</document_metadata>\n\n`;
} | Creates a string of metadata to be prepended to each chunk. | stringifyHeader ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/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 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: config?.server || null,
running: false,
tools: [],
error: result.message,
process: null,
});
continue;
}
const mcp = this.mcps[name];
if (!mcp) {
delete this.mcpLoadingResults[name];
delete this.mcps[name];
continue;
}
const online = !!(await mcp.ping());
const tools = online ? (await mcp.listTools()).tools : [];
servers.push({
name,
config: config?.server || null,
running: online,
tools,
error: null,
process: {
pid: mcp.transport._process.pid,
},
});
}
return servers;
} | 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: string|null
}[]>} - The active MCP servers | 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 |
async toggleServerStatus(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) {
const killed = this.pruneMCPServer(name);
return {
success: killed,
error: killed ? null : `Failed to kill MCP server: ${name}`,
};
} else {
const startupResult = await this.startMCPServer(name);
return { success: startupResult.success, error: startupResult.error };
}
} | Toggle the MCP server (start or stop)
@param {string} name - The name of the MCP server to toggle
@returns {Promise<{success: boolean, error: string | null}>} | toggleServerStatus ( name ) | 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 deleteServer(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) this.pruneMCPServer(name);
this.removeMCPServerFromConfig(name);
delete this.mcps[name];
delete this.mcpLoadingResults[name];
this.log(`MCP server was killed and removed from config file: ${name}`);
return { success: true, error: null };
} | Delete the MCP server - will also remove it from the config file
@param {string} name - The name of the MCP server to delete
@returns {Promise<{success: boolean, error: string | null}>} | deleteServer ( name ) | 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 |
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.gemini.embedContent(textInput);
return result.embedding.values || [];
} | Embeds a single text input
@param {string} textInput - The text to embed
@returns {Promise<Array<number>>} The embedding values | embedTextInput ( textInput ) | 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 = []) {
let embeddings = [];
for (const chunk of textChunks) {
const results = await this.gemini.embedContent(chunk);
if (!results.embedding || !results.embedding.values)
throw new Error("No embedding values returned from gemini");
embeddings.push(results.embedding.values);
}
return embeddings;
} | Embeds a list of text inputs
@param {Array<string>} textInputs - The list of text to embed
@returns {Promise<Array<Array<number>>>} The embedding values | embedChunks ( textChunks = [ ] ) | 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 |
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("../vectorDbProviders/chroma");
return Chroma;
case "lancedb":
const { LanceDb } = require("../vectorDbProviders/lance");
return LanceDb;
case "weaviate":
const { Weaviate } = require("../vectorDbProviders/weaviate");
return Weaviate;
case "qdrant":
const { QDrant } = require("../vectorDbProviders/qdrant");
return QDrant;
case "milvus":
const { Milvus } = require("../vectorDbProviders/milvus");
return Milvus;
case "zilliz":
const { Zilliz } = require("../vectorDbProviders/zilliz");
return Zilliz;
case "astra":
const { AstraDB } = require("../vectorDbProviders/astra");
return AstraDB;
default:
throw new Error("ENV: No VECTOR_DB value found in environment!");
}
} | 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 ( getExactly = null ) | 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 OpenAiLLM(embedder, model);
case "azure":
const { AzureOpenAiLLM } = require("../AiProviders/azureOpenAi");
return new AzureOpenAiLLM(embedder, model);
case "anthropic":
const { AnthropicLLM } = require("../AiProviders/anthropic");
return new AnthropicLLM(embedder, model);
case "gemini":
const { GeminiLLM } = require("../AiProviders/gemini");
return new GeminiLLM(embedder, model);
case "lmstudio":
const { LMStudioLLM } = require("../AiProviders/lmStudio");
return new LMStudioLLM(embedder, model);
case "localai":
const { LocalAiLLM } = require("../AiProviders/localAi");
return new LocalAiLLM(embedder, model);
case "ollama":
const { OllamaAILLM } = require("../AiProviders/ollama");
return new OllamaAILLM(embedder, model);
case "togetherai":
const { TogetherAiLLM } = require("../AiProviders/togetherAi");
return new TogetherAiLLM(embedder, model);
case "fireworksai":
const { FireworksAiLLM } = require("../AiProviders/fireworksAi");
return new FireworksAiLLM(embedder, model);
case "perplexity":
const { PerplexityLLM } = require("../AiProviders/perplexity");
return new PerplexityLLM(embedder, model);
case "openrouter":
const { OpenRouterLLM } = require("../AiProviders/openRouter");
return new OpenRouterLLM(embedder, model);
case "mistral":
const { MistralLLM } = require("../AiProviders/mistral");
return new MistralLLM(embedder, model);
case "huggingface":
const { HuggingFaceLLM } = require("../AiProviders/huggingface");
return new HuggingFaceLLM(embedder, model);
case "groq":
const { GroqLLM } = require("../AiProviders/groq");
return new GroqLLM(embedder, model);
case "koboldcpp":
const { KoboldCPPLLM } = require("../AiProviders/koboldCPP");
return new KoboldCPPLLM(embedder, model);
case "textgenwebui":
const { TextGenWebUILLM } = require("../AiProviders/textGenWebUI");
return new TextGenWebUILLM(embedder, model);
case "cohere":
const { CohereLLM } = require("../AiProviders/cohere");
return new CohereLLM(embedder, model);
case "litellm":
const { LiteLLM } = require("../AiProviders/liteLLM");
return new LiteLLM(embedder, model);
case "generic-openai":
const { GenericOpenAiLLM } = require("../AiProviders/genericOpenAi");
return new GenericOpenAiLLM(embedder, model);
case "bedrock":
const { AWSBedrockLLM } = require("../AiProviders/bedrock");
return new AWSBedrockLLM(embedder, model);
case "deepseek":
const { DeepSeekLLM } = require("../AiProviders/deepseek");
return new DeepSeekLLM(embedder, model);
case "apipie":
const { ApiPieLLM } = require("../AiProviders/apipie");
return new ApiPieLLM(embedder, model);
case "novita":
const { NovitaLLM } = require("../AiProviders/novita");
return new NovitaLLM(embedder, model);
case "xai":
const { XAiLLM } = require("../AiProviders/xai");
return new XAiLLM(embedder, model);
case "nvidia-nim":
const { NvidiaNimLLM } = require("../AiProviders/nvidiaNim");
return new NvidiaNimLLM(embedder, model);
case "ppio":
const { PPIOLLM } = require("../AiProviders/ppio");
return new PPIOLLM(embedder, model);
default:
throw new Error(
`ENV: No valid LLM_PROVIDER value found in environment! Using ${process.env.LLM_PROVIDER}`
);
}
} | 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 ( { provider = null , model = null } = { } ) | 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();
case "azure":
const {
AzureOpenAiEmbedder,
} = require("../EmbeddingEngines/azureOpenAi");
return new AzureOpenAiEmbedder();
case "localai":
const { LocalAiEmbedder } = require("../EmbeddingEngines/localAi");
return new LocalAiEmbedder();
case "ollama":
const { OllamaEmbedder } = require("../EmbeddingEngines/ollama");
return new OllamaEmbedder();
case "native":
return new NativeEmbedder();
case "lmstudio":
const { LMStudioEmbedder } = require("../EmbeddingEngines/lmstudio");
return new LMStudioEmbedder();
case "cohere":
const { CohereEmbedder } = require("../EmbeddingEngines/cohere");
return new CohereEmbedder();
case "voyageai":
const { VoyageAiEmbedder } = require("../EmbeddingEngines/voyageAi");
return new VoyageAiEmbedder();
case "litellm":
const { LiteLLMEmbedder } = require("../EmbeddingEngines/liteLLM");
return new LiteLLMEmbedder();
case "mistral":
const { MistralEmbedder } = require("../EmbeddingEngines/mistral");
return new MistralEmbedder();
case "generic-openai":
const {
GenericOpenAiEmbedder,
} = require("../EmbeddingEngines/genericOpenAi");
return new GenericOpenAiEmbedder();
case "gemini":
const { GeminiEmbedder } = require("../EmbeddingEngines/gemini");
return new GeminiEmbedder();
default:
return new NativeEmbedder();
}
} | 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 "anthropic":
const { AnthropicLLM } = require("../AiProviders/anthropic");
return AnthropicLLM;
case "gemini":
const { GeminiLLM } = require("../AiProviders/gemini");
return GeminiLLM;
case "lmstudio":
const { LMStudioLLM } = require("../AiProviders/lmStudio");
return LMStudioLLM;
case "localai":
const { LocalAiLLM } = require("../AiProviders/localAi");
return LocalAiLLM;
case "ollama":
const { OllamaAILLM } = require("../AiProviders/ollama");
return OllamaAILLM;
case "togetherai":
const { TogetherAiLLM } = require("../AiProviders/togetherAi");
return TogetherAiLLM;
case "fireworksai":
const { FireworksAiLLM } = require("../AiProviders/fireworksAi");
return FireworksAiLLM;
case "perplexity":
const { PerplexityLLM } = require("../AiProviders/perplexity");
return PerplexityLLM;
case "openrouter":
const { OpenRouterLLM } = require("../AiProviders/openRouter");
return OpenRouterLLM;
case "mistral":
const { MistralLLM } = require("../AiProviders/mistral");
return MistralLLM;
case "huggingface":
const { HuggingFaceLLM } = require("../AiProviders/huggingface");
return HuggingFaceLLM;
case "groq":
const { GroqLLM } = require("../AiProviders/groq");
return GroqLLM;
case "koboldcpp":
const { KoboldCPPLLM } = require("../AiProviders/koboldCPP");
return KoboldCPPLLM;
case "textgenwebui":
const { TextGenWebUILLM } = require("../AiProviders/textGenWebUI");
return TextGenWebUILLM;
case "cohere":
const { CohereLLM } = require("../AiProviders/cohere");
return CohereLLM;
case "litellm":
const { LiteLLM } = require("../AiProviders/liteLLM");
return LiteLLM;
case "generic-openai":
const { GenericOpenAiLLM } = require("../AiProviders/genericOpenAi");
return GenericOpenAiLLM;
case "bedrock":
const { AWSBedrockLLM } = require("../AiProviders/bedrock");
return AWSBedrockLLM;
case "deepseek":
const { DeepSeekLLM } = require("../AiProviders/deepseek");
return DeepSeekLLM;
case "apipie":
const { ApiPieLLM } = require("../AiProviders/apipie");
return ApiPieLLM;
case "novita":
const { NovitaLLM } = require("../AiProviders/novita");
return NovitaLLM;
case "xai":
const { XAiLLM } = require("../AiProviders/xai");
return XAiLLM;
case "nvidia-nim":
const { NvidiaNimLLM } = require("../AiProviders/nvidiaNim");
return NvidiaNimLLM;
case "ppio":
const { PPIOLLM } = require("../AiProviders/ppio");
return PPIOLLM;
default:
return null;
}
} | 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 ( { provider = null } = { } ) | 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 |
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 ( messages = [ ] ) | 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 |
async function resetAllVectorStores({ vectorDbKey }) {
try {
const workspaces = await Workspace.where();
purgeEntireVectorCache(); // Purges the entire vector-cache folder.
await DocumentVectors.delete(); // Deletes all document vectors from the database.
await Document.delete(); // Deletes all documents from the database.
await EventLogs.logEvent("workspace_vectors_reset", {
reason: "System vector configuration changed",
});
console.log(
"Resetting anythingllm managed vector namespaces for",
vectorDbKey
);
const VectorDb = getVectorDbClass(vectorDbKey);
for (const workspace of workspaces) {
try {
await VectorDb["delete-namespace"]({ namespace: workspace.slug });
} catch (e) {
console.error(e.message);
}
}
return true;
} catch (error) {
console.error("Failed to reset vector stores:", error);
return false;
}
} | Resets all vector database and associated content:
- Purges the entire vector-cache folder.
- Deletes all document vectors from the database.
- Deletes all documents from the database.
- Deletes all vector db namespaces for each workspace.
- Logs an event indicating the reset.
@param {string} vectorDbKey - The _previous_ vector database provider name that we will be resetting.
@returns {Promise<boolean>} - True if successful, false otherwise. | resetAllVectorStores ( { vectorDbKey } ) | javascript | Mintplex-Labs/anything-llm | server/utils/vectorStore/resetAllVectorStores.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/vectorStore/resetAllVectorStores.js | MIT |
static createOrCheckFlowsDir() {
try {
if (fs.existsSync(AgentFlows.flowsDir)) return true;
fs.mkdirSync(AgentFlows.flowsDir, { recursive: true });
return true;
} catch (error) {
console.error("Failed to create flows directory:", error);
return false;
}
} | Ensure flows directory exists
@returns {Boolean} True if directory exists, false otherwise | createOrCheckFlowsDir ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static getAllFlows() {
AgentFlows.createOrCheckFlowsDir();
const files = fs.readdirSync(AgentFlows.flowsDir);
const flows = {};
for (const file of files) {
if (!file.endsWith(".json")) continue;
try {
const filePath = path.join(AgentFlows.flowsDir, file);
const content = fs.readFileSync(normalizePath(filePath), "utf8");
const config = JSON.parse(content);
const id = file.replace(".json", "");
flows[id] = config;
} catch (error) {
console.error(`Error reading flow file ${file}:`, error);
}
}
return flows;
} | Helper to get all flow files with their contents
@returns {Object} Map of flow UUID to flow config | getAllFlows ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static loadFlow(uuid) {
try {
const flowJsonPath = normalizePath(
path.join(AgentFlows.flowsDir, `${uuid}.json`)
);
if (!uuid || !fs.existsSync(flowJsonPath)) return null;
const flow = safeJsonParse(fs.readFileSync(flowJsonPath, "utf8"), null);
if (!flow) return null;
return {
name: flow.name,
uuid,
config: flow,
};
} catch (error) {
console.error("Failed to load flow:", error);
return null;
}
} | Load a flow configuration by UUID
@param {string} uuid - The UUID of the flow to load
@returns {LoadedFlow|null} Flow configuration or null if not found | loadFlow ( uuid ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static saveFlow(name, config, uuid = null) {
try {
AgentFlows.createOrCheckFlowsDir();
if (!uuid) uuid = uuidv4();
const normalizedUuid = normalizePath(`${uuid}.json`);
const filePath = path.join(AgentFlows.flowsDir, normalizedUuid);
fs.writeFileSync(filePath, JSON.stringify({ ...config, name }, null, 2));
return { success: true, uuid };
} catch (error) {
console.error("Failed to save flow:", error);
return { success: false, error: error.message };
}
} | Save a flow configuration
@param {string} name - The name of the flow
@param {Object} config - The flow configuration
@param {string|null} uuid - Optional UUID for the flow
@returns {Object} Result of the save operation | saveFlow ( name , config , uuid = null ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static listFlows() {
try {
const flows = AgentFlows.getAllFlows();
return Object.entries(flows).map(([uuid, flow]) => ({
name: flow.name,
uuid,
description: flow.description,
active: flow.active !== false,
}));
} catch (error) {
console.error("Failed to list flows:", error);
return [];
}
} | List all available flows
@returns {Array} Array of flow summaries | listFlows ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static deleteFlow(uuid) {
try {
const filePath = normalizePath(
path.join(AgentFlows.flowsDir, `${uuid}.json`)
);
if (!fs.existsSync(filePath)) throw new Error(`Flow ${uuid} not found`);
fs.rmSync(filePath);
return { success: true };
} catch (error) {
console.error("Failed to delete flow:", error);
return { success: false, error: error.message };
}
} | Delete a flow by UUID
@param {string} uuid - The UUID of the flow to delete
@returns {Object} Result of the delete operation | deleteFlow ( uuid ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static async executeFlow(uuid, variables = {}, aibitat = null) {
const flow = AgentFlows.loadFlow(uuid);
if (!flow) throw new Error(`Flow ${uuid} not found`);
const flowExecutor = new FlowExecutor();
return await flowExecutor.executeFlow(flow, variables, aibitat);
} | Execute a flow by UUID
@param {string} uuid - The UUID of the flow to execute
@param {Object} variables - Initial variables for the flow
@param {Object} aibitat - The aibitat instance from the agent handler
@returns {Promise<Object>} Result of flow execution | executeFlow ( uuid , variables = { } , aibitat = null ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
static activeFlowPlugins() {
const flows = AgentFlows.getAllFlows();
return Object.entries(flows)
.filter(([_, flow]) => flow.active !== false)
.map(([uuid]) => `@@flow_${uuid}`);
} | Get all active flows as plugins that can be loaded into the agent
@returns {string[]} Array of flow names in @@flow_{uuid} format | activeFlowPlugins ( ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js | MIT |
async function executeWebScraping(config, context) {
const { url, captureAs = "text" } = config;
const { introspect, logger, aibitat } = context;
logger(
`\x1b[43m[AgentFlowToolExecutor]\x1b[0m - executing Web Scraping block`
);
if (!url) {
throw new Error("URL is required for web scraping");
}
const captureMode = captureAs === "querySelector" ? "html" : captureAs;
introspect(`Scraping the content of ${url} as ${captureAs}`);
const { success, content } = await new CollectorApi()
.getLinkContent(url, captureMode)
.then((res) => {
if (captureAs !== "querySelector") return res;
return parseHTMLwithSelector(res.content, config.querySelector, context);
});
if (!success) {
introspect(`Could not scrape ${url}. Cannot use this page's content.`);
throw new Error("URL could not be scraped and no content was found.");
}
introspect(`Successfully scraped content from ${url}`);
if (!content || content?.length === 0) {
introspect("There was no content to be collected or read.");
throw new Error("There was no content to be collected or read.");
}
const tokenCount = new TokenManager(
aibitat.defaultProvider.model
).countFromString(content);
const contextLimit = Provider.contextLimit(
aibitat.defaultProvider.provider,
aibitat.defaultProvider.model
);
if (tokenCount < contextLimit) return content;
introspect(
`This page's content is way too long (${tokenCount} tokens). I will summarize it right now.`
);
const summary = await summarizeContent({
provider: aibitat.defaultProvider.provider,
model: aibitat.defaultProvider.model,
content,
});
introspect(`Successfully summarized content`);
return summary;
} | Execute a web scraping flow step
@param {Object} config Flow step configuration
@param {Object} context Execution context with introspect function
@returns {Promise<string>} Scraped content | executeWebScraping ( config , context ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/web-scraping.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/web-scraping.js | MIT |
function parseHTMLwithSelector(html, selector = null, context) {
if (!selector || selector.length === 0) {
context.introspect("No selector provided. Returning the entire HTML.");
return { success: true, content: html };
}
const Cheerio = require("cheerio");
const $ = Cheerio.load(html);
const selectedElements = $(selector);
let content;
if (selectedElements.length === 0) {
return { success: false, content: null };
} else if (selectedElements.length === 1) {
content = selectedElements.html();
} else {
context.introspect(
`Found ${selectedElements.length} elements matching selector: ${selector}`
);
content = selectedElements
.map((_, element) => $(element).html())
.get()
.join("\n");
}
return { success: true, content };
} | Parse HTML with a CSS selector
@param {string} html - The HTML to parse
@param {string|null} selector - The CSS selector to use (as text string)
@param {{introspect: Function}} context - The context object
@returns {Object} The parsed content | parseHTMLwithSelector ( html , selector = null , context ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/web-scraping.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/web-scraping.js | MIT |
async function executeLLMInstruction(config, context) {
const { instruction, inputVariable, resultVariable } = config;
const { introspect, variables, logger, aibitat } = context;
logger(
`\x1b[43m[AgentFlowToolExecutor]\x1b[0m - executing LLM Instruction block`
);
introspect(`Processing data with LLM instruction...`);
if (!variables[inputVariable]) {
logger(`Input variable ${inputVariable} not found`);
throw new Error(`Input variable ${inputVariable} not found`);
}
try {
logger(
`Sending request to LLM (${aibitat.defaultProvider.provider}::${aibitat.defaultProvider.model})`
);
introspect(`Sending request to LLM...`);
// Ensure the input is a string since we are sending it to the LLM direct as a message
let input = variables[inputVariable];
if (typeof input === "object") input = JSON.stringify(input);
if (typeof input !== "string") input = String(input);
const provider = aibitat.getProviderForConfig(aibitat.defaultProvider);
const completion = await provider.complete([
{
role: "system",
content: `Follow these instructions carefully: ${instruction}`,
},
{
role: "user",
content: input,
},
]);
introspect(`Successfully received LLM response`);
if (resultVariable) config.resultVariable = resultVariable;
return completion.result;
} catch (error) {
logger(`LLM processing failed: ${error.message}`, error);
throw new Error(`LLM processing failed: ${error.message}`);
}
} | Execute an LLM instruction flow step
@param {Object} config Flow step configuration
@param {{introspect: Function, variables: Object, logger: Function}} context Execution context with introspect function
@returns {Promise<string>} Processed result | executeLLMInstruction ( config , context ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/llm-instruction.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/llm-instruction.js | MIT |
async function executeCode(config) {
// For now just log what would happen
console.log("Code execution:", config);
return { success: true, message: "Code executed (placeholder)" };
} | Execute a code flow step
@param {Object} config Flow step configuration
@returns {Promise<Object>} Result of the code execution | executeCode ( config ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/code.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/code.js | MIT |
async function executeWebsite(config) {
// For now just log what would happen
console.log("Website action:", config);
return { success: true, message: "Website action executed (placeholder)" };
} | Execute a website interaction flow step
@param {Object} config Flow step configuration
@returns {Promise<Object>} Result of the website interaction | executeWebsite ( config ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/website.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/website.js | MIT |
async function executeFile(config) {
// For now just log what would happen
console.log("File operation:", config);
return { success: true, message: "File operation executed (placeholder)" };
} | Execute a file operation flow step
@param {Object} config Flow step configuration
@returns {Promise<Object>} Result of the file operation | executeFile ( config ) | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/file.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/file.js | MIT |
makeSecret: () => {
const uuidAPIKey = require("uuid-apikey");
return `brx-${uuidAPIKey.create().apiKey}`;
}, | Creates a new secret for a browser extension API key.
@returns {string} brx-*** API key to use with extension | makeSecret | javascript | Mintplex-Labs/anything-llm | server/models/browserExtensionApiKey.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/browserExtensionApiKey.js | MIT |
get: async function (clause = {}) {
try {
const apiKey = await prisma.browser_extension_api_keys.findFirst({
where: clause,
});
return apiKey;
} catch (error) {
console.error("FAILED TO GET BROWSER EXTENSION API KEY.", error.message);
return null;
}
}, | Fetches browser api key by params.
@param {object} clause - Prisma props for search
@returns {Promise<{apiKey: import("@prisma/client").browser_extension_api_keys|boolean}>} | get ( clause = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/browserExtensionApiKey.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/browserExtensionApiKey.js | MIT |
migrateApiKeysToMultiUser: async function (userId) {
try {
await prisma.browser_extension_api_keys.updateMany({
where: {
user_id: null,
},
data: {
user_id: userId,
},
});
console.log("Successfully migrated API keys to multi-user mode");
} catch (error) {
console.error("Error migrating API keys to multi-user mode:", error);
}
}, | Updates owner of all DB ids to new admin.
@param {number} userId
@returns {Promise<void>} | migrateApiKeysToMultiUser ( userId ) | javascript | Mintplex-Labs/anything-llm | server/models/browserExtensionApiKey.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/browserExtensionApiKey.js | MIT |
slugify: function (...args) {
slugifyModule.extend({
"+": " plus ",
"!": " bang ",
"@": " at ",
"*": " splat ",
".": " dot ",
":": "",
"~": "",
"(": "",
")": "",
"'": "",
'"': "",
"|": "",
});
return slugifyModule(...args);
}, | The default Slugify module requires some additional mapping to prevent downstream issues
if the user is able to define a slug externally. We have to block non-escapable URL chars
so that is the slug is rendered it doesn't break the URL or UI when visited.
@param {...any} args - slugify args for npm package.
@returns {string} | slugify ( ... args ) | javascript | Mintplex-Labs/anything-llm | server/models/workspaceThread.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspaceThread.js | MIT |
isOnCooldown: function (event) {
// If the event is not debounced, return false
if (!this.debounced[event]) return false;
// If the event is not in the cooldown map, return false
const lastSent = TelemetryCooldown.get(event);
if (!lastSent) return false;
// If the event is in the cooldown map, check if it has expired
const now = Date.now();
const cooldown = this.debounced[event] * 1000;
return now - lastSent < cooldown;
}, | Checks if the event is on cooldown
@param {string} event - The event to check
@returns {boolean} - True if the event is on cooldown, false otherwise | isOnCooldown ( event ) | javascript | Mintplex-Labs/anything-llm | server/models/telemetry.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/telemetry.js | MIT |
markOnCooldown: function (event) {
if (!this.debounced[event]) return;
TelemetryCooldown.set(event, Date.now());
}, | Marks the event as on cooldown - will check if the event is debounced first
@param {string} event - The event to mark | markOnCooldown ( event ) | javascript | Mintplex-Labs/anything-llm | server/models/telemetry.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/telemetry.js | MIT |
fetchExploreItems: async function () {
return await fetch(`${this.apiBase}/explore`, {
method: "GET",
})
.then((response) => response.json())
.catch((error) => {
console.error("Error fetching explore items:", error);
return {
agentSkills: {
items: [],
hasMore: false,
totalCount: 0,
},
systemPrompts: {
items: [],
hasMore: false,
totalCount: 0,
},
slashCommands: {
items: [],
hasMore: false,
totalCount: 0,
},
};
});
}, | Fetch the explore items from the community hub that are publicly available.
@returns {Promise<{agentSkills: {items: [], hasMore: boolean, totalCount: number}, systemPrompts: {items: [], hasMore: boolean, totalCount: number}, slashCommands: {items: [], hasMore: boolean, totalCount: number}}>} | fetchExploreItems ( ) | javascript | Mintplex-Labs/anything-llm | server/models/communityHub.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/communityHub.js | MIT |
markHistoryInvalid: async function (workspaceId = null, user = null) {
if (!workspaceId) return;
try {
await prisma.workspace_chats.updateMany({
where: {
workspaceId,
user_id: user?.id,
thread_id: null, // this function is now only used for the default thread on workspaces
},
data: {
include: false,
},
});
return;
} catch (error) {
console.error(error.message);
}
}, | @deprecated Use markThreadHistoryInvalidV2 instead. | markHistoryInvalid ( workspaceId = null , user = null ) | javascript | Mintplex-Labs/anything-llm | server/models/workspaceChats.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspaceChats.js | MIT |
markThreadHistoryInvalidV2: async function (whereClause = {}) {
if (!whereClause) return;
try {
await prisma.workspace_chats.updateMany({
where: whereClause,
data: {
include: false,
},
});
return;
} catch (error) {
console.error(error.message);
}
}, | @description This function is used to mark a thread's history as invalid.
and works with an arbitrary where clause.
@param {Object} whereClause - The where clause to update the chats.
@param {Object} data - The data to update the chats with.
@returns {Promise<void>} | markThreadHistoryInvalidV2 ( whereClause = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/workspaceChats.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspaceChats.js | MIT |
validateFields: function (updates = {}) {
const validatedFields = {};
for (const [key, value] of Object.entries(updates)) {
if (!this.writable.includes(key)) continue;
if (this.validations[key]) {
validatedFields[key] = this.validations[key](value);
} else {
// If there is no validation for the field then we will just pass it through.
validatedFields[key] = value;
}
}
return validatedFields;
}, | Validate the fields for a workspace update.
@param {Object} updates - The updates to validate - should be writable fields
@returns {Object} The validated updates. Only valid fields are returned. | validateFields ( updates = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/workspace.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspace.js | MIT |
update: async function (id = null, updates = {}) {
if (!id) throw new Error("No workspace id provided for update");
const validatedUpdates = this.validateFields(updates);
if (Object.keys(validatedUpdates).length === 0)
return { workspace: { id }, message: "No valid fields to update!" };
// If the user unset the chatProvider we will need
// to then clear the chatModel as well to prevent confusion during
// LLM loading.
if (validatedUpdates?.chatProvider === "default") {
validatedUpdates.chatProvider = null;
validatedUpdates.chatModel = null;
}
return this._update(id, validatedUpdates);
}, | Update the settings for a workspace. Applies validations to the updates provided.
@param {number} id - The ID of the workspace to update.
@param {Object} updates - The data to update.
@returns {Promise<{workspace: Object | null, message: string | null}>} A promise that resolves to an object containing the updated workspace and an error message if applicable. | update ( id = null , updates = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/workspace.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspace.js | MIT |
_update: async function (id = null, data = {}) {
if (!id) throw new Error("No workspace id provided for update");
try {
const workspace = await prisma.workspaces.update({
where: { id },
data,
});
return { workspace, message: null };
} catch (error) {
console.error(error.message);
return { workspace: null, message: error.message };
}
}, | Direct update of workspace settings without any validation.
@param {number} id - The ID of the workspace to update.
@param {Object} data - The data to update.
@returns {Promise<{workspace: Object | null, message: string | null}>} A promise that resolves to an object containing the updated workspace and an error message if applicable. | _update ( id = null , data = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/workspace.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/workspace.js | MIT |
calcNextSync: function (queueRecord) {
return new Date(Number(new Date()) + queueRecord.staleAfterMs);
}, | @param {import("@prisma/client").document_sync_queues} queueRecord - queue record to calculate for | calcNextSync ( queueRecord ) | javascript | Mintplex-Labs/anything-llm | server/models/documentSyncQueue.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/documentSyncQueue.js | MIT |
canWatch: function ({ title, chunkSource = null } = {}) {
if (chunkSource.startsWith("link://") && title.endsWith(".html"))
return true; // If is web-link material (prior to feature most chunkSources were links://)
if (chunkSource.startsWith("youtube://")) return true; // If is a youtube link
if (chunkSource.startsWith("confluence://")) return true; // If is a confluence document link
if (chunkSource.startsWith("github://")) return true; // If is a GitHub file reference
if (chunkSource.startsWith("gitlab://")) return true; // If is a GitLab file reference
return false;
}, | Check if the document can be watched based on the metadata fields
@param {object} metadata - metadata to check
@param {string} metadata.title - title of the document
@param {string} metadata.chunkSource - chunk source of the document
@returns {boolean} - true if the document can be watched, false otherwise | canWatch ( { title , chunkSource = null } = { } ) | javascript | Mintplex-Labs/anything-llm | server/models/documentSyncQueue.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/documentSyncQueue.js | MIT |
viewMoreOfType: function (type) {
return `${this.website()}/list/${type}`;
}, | View more items of a given type on the community hub.
@param {string} type - The type of items to view more of. Should be kebab-case.
@returns {string} The path to view more items of the given type. | viewMoreOfType ( type ) | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/paths.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/paths.js | MIT |
function setTheme(newTheme) {
_setTheme(newTheme);
} | Sets the theme of the application and runs any
other necessary side effects
@param {string} newTheme The new theme to set | setTheme ( newTheme ) | javascript | Mintplex-Labs/anything-llm | frontend/src/hooks/useTheme.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useTheme.js | MIT |
export function useTheme() {
const [theme, _setTheme] = useState(() => {
return localStorage.getItem("theme") || "default";
});
useEffect(() => {
if (localStorage.getItem("theme") !== null) return;
if (!window.matchMedia) return;
if (window.matchMedia("(prefers-color-scheme: light)").matches)
return _setTheme("light");
_setTheme("default");
}, []);
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
document.body.classList.toggle("light", theme === "light");
localStorage.setItem("theme", theme);
window.dispatchEvent(new Event(REFETCH_LOGO_EVENT));
}, [theme]);
// In development, attach keybind combinations to toggle theme
useEffect(() => { | Determines the current theme of the application
@returns {{theme: ('default' | 'light'), setTheme: function, availableThemes: object}} The current theme, a function to set the theme, and the available themes | useTheme ( ) | javascript | Mintplex-Labs/anything-llm | frontend/src/hooks/useTheme.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useTheme.js | MIT |
export function useChatMessageAlignment() {
const [msgDirection, setMsgDirection] = useState(
() => localStorage.getItem(ALIGNMENT_STORAGE_KEY) ?? "left"
);
useEffect(() => {
if (msgDirection) localStorage.setItem(ALIGNMENT_STORAGE_KEY, msgDirection);
}, [msgDirection]);
const getMessageAlignment = useCallback(
(role) => {
const isLeftToRight = role === "user" && msgDirection === "left_right";
return isLeftToRight ? "flex-row-reverse" : "";
},
[msgDirection]
);
return {
msgDirection,
setMsgDirection,
getMessageAlignment,
};
} | Store the message alignment in localStorage as well as provide a function to get the alignment of a message via role.
@returns {{msgDirection: 'left'|'left_right', setMsgDirection: (direction: string) => void, getMessageAlignment: (role: string) => string}} - The message direction and the class name for the direction. | useChatMessageAlignment ( ) | javascript | Mintplex-Labs/anything-llm | frontend/src/hooks/useChatMessageAlignment.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useChatMessageAlignment.js | MIT |
simpleSSOLogin: async function (publicToken) {
return fetch(`${API_BASE}/request-token/sso/simple?token=${publicToken}`, {
method: "GET",
})
.then(async (res) => {
if (!res.ok) {
const text = await res.text();
if (!text.startsWith("{")) throw new Error(text);
return JSON.parse(text);
}
return await res.json();
})
.catch((e) => {
console.error(e);
return { valid: false, user: null, token: null, message: e.message };
});
}, | Validates a temporary auth token and logs in the user if the token is valid.
@param {string} publicToken - the token to validate against
@returns {Promise<{valid: boolean, user: import("@prisma/client").users | null, token: string | null, message: string | null}>} | simpleSSOLogin ( publicToken ) | javascript | Mintplex-Labs/anything-llm | frontend/src/models/system.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/models/system.js | MIT |
getSettings: () => {
try {
const settings = localStorage.getItem(APPEARANCE_SETTINGS);
return settings ? JSON.parse(settings) : Appearance.defaultSettings;
} catch (e) {
return Appearance.defaultSettings;
}
}, | Fetches any locally storage settings for the user
@returns {{showScrollbar: boolean}} | getSettings | javascript | Mintplex-Labs/anything-llm | frontend/src/models/appearance.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/models/appearance.js | MIT |
storeWorkspaceOrder: function (workspaceIds = []) {
try {
localStorage.setItem(
this.workspaceOrderStorageKey,
JSON.stringify(workspaceIds)
);
return true;
} catch (error) {
console.error("Error reordering workspaces:", error);
return false;
}
}, | Reorders workspaces in the UI via localstorage on client side.
@param {string[]} workspaceIds - array of workspace ids to reorder
@returns {boolean} | storeWorkspaceOrder ( workspaceIds = [ ] ) | javascript | Mintplex-Labs/anything-llm | frontend/src/models/workspace.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/models/workspace.js | MIT |
orderWorkspaces: function (workspaces = []) {
const workspaceOrderPreference =
safeJsonParse(localStorage.getItem(this.workspaceOrderStorageKey)) || [];
if (workspaceOrderPreference.length === 0) return workspaces;
const orderedWorkspaces = Array.from(workspaces);
orderedWorkspaces.sort(
(a, b) =>
workspaceOrderPreference.indexOf(a.id) -
workspaceOrderPreference.indexOf(b.id)
);
return orderedWorkspaces;
}, | Orders workspaces based on the order preference stored in localstorage
@param {Array} workspaces - array of workspace JSON objects
@returns {Array} - ordered workspaces | orderWorkspaces ( workspaces = [ ] ) | javascript | Mintplex-Labs/anything-llm | frontend/src/models/workspace.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/models/workspace.js | MIT |
export function readableType(type) {
switch (type) {
case "agentSkills":
case "agentSkill":
return "Agent Skills";
case "systemPrompt":
case "systemPrompts":
return "System Prompts";
case "slashCommand":
case "slashCommands":
return "Slash Commands";
}
} | Convert a type to a readable string for the community hub.
@param {("agentSkills" | "agentSkill" | "systemPrompts" | "systemPrompt" | "slashCommands" | "slashCommand")} type
@returns {string} | readableType ( type ) | javascript | Mintplex-Labs/anything-llm | frontend/src/pages/GeneralSettings/CommunityHub/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/pages/GeneralSettings/CommunityHub/utils.js | MIT |
export function typeToPath(type) {
switch (type) {
case "agentSkill":
case "agentSkills":
return "agent-skills";
case "systemPrompt":
case "systemPrompts":
return "system-prompts";
case "slashCommand":
case "slashCommands":
return "slash-commands";
}
} | Convert a type to a path for the community hub.
@param {("agentSkill" | "agentSkills" | "systemPrompt" | "systemPrompts" | "slashCommand" | "slashCommands")} type
@returns {string} | typeToPath ( type ) | javascript | Mintplex-Labs/anything-llm | frontend/src/pages/GeneralSettings/CommunityHub/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/pages/GeneralSettings/CommunityHub/utils.js | MIT |
function setDataSigner(request, response, next) {
const comKey = new CommunicationKey();
const encryptedPayloadSigner = request.header("X-Payload-Signer");
if (!encryptedPayloadSigner) console.log('Failed to find signed-payload to set encryption worker! Encryption calls will fail.');
const decryptedPayloadSignerKey = comKey.decrypt(encryptedPayloadSigner);
const encryptionWorker = new EncryptionWorker(decryptedPayloadSignerKey);
response.locals.encryptionWorker = encryptionWorker;
next();
} | @param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next | setDataSigner ( request , response , next ) | javascript | Mintplex-Labs/anything-llm | collector/middleware/setDataSigner.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/middleware/setDataSigner.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.