code stringlengths 28 313k | docstring stringlengths 25 85.3k | func_name stringlengths 1 74 | language stringclasses 1
value | repo stringlengths 5 60 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
constructPrompt({
systemPrompt = "",
contextTexts = [],
chatHistory = [],
userPrompt = "",
attachments = [], // This is the specific attachment for only this prompt
}) {
const prompt = {
role: "system",
content: `${systemPrompt}${this.#appendContext(contextTexts)}`,
};
ret... | Generates appropriate content array for a message + attachments.
@param {{userPrompt:string, attachments: import("../../helpers").Attachment[]}}
@returns {string|object[]} | constructPrompt | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/anthropic/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/anthropic/index.js | MIT |
handleStream(response, stream, responseProps) {
return new Promise((resolve) => {
let fullText = "";
const { uuid = v4(), sources = [] } = responseProps;
let usage = {
prompt_tokens: 0,
completion_tokens: 0,
};
// Establish listener to early-abort a streaming response
... | Handles the stream response from the Anthropic API.
@param {Object} response - the response object
@param {import('../../helpers/chat/LLMPerformanceMonitor').MonitoredStream} stream - the stream response from the Anthropic API w/tracking
@param {Object} responseProps - the response properties
@returns {Promise<string>} | handleStream | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/anthropic/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/anthropic/index.js | MIT |
constructor(embedder = null, modelPreference = null) {
const requiredEnvVars = [
...(this.authMethod !== "iam_role"
? [
// required for iam and sessionToken
"AWS_BEDROCK_LLM_ACCESS_KEY_ID",
"AWS_BEDROCK_LLM_ACCESS_KEY",
]
: []),
...(this.auth... | Initializes the AWS Bedrock LLM connector.
@param {object | null} [embedder=null] - An optional embedder instance. Defaults to NativeEmbedder.
@param {string | null} [modelPreference=null] - Optional model ID override. Defaults to environment variable.
@throws {Error} If required environment variables are missing or in... | constructor | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
streamingEnabled() {
return "streamGetChatCompletion" in this;
} | Indicates if the provider supports streaming responses.
@returns {boolean} True. | streamingEnabled | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
async isValidChatCompletionModel(_modelName = "") {
return true;
} | Stubbed method for compatibility with LLM interface. | isValidChatCompletionModel | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
constructPrompt({
systemPrompt = "",
contextTexts = [],
chatHistory = [],
userPrompt = "",
attachments = [],
}) {
const systemMessageContent = `${systemPrompt}${this.#appendContext(contextTexts)}`;
let messages = [];
// Handle system prompt (either real or simulated)
if (this.noSy... | Constructs the complete message array in the format expected by the Bedrock Converse API.
@param {object} params
@param {string} params.systemPrompt - The system prompt text.
@param {string[]} params.contextTexts - Array of context text snippets.
@param {Array<{role: 'user' | 'assistant', content: string, attachments?:... | constructPrompt | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
async getChatCompletion(messages = null, { temperature }) {
if (!messages?.length)
throw new Error(
"AWSBedrock::getChatCompletion requires a non-empty messages array."
);
const hasSystem = messages[0]?.role === "system";
const systemBlock = hasSystem ? messages[0].content : undefined;
... | Sends a request for chat completion (non-streaming).
@param {Array<object> | null} messages - Formatted message array from constructPrompt.
@param {object} options - Request options.
@param {number} options.temperature - Sampling temperature.
@returns {Promise<object | null>} Response object with textResponse and metri... | getChatCompletion | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
async streamGetChatCompletion(messages = null, { temperature }) {
if (!Array.isArray(messages) || messages.length === 0) {
throw new Error(
"AWSBedrock::streamGetChatCompletion requires a non-empty messages array."
);
}
const hasSystem = messages[0]?.role === "system";
const systemB... | Sends a request for streaming chat completion.
@param {Array<object> | null} messages - Formatted message array from constructPrompt.
@param {object} options - Request options.
@param {number} [options.temperature] - Sampling temperature.
@returns {Promise<import('../../helpers/chat/LLMPerformanceMonitor').MonitoredStr... | streamGetChatCompletion | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
handleStream(response, stream, responseProps) {
const { uuid = uuidv4(), sources = [] } = responseProps;
let hasUsageMetrics = false;
let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
return new Promise(async (resolve) => {
let fullText = "";
let reasoningText = "";
... | Handles the stream response from the AWS Bedrock API ConverseStreamCommand.
Parses chunks, handles reasoning tags, and estimates token usage if not provided.
@param {object} response - The HTTP response object to write chunks to.
@param {import('../../helpers/chat/LLMPerformanceMonitor').MonitoredStream} stream - The m... | handleStream | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/index.js | MIT |
function getImageFormatFromMime(mimeType = "") {
if (!mimeType) return null;
const parts = mimeType.toLowerCase().split("/");
if (parts?.[0] !== "image") return null;
let format = parts?.[1];
if (!format) return null;
// Remap jpg to jpeg
switch (format) {
case "jpg":
format = "jpeg";
bre... | Parses a MIME type string (e.g., "image/jpeg") to extract and validate the image format
supported by Bedrock Converse. Handles 'image/jpg' as 'jpeg'.
@param {string | null | undefined} mimeType - The MIME type string.
@returns {string | null} The validated image format (e.g., "jpeg") or null if invalid/unsupported. | getImageFormatFromMime | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/utils.js | MIT |
function base64ToUint8Array(base64String) {
try {
const binaryString = atob(base64String);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = binaryString.charCodeAt(i);
return bytes;
} catch (e) {
console.error(
`[AWSBedrock] E... | Decodes a pure base64 string (without data URI prefix) into a Uint8Array using the atob method.
This approach matches the technique previously used by Langchain's implementation.
@param {string} base64String - The pure base64 encoded data.
@returns {Uint8Array | null} The resulting byte array or null on decoding error. | base64ToUint8Array | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/bedrock/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/bedrock/utils.js | MIT |
async handleStream(response, stream, responseProps) {
return new Promise(async (resolve) => {
const { uuid = v4(), sources = [] } = responseProps;
let fullText = "";
let usage = {
prompt_tokens: 0,
completion_tokens: 0,
};
const handleAbort = () => {
writeRespo... | Handles the stream response from the Cohere API.
@param {Object} response - the response object
@param {import('../../helpers/chat/LLMPerformanceMonitor').MonitoredStream} stream - the stream response from the Cohere API w/tracking
@param {Object} responseProps - the response properties
@returns {Promise<string>} | handleStream | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/cohere/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/cohere/index.js | MIT |
async getChatCompletion(messages = null, { temperature = 0.7 }) {
if (!(await this.isValidChatCompletionModel(this.model)))
throw new Error(
`DeepSeek chat: ${this.model} is not valid for chat completion!`
);
const result = await LLMPerformanceMonitor.measureAsyncFunction(
this.openai... | Parses and prepends reasoning from the response and returns the full text response.
@param {Object} response
@returns {string} | getChatCompletion | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/deepseek/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/deepseek/index.js | MIT |
static parseBasePath(providedBasePath = process.env.DPAIS_LLM_BASE_PATH) {
try {
const baseURL = new URL(providedBasePath);
const basePath = `${baseURL.origin}/v1/openai`;
return basePath;
} catch (e) {
return null;
}
} | Parse the base path for the Dell Pro AI Studio API
so we can use it for inference requests
@param {string} providedBasePath
@returns {string} | parseBasePath | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/dellProAiStudio/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/dellProAiStudio/index.js | MIT |
constructPrompt({
systemPrompt = "",
contextTexts = [],
chatHistory = [],
userPrompt = "",
_attachments = [], // not used for Dell Pro AI Studio - `attachments` passed in is ignored
}) {
const prompt = {
role: "system",
content: `${systemPrompt}${this.#appendContext(contextTexts)}`... | Construct the user prompt for this model.
@param {{attachments: import("../../helpers").Attachment[]}} param0
@returns | constructPrompt | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/dellProAiStudio/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/dellProAiStudio/index.js | MIT |
get supportsSystemPrompt() {
return !NO_SYSTEM_PROMPT_MODELS.includes(this.model);
} | Checks if the model supports system prompts
This is a static list of models that are known to not support system prompts
since this information is not available in the API model response.
@returns {boolean} | supportsSystemPrompt | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/gemini/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/gemini/index.js | MIT |
isExperimentalModel(modelName) {
if (
fs.existsSync(cacheFolder) &&
fs.existsSync(path.resolve(cacheFolder, "models.json"))
) {
const models = safeJsonParse(
fs.readFileSync(path.resolve(cacheFolder, "models.json"))
);
const model = models.find((model) => model.id === model... | Checks if a model is experimental by reading from the cache if available, otherwise it will perform
a blind check against the v1BetaModels list - which is manually maintained and updated.
@param {string} modelName - The name of the model to check
@returns {boolean} A boolean indicating if the model is experimental | isExperimentalModel | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/gemini/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/gemini/index.js | MIT |
async isValidChatCompletionModel(modelName = "") {
const models = await this.fetchModels(process.env.GEMINI_API_KEY);
return models.some((model) => model.id === modelName);
} | Checks if a model is valid for chat completion (unused)
@deprecated
@param {string} modelName - The name of the model to check
@returns {Promise<boolean>} A promise that resolves to a boolean indicating if the model is valid | isValidChatCompletionModel | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/gemini/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/gemini/index.js | MIT |
function parseLMStudioBasePath(providedBasePath = "") {
try {
const baseURL = new URL(providedBasePath);
const basePath = `${baseURL.origin}/v1`;
return basePath;
} catch (e) {
return providedBasePath;
}
} | Parse the base path for the LMStudio API. Since the base path must end in /v1 and cannot have a trailing slash,
and the user can possibly set it to anything and likely incorrectly due to pasting behaviors, we need to ensure it is in the correct format.
@param {string} basePath
@returns {string} | parseLMStudioBasePath | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/lmStudio/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/lmStudio/index.js | MIT |
constructor() {
if (ContextWindowFinder.instance) return ContextWindowFinder.instance;
ContextWindowFinder.instance = this;
if (!fs.existsSync(this.cacheLocation))
fs.mkdirSync(this.cacheLocation, { recursive: true });
// If the cache is stale or not found at all, pull the model map from remote
... | Mapping for AnythingLLM provider <> LiteLLM provider
@type {Record<string, string>} | constructor | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/modelMap/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/modelMap/index.js | MIT |
get isCacheStale() {
if (!fs.existsSync(this.cacheFileExpiryPath)) return true;
const cachedAt = fs.readFileSync(this.cacheFileExpiryPath, "utf8");
return Date.now() - cachedAt > ContextWindowFinder.expiryMs;
} | Checks if the cache is stale by checking if the cache file exists and if the cache file is older than the expiry time.
@returns {boolean} | isCacheStale | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/modelMap/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/modelMap/index.js | MIT |
get cachedModelMap() {
if (!fs.existsSync(this.cacheFilePath)) {
this.log(`\x1b[33m
--------------------------------
[WARNING] Model map cache is not found!
Invalid context windows will be returned leading to inaccurate model responses
or smaller context windows than expected.
You can fix this by restarting A... | Gets the cached model map.
Always returns the available model map - even if it is expired since re-pulling
the model map only occurs on container start/system start.
@returns {Record<string, Record<string, number>> | null} - The cached model map | cachedModelMap | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/modelMap/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/modelMap/index.js | MIT |
get(provider = null, model = null) {
if (!provider || !this.cachedModelMap || !this.cachedModelMap[provider])
return null;
if (!model) return this.cachedModelMap[provider];
const modelContextWindow = this.cachedModelMap[provider][model];
if (!modelContextWindow) {
this.log("Invalid access t... | Gets the context window for a given provider and model.
If the provider is not found, null is returned.
If the model is not found, the provider's entire model map is returned.
if both provider and model are provided, the context window for the given model is returned.
@param {string|null} provider - The provider to g... | get | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/modelMap/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/modelMap/index.js | MIT |
models() {
if (!fs.existsSync(this.cacheModelPath)) return {};
return safeJsonParse(
fs.readFileSync(this.cacheModelPath, { encoding: "utf-8" }),
{}
);
} | Novita has various models that never return `finish_reasons` and thus leave the stream open
which causes issues in subsequent messages. This timeout value forces us to close the stream after
x milliseconds. This is a configurable value via the NOVITA_LLM_TIMEOUT_MS value
@returns {number} The timeout value in milliseco... | models | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/novita/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/novita/index.js | MIT |
handleStream(response, stream, responseProps) {
const timeoutThresholdMs = this.timeout;
const { uuid = uuidv4(), sources = [] } = responseProps;
return new Promise(async (resolve) => {
let fullText = "";
let lastChunkTime = null; // null when first token is still not received.
// Establ... | Handles the default stream response for a chat.
@param {import("express").Response} response
@param {import('../../helpers/chat/LLMPerformanceMonitor').MonitoredStream} stream
@param {Object} responseProps
@returns {Promise<string>} | handleStream | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/novita/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/novita/index.js | MIT |
function parseNvidiaNimBasePath(providedBasePath = "") {
try {
const baseURL = new URL(providedBasePath);
const basePath = `${baseURL.origin}/v1`;
return basePath;
} catch (e) {
return providedBasePath;
}
} | Parse the base path for the Nvidia NIM container API. Since the base path must end in /v1 and cannot have a trailing slash,
and the user can possibly set it to anything and likely incorrectly due to pasting behaviors, we need to ensure it is in the correct format.
@param {string} basePath
@returns {string} | parseNvidiaNimBasePath | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/nvidiaNim/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/nvidiaNim/index.js | MIT |
handleStream(response, stream, responseProps) {
const { uuid = uuidv4(), sources = [] } = responseProps;
return new Promise(async (resolve) => {
let fullText = "";
let usage = {
prompt_tokens: 0,
completion_tokens: 0,
};
// Establish listener to early-abort a streaming ... | Handles streaming responses from Ollama.
@param {import("express").Response} response
@param {import("../../helpers/chat/LLMPerformanceMonitor").MonitoredStream} stream
@param {import("express").Request} request
@returns {Promise<string>} | handleStream | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/ollama/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/ollama/index.js | MIT |
get isOTypeModel() {
return this.model.startsWith("o");
} | Check if the model is an o1 model.
@returns {boolean} | isOTypeModel | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/openAi/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/openAi/index.js | MIT |
get isPerplexityModel() {
return this.model.startsWith("perplexity/");
} | Returns true if the model is a Perplexity model.
OpenRouter has support for a lot of models and we have some special handling for Perplexity models
that support in-line citations.
@returns {boolean} | isPerplexityModel | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/openRouter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/openRouter/index.js | MIT |
enrichToken({ token, citations = [] }) {
if (!Array.isArray(citations) || citations.length === 0) return token;
return token.replace(/\[(\d+)\]/g, (match, index) => {
const citationIndex = parseInt(index) - 1;
return citations[citationIndex]
? `[[${index}](${citations[citationIndex]})]`
... | Generic formatting of a token for the following use cases:
- Perplexity models that return inline citations in the token text
@param {{token: string, citations: string[]}} options - The token text and citations.
@returns {string} - The formatted token text. | enrichToken | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/openRouter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/openRouter/index.js | MIT |
static promptWindowLimit(modelName) {
const cacheModelPath = path.resolve(cacheFolder, "models.json");
const availableModels = fs.existsSync(cacheModelPath)
? safeJsonParse(
fs.readFileSync(cacheModelPath, { encoding: "utf-8" }),
{}
)
: {};
return availableModels[mode... | OpenRouter has various models that never return `finish_reasons` and thus leave the stream open
which causes issues in subsequent messages. This timeout value forces us to close the stream after
x milliseconds. This is a configurable value via the OPENROUTER_TIMEOUT_MS value
@returns {number} The timeout value in milli... | promptWindowLimit | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/openRouter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/openRouter/index.js | MIT |
enrichToken(token, citations) {
if (!Array.isArray(citations) || citations.length === 0) return token;
return token.replace(/\[(\d+)\]/g, (match, index) => {
const citationIndex = parseInt(index) - 1;
return citations[citationIndex]
? `[[${index}](${citations[citationIndex]})]`
: mat... | Enrich a token with citations if available for in-line citations.
@param {string} token - The token to enrich.
@param {Array} citations - The citations to enrich the token with.
@returns {string} The enriched token. | enrichToken | javascript | Mintplex-Labs/anything-llm | server/utils/AiProviders/perplexity/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/AiProviders/perplexity/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 |
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 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 |
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 |
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 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 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 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 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 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 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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 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 |
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 |
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... | 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 | 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; // ... | 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 | 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 |
constructor() {
if (MCPHypervisor._instance) return MCPHypervisor._instance;
MCPHypervisor._instance = this;
this.log("Initializing MCP Hypervisor - subsequent calls will boot faster");
this.#setupConfigFile();
return this;
} | The results of the MCP server loading process.
@type { { [key: string]: {status: 'success' | 'failed', message: string} } } | constructor | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
log(text, ...args) {
console.log(`\x1b[36m[${this.constructor.name}]\x1b[0m ${text}`, ...args);
} | Setup the MCP server definitions file.
Will create the file/directory if it doesn't exist already in storage/plugins with blank options | log | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
get mcpServerConfigs() {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
return Object.entries(servers.mcpServers).map(([name, server]) => ({
name,
server,
}));
} | Get the MCP servers from the JSON file.
@returns { { name: string, server: { command: string, args: string[], env: { [key: string]: string } } }[] } The MCP servers. | mcpServerConfigs | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
removeMCPServerFromConfig(name) {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
if (!servers.mcpServers[name]) return false;
delete servers.mcpServers[name];
fs.writeFileSync(
this.mcpServerJSONPath,
JSON.stringify(serv... | Remove the MCP server from the config file
@param {string} name - The name of the MCP server to remove
@returns {boolean} - True if the MCP server was removed, false otherwise | removeMCPServerFromConfig | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
async reloadMCPServers() {
this.pruneMCPServers();
await this.bootMCPServers();
} | Reload the MCP servers - can be used to reload the MCP servers without restarting the server or app
and will also apply changes to the config file if any where made. | reloadMCPServers | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
async startMCPServer(name) {
if (this.mcps[name])
return { success: false, error: `MCP server ${name} already running` };
const config = this.mcpServerConfigs.find((s) => s.name === name);
if (!config)
return {
success: false,
error: `MCP server ${name} not found in config file`,... | Start a single MCP server by its server name - public method
@param {string} name - The name of the MCP server to start
@returns {Promise<{success: boolean, error: string | null}>} | startMCPServer | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
pruneMCPServer(name) {
if (!name || !this.mcps[name]) return true;
this.log(`Pruning MCP server: ${name}`);
const mcp = this.mcps[name];
const childProcess = mcp.transport._process;
if (childProcess) childProcess.kill(1);
mcp.transport.close();
delete this.mcps[name];
this.mcpLoadingRe... | Prune a single MCP server by its server name
@param {string} name - The name of the MCP server to prune
@returns {boolean} - True if the MCP server was pruned, false otherwise | pruneMCPServer | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
pruneMCPServers() {
this.log(`Pruning ${Object.keys(this.mcps).length} MCP servers...`);
for (const name of Object.keys(this.mcps)) {
if (!this.mcps[name]) continue;
const mcp = this.mcps[name];
const childProcess = mcp.transport._process;
if (childProcess)
this.log(`Killing MCP... | Prune the MCP servers - pkills and forgets all MCP servers
@returns {void} | pruneMCPServers | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
createHttpTransport(server) {
const url = new URL(server.url);
// If the server block has a type property then use that to determine the transport type
switch (server.type) {
case "streamable":
return new StreamableHTTPClientTransport(url, {
requestInit: {
headers: serve... | Create MCP client transport for http MCP server.
@param {Object} server - The server definition
@returns {StreamableHTTPClientTransport | SSEClientTransport} - The server transport | createHttpTransport | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
async bootMCPServers() {
if (Object.keys(this.mcps).length > 0) {
this.log("MCP Servers already running, skipping boot.");
return this.mcpLoadingResults;
}
const serverDefinitions = this.mcpServerConfigs;
for (const { name, server } of serverDefinitions) {
if (
server.anything... | Boot the MCP servers according to the server definitions.
This function will skip booting MCP servers if they are already running.
@returns { Promise<{ [key: string]: {status: string, message: string} }> } The results of the boot process. | bootMCPServers | javascript | Mintplex-Labs/anything-llm | server/utils/MCP/hypervisor/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js | MIT |
function chatHistoryViewable(_request, response, next) {
if ("DISABLE_VIEW_CHAT_HISTORY" in process.env)
return response
.status(422)
.send("This feature has been disabled by the administrator.");
next();
} | A simple middleware that validates that the chat history is viewable.
via the `DISABLE_VIEW_CHAT_HISTORY` environment variable being set AT ALL.
@param {Request} request - The request object.
@param {Response} response - The response object.
@param {NextFunction} next - The next function. | chatHistoryViewable | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/chatHistoryViewable.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/chatHistoryViewable.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.