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; this.withWikis = args?.fetchWikis || false; this.projectId = null; this.apiBase = "https://gitlab.com"; this.author = null; this.project = null; this.branches = []; }
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.`); const files = await this.fetchFilesRecursive(); console.log(`[Gitlab Loader]: Fetched ${files.length} files.`); for (const file of files) { if (this.ignoreFilter.ignores(file.path)) continue; docs.push({ pageContent: file.content, metadata: { source: file.path, url: `${this.repo}/-/blob/${this.branch}/${file.path}`, }, }); } if (this.withIssues) { console.log(`[Gitlab Loader]: Fetching issues.`); const issues = await this.fetchIssues(); console.log( `[Gitlab Loader]: Fetched ${issues.length} issues with discussions.` ); docs.push( ...issues.map((issue) => ({ issue, metadata: { source: `issue-${this.repo}-${issue.iid}`, url: issue.web_url, }, })) ); } if (this.withWikis) { console.log(`[Gitlab Loader]: Fetching wiki.`); const wiki = await this.fetchWiki(); console.log(`[Gitlab Loader]: Fetched ${wiki.length} wiki pages.`); docs.push( ...wiki.map((wiki) => ({ wiki, metadata: { source: `wiki-${this.repo}-${wiki.slug}`, url: `${this.repo}/-/wikis/${wiki.slug}`, }, })) ); } return docs; }
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 = await this.fetchNextPage(branchesRequestData))) { this.branches.push(...branchesPage.map((branch) => branch.name)); } return this.#branchPrefSort(this.branches); }
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 = await this.fetchNextPage(filesRequestData))) { // Fetch all the files that are not ignored in parallel. pagePromises = filesPage .filter((file) => { if (file.type !== "blob") return false; return !this.ignoreFilter.ignores(file.path); }) .map(async (file) => { const content = await this.fetchSingleFileContents(file.path); if (!content) return null; return { path: file.path, content, }; }); const pageFiles = await Promise.all(pagePromises); files.push(...pageFiles.filter((item) => item !== null)); console.log(`Fetched ${files.length} files.`); } console.log(`Total files fetched: ${files.length}`); return files; }
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. pagePromises = issuesPage.map(async (issue) => { const discussionsRequestData = { endpoint: `/api/v4/projects/${this.projectId}/issues/${issue.iid}/discussions`, }; let discussionPage = null; const discussions = []; while ( (discussionPage = await this.fetchNextPage(discussionsRequestData)) ) { discussions.push( ...discussionPage.map(({ notes }) => notes.map( ({ body, author, created_at }) => `${author.username} at ${created_at}: ${body}` ) ) ); } const result = { ...issue, discussions, }; return result; }); const pageIssues = await Promise.all(pagePromises); issues.push(...pageIssues); console.log(`Fetched ${issues.length} issues.`); } console.log(`Total issues fetched: ${issues.length}`); return issues; }
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 wikiPages; }
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", headers: this.accessToken ? { "PRIVATE-TOKEN": this.accessToken } : {}, } ).then((res) => { if (res.ok) return res.text(); throw new Error(`Failed to fetch single file ${sourceFilePath}`); }); return data; } catch (e) { console.error(`RepoLoader.fetchSingleFileContents`, e); return null; } }
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, page: requestData.page, }); const url = `${this.apiBase}${endpoint}?${params.toString()}`; const response = await fetch(url, { method: "GET", headers: this.accessToken ? { "PRIVATE-TOKEN": this.accessToken } : {}, }); // Rate limits get hit very often if no PAT is provided if (response.status === 401) { console.warn(`Rate limit hit for ${endpoint}. Skipping.`); return null; } const totalPages = Number(response.headers.get("x-total-pages")); const data = await response.json(); if (!Array.isArray(data)) { console.warn(`Unexpected response format for ${endpoint}:`, data); return []; } console.log( `Gitlab RepoLoader: fetched ${endpoint} page ${requestData.page}/${totalPages} with ${data.length} records.` ); if (totalPages === requestData.page) { requestData.page = -1; } else { requestData.page = Number(response.headers.get("x-next-page")); } return data; } catch (e) { console.error(`RepoLoader.fetchNextPage`, e); return null; } }
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) { throw new Error("Transcription not found"); } if (this.#addVideoInfo) { const { Innertube } = require("youtubei.js"); const youtube = await Innertube.create(); const info = (await youtube.getBasicInfo(this.#videoId)).basic_info; metadata.description = info.short_description; metadata.title = info.title; metadata.view_count = info.view_count; metadata.author = info.author; } } catch (e) { throw new Error( `Failed to get YouTube video transcription: ${e?.message}` ); } return [ { pageContent: transcript, metadata, }, ]; }
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_AGENT, }, } ) .then((res) => res.text()) .then((html) => parse(html)) .then((html) => this.#parseTranscriptEndpoint(html, lang)); if (!transcriptUrl) throw new Error("Failed to locate a transcript for this video!"); // Result is hopefully some XML. const transcriptXML = await fetch(transcriptUrl) .then((res) => res.text()) .then((xml) => parse(xml)); let transcript = ""; const chunks = transcriptXML.getElementsByTagName("text"); for (const chunk of chunks) { // Add space after each text chunk transcript += chunk.textContent + " "; } // Trim extra whitespace return transcript.trim().replace(/\s+/g, " "); } catch (e) { throw new YoutubeTranscriptError(e); } }
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(filepath); // Fallback to parsing as text via buffer inspection. }
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} - Returns true if the file is text, false otherwise.
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 { valid: false, reason: "non_text_mime" }; return { valid: true, reason: "valid_mime" }; } catch (e) { return { valid: false, reason: "generic" }; } }
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"); const nullCount = (content.match(/\0/g) || []).length; const controlCount = (content.match(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g) || []) .length; const threshold = bytesRead * 0.1; return nullCount + controlCount < threshold; } catch { return false; } }
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)) fs.mkdirSync(destination, { recursive: true }); const destinationFilePath = path.resolve(destination, filename) + ".json"; fs.writeFileSync(destinationFilePath, JSON.stringify(data, null, 4), { encoding: "utf-8", }); return { ...data, // relative location string that can be passed into the /update-embeddings api // that will work since we know the location exists and since we only allow // 1-level deep folders this will always work. This still works for integrations like GitHub and YouTube. location: destinationFilePath.split("/").slice(-2).join("/"), }; }
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 { fs.rmSync(path.join(directory, file)); } catch {} } resolve(); }); }); const cleanTmpDir = new Promise((resolve) => { const directory = path.resolve(__dirname, "../../storage/tmp"); fs.readdir(directory, (err, files) => { if (err) resolve(); for (const file of files) { if (file === ".placeholder") continue; try { fs.rmSync(path.join(directory, file)); } catch {} } resolve(); }); }); await Promise.all([cleanHotDir, cleanTmpDir]); console.log(`Collector hot directory and tmp storage wiped!`); 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.
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`) ); // Ensure the cache directory exists or else Tesseract will persist the cache in the default location. if (!fs.existsSync(this.cacheDir)) fs.mkdirSync(this.cacheDir, { recursive: true }); this.log( `OCRLoader initialized with language support for:`, this.language.map((lang) => VALID_LANGUAGE_CODES[lang]).join(", ") ); }
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(lang)); if (langList.length === 0) return ["eng"]; return langList; } catch (e) { this.log(`Error parsing languages: ${e.message}`, e.stack); return ["eng"]; } }
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 documentTitle = path.basename(filePath); try { this.log(`Starting OCR of ${documentTitle}`); const startTime = Date.now(); const { createWorker, OEM } = require("tesseract.js"); worker = await createWorker(this.language, OEM.LSTM_ONLY, { cachePath: this.cacheDir, }); // Race the timeout with the OCR const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `OCR job took too long to complete (${ maxExecutionTime / 1000 } seconds)` ) ); }, maxExecutionTime); }); const processImage = async () => { const { data } = await worker.recognize(filePath, {}, "text"); content = data.text; }; await Promise.race([timeoutPromise, processImage()]); this.log(`Completed OCR of ${documentTitle}!`, { executionTime: `${((Date.now() - startTime) / 1000).toFixed(2)}s`, }); return content; } catch (e) { this.log(`Error: ${e.message}`); return null; } finally { if (!worker) return; await worker.terminate(); } }
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.validOps.includes(ops.fnArray[i])) continue; const name = ops.argsArray[i][0]; const img = await page.objs.get(name); const { width, height } = img; const size = img.data.length; const channels = size / width / height; const targetDPI = 70; const targetWidth = Math.floor(width * (targetDPI / 72)); const targetHeight = Math.floor(height * (targetDPI / 72)); const image = this.sharp(img.data, { raw: { width, height, channels }, density: targetDPI, }) .resize({ width: targetWidth, height: targetHeight, fit: "fill", }) .withMetadata({ density: targetDPI, resolution: targetDPI, }) .png(); // For debugging purposes // await image.toFile(path.resolve(__dirname, `../../storage/`, `pg${page.pageNumber}.png`)); return await image.toBuffer(); } catch (error) { this.log(`Iteration error: ${error.message}`, error.stack); continue; } } this.log(`No valid images found on page ${page.pageNumber}`); return null; } catch (error) { this.log(`Error: ${error.message}`, error.stack); return null; } }
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 collector and backend can share the same ENV variables but only pass the relevant settings to the collector per-request and be able to access them across the collector via a single instance of RuntimeSettings. TODO: We may want to set all options passed from backend to collector here, but for now - we are only setting the runtime settings specifically for backwards compatibility with existing CollectorApi usage.
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 tokenize string! Estimating...", e.message, e.stack); return Math.ceil(input?.length / TikTokenTokenizer.DIVISOR) || 0; } }
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]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi ); // Not an IP address at all - passthrough if (!IPRegex.test(hostname)) return false; const [octetOne, ..._rest] = hostname.split("."); // If fails to validate to number - abort and return as invalid. if (isNaN(Number(octetOne))) return true; // Allow localhost loopback and 0.0.0.0 for scraping convenience // for locally hosted services or websites if (["127.0.0.1", "0.0.0.0"].includes(hostname)) return false; return INVALID_OCTETS.includes(Number(octetOne)); }
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 @param {URL['hostname']} param0.hostname @returns {boolean}
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 first model in the dropdown // to prevent invalid provider<>model selection issues const selectedOption = selectOption.querySelector( `option[value="${model}"]` ); if (!selectedOption) return selectOption.querySelector(`option`).value; // If the model is in the dropdown, return the model as is return model; } catch (error) { return null; // If the dropdown was empty or something else went wrong, return null to abort the save } }
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 first model in the picker was OK. This prevents invalid provider<>model selection issues @param {string} model - The model to validate @returns {string} - The validated model
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[requiredKey]) return true; } return false; }
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 first model in the picker was OK. This prevents invalid provider<>model selection issues @param {string} model - The model to validate @returns {string} - The validated model
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 = useCallback( (role) => { const isLeftToRight = role === "user" && msgDirection === "left_right"; return isLeftToRight ? "flex-row-reverse" : ""; }, [msgDirection] ); return { msgDirection, setMsgDirection, getMessageAlignment, }; }
Store the message alignment in localStorage as well as provide a function to get the alignment of a message via role. @returns {{msgDirection: 'left'|'left_right', setMsgDirection: (direction: string) => void, getMessageAlignment: (role: string) => string}} - The message direction and the class name for the direction.
useChatMessageAlignment
javascript
Mintplex-Labs/anything-llm
frontend/src/hooks/useChatMessageAlignment.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/frontend/src/hooks/useChatMessageAlignment.js
MIT
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({ enabled: settings?.SimpleSSOEnabled, noLogin: settings?.SimpleSSONoLogin, }); } catch (e) { console.error(e); } finally { setLoading(false); } } checkSsoConfig(); }, []); return { loading, ssoConfig }; }
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) return _setTheme("light"); _setTheme("default"); }, []); useEffect(() => { document.documentElement.setAttribute("data-theme", theme); document.body.classList.toggle("light", theme === "light"); localStorage.setItem("theme", theme); window.dispatchEvent(new Event(REFETCH_LOGO_EVENT)); }, [theme]); // In development, attach keybind combinations to toggle theme useEffect(() => { if (!import.meta.env.DEV) return; function toggleOnKeybind(e) { if (e.metaKey && e.key === ".") { e.preventDefault(); setTheme((prev) => (prev === "light" ? "default" : "light")); } } document.addEventListener("keydown", toggleOnKeybind); return () => document.removeEventListener("keydown", toggleOnKeybind); }, []); /** * Sets the theme of the application and runs any * other necessary side effects * @param {string} newTheme The new theme to set */ function setTheme(newTheme) { _setTheme(newTheme); } return { theme, setTheme, availableThemes }; }
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 "agentFlow": return "Agent Flows"; } }
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 "agentFlows": return "agent-flows"; } }
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 }) => { showNewWsModal(); return true; }, icon: SquaresFour, }, { id: "send_chat", title: t("main-page.checklist.tasks.send_chat.title"), description: t("main-page.checklist.tasks.send_chat.description"), action: t("main-page.checklist.tasks.send_chat.action"), handler: ({ workspaces = [], navigate = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate(paths.workspace.chat(workspaces[0].slug)); return true; }, icon: ChatDots, }, { id: "embed_document", title: t("main-page.checklist.tasks.embed_document.title"), description: t("main-page.checklist.tasks.embed_document.description"), action: t("main-page.checklist.tasks.embed_document.action"), handler: ({ workspaces = [], setSelectedWorkspace = noop, showManageWsModal = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } setSelectedWorkspace(workspaces[0]); showManageWsModal(); return true; }, icon: Files, }, { id: "setup_system_prompt", title: t("main-page.checklist.tasks.setup_system_prompt.title"), description: t("main-page.checklist.tasks.setup_system_prompt.description"), action: t("main-page.checklist.tasks.setup_system_prompt.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate( paths.workspace.settings.chatSettings(workspaces[0].slug, { search: { action: "focus-system-prompt" }, }) ); return true; }, icon: ChatCenteredText, }, { id: "define_slash_command", title: t("main-page.checklist.tasks.define_slash_command.title"), description: t( "main-page.checklist.tasks.define_slash_command.description" ), action: t("main-page.checklist.tasks.define_slash_command.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true }); showNewWsModal(); return false; } navigate( paths.workspace.chat(workspaces[0].slug, { search: { action: "open-new-slash-command-modal" }, }) ); return true; }, icon: SlashCommandIcon, }, { id: "visit_community", title: t("main-page.checklist.tasks.visit_community.title"), description: t("main-page.checklist.tasks.visit_community.description"), action: t("main-page.checklist.tasks.visit_community.action"), handler: () => { window.open(paths.communityHub.website(), "_blank"); return true; }, icon: UsersThree, }, ]
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 }) => { showNewWsModal(); return true; }, icon: SquaresFour, }, { id: "send_chat", title: t("main-page.checklist.tasks.send_chat.title"), description: t("main-page.checklist.tasks.send_chat.description"), action: t("main-page.checklist.tasks.send_chat.action"), handler: ({ workspaces = [], navigate = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate(paths.workspace.chat(workspaces[0].slug)); return true; }, icon: ChatDots, }, { id: "embed_document", title: t("main-page.checklist.tasks.embed_document.title"), description: t("main-page.checklist.tasks.embed_document.description"), action: t("main-page.checklist.tasks.embed_document.action"), handler: ({ workspaces = [], setSelectedWorkspace = noop, showManageWsModal = noop, showToast = noop, showNewWsModal = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } setSelectedWorkspace(workspaces[0]); showManageWsModal(); return true; }, icon: Files, }, { id: "setup_system_prompt", title: t("main-page.checklist.tasks.setup_system_prompt.title"), description: t("main-page.checklist.tasks.setup_system_prompt.description"), action: t("main-page.checklist.tasks.setup_system_prompt.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true, }); showNewWsModal(); return false; } navigate( paths.workspace.settings.chatSettings(workspaces[0].slug, { search: { action: "focus-system-prompt" }, }) ); return true; }, icon: ChatCenteredText, }, { id: "define_slash_command", title: t("main-page.checklist.tasks.define_slash_command.title"), description: t( "main-page.checklist.tasks.define_slash_command.description" ), action: t("main-page.checklist.tasks.define_slash_command.action"), handler: ({ workspaces = [], navigate = noop, showNewWsModal = noop, showToast = noop, }) => { if (workspaces.length === 0) { showToast(t("main-page.noWorkspaceError"), "warning", { clear: true }); showNewWsModal(); return false; } navigate( paths.workspace.chat(workspaces[0].slug, { search: { action: "open-new-slash-command-modal" }, }) ); return true; }, icon: SlashCommandIcon, }, { id: "visit_community", title: t("main-page.checklist.tasks.visit_community.title"), description: t("main-page.checklist.tasks.visit_community.description"), action: t("main-page.checklist.tasks.visit_community.action"), handler: () => { window.open(paths.communityHub.website(), "_blank"); return true; }, icon: UsersThree, }, ]
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 !== "voices") { console.log("PiperTTSWorker debug event:", event.data); return; } resolve(event.data.voices); tmpWorker.removeEventListener("message", handleMessage); timeout && clearTimeout(timeout); tmpWorker.terminate(); }; timeout = setTimeout(() => { reject("TTS Worker timed out."); }, 30_000); tmpWorker.addEventListener("message", handleMessage); }); }
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); tmpWorker.terminate(); }
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); tmpWorker.terminate(); }
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 !== "flush") { console.log("PiperTTSWorker debug event:", event.data); return; } resolve(event.data.flushed); tmpWorker.removeEventListener("message", handleMessage); timeout && clearTimeout(timeout); tmpWorker.terminate(); }; timeout = setTimeout(() => { reject("TTS Worker timed out."); }, 30_000); tmpWorker.addEventListener("message", handleMessage); }); }
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); tmpWorker.terminate(); }
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); tmpWorker.terminate(); }
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({ blobURL: null, error: event.data.message }); } if (event.data.type !== "result") { console.log("PiperTTSWorker debug event:", event.data); return; } resolve({ blobURL: URL.createObjectURL(event.data.audio), error: null, }); this.worker.removeEventListener("message", handleMessage); timeout && clearTimeout(timeout); }; timeout = setTimeout(() => { resolve({ blobURL: null, error: "PiperTTSWorker Worker timed out." }); }, 30_000); this.worker.addEventListener("message", handleMessage); }); }
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") { console.log("PiperTTSWorker debug event:", event.data); return; } resolve({ blobURL: URL.createObjectURL(event.data.audio), error: null, }); this.worker.removeEventListener("message", handleMessage); timeout && clearTimeout(timeout); }
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") { console.log("PiperTTSWorker debug event:", event.data); return; } resolve({ blobURL: URL.createObjectURL(event.data.audio), error: null, }); this.worker.removeEventListener("message", handleMessage); timeout && clearTimeout(timeout); }
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 to internet (mostly) // and it bloats the app size on the frontend or app significantly // and running the docker image fully offline is not an intended use-case unlike the app. }); const { blobURL, error } = await this.waitForBlobResponse(); if (!!error) { showToast( `Could not generate voice prediction. Error: ${error}`, "error", { clear: true } ); return; } return blobURL; }
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 === "flush") { await TTS.flush(); self.postMessage({ type: "flush", flushed: true }); return; } if (event.data?.type !== "init") return; if (!PIPER_SESSION) { PIPER_SESSION = new TTS.TtsSession({ voiceId: event.data.voiceId, progress: (e) => self.postMessage(JSON.stringify(e)), logger: (msg) => self.postMessage(msg), ...(!!event.data.baseUrl ? { wasmPaths: { onnxWasm: `${event.data.baseUrl}/piper/ort/`, piperData: `${event.data.baseUrl}/piper/piper_phonemize.data`, piperWasm: `${event.data.baseUrl}/piper/piper_phonemize.wasm`, }, } : {}), }); } if (event.data.voiceId && PIPER_SESSION.voiceId !== event.data.voiceId) PIPER_SESSION.voiceId = event.data.voiceId; PIPER_SESSION.predict(event.data.text) .then((res) => { if (res instanceof Blob) { self.postMessage({ type: "result", audio: res }); return; } }) .catch((error) => { self.postMessage({ type: "error", message: error.message, error }); // Will be an error. }); }
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.LMSTUDIO_MODEL_PREF; break; case "ollama": model = process.env.OLLAMA_MODEL_PREF; break; case "groq": model = process.env.GROQ_MODEL_PREF; break; case "togetherai": model = process.env.TOGETHER_AI_MODEL_PREF; break; case "azure": model = process.env.OPEN_MODEL_PREF; break; case "koboldcpp": model = process.env.KOBOLD_CPP_MODEL_PREF; break; case "localai": model = process.env.LOCAL_AI_MODEL_PREF; break; case "openrouter": model = process.env.OPENROUTER_MODEL_PREF; break; case "mistral": model = process.env.MISTRAL_MODEL_PREF; break; case "generic-openai": model = process.env.GENERIC_OPEN_AI_MODEL_PREF; break; case "perplexity": model = process.env.PERPLEXITY_MODEL_PREF; break; case "textgenwebui": model = "textgenwebui-default"; break; case "bedrock": model = process.env.AWS_BEDROCK_LLM_MODEL_PREFERENCE; break; case "fireworksai": model = process.env.FIREWORKS_AI_LLM_MODEL_PREF; break; case "deepseek": model = process.env.DEEPSEEK_MODEL_PREF; break; case "litellm": model = process.env.LITE_LLM_MODEL_PREF; break; case "apipie": model = process.env.APIPIE_LLM_MODEL_PREF; break; case "xai": model = process.env.XAI_LLM_MODEL_PREF; break; case "novita": model = process.env.NOVITA_LLM_MODEL_PREF; break; case "nvidia-nim": model = process.env.NVIDIA_NIM_LLM_MODEL_PREF; break; case "ppio": model = process.env.PPIO_MODEL_PREF; break; case "gemini": model = process.env.GEMINI_LLM_MODEL_PREF; break; default: model = "--"; break; } return model; }
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 https://github.com/Mintplex-Labs/anything-llm?tab=readme-ov-file#telemetry--privacy|Disable Telemetry} @returns {string} The model tag.
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) => conn.action === "remove") .map((conn) => conn.database_id); updatedConnections = updatedConnections.filter( (conn) => !toRemove.includes(conn.database_id) ); // Next add all 'action:add' candidates into the updatedConnections; We DO NOT validate the connection strings. // but we do validate their database_id is unique. updates .filter((conn) => conn.action === "add") .forEach((update) => { if (!update.connectionString) return; // invalid connection string // Remap name to be unique to entire set. if (existingDbIds.includes(update.database_id)) { update.database_id = slugify( `${update.database_id}-${v4().slice(0, 4)}` ); } else { update.database_id = slugify(update.database_id); } updatedConnections.push({ engine: update.engine, database_id: update.database_id, connectionString: update.connectionString, }); }); return updatedConnections; }
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 brackets const parts = []; let currentPart = ""; let inBrackets = false; for (let i = 0; i < path.length; i++) { const char = path[i]; if (char === "[") { inBrackets = true; if (currentPart) { parts.push(currentPart); currentPart = ""; } currentPart += char; } else if (char === "]") { inBrackets = false; currentPart += char; parts.push(currentPart); currentPart = ""; } else if (char === "." && !inBrackets) { if (currentPart) { parts.push(currentPart); currentPart = ""; } } else { currentPart += char; } } if (currentPart) parts.push(currentPart); let current = obj; for (const part of parts) { if (current === null || typeof current !== "object") return undefined; // Handle bracket notation if (part.startsWith("[") && part.endsWith("]")) { const key = part.slice(1, -1); const cleanKey = key.replace(/^['"]|['"]$/g, ""); if (!isNaN(cleanKey)) { if (!Array.isArray(current)) return undefined; current = current[parseInt(cleanKey)]; } else { if (!(cleanKey in current)) return undefined; current = current[cleanKey]; } } else { // Handle dot notation if (!(part in current)) return undefined; current = current[part]; } if (current === undefined || current === null) return undefined; } return typeof current === "object" ? JSON.stringify(current) : current; }
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 {string} The resolved value
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 (Array.isArray(obj)) return obj.map((item) => deepReplace(item)); if (obj && typeof obj === "object") { const result = {}; for (const [key, value] of Object.entries(obj)) { result[key] = deepReplace(value); } return result; } return obj; }; return deepReplace(config); }
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((item) => deepReplace(item)); if (obj && typeof obj === "object") { const result = {}; for (const [key, value] of Object.entries(obj)) { result[key] = deepReplace(value); } return result; } return obj; }
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((item) => deepReplace(item)); if (obj && typeof obj === "object") { const result = {}; for (const [key, value] of Object.entries(obj)) { result[key] = deepReplace(value); } return result; } return obj; }
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) { case FLOW_TYPES.START.type: // For start blocks, we just initialize variables if they're not already set if (config.variables) { config.variables.forEach((v) => { if (v.name && !this.variables[v.name]) { this.variables[v.name] = v.value || ""; } }); } result = this.variables; break; case FLOW_TYPES.API_CALL.type: result = await executeApiCall(config, context); break; case FLOW_TYPES.LLM_INSTRUCTION.type: result = await executeLLMInstruction(config, context); break; case FLOW_TYPES.WEB_SCRAPING.type: result = await executeWebScraping(config, context); break; default: throw new Error(`Unknown flow type: ${step.type}`); } // Store result in variable if specified if (config.resultVariable || config.responseVariable) { const varName = config.resultVariable || config.responseVariable; this.variables[varName] = result; } // If directOutput is true, mark this result for direct output if (config.directOutput) result = { directOutput: true, result }; return result; }
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 || [] ).reduce((acc, v) => ({ ...acc, [v.name]: v.value }), {}), ...initialVariables, // This will override any default values with passed-in values }; this.aibitat = aibitat; this.attachLogging(aibitat?.introspect, aibitat?.handlerProps?.log); const results = []; let directOutputResult = null; for (const step of flow.config.steps) { try { const result = await this.executeStep(step); // If the step has directOutput, stop processing and return the result // so that no other steps are executed or processed if (result?.directOutput) { directOutputResult = result.result; break; } results.push({ success: true, result }); } catch (error) { results.push({ success: false, error: error.message }); break; } } return { success: results.every((r) => r.success), results, variables: this.variables, directOutput: directOutputResult, }; }
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.readFileSync(normalizePath(filePath), "utf8"); const config = JSON.parse(content); const id = file.replace(".json", ""); flows[id] = config; } catch (error) { console.error(`Error reading flow file ${file}:`, error); } } return flows; }
Helper to get all flow files with their contents @returns {Object} Map of flow UUID to flow config
getAllFlows
javascript
Mintplex-Labs/anything-llm
server/utils/agentFlows/index.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js
MIT
static loadFlow(uuid) { try { const flowJsonPath = normalizePath( path.join(AgentFlows.flowsDir, `${uuid}.json`) ); if (!uuid || !fs.existsSync(flowJsonPath)) return null; const flow = safeJsonParse(fs.readFileSync(flowJsonPath, "utf8"), null); if (!flow) return null; return { name: flow.name, uuid, config: flow, }; } catch (error) { console.error("Failed to load flow:", error); return null; } }
Load a flow configuration by UUID @param {string} uuid - The UUID of the flow to load @returns {LoadedFlow|null} Flow configuration or null if not found
loadFlow
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 importing // flows with unsupported blocks (eg: file writing or code execution on Desktop importing to Docker) const supportedFlowTypes = Object.values(FLOW_TYPES).map( (definition) => definition.type ); const supportsAllBlocks = config.steps.every((step) => supportedFlowTypes.includes(step.type) ); if (!supportsAllBlocks) throw new Error( "This flow includes unsupported blocks. They may not be supported by your version of AnythingLLM or are not available on this platform." ); fs.writeFileSync(filePath, JSON.stringify({ ...config, name }, null, 2)); return { success: true, uuid }; } catch (error) { console.error("Failed to save flow:", error); return { success: false, error: error.message }; } }
Save a flow configuration @param {string} name - The name of the flow @param {Object} config - The flow configuration @param {string|null} uuid - Optional UUID for the flow @returns {Object} Result of the save operation
saveFlow
javascript
Mintplex-Labs/anything-llm
server/utils/agentFlows/index.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js
MIT
static listFlows() { try { const flows = AgentFlows.getAllFlows(); return Object.entries(flows).map(([uuid, flow]) => ({ name: flow.name, uuid, description: flow.description, active: flow.active !== false, })); } catch (error) { console.error("Failed to list flows:", error); return []; } }
List all available flows @returns {Array} Array of flow summaries
listFlows
javascript
Mintplex-Labs/anything-llm
server/utils/agentFlows/index.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/index.js
MIT
static deleteFlow(uuid) { try { const filePath = normalizePath( path.join(AgentFlows.flowsDir, `${uuid}.json`) ); if (!fs.existsSync(filePath)) throw new Error(`Flow ${uuid} not found`); fs.rmSync(filePath); return { success: true }; } catch (error) { console.error("Failed to delete flow:", error); return { success: false, error: error.message }; } }
Delete a flow by UUID @param {string} uuid - The UUID of the flow to delete @returns {Object} Result of the delete operation
deleteFlow
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: ${flow.name}`, plugin: (_runtimeArgs = {}) => ({ name: `flow_${uuid}`, description: flow.config.description || `Execute agent flow: ${flow.name}`, setup: (aibitat) => { aibitat.function({ name: `flow_${uuid}`, description: flow.config.description || `Execute agent flow: ${flow.name}`, parameters: { type: "object", properties: variables.reduce((acc, v) => { if (v.name) { acc[v.name] = { type: "string", description: v.description || `Value for variable ${v.name}`, }; } return acc; }, {}), }, handler: async (args) => { aibitat.introspect(`Executing flow: ${flow.name}`); const result = await AgentFlows.executeFlow(uuid, args, aibitat); if (!result.success) { aibitat.introspect( `Flow failed: ${result.results[0]?.error || "Unknown error"}` ); return `Flow execution failed: ${result.results[0]?.error || "Unknown error"}`; } aibitat.introspect(`${flow.name} completed successfully`); // If the flow result has directOutput, return it // as the aibitat result so that no other processing is done if (!!result.directOutput) { aibitat.skipHandleExecution = true; return AgentFlows.stringifyResult(result.directOutput); } return AgentFlows.stringifyResult(result); }, }); }, }), flowName: flow.name, }; }
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 requestConfig = { method, headers: headers.reduce((acc, h) => ({ ...acc, [h.key]: h.value }), {}), }; if (["POST", "PUT", "PATCH"].includes(method)) { if (bodyType === "form") { const formDataObj = new URLSearchParams(); formData.forEach(({ key, value }) => formDataObj.append(key, value)); requestConfig.body = formDataObj.toString(); requestConfig.headers["Content-Type"] = "application/x-www-form-urlencoded"; } else if (bodyType === "json") { const parsedBody = safeJsonParse(body, null); if (parsedBody !== null) { requestConfig.body = JSON.stringify(parsedBody); } requestConfig.headers["Content-Type"] = "application/json"; } else if (bodyType === "text") { requestConfig.body = String(body); } else { requestConfig.body = body; } } try { introspect(`Sending body to ${url}: ${requestConfig?.body || "No body"}`); const response = await fetch(url, requestConfig); if (!response.ok) { introspect(`Request failed with status ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`); } introspect(`API call completed`); return await response .text() .then((text) => safeJsonParse(text, "Failed to parse output from API call block") ); } catch (error) { console.error(error); throw new Error(`API Call failed: ${error.message}`); } }
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 { logger( `Sending request to LLM (${aibitat.defaultProvider.provider}::${aibitat.defaultProvider.model})` ); introspect(`Sending request to LLM...`); // Ensure the input is a string since we are sending it to the LLM direct as a message let input = instruction; if (typeof input === "object") input = JSON.stringify(input); if (typeof input !== "string") input = String(input); const provider = aibitat.getProviderForConfig(aibitat.defaultProvider); const completion = await provider.complete([ { role: "user", content: input, }, ]); introspect(`Successfully received LLM response`); if (resultVariable) config.resultVariable = resultVariable; return completion.result; } catch (error) { logger(`LLM processing failed: ${error.message}`, error); throw new Error(`LLM processing failed: ${error.message}`); } }
Execute an LLM instruction flow step @param {Object} config Flow step configuration @param {{introspect: Function, 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/summarize"); const { url, captureAs = "text", enableSummarization = true } = config; const { introspect, logger, aibitat } = context; logger( `\x1b[43m[AgentFlowToolExecutor]\x1b[0m - executing Web Scraping block` ); if (!url) { throw new Error("URL is required for web scraping"); } const captureMode = captureAs === "querySelector" ? "html" : captureAs; introspect(`Scraping the content of ${url} as ${captureAs}`); const { success, content } = await new CollectorApi() .getLinkContent(url, captureMode) .then((res) => { if (captureAs !== "querySelector") return res; return parseHTMLwithSelector(res.content, config.querySelector, context); }); if (!success) { introspect(`Could not scrape ${url}. Cannot use this page's content.`); throw new Error("URL could not be scraped and no content was found."); } introspect(`Successfully scraped content from ${url}`); if (!content || content?.length === 0) { introspect("There was no content to be collected or read."); throw new Error("There was no content to be collected or read."); } if (!enableSummarization) { logger(`Returning raw content as summarization is disabled`); return content; } const tokenCount = new TokenManager( aibitat.defaultProvider.model ).countFromString(content); const contextLimit = Provider.contextLimit( aibitat.defaultProvider.provider, aibitat.defaultProvider.model ); if (tokenCount < contextLimit) { logger( `Content within token limit (${tokenCount}/${contextLimit}). Returning raw content.` ); return content; } introspect( `This page's content is way too long (${tokenCount} tokens). I will summarize it right now.` ); const summary = await summarizeContent({ provider: aibitat.defaultProvider.provider, model: aibitat.defaultProvider.model, content, }); introspect(`Successfully summarized content`); return summary; }
Execute a web scraping flow step @param {Object} config Flow step configuration @param {Object} context Execution context with introspect function @returns {Promise<string>} Scraped content
executeWebScraping
javascript
Mintplex-Labs/anything-llm
server/utils/agentFlows/executors/web-scraping.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agentFlows/executors/web-scraping.js
MIT
function parseHTMLwithSelector(html, selector = null, context) { if (!selector || selector.length === 0) { context.introspect("No selector provided. Returning the entire HTML."); return { success: true, content: html }; } const Cheerio = require("cheerio"); const $ = Cheerio.load(html); const selectedElements = $(selector); let content; if (selectedElements.length === 0) { return { success: false, content: null }; } else if (selectedElements.length === 1) { content = selectedElements.html(); } else { context.introspect( `Found ${selectedElements.length} elements matching selector: ${selector}` ); content = selectedElements .map((_, element) => $(element).html()) .get() .join("\n"); } return { success: true, content }; }
Parse HTML with a CSS selector @param {string} html - The HTML to parse @param {string|null} selector - The CSS selector to use (as text string) @param {{introspect: Function}} context - The context object @returns {Object} The parsed content
parseHTMLwithSelector
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" }, "[]" ), [] ); DEFAULT_SKILLS.forEach((skill) => { if (!_disabledDefaultSkills.includes(skill)) systemFunctions.push(AgentPlugins[skill].name); }); // Load non-imported built-in skills that are configurable. const _setting = safeJsonParse( await SystemSettings.getValueOrFallback( { label: "default_agent_skills" }, "[]" ), [] ); _setting.forEach((skillName) => { if (!AgentPlugins.hasOwnProperty(skillName)) return; // This is a plugin module with many sub-children plugins who // need to be named via `${parent}#${child}` naming convention if (Array.isArray(AgentPlugins[skillName].plugin)) { for (const subPlugin of AgentPlugins[skillName].plugin) { systemFunctions.push( `${AgentPlugins[skillName].name}#${subPlugin.name}` ); } return; } // This is normal single-stage plugin systemFunctions.push(AgentPlugins[skillName].name); }); return systemFunctions; }
Fetches and preloads the names/identifiers for plugins that will be dynamically loaded later @returns {Promise<string[]>}
agentSkillsFromSystemSettings
javascript
Mintplex-Labs/anything-llm
server/utils/agents/defaults.js
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/agents/defaults.js
MIT
constructor({ uuid, workspace, prompt, userId = null, threadId = null, sessionId = null, }) { super({ uuid }); this.#invocationUUID = uuid; this.#workspace = workspace; this.#prompt = prompt; this.#userId = userId; this.#threadId = threadId; this.#sessionId = sessionId; }
@param {{ uuid: string, workspace: import("@prisma/client").workspaces, prompt: string, userId: import("@prisma/client").users["id"]|null, threadId: import("@prisma/client").workspace_threads["id"]|null, sessionId: string|null }} parameters
constructor
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 {string|null} the model preference value to use in API calls
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: this.#workspace.id, }, log: this.log, }, }); // Attach HTTP response object if defined for chunk streaming. this.log(`Attached ${httpSocket.name} plugin to Agent cluster`); this.aibitat.use( httpSocket.plugin({ handler: args.handler, muteUserReply: true, introspection: true, }) ); // Load required agents (Default + custom) await this.#loadAgents(); // Attach all required plugins for functions to operate. await this.#attachPlugins(args); }
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 {string|null} the model preference value to use in API calls
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 {string|null} the model preference value to use in API calls
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