code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
constructor(args = {}) {
this.ready = false;
this.repo = args?.repo;
this.branch = args?.branch;
this.accessToken = args?.accessToken || null;
this.ignorePaths = args?.ignorePaths || [];
this.ignoreFilter = ignore().add(this.ignorePaths);
this.withIssues = args?.fetchIssues || false;
thi... | Creates an instance of RepoLoader.
@param {RepoLoaderArgs} [args] - The configuration options.
@returns {GitLabRepoLoader} | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async init() {
if (!this.#validGitlabUrl()) return;
await this.#validBranch();
await this.#validateAccessToken();
this.ready = true;
return this;
} | Initializes the RepoLoader instance.
@returns {Promise<RepoLoader>} The initialized RepoLoader instance. | init | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async recursiveLoader() {
if (!this.ready) throw new Error("[Gitlab Loader]: not in ready state!");
if (this.accessToken)
console.log(
`[Gitlab Loader]: Access token set! Recursive loading enabled for ${this.repo}!`
);
const docs = [];
console.log(`[Gitlab Loader]: Fetching files.... | Recursively loads the repository content.
@returns {Promise<Array<Object>>} An array of loaded documents.
@throws {Error} If the RepoLoader is not in a ready state. | recursiveLoader | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async getRepoBranches() {
if (!this.#validGitlabUrl() || !this.projectId) return [];
await this.#validateAccessToken();
this.branches = [];
const branchesRequestData = {
endpoint: `/api/v4/projects/${this.projectId}/repository/branches`,
};
let branchesPage = [];
while ((branchesPage... | Retrieves all branches for the repository.
@returns {Promise<string[]>} An array of branch names. | getRepoBranches | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async fetchFilesRecursive() {
const files = [];
const filesRequestData = {
endpoint: `/api/v4/projects/${this.projectId}/repository/tree`,
queryParams: {
ref: this.branch,
recursive: true,
},
};
let filesPage = null;
let pagePromises = [];
while ((filesPage = a... | Returns list of all file objects from tree API for GitLab
@returns {Promise<FileTreeObject[]>} | fetchFilesRecursive | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async fetchIssues() {
const issues = [];
const issuesRequestData = {
endpoint: `/api/v4/projects/${this.projectId}/issues`,
};
let issuesPage = null;
let pagePromises = [];
while ((issuesPage = await this.fetchNextPage(issuesRequestData))) {
// Fetch all the issues in parallel.
... | Fetches all issues from the repository.
@returns {Promise<Issue[]>} An array of issue objects. | fetchIssues | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async fetchWiki() {
const wikiRequestData = {
endpoint: `/api/v4/projects/${this.projectId}/wikis`,
queryParams: {
with_content: "1",
},
};
const wikiPages = await this.fetchNextPage(wikiRequestData);
console.log(`Total wiki pages fetched: ${wikiPages.length}`);
return wik... | Fetches all wiki pages from the repository.
@returns {Promise<WikiPage[]>} An array of wiki page objects. | fetchWiki | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async fetchSingleFileContents(sourceFilePath) {
try {
const data = await fetch(
`${this.apiBase}/api/v4/projects/${
this.projectId
}/repository/files/${encodeURIComponent(sourceFilePath)}/raw?ref=${
this.branch
}`,
{
method: "GET",
header... | Fetches the content of a single file from the repository.
@param {string} sourceFilePath - The path to the file in the repository.
@returns {Promise<string|null>} The content of the file, or null if fetching fails. | fetchSingleFileContents | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
async fetchNextPage(requestData) {
try {
if (requestData.page === -1) return null;
if (!requestData.page) requestData.page = 1;
const { endpoint, perPage = 100, queryParams = {} } = requestData;
const params = new URLSearchParams({
...queryParams,
per_page: perPage,
... | Fetches the next page of data from the API.
@param {Object} requestData - The request data.
@returns {Promise<Array<Object>|null>} The next page of data, or null if no more pages. | fetchNextPage | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/RepoLoader/index.js | MIT |
static getVideoID(url) {
const match = url.match(
/.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#&?]*).*/
);
if (match !== null && match[1].length === 11) {
return match[1];
} else {
throw new Error("Failed to get youtube video id from the url");
}
} | Extracts the videoId from a YouTube video URL.
@param url The URL of the YouTube video.
@returns The videoId of the YouTube video. | getVideoID | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | MIT |
static createFromUrl(url, config = {}) {
const videoId = YoutubeLoader.getVideoID(url);
return new YoutubeLoader({ ...config, videoId });
} | Creates a new instance of the YoutubeLoader class from a YouTube video
URL.
@param url The URL of the YouTube video.
@param config Optional configuration options for the YoutubeLoader instance, excluding the videoId.
@returns A new instance of the YoutubeLoader class. | createFromUrl | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | MIT |
async load() {
let transcript;
const metadata = {
source: this.#videoId,
};
try {
const { YoutubeTranscript } = require("./youtube-transcript");
transcript = await YoutubeTranscript.fetchTranscript(this.#videoId, {
lang: this.#language,
});
if (!transcript) {
... | Loads the transcript and video metadata from the specified YouTube
video. It uses the youtube-transcript library to fetch the transcript
and the youtubei.js library to fetch the video metadata.
@returns Langchain like doc that is 1 element with PageContent and | load | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/index.js | MIT |
static async fetchTranscript(videoId, config = {}) {
const identifier = this.retrieveVideoId(videoId);
const lang = config?.lang ?? "en";
try {
const transcriptUrl = await fetch(
`https://www.youtube.com/watch?v=${identifier}`,
{
headers: {
"User-Agent": USER_AGEN... | Fetch transcript from YTB Video
@param videoId Video url or video identifier
@param config Object with lang param (eg: en, es, hk, uk) format.
Will just the grab first caption if it can find one, so no special lang caption support. | fetchTranscript | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js | MIT |
static retrieveVideoId(videoId) {
if (videoId.length === 11) {
return videoId;
}
const matchId = videoId.match(RE_YOUTUBE);
if (matchId && matchId.length) {
return matchId[1];
}
throw new YoutubeTranscriptError(
"Impossible to retrieve Youtube video ID."
);
} | Retrieve video id from url or string
@param videoId video url or video id | retrieveVideoId | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/YoutubeTranscript/YoutubeLoader/youtube-transcript.js | MIT |
function isTextType(filepath) {
if (!fs.existsSync(filepath)) return false;
const result = isKnownTextMime(filepath);
if (result.valid) return true; // Known text type - return true.
if (result.reason !== "generic") return false; // If any other reason than generic - return false.
return parseableAsText(filep... | Checks if a file is text by checking the mime type and then falling back to buffer inspection.
This way we can capture all the cases where the mime type is not known but still parseable as text
without having to constantly add new mime type overrides.
@param {string} filepath - The path to the file.
@returns {boolean} ... | isTextType | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function isKnownTextMime(filepath) {
try {
const mimeLib = new MimeDetector();
const mime = mimeLib.getType(filepath);
if (mimeLib.badMimes.includes(mime))
return { valid: false, reason: "bad_mime" };
const type = mime.split("/")[0];
if (mimeLib.nonTextTypes.includes(type))
return { v... | Checks if a file is known to be text by checking the mime type.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is known to be text, false otherwise. | isKnownTextMime | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function parseableAsText(filepath) {
try {
const fd = fs.openSync(filepath, "r");
const buffer = Buffer.alloc(1024); // Read first 1KB of the file synchronously
const bytesRead = fs.readSync(fd, buffer, 0, 1024, 0);
fs.closeSync(fd);
const content = buffer.subarray(0, bytesRead).toString("utf8");... | Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding.
If the file looks too much like a binary file, it will return false.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is parseable as text, false otherwise. | parseableAsText | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function trashFile(filepath) {
if (!fs.existsSync(filepath)) return;
try {
const isDir = fs.lstatSync(filepath).isDirectory();
if (isDir) return;
} catch {
return;
}
fs.rmSync(filepath);
return;
} | Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding.
If the file looks too much like a binary file, it will return false.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is parseable as text, false otherwise. | trashFile | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function createdDate(filepath) {
try {
const { birthtimeMs, birthtime } = fs.statSync(filepath);
if (birthtimeMs === 0) throw new Error("Invalid stat for file!");
return birthtime.toLocaleString();
} catch {
return "unknown";
}
} | Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding.
If the file looks too much like a binary file, it will return false.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is parseable as text, false otherwise. | createdDate | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function writeToServerDocuments(
data = {},
filename,
destinationOverride = null
) {
const destination = destinationOverride
? path.resolve(destinationOverride)
: path.resolve(
__dirname,
"../../../server/storage/documents/custom-documents"
);
if (!fs.existsSync(destination))
... | Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding.
If the file looks too much like a binary file, it will return false.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is parseable as text, false otherwise. | writeToServerDocuments | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
async function wipeCollectorStorage() {
const cleanHotDir = new Promise((resolve) => {
const directory = path.resolve(__dirname, "../../hotdir");
fs.readdir(directory, (err, files) => {
if (err) resolve();
for (const file of files) {
if (file === "__HOTDIR__.md") continue;
try {
... | Checks if a file is parseable as text by forcing it to be read as text in utf8 encoding.
If the file looks too much like a binary file, it will return false.
@param {string} filepath - The path to the file.
@returns {boolean} - Returns true if the file is parseable as text, false otherwise. | wipeCollectorStorage | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function isWithin(outer, inner) {
if (outer === inner) return false;
const rel = path.relative(outer, inner);
return !rel.startsWith("../") && rel !== "..";
} | Checks if a given path is within another path.
@param {string} outer - The outer path (should be resolved).
@param {string} inner - The inner path (should be resolved).
@returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. | isWithin | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function normalizePath(filepath = "") {
const result = path
.normalize(filepath.trim())
.replace(/^(\.\.(\/|\\|$))+/, "")
.trim();
if (["..", ".", "/"].includes(result)) throw new Error("Invalid path.");
return result;
} | Checks if a given path is within another path.
@param {string} outer - The outer path (should be resolved).
@param {string} inner - The inner path (should be resolved).
@returns {boolean} - Returns true if the inner path is within the outer path, false otherwise. | normalizePath | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
function sanitizeFileName(fileName) {
if (!fileName) return fileName;
return fileName.replace(/[<>:"\/\\|?*]/g, "");
} | 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. | sanitizeFileName | javascript | Mintplex-Labs/anything-llm | collector/utils/files/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/index.js | MIT |
getType(filepath) {
const parsedMime = this.lib.getType(filepath);
if (!!parsedMime) return parsedMime;
return null;
} | Returns the MIME type of the file. If the file has no extension found, it will be processed as a text file.
@param {string} filepath
@returns {string} | getType | javascript | Mintplex-Labs/anything-llm | collector/utils/files/mime.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/files/mime.js | MIT |
function validBaseUrl(baseUrl) {
try {
new URL(baseUrl);
return true;
} catch (e) {
return false;
}
} | Validates if the provided baseUrl is a valid URL at all.
- Does not validate if the URL is reachable or accessible.
- Does not do any further validation of the URL like `validURL` in `utils/url/index.js`
@param {string} baseUrl
@returns {boolean} | validBaseUrl | javascript | Mintplex-Labs/anything-llm | collector/utils/http/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/http/index.js | MIT |
function setLogger() {
return new Logger().logger;
} | Sets and overrides Console methods for logging when called.
This is a singleton method and will not create multiple loggers.
@returns {winston.Logger | console} - instantiated logger interface. | setLogger | javascript | Mintplex-Labs/anything-llm | collector/utils/logger/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/logger/index.js | MIT |
constructor({ targetLanguages = "eng" } = {}) {
this.language = this.parseLanguages(targetLanguages);
this.cacheDir = path.resolve(
process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, `models`, `tesseract`)
: path.resolve(__dirname, `../../../server/storage/models/tesseract`)
... | The constructor for the OCRLoader.
@param {Object} options - The options for the OCRLoader.
@param {string} options.targetLanguages - The target languages to use for the OCR as a comma separated string. eg: "eng,deu,..." | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
parseLanguages(language = null) {
try {
if (!language || typeof language !== "string") return ["eng"];
const langList = language
.split(",")
.map((lang) => (lang.trim() !== "" ? lang.trim() : null))
.filter(Boolean)
.filter((lang) => VALID_LANGUAGE_CODES.hasOwnProperty(la... | Parses the language code from a provided comma separated string of language codes.
@param {string} language - The language code to parse.
@returns {string[]} The parsed language code. | parseLanguages | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
log(text, ...args) {
console.log(`\x1b[36m[OCRLoader]\x1b[0m ${text}`, ...args);
} | Parses the language code from a provided comma separated string of language codes.
@param {string} language - The language code to parse.
@returns {string[]} The parsed language code. | log | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
async ocrImage(filePath, { maxExecutionTime = 300_000 } = {}) {
let content = "";
let worker = null;
if (
!filePath ||
!fs.existsSync(filePath) ||
!fs.statSync(filePath).isFile()
) {
this.log(`File ${filePath} does not exist. Skipping OCR.`);
return null;
}
const d... | Loads an image file and returns the OCRed text.
@param {string} filePath - The path to the image file.
@param {Object} options - The options for the OCR.
@param {number} options.maxExecutionTime - The maximum execution time of the OCR in milliseconds.
@returns {Promise<string>} The OCRed text. | ocrImage | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
processImage = async () => {
const { data } = await worker.recognize(filePath, {}, "text");
content = data.text;
} | Loads an image file and returns the OCRed text.
@param {string} filePath - The path to the image file.
@param {Object} options - The options for the OCR.
@param {number} options.maxExecutionTime - The maximum execution time of the OCR in milliseconds.
@returns {Promise<string>} The OCRed text. | processImage | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
processImage = async () => {
const { data } = await worker.recognize(filePath, {}, "text");
content = data.text;
} | Loads an image file and returns the OCRed text.
@param {string} filePath - The path to the image file.
@param {Object} options - The options for the OCR.
@param {number} options.maxExecutionTime - The maximum execution time of the OCR in milliseconds.
@returns {Promise<string>} The OCRed text. | processImage | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
constructor({ validOps = [] } = {}) {
this.sharp = null;
this.validOps = validOps;
} | Converts a PDF page to a buffer using Sharp.
@param {Object} options - The options for the Sharp PDF page object.
@param {Object} options.page - The PDFJS page proxy object.
@returns {Promise<Buffer>} The buffer of the page. | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
log(text, ...args) {
console.log(`\x1b[36m[PDFSharp]\x1b[0m ${text}`, ...args);
} | Converts a PDF page to a buffer using Sharp.
@param {Object} options - The options for the Sharp PDF page object.
@param {Object} options.page - The PDFJS page proxy object.
@returns {Promise<Buffer>} The buffer of the page. | log | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
async init() {
this.sharp = (await import("sharp")).default;
} | Converts a PDF page to a buffer using Sharp.
@param {Object} options - The options for the Sharp PDF page object.
@param {Object} options.page - The PDFJS page proxy object.
@returns {Promise<Buffer>} The buffer of the page. | init | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
async pageToBuffer({ page }) {
if (!this.sharp) await this.init();
try {
this.log(`Converting page ${page.pageNumber} to image...`);
const ops = await page.getOperatorList();
const pageImages = ops.fnArray.length;
for (let i = 0; i < pageImages; i++) {
try {
if (!this.... | Converts a PDF page to a buffer.
@param {Object} options - The options for the Sharp PDF page object.
@param {Object} options.page - The PDFJS page proxy object.
@returns {Promise<Buffer>} The buffer of the page. | pageToBuffer | javascript | Mintplex-Labs/anything-llm | collector/utils/OCRLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/OCRLoader/index.js | MIT |
constructor() {
if (RuntimeSettings._instance) return RuntimeSettings._instance;
RuntimeSettings._instance = this;
return this;
} | Runtime settings are used to configure the collector per-request.
These settings are persisted across requests, but can be overridden per-request.
The settings are passed in the request body via `options.runtimeSettings`
which is set in the backend #attachOptions function in CollectorApi.
We do this so that the colle... | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/runtimeSettings/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/runtimeSettings/index.js | MIT |
parseOptionsFromRequest(request = {}) {
const options = reqBody(request)?.options?.runtimeSettings || {};
for (const [key, value] of Object.entries(options)) {
if (!this.settingConfigs.hasOwnProperty(key)) continue;
this.set(key, value);
}
return;
} | Parse the runtime settings from the request body options body
see #attachOptions https://github.com/Mintplex-Labs/anything-llm/blob/ebf112007e0d579af3d2b43569db95bdfc59074b/server/utils/collectorApi/index.js#L18
@param {import('express').Request} request
@returns {void} | parseOptionsFromRequest | javascript | Mintplex-Labs/anything-llm | collector/utils/runtimeSettings/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/runtimeSettings/index.js | MIT |
get(key) {
if (!this.settingConfigs[key])
throw new Error(`Invalid runtime setting: ${key}`);
return this.settings.hasOwnProperty(key)
? this.settings[key]
: this.settingConfigs[key].default;
} | Get a runtime setting
- Will throw an error if the setting requested is not a supported runtime setting key
- Will return the default value if the setting requested is not set at all
@param {string} key
@returns {any} | get | javascript | Mintplex-Labs/anything-llm | collector/utils/runtimeSettings/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/runtimeSettings/index.js | MIT |
set(key, value = null) {
if (!this.settingConfigs[key])
throw new Error(`Invalid runtime setting: ${key}`);
this.settings[key] = this.settingConfigs[key].validate(value);
} | Set a runtime setting
- Will throw an error if the setting requested is not a supported runtime setting key
- Will validate the value against the setting's validate function
@param {string} key
@param {any} value
@returns {void} | set | javascript | Mintplex-Labs/anything-llm | collector/utils/runtimeSettings/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/runtimeSettings/index.js | MIT |
tokenizeString(input = "") {
try {
if (this.#isTooLong(input)) {
this.log("Input will take too long to encode - estimating");
return Math.ceil(input.length / TikTokenTokenizer.DIVISOR);
}
return this.encoder.encode(input).length;
} catch (e) {
this.log("Could not tokeniz... | Encode a string into tokens for rough token count estimation.
@param {string} input
@returns {number} | tokenizeString | javascript | Mintplex-Labs/anything-llm | collector/utils/tokenizer/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/tokenizer/index.js | MIT |
function isInvalidIp({ hostname }) {
if (runtimeSettings.get("allowAnyIp")) {
console.log(
"\x1b[33mURL IP local address restrictions have been disabled by administrator!\x1b[0m"
);
return false;
}
const IPRegex = new RegExp(
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[... | If an ip address is passed in the user is attempting to collector some internal service running on internal/private IP.
This is not a security feature and simply just prevents the user from accidentally entering invalid IP addresses.
Can be bypassed via COLLECTOR_ALLOW_ANY_IP environment variable.
@param {URL} param0
@... | isInvalidIp | javascript | Mintplex-Labs/anything-llm | collector/utils/url/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/url/index.js | MIT |
function validURL(url) {
try {
const destination = new URL(url);
if (!VALID_PROTOCOLS.includes(destination.protocol)) return false;
if (isInvalidIp(destination)) return false;
return true;
} catch {}
return false;
} | Validates a URL
- Checks the URL forms a valid URL
- Checks the URL is at least HTTP(S)
- Checks the URL is not an internal IP - can be bypassed via COLLECTOR_ALLOW_ANY_IP
@param {string} url
@returns {boolean} | validURL | javascript | Mintplex-Labs/anything-llm | collector/utils/url/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/url/index.js | MIT |
function validatedModelSelection(model) {
try {
// If the entire select element is not found, return the model as is and cross our fingers
const selectOption = document.getElementById(`workspace-llm-model-select`);
if (!selectOption) return model;
// If the model is not in the dropdown, return the fi... | Validates the model selection by checking if the model is in the select option in the available models
dropdown. If the model is not in the dropdown, it will return the first model in the dropdown.
This exists when the user swaps providers, but did not select a model in the new provider's dropdown
and assumed the firs... | validatedModelSelection | javascript | Mintplex-Labs/anything-llm | frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js | MIT |
function hasMissingCredentials(settings, provider) {
const providerEntry = AVAILABLE_LLM_PROVIDERS.find(
(p) => p.value === provider
);
if (!providerEntry) return false;
for (const requiredKey of providerEntry.requiredConfig) {
if (!settings.hasOwnProperty(requiredKey)) return true;
if (!settings[r... | Validates the model selection by checking if the model is in the select option in the available models
dropdown. If the model is not in the dropdown, it will return the first model in the dropdown.
This exists when the user swaps providers, but did not select a model in the new provider's dropdown
and assumed the firs... | hasMissingCredentials | javascript | Mintplex-Labs/anything-llm | frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/components/WorkspaceChat/ChatContainer/PromptInput/LLMSelector/utils.js | MIT |
function useChatMessageAlignment() {
const [msgDirection, setMsgDirection] = useState(
() => localStorage.getItem(ALIGNMENT_STORAGE_KEY) ?? "left"
);
useEffect(() => {
if (msgDirection) localStorage.setItem(ALIGNMENT_STORAGE_KEY, msgDirection);
}, [msgDirection]);
const getMessageAlignment = useCall... | 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 |
function useSimpleSSO() {
const [loading, setLoading] = useState(true);
const [ssoConfig, setSsoConfig] = useState({
enabled: false,
noLogin: false,
});
useEffect(() => {
async function checkSsoConfig() {
try {
const settings = await System.keys();
setSsoConfig({
ena... | Checks if Simple SSO is enabled and if the user should be redirected to the SSO login page.
@returns {{loading: boolean, ssoConfig: {enabled: boolean, noLogin: boolean}}} | useSimpleSSO | javascript | Mintplex-Labs/anything-llm | frontend/src/hooks/useSimpleSSO.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useSimpleSSO.js | MIT |
async function checkSsoConfig() {
try {
const settings = await System.keys();
setSsoConfig({
enabled: settings?.SimpleSSOEnabled,
noLogin: settings?.SimpleSSONoLogin,
});
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
... | Checks if Simple SSO is enabled and if the user should be redirected to the SSO login page.
@returns {{loading: boolean, ssoConfig: {enabled: boolean, noLogin: boolean}}} | checkSsoConfig | javascript | Mintplex-Labs/anything-llm | frontend/src/hooks/useSimpleSSO.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useSimpleSSO.js | MIT |
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)
retu... | 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 |
function toggleOnKeybind(e) {
if (e.metaKey && e.key === ".") {
e.preventDefault();
setTheme((prev) => (prev === "light" ? "default" : "light"));
}
} | 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 | toggleOnKeybind | 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 |
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";
case "agentFlows":
case ... | Convert a type to a readable string for the community hub.
@param {("agentSkills" | "agentSkill" | "systemPrompts" | "systemPrompt" | "slashCommands" | "slashCommand" | "agentFlows" | "agentFlow")} type
@returns {string} | readableType | 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 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";
case "agentFlow":
case "ag... | Convert a type to a path for the community hub.
@param {("agentSkill" | "agentSkills" | "systemPrompt" | "systemPrompts" | "slashCommand" | "slashCommands" | "agentFlow" | "agentFlows")} type
@returns {string} | typeToPath | 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 |
CHECKLIST_ITEMS = () => [
{
id: "create_workspace",
title: t("main-page.checklist.tasks.create_workspace.title"),
description: t("main-page.checklist.tasks.create_workspace.description"),
action: t("main-page.checklist.tasks.create_workspace.action"),
handler: ({ showNewWsModal = noop }) => {
... | Function to generate the checklist items
@returns {ChecklistItem[]} | CHECKLIST_ITEMS | javascript | Mintplex-Labs/anything-llm | frontend/src/pages/Main/Home/Checklist/constants.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/pages/Main/Home/Checklist/constants.js | MIT |
CHECKLIST_ITEMS = () => [
{
id: "create_workspace",
title: t("main-page.checklist.tasks.create_workspace.title"),
description: t("main-page.checklist.tasks.create_workspace.description"),
action: t("main-page.checklist.tasks.create_workspace.action"),
handler: ({ showNewWsModal = noop }) => {
... | Function to generate the checklist items
@returns {ChecklistItem[]} | CHECKLIST_ITEMS | javascript | Mintplex-Labs/anything-llm | frontend/src/pages/Main/Home/Checklist/constants.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/pages/Main/Home/Checklist/constants.js | MIT |
static async voices() {
const tmpWorker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module",
});
tmpWorker.postMessage({ type: "voices" });
return new Promise((resolve, reject) => {
let timeout = null;
const handleMessage = (event) => {
if (event.data.type !=... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | voices | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type !== "voices") {
console.log("PiperTTSWorker debug event:", event.data);
return;
}
resolve(event.data.voices);
tmpWorker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
tm... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type !== "voices") {
console.log("PiperTTSWorker debug event:", event.data);
return;
}
resolve(event.data.voices);
tmpWorker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
tm... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
static async flush() {
const tmpWorker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module",
});
tmpWorker.postMessage({ type: "flush" });
return new Promise((resolve, reject) => {
let timeout = null;
const handleMessage = (event) => {
if (event.data.type !== ... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | flush | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type !== "flush") {
console.log("PiperTTSWorker debug event:", event.data);
return;
}
resolve(event.data.flushed);
tmpWorker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
tm... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type !== "flush") {
console.log("PiperTTSWorker debug event:", event.data);
return;
}
resolve(event.data.flushed);
tmpWorker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
tm... | Get all available voices for a client
@returns {Promise<import("@mintplex-labs/piper-tts-web/dist/types").Voice[]}>} | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
async waitForBlobResponse() {
return new Promise((resolve) => {
let timeout = null;
const handleMessage = (event) => {
if (event.data.type === "error") {
this.worker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
return resolve({ bl... | Runs prediction via webworker so we can get an audio blob back.
@returns {Promise<{blobURL: string|null, error: string|null}>} objectURL blob: type. | waitForBlobResponse | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type === "error") {
this.worker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
return resolve({ blobURL: null, error: event.data.message });
}
if (event.data.type !== "result") {
... | Runs prediction via webworker so we can get an audio blob back.
@returns {Promise<{blobURL: string|null, error: string|null}>} objectURL blob: type. | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
handleMessage = (event) => {
if (event.data.type === "error") {
this.worker.removeEventListener("message", handleMessage);
timeout && clearTimeout(timeout);
return resolve({ blobURL: null, error: event.data.message });
}
if (event.data.type !== "result") {
... | Runs prediction via webworker so we can get an audio blob back.
@returns {Promise<{blobURL: string|null, error: string|null}>} objectURL blob: type. | handleMessage | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
async getAudioBlobForText(textToSpeak, voiceId = null) {
const primaryWorker = this.#getWorker();
primaryWorker.postMessage({
type: "init",
text: String(textToSpeak),
voiceId: voiceId ?? this.voiceId,
// Don't reference WASM because in the docker image
// the user will be connected... | Runs prediction via webworker so we can get an audio blob back.
@returns {Promise<{blobURL: string|null, error: string|null}>} objectURL blob: type. | getAudioBlobForText | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/index.js | MIT |
async function main(event) {
if (event.data.type === "voices") {
const stored = await TTS.stored();
const voices = await TTS.voices();
voices.forEach((voice) => (voice.is_stored = stored.includes(voice.key)));
self.postMessage({ type: "voices", voices });
return;
}
if (event.data.type === "f... | Web worker for generating client-side PiperTTS predictions
@param {MessageEvent<PredictionRequest | VoicesRequest | FlushRequest>} event - The event object containing the prediction request
@returns {Promise<PredictionRequestResponse|VoicesRequestResponse|FlushRequestResponse>} | main | javascript | Mintplex-Labs/anything-llm | frontend/src/utils/piperTTS/worker.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/utils/piperTTS/worker.js | MIT |
function getModelTag() {
let model = null;
const provider = process.env.LLM_PROVIDER;
switch (provider) {
case "openai":
model = process.env.OPEN_MODEL_PREF;
break;
case "anthropic":
model = process.env.ANTHROPIC_MODEL_PREF;
break;
case "lmstudio":
model = process.env.LM... | Returns the model tag based on the provider set in the environment.
This information is used to identify the parent model for the system
so that we can prioritize the correct model and types for future updates
as well as build features in AnythingLLM directly for a specific model or capabilities.
Disable with {@link ... | getModelTag | javascript | Mintplex-Labs/anything-llm | server/endpoints/utils.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/endpoints/utils.js | MIT |
function mergeConnections(existingConnections = [], updates = []) {
let updatedConnections = [...existingConnections];
const existingDbIds = existingConnections.map((conn) => conn.database_id);
// First remove all 'action:remove' candidates from existing connections.
const toRemove = updates
.filter((conn)... | Get user configured Community Hub Settings
Connection key is used to authenticate with the Community Hub API
for your account.
@returns {Promise<{connectionKey: string}>} | mergeConnections | javascript | Mintplex-Labs/anything-llm | server/models/systemSettings.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/models/systemSettings.js | MIT |
getValueFromPath(obj = {}, path = "") {
if (typeof obj === "string") obj = safeJsonParse(obj, {});
if (
!obj ||
!path ||
typeof obj !== "object" ||
Object.keys(obj).length === 0 ||
typeof path !== "string"
)
return "";
// First split by dots that are not inside brac... | Resolves nested values from objects using dot notation and array indices
Supports paths like "data.items[0].name" or "response.users[2].address.city"
Returns undefined for invalid paths or errors
@param {Object|string} obj - The object to resolve the value from
@param {string} path - The path to the value
@returns {str... | getValueFromPath | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.js | MIT |
replaceVariables(config) {
const deepReplace = (obj) => {
if (typeof obj === "string") {
return obj.replace(/\${([^}]+)}/g, (match, varName) => {
const value = this.getValueFromPath(this.variables, varName);
return value !== undefined ? value : match;
});
}
if ... | Replaces variables in the config with their values
@param {Object} config - The config to replace variables in
@returns {Object} The config with variables replaced | replaceVariables | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.js | MIT |
deepReplace = (obj) => {
if (typeof obj === "string") {
return obj.replace(/\${([^}]+)}/g, (match, varName) => {
const value = this.getValueFromPath(this.variables, varName);
return value !== undefined ? value : match;
});
}
if (Array.isArray(obj)) return obj.map((... | Replaces variables in the config with their values
@param {Object} config - The config to replace variables in
@returns {Object} The config with variables replaced | deepReplace | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.js | MIT |
deepReplace = (obj) => {
if (typeof obj === "string") {
return obj.replace(/\${([^}]+)}/g, (match, varName) => {
const value = this.getValueFromPath(this.variables, varName);
return value !== undefined ? value : match;
});
}
if (Array.isArray(obj)) return obj.map((... | Replaces variables in the config with their values
@param {Object} config - The config to replace variables in
@returns {Object} The config with variables replaced | deepReplace | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.js | MIT |
async executeStep(step) {
const config = this.replaceVariables(step.config);
let result;
// Create execution context with introspect
const context = {
introspect: this.introspect,
variables: this.variables,
logger: this.logger,
aibitat: this.aibitat,
};
switch (step.type... | Executes a single step of the flow
@param {Object} step - The step to execute
@returns {Promise<Object>} The result of the step | executeStep | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.js | MIT |
async executeFlow(flow, initialVariables = {}, aibitat) {
await Telemetry.sendTelemetry("agent_flow_execution_started");
// Initialize variables with both initial values and any passed-in values
this.variables = {
...(
flow.config.steps.find((s) => s.type === "start")?.config?.variables ||
... | Execute entire flow
@param {Object} flow - The flow to execute
@param {Object} initialVariables - Initial variables for the flow
@param {Object} aibitat - The aibitat instance from the agent handler | executeFlow | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executor.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executor.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.... | 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;
re... | 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 | 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);
// Prevent saving flows with unsupported blocks or... | 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 | 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 li... | 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("F... | Delete a flow by UUID
@param {string} uuid - The UUID of the flow to delete
@returns {Object} Result of the delete operation | deleteFlow | 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 | 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 |
static loadFlowPlugin(uuid) {
const flow = AgentFlows.loadFlow(uuid);
if (!flow) return null;
const startBlock = flow.config.steps?.find((s) => s.type === "start");
const variables = startBlock?.config?.variables || [];
return {
name: `flow_${uuid}`,
description: `Execute agent flow: $... | Load a flow plugin by its UUID
@param {string} uuid - The UUID of the flow to load
@returns {Object|null} Plugin configuration or null if not found | loadFlowPlugin | 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 stringifyResult(input) {
return typeof input === "object" ? JSON.stringify(input) : String(input);
} | Stringify the result of a flow execution or return the input as is
@param {Object|string} input - The result to stringify
@returns {string} The stringified result | stringifyResult | 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 executeApiCall(config, context) {
const { url, method, headers = [], body, bodyType, formData } = config;
const { introspect, logger } = context;
logger(`\x1b[43m[AgentFlowToolExecutor]\x1b[0m - executing API Call block`);
introspect(`Making ${method} request to external API...`);
const reques... | Execute an API call flow step
@param {Object} config Flow step configuration
@param {Object} context Execution context with introspect function
@returns {Promise<string>} Response data | executeApiCall | javascript | Mintplex-Labs/anything-llm | server/utils/agentFlows/executors/api-call.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/api-call.js | MIT |
async function executeLLMInstruction(config, context) {
const { instruction, resultVariable } = config;
const { introspect, logger, aibitat } = context;
logger(
`\x1b[43m[AgentFlowToolExecutor]\x1b[0m - executing LLM Instruction block`
);
introspect(`Processing data with LLM instruction...`);
try {
... | Execute an LLM instruction flow step
@param {Object} config Flow step configuration
@param {{introspect: Function, logger: Function}} context Execution context with introspect function
@returns {Promise<string>} Processed result | executeLLMInstruction | 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 executeWebScraping(config, context) {
const { CollectorApi } = require("../../collectorApi");
const { TokenManager } = require("../../helpers/tiktoken");
const Provider = require("../../agents/aibitat/providers/ai-provider");
const { summarizeContent } = require("../../agents/aibitat/utils/summar... | 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 | 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 selecte... | 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 | 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 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" },
"[]"
),
... | 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 = sessi... | @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 | 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 |
log(text, ...args) {
console.log(`\x1b[36m[EphemeralAgentHandler]\x1b[0m ${text}`, ...args);
} | @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 | log | 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 |
closeAlert() {
this.log(`End ${this.#invocationUUID}::${this.provider}:${this.model}`);
} | @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 | closeAlert | 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 init() {
this.#providerSetupAndCheck();
return this;
} | Finds or assumes the model preference value to use for API calls.
If multi-model loading is supported, we use their agent model selection of the workspace
If not supported, we attempt to fallback to the system provider value for the LLM preference
and if that fails - we assume a reasonable base model to exist.
@returns... | init | 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 createAIbitat(
args = {
handler,
}
) {
this.aibitat = new AIbitat({
provider: this.provider ?? "openai",
model: this.model ?? "gpt-4o",
chats: await this.#chatHistory(20),
handlerProps: {
invocation: {
workspace: this.#workspace,
workspace_id... | Finds or assumes the model preference value to use for API calls.
If multi-model loading is supported, we use their agent model selection of the workspace
If not supported, we attempt to fallback to the system provider value for the LLM preference
and if that fails - we assume a reasonable base model to exist.
@returns... | createAIbitat | 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 |
startAgentCluster() {
return this.aibitat.start({
from: USER_AGENT.name,
to: this.channel ?? WORKSPACE_AGENT.name,
content: this.#prompt,
});
} | Finds or assumes the model preference value to use for API calls.
If multi-model loading is supported, we use their agent model selection of the workspace
If not supported, we attempt to fallback to the system provider value for the LLM preference
and if that fails - we assume a reasonable base model to exist.
@returns... | startAgentCluster | 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 |
static isAgentInvocation({ message }) {
const agentHandles = WorkspaceAgentInvocation.parseAgents(message);
if (agentHandles.length > 0) return true;
return false;
} | Determine if the message provided is an agent invocation.
@param {{message:string}} parameters
@returns {boolean} | isAgentInvocation | 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 |
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 | 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 isValidLocation(pathToValidate) {
if (!isWithin(pluginsPath, pathToValidate)) return false;
if (!fs.existsSync(pathToValidate)) return false;
return true;
} | Gets the imported plugin handler.
@param {string} hubId - The hub ID of the plugin.
@returns {ImportedPlugin} - The plugin handler. | isValidLocation | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.