repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/web-scraping.js
server/utils/agents/aibitat/plugins/web-scraping.js
const { CollectorApi } = require("../../../collectorApi"); const Provider = require("../providers/ai-provider"); const { summarizeContent } = require("../utils/summarize"); const webScraping = { name: "web-scraping", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, controller: new AbortController(), description: "Scrapes the content of a webpage or online resource from a provided URL.", examples: [ { prompt: "What is anythingllm.com about?", call: JSON.stringify({ url: "https://anythingllm.com" }), }, { prompt: "Scrape https://example.com", call: JSON.stringify({ url: "https://example.com" }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { url: { type: "string", format: "uri", description: "A complete web address URL including protocol. Assumes https if not provided.", }, }, additionalProperties: false, }, handler: async function ({ url }) { try { if (url) return await this.scrape(url); return "There is nothing we can do. This function call returns no information."; } catch (error) { this.super.handlerProps.log( `Web Scraping Error: ${error.message}` ); this.super.introspect( `${this.caller}: Web Scraping Error: ${error.message}` ); return `There was an error while calling the function. No data or response was found. Let the user know this was the error: ${error.message}`; } }, /** * Scrape a website and summarize the content based on objective if the content is too large. * Objective is the original objective & task that user give to the agent, url is the url of the website to be scraped. * Here we can leverage the document collector to get raw website text quickly. * * @param url * @returns */ scrape: async function (url) { this.super.introspect( `${this.caller}: Scraping the content of ${url}` ); const { success, content } = await new CollectorApi().getLinkContent(url); if (!success) { this.super.introspect( `${this.caller}: could not scrape ${url}. I can't use this page's content.` ); throw new Error( `URL could not be scraped and no content was found.` ); } if (!content || content?.length === 0) { throw new Error("There was no content to be collected or read."); } const { TokenManager } = require("../../../helpers/tiktoken"); const tokenEstimate = new TokenManager( this.super.model ).countFromString(content); if ( tokenEstimate < Provider.contextLimit(this.super.provider, this.super.model) ) { this.super.introspect( `${this.caller}: Looking over the content of the page. ~${tokenEstimate} tokens.` ); return content; } this.super.introspect( `${this.caller}: This page's content exceeds the model's context limit. Summarizing it right now.` ); this.super.onAbort(() => { this.super.handlerProps.log( "Abort was triggered, exiting summarization early." ); this.controller.abort(); }); return summarizeContent({ provider: this.super.provider, model: this.super.model, controllerSignal: this.controller.signal, content, }); }, }); }, }; }, }; module.exports = { webScraping, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/http-socket.js
server/utils/agents/aibitat/plugins/http-socket.js
const chalk = require("chalk"); const { Telemetry } = require("../../../../models/telemetry"); /** * HTTP Interface plugin for Aibitat to emulate a websocket interface in the agent * framework so we dont have to modify the interface for passing messages and responses * in REST or WSS. */ const httpSocket = { name: "httpSocket", startupConfig: { params: { handler: { required: true, }, muteUserReply: { required: false, default: true, }, introspection: { required: false, default: true, }, }, }, plugin: function ({ handler, muteUserReply = true, // Do not post messages to "USER" back to frontend. introspection = false, // when enabled will attach socket to Aibitat object with .introspect method which reports status updates to frontend. }) { return { name: this.name, setup(aibitat) { aibitat.onError(async (error) => { let errorMessage = error?.message || "An error occurred while running the agent."; console.error(chalk.red(` error: ${errorMessage}`), error); aibitat.introspect( `Error encountered while running: ${errorMessage}` ); handler.send( JSON.stringify({ type: "wssFailure", content: errorMessage }) ); aibitat.terminate(); }); aibitat.introspect = (messageText) => { if (!introspection) return; // Dump thoughts when not wanted. handler.send( JSON.stringify({ type: "statusResponse", content: messageText }) ); }; // expose function for sockets across aibitat // type param must be set or else msg will not be shown or handled in UI. aibitat.socket = { send: (type = "__unhandled", content = "") => { handler.send(JSON.stringify({ type, content })); }, }; // We can only receive one message response with HTTP // so we end on first response. aibitat.onMessage((message) => { if (message.from !== "USER") Telemetry.sendTelemetry("agent_chat_sent"); if (message.from === "USER" && muteUserReply) return; handler.send(JSON.stringify(message)); handler.close(); }); aibitat.onTerminate(() => { handler.close(); }); }, }; }, }; module.exports = { httpSocket, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/memory.js
server/utils/agents/aibitat/plugins/memory.js
const { v4 } = require("uuid"); const { getVectorDbClass, getLLMProvider } = require("../../../helpers"); const { Deduplicator } = require("../utils/dedupe"); const memory = { name: "rag-memory", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { aibitat.function({ super: aibitat, tracker: new Deduplicator(), name: this.name, description: "Search against local documents for context that is relevant to the query or store a snippet of text into memory for retrieval later. Storing information should only be done when the user specifically requests for information to be remembered or saved to long-term memory. You should use this tool before search the internet for information. Do not use this tool unless you are explicitly told to 'remember' or 'store' information.", examples: [ { prompt: "What is AnythingLLM?", call: JSON.stringify({ action: "search", content: "What is AnythingLLM?", }), }, { prompt: "What do you know about Plato's motives?", call: JSON.stringify({ action: "search", content: "What are the facts about Plato's motives?", }), }, { prompt: "Remember that you are a robot", call: JSON.stringify({ action: "store", content: "I am a robot, the user told me that i am.", }), }, { prompt: "Save that to memory please.", call: JSON.stringify({ action: "store", content: "<insert summary of conversation until now>", }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { action: { type: "string", enum: ["search", "store"], description: "The action we want to take to search for existing similar context or storage of new context.", }, content: { type: "string", description: "The plain text to search our local documents with or to store in our vector database.", }, }, additionalProperties: false, }, handler: async function ({ action = "", content = "" }) { try { const { isDuplicate } = this.tracker.isDuplicate(this.name, { action, content, }); if (isDuplicate) return `This was a duplicated call and it's output will be ignored.`; let response = "There was nothing to do."; if (action === "search") response = await this.search(content); if (action === "store") response = await this.store(content); this.tracker.trackRun(this.name, { action, content }); return response; } catch (error) { console.log(error); return `There was an error while calling the function. ${error.message}`; } }, search: async function (query = "") { try { const workspace = this.super.handlerProps.invocation.workspace; const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const vectorDB = getVectorDbClass(); const { contextTexts = [] } = await vectorDB.performSimilaritySearch({ namespace: workspace.slug, input: query, LLMConnector, topN: workspace?.topN ?? 4, rerank: workspace?.vectorSearchMode === "rerank", }); if (contextTexts.length === 0) { this.super.introspect( `${this.caller}: I didn't find anything locally that would help answer this question.` ); return "There was no additional context found for that query. We should search the web for this information."; } this.super.introspect( `${this.caller}: Found ${contextTexts.length} additional piece of context to help answer this question.` ); let combinedText = "Additional context for query:\n"; for (const text of contextTexts) combinedText += text + "\n\n"; return combinedText; } catch (error) { this.super.handlerProps.log( `memory.search raised an error. ${error.message}` ); return `An error was raised while searching the vector database. ${error.message}`; } }, store: async function (content = "") { try { const workspace = this.super.handlerProps.invocation.workspace; const vectorDB = getVectorDbClass(); const { error } = await vectorDB.addDocumentToNamespace( workspace.slug, { docId: v4(), id: v4(), url: "file://embed-via-agent.txt", title: "agent-memory.txt", docAuthor: "@agent", description: "Unknown", docSource: "a text file stored by the workspace agent.", chunkSource: "", published: new Date().toLocaleString(), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: 0, }, null ); if (!!error) return "The content was failed to be embedded properly."; this.super.introspect( `${this.caller}: I saved the content to long-term memory in this workspaces vector database.` ); return "The content given was successfully embedded. There is nothing else to do."; } catch (error) { this.super.handlerProps.log( `memory.store raised an error. ${error.message}` ); return `Let the user know this action was not successful. An error was raised while storing data in the vector database. ${error.message}`; } }, }); }, }; }, }; module.exports = { memory, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/web-browsing.js
server/utils/agents/aibitat/plugins/web-browsing.js
const { SystemSettings } = require("../../../../models/systemSettings"); const { TokenManager } = require("../../../helpers/tiktoken"); const tiktoken = new TokenManager(); const webBrowsing = { name: "web-browsing", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, countTokens: (string) => tiktoken .countFromString(string) .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, ","), description: "Searches for a given query using a search engine to get better results for the user query.", examples: [ { prompt: "Who won the world series today?", call: JSON.stringify({ query: "Winner of today's world series" }), }, { prompt: "What is AnythingLLM?", call: JSON.stringify({ query: "AnythingLLM" }), }, { prompt: "Current AAPL stock price", call: JSON.stringify({ query: "AAPL stock price today" }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { query: { type: "string", description: "A search query.", }, }, additionalProperties: false, }, handler: async function ({ query }) { try { if (query) return await this.search(query); return "There is nothing we can do. This function call returns no information."; } catch (error) { return `There was an error while calling the function. No data or response was found. Let the user know this was the error: ${error.message}`; } }, /** * Use Google Custom Search Engines * Free to set up, easy to use, 100 calls/day! * https://programmablesearchengine.google.com/controlpanel/create */ search: async function (query) { const provider = (await SystemSettings.get({ label: "agent_search_provider" })) ?.value ?? "unknown"; let engine; switch (provider) { case "google-search-engine": engine = "_googleSearchEngine"; break; case "serpapi": engine = "_serpApi"; break; case "searchapi": engine = "_searchApi"; break; case "serper-dot-dev": engine = "_serperDotDev"; break; case "bing-search": engine = "_bingWebSearch"; break; case "serply-engine": engine = "_serplyEngine"; break; case "searxng-engine": engine = "_searXNGEngine"; break; case "tavily-search": engine = "_tavilySearch"; break; case "duckduckgo-engine": engine = "_duckDuckGoEngine"; break; case "exa-search": engine = "_exaSearch"; break; default: engine = "_googleSearchEngine"; } return await this[engine](query); }, /** * Utility function to truncate a string to a given length for debugging * calls to the API while keeping the actual values mostly intact * @param {string} str - The string to truncate * @param {number} length - The length to truncate the string to * @returns {string} The truncated string */ middleTruncate(str, length = 5) { if (str.length <= length) return str; return `${str.slice(0, length)}...${str.slice(-length)}`; }, /** * Use Google Custom Search Engines * Free to set up, easy to use, 100 calls/day * https://programmablesearchengine.google.com/controlpanel/create */ _googleSearchEngine: async function (query) { if (!process.env.AGENT_GSE_CTX || !process.env.AGENT_GSE_KEY) { this.super.introspect( `${this.caller}: I can't use Google searching because the user has not defined the required API keys.\nVisit: https://programmablesearchengine.google.com/controlpanel/create to create the API keys.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } const searchURL = new URL( "https://www.googleapis.com/customsearch/v1" ); searchURL.searchParams.append("key", process.env.AGENT_GSE_KEY); searchURL.searchParams.append("cx", process.env.AGENT_GSE_CTX); searchURL.searchParams.append("q", query); this.super.introspect( `${this.caller}: Searching on Google for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const data = await fetch(searchURL) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ key: this.middleTruncate(process.env.AGENT_GSE_KEY, 5), cx: this.middleTruncate(process.env.AGENT_GSE_CTX, 5), q: query })}` ); }) .then((searchResult) => searchResult?.items || []) .then((items) => { return items.map((item) => { return { title: item.title, link: item.link, snippet: item.snippet, }; }); }) .catch((e) => { this.super.handlerProps.log( `${this.name}: Google Search Error: ${e.message}` ); return []; }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, /** * Use SerpApi * SerpApi supports dozens of search engines across the major platforms including Google, DuckDuckGo, Bing, eBay, Amazon, Baidu, Yandex, and more. * https://serpapi.com/ */ _serpApi: async function (query) { if (!process.env.AGENT_SERPAPI_API_KEY) { this.super.introspect( `${this.caller}: I can't use SerpApi searching because the user has not defined the required API key.\nVisit: https://serpapi.com/ to create the API key for free.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using SerpApi to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const engine = process.env.AGENT_SERPAPI_ENGINE; const queryParamKey = engine === "amazon" ? "k" : "q"; const params = new URLSearchParams({ engine: engine, [queryParamKey]: query, api_key: process.env.AGENT_SERPAPI_API_KEY, }); const url = `https://serpapi.com/search.json?${params.toString()}`; const { response, error } = await fetch(url, { method: "GET", headers: {}, }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_SERPAPI_API_KEY, 5), q: query })}` ); }) .then((data) => { return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log(`SerpApi Error: ${e.message}`); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; switch (engine) { case "google": if (response.hasOwnProperty("knowledge_graph")) data.push(response.knowledge_graph); if (response.hasOwnProperty("answer_box")) data.push(response.answer_box); response.organic_results?.forEach((searchResult) => { const { title, link, snippet } = searchResult; data.push({ title, link, snippet, }); }); response.local_results?.forEach((searchResult) => { const { title, rating, reviews, description, address, website, extensions, } = searchResult; data.push({ title, rating, reviews, description, address, website, extensions, }); }); case "google_maps": response.local_results?.slice(0, 10).forEach((searchResult) => { const { title, rating, reviews, description, address, website, extensions, } = searchResult; data.push({ title, rating, reviews, description, address, website, extensions, }); }); case "google_images_light": response.images_results ?.slice(0, 10) .forEach((searchResult) => { const { title, source, link, thumbnail } = searchResult; data.push({ title, source, link, thumbnail, }); }); case "google_shopping_light": response.shopping_results ?.slice(0, 10) .forEach((searchResult) => { const { title, source, price, rating, reviews, snippet, thumbnail, product_link, } = searchResult; data.push({ title, source, price, rating, reviews, snippet, thumbnail, product_link, }); }); case "google_news_light": response.news_results?.slice(0, 10).forEach((searchResult) => { const { title, link, source, thumbnail, snippet, date } = searchResult; data.push({ title, link, source, thumbnail, snippet, date, }); }); case "google_jobs": response.jobs_results?.forEach((searchResult) => { const { title, company_name, location, description, apply_options, extensions, } = searchResult; data.push({ title, company_name, location, description, apply_options, extensions, }); }); case "google_patents": response.organic_results?.forEach((searchResult) => { const { title, patent_link, snippet, inventor, assignee, publication_number, } = searchResult; data.push({ title, patent_link, snippet, inventor, assignee, publication_number, }); }); case "google_scholar": response.organic_results?.forEach((searchResult) => { const { title, link, snippet, publication_info } = searchResult; data.push({ title, link, snippet, publication_info, }); }); case "baidu": if (response.hasOwnProperty("answer_box")) data.push(response.answer_box); response.organic_results?.forEach((searchResult) => { const { title, link, snippet } = searchResult; data.push({ title, link, snippet, }); }); case "amazon": response.organic_results ?.slice(0, 10) .forEach((searchResult) => { const { title, rating, reviews, price, link_clean, thumbnail, } = searchResult; data.push({ title, rating, reviews, price, link_clean, thumbnail, }); }); } if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, /** * Use SearchApi * SearchApi supports multiple search engines like Google Search, Bing Search, Baidu Search, Google News, YouTube, and many more. * https://www.searchapi.io/ */ _searchApi: async function (query) { if (!process.env.AGENT_SEARCHAPI_API_KEY) { this.super.introspect( `${this.caller}: I can't use SearchApi searching because the user has not defined the required API key.\nVisit: https://www.searchapi.io/ to create the API key for free.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using SearchApi to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const engine = process.env.AGENT_SEARCHAPI_ENGINE; const params = new URLSearchParams({ engine: engine, q: query, }); const url = `https://www.searchapi.io/api/v1/search?${params.toString()}`; const { response, error } = await fetch(url, { method: "GET", headers: { Authorization: `Bearer ${process.env.AGENT_SEARCHAPI_API_KEY}`, "Content-Type": "application/json", "X-SearchApi-Source": "AnythingLLM", }, }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_SEARCHAPI_API_KEY, 5), q: query })}` ); }) .then((data) => { return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log(`SearchApi Error: ${e.message}`); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; if (response.hasOwnProperty("knowledge_graph")) data.push(response.knowledge_graph?.description); if (response.hasOwnProperty("answer_box")) data.push(response.answer_box?.answer); response.organic_results?.forEach((searchResult) => { const { title, link, snippet } = searchResult; data.push({ title, link, snippet, }); }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, /** * Use Serper.dev * Free to set up, easy to use, 2,500 calls for free one-time * https://serper.dev */ _serperDotDev: async function (query) { if (!process.env.AGENT_SERPER_DEV_KEY) { this.super.introspect( `${this.caller}: I can't use Serper.dev searching because the user has not defined the required API key.\nVisit: https://serper.dev to create the API key for free.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using Serper.dev to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const { response, error } = await fetch( "https://google.serper.dev/search", { method: "POST", headers: { "X-API-KEY": process.env.AGENT_SERPER_DEV_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ q: query }), redirect: "follow", } ) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_SERPER_DEV_KEY, 5), q: query })}` ); }) .then((data) => { return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log(`Serper.dev Error: ${e.message}`); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; if (response.hasOwnProperty("knowledgeGraph")) data.push(response.knowledgeGraph); response.organic?.forEach((searchResult) => { const { title, link, snippet } = searchResult; data.push({ title, link, snippet, }); }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, _bingWebSearch: async function (query) { if (!process.env.AGENT_BING_SEARCH_API_KEY) { this.super.introspect( `${this.caller}: I can't use Bing Web Search because the user has not defined the required API key.\nVisit: https://portal.azure.com/ to create the API key.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } const searchURL = new URL( "https://api.bing.microsoft.com/v7.0/search" ); searchURL.searchParams.append("q", query); this.super.introspect( `${this.caller}: Using Bing Web Search to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const searchResponse = await fetch(searchURL, { headers: { "Ocp-Apim-Subscription-Key": process.env.AGENT_BING_SEARCH_API_KEY, }, }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_BING_SEARCH_API_KEY, 5), q: query })}` ); }) .then((data) => { const searchResults = data.webPages?.value || []; return searchResults.map((result) => ({ title: result.name, link: result.url, snippet: result.snippet, })); }) .catch((e) => { this.super.handlerProps.log( `Bing Web Search Error: ${e.message}` ); return []; }); if (searchResponse.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(searchResponse); this.super.introspect( `${this.caller}: I found ${searchResponse.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, _serplyEngine: async function ( query, language = "en", hl = "us", limit = 100, device_type = "desktop", proxy_location = "US" ) { // query (str): The query to search for // hl (str): Host Language code to display results in (reference https://developers.google.com/custom-search/docs/xml_results?hl=en#wsInterfaceLanguages) // limit (int): The maximum number of results to return [10-100, defaults to 100] // device_type: get results based on desktop/mobile (defaults to desktop) if (!process.env.AGENT_SERPLY_API_KEY) { this.super.introspect( `${this.caller}: I can't use Serply.io searching because the user has not defined the required API key.\nVisit: https://serply.io to create the API key for free.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using Serply to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const params = new URLSearchParams({ q: query, language: language, hl, gl: proxy_location.toUpperCase(), }); const url = `https://api.serply.io/v1/search/${params.toString()}`; const { response, error } = await fetch(url, { method: "GET", headers: { "X-API-KEY": process.env.AGENT_SERPLY_API_KEY, "Content-Type": "application/json", "User-Agent": "anything-llm", "X-Proxy-Location": proxy_location, "X-User-Agent": device_type, }, }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_SERPLY_API_KEY, 5), q: query })}` ); }) .then((data) => { if (data?.message === "Unauthorized") throw new Error( "Unauthorized. Please double check your AGENT_SERPLY_API_KEY" ); return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log(`Serply Error: ${e.message}`); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; response.results?.forEach((searchResult) => { const { title, link, description } = searchResult; data.push({ title, link, snippet: description, }); }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, _searXNGEngine: async function (query) { let searchURL; if (!process.env.AGENT_SEARXNG_API_URL) { this.super.introspect( `${this.caller}: I can't use SearXNG searching because the user has not defined the required base URL.\nPlease set this value in the agent skill settings.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } try { searchURL = new URL(process.env.AGENT_SEARXNG_API_URL); searchURL.searchParams.append("q", encodeURIComponent(query)); searchURL.searchParams.append("format", "json"); } catch (e) { this.super.handlerProps.log(`SearXNG Search: ${e.message}`); this.super.introspect( `${this.caller}: I can't use SearXNG searching because the url provided is not a valid URL.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using SearXNG to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const { response, error } = await fetch(searchURL.toString(), { method: "GET", headers: { "Content-Type": "application/json", "User-Agent": "anything-llm", }, }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ url: searchURL.toString() })}` ); }) .then((data) => { return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log( `SearXNG Search Error: ${e.message}` ); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; response.results?.forEach((searchResult) => { const { url, title, content, publishedDate } = searchResult; data.push({ title, link: url, snippet: content, publishedDate, }); }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect( `${this.caller}: I found ${data.length} results - reviewing the results now. (~${this.countTokens(result)} tokens)` ); return result; }, _tavilySearch: async function (query) { if (!process.env.AGENT_TAVILY_API_KEY) { this.super.introspect( `${this.caller}: I can't use Tavily searching because the user has not defined the required API key.\nVisit: https://tavily.com/ to create the API key.` ); return `Search is disabled and no content was found. This functionality is disabled because the user has not set it up yet.`; } this.super.introspect( `${this.caller}: Using Tavily to search for "${ query.length > 100 ? `${query.slice(0, 100)}...` : query }"` ); const url = "https://api.tavily.com/search"; const { response, error } = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ api_key: process.env.AGENT_TAVILY_API_KEY, query: query, }), }) .then((res) => { if (res.ok) return res.json(); throw new Error( `${res.status} - ${res.statusText}. params: ${JSON.stringify({ auth: this.middleTruncate(process.env.AGENT_TAVILY_API_KEY, 5), q: query })}` ); }) .then((data) => { return { response: data, error: null }; }) .catch((e) => { this.super.handlerProps.log( `Tavily Search Error: ${e.message}` ); return { response: null, error: e.message }; }); if (error) return `There was an error searching for content. ${error}`; const data = []; response.results?.forEach((searchResult) => { const { title, url, content } = searchResult; data.push({ title, link: url, snippet: content, }); }); if (data.length === 0) return `No information was found online for the search query.`; const result = JSON.stringify(data); this.super.introspect(
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
true
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/summarize.js
server/utils/agents/aibitat/plugins/summarize.js
const { Document } = require("../../../../models/documents"); const { safeJsonParse } = require("../../../http"); const { summarizeContent } = require("../utils/summarize"); const Provider = require("../providers/ai-provider"); const docSummarizer = { name: "document-summarizer", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, controller: new AbortController(), description: "Can get the list of files available to search with descriptions and can select a single file to open and summarize.", examples: [ { prompt: "Summarize example.txt", call: JSON.stringify({ action: "summarize", document_filename: "example.txt", }), }, { prompt: "What files can you see?", call: JSON.stringify({ action: "list", document_filename: null }), }, { prompt: "Tell me about readme.md", call: JSON.stringify({ action: "summarize", document_filename: "readme.md", }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { action: { type: "string", enum: ["list", "summarize"], description: "The action to take. 'list' will return all files available with their filename and descriptions. 'summarize' will open and summarize the file by the a document name.", }, document_filename: { type: "string", "x-nullable": true, description: "The file name of the document you want to get the full content of.", }, }, additionalProperties: false, }, handler: async function ({ action, document_filename }) { if (action === "list") return await this.listDocuments(); if (action === "summarize") return await this.summarizeDoc(document_filename); return "There is nothing we can do. This function call returns no information."; }, /** * List all documents available in a workspace * @returns List of files and their descriptions if available. */ listDocuments: async function () { try { this.super.introspect( `${this.caller}: Looking at the available documents.` ); const documents = await Document.where({ workspaceId: this.super.handlerProps.invocation.workspace_id, }); if (documents.length === 0) return "No documents found - nothing can be done. Stop."; this.super.introspect( `${this.caller}: Found ${documents.length} documents` ); const foundDocuments = documents.map((doc) => { const metadata = safeJsonParse(doc.metadata, {}); return { document_id: doc.docId, filename: metadata?.title ?? "unknown.txt", description: metadata?.description ?? "no description", }; }); return JSON.stringify(foundDocuments); } catch (error) { this.super.handlerProps.log( `document-summarizer.list raised an error. ${error.message}` ); return `Let the user know this action was not successful. An error was raised while listing available files. ${error.message}`; } }, summarizeDoc: async function (filename) { try { const availableDocs = safeJsonParse( await this.listDocuments(), [] ); if (!availableDocs.length) { this.super.handlerProps.log( `${this.caller}: No available documents to summarize.` ); return "No documents were found."; } const docInfo = availableDocs.find( (info) => info.filename === filename ); if (!docInfo) { this.super.handlerProps.log( `${this.caller}: No available document by the name "${filename}".` ); return `No available document by the name "${filename}".`; } const document = await Document.content(docInfo.document_id); this.super.introspect( `${this.caller}: Grabbing all content for ${ filename ?? "a discovered file." }` ); if (!document.content || document.content.length === 0) { throw new Error( "This document has no readable content that could be found." ); } const { TokenManager } = require("../../../helpers/tiktoken"); if ( new TokenManager(this.super.model).countFromString( document.content ) < Provider.contextLimit(this.super.provider, this.super.model) ) { return document.content; } this.super.introspect( `${this.caller}: Summarizing ${filename ?? ""}...` ); this.super.onAbort(() => { this.super.handlerProps.log( "Abort was triggered, exiting summarization early." ); this.controller.abort(); }); return await summarizeContent({ provider: this.super.provider, model: this.super.model, controllerSignal: this.controller.signal, content: document.content, }); } catch (error) { this.super.handlerProps.log( `document-summarizer.summarizeDoc raised an error. ${error.message}` ); return `Let the user know this action was not successful. An error was raised while summarizing the file. ${error.message}`; } }, }); }, }; }, }; module.exports = { docSummarizer, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/file-history.js
server/utils/agents/aibitat/plugins/file-history.js
const fs = require("fs"); const path = require("path"); /** * Plugin to save chat history to a json file */ const fileHistory = { name: "file-history-plugin", startupConfig: { params: {}, }, plugin: function ({ filename = `history/chat-history-${new Date().toISOString()}.json`, } = {}) { return { name: this.name, setup(aibitat) { const folderPath = path.dirname(filename); // get path from filename if (folderPath) { fs.mkdirSync(folderPath, { recursive: true }); } aibitat.onMessage(() => { const content = JSON.stringify(aibitat.chats, null, 2); fs.writeFile(filename, content, (err) => { if (err) { console.error(err); } }); }); }, }; }, }; module.exports = { fileHistory };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/save-file-browser.js
server/utils/agents/aibitat/plugins/save-file-browser.js
const { Deduplicator } = require("../utils/dedupe"); const saveFileInBrowser = { name: "save-file-to-browser", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { // List and summarize the contents of files that are embedded in the workspace aibitat.function({ super: aibitat, tracker: new Deduplicator(), name: this.name, description: "Save content to a file when the user explicitly asks for a download of the file.", examples: [ { prompt: "Save me that to a file named 'output'", call: JSON.stringify({ file_content: "<content of the file we will write previous conversation>", filename: "output.txt", }), }, { prompt: "Save me that to my desktop", call: JSON.stringify({ file_content: "<content of the file we will write previous conversation>", filename: "<relevant filename>.txt", }), }, { prompt: "Save me that to a file", call: JSON.stringify({ file_content: "<content of the file we will write from previous conversation>", filename: "<descriptive filename>.txt", }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { file_content: { type: "string", description: "The content of the file that will be saved.", }, filename: { type: "string", description: "filename to save the file as with extension. Extension should be plaintext file extension.", }, }, additionalProperties: false, }, handler: async function ({ file_content = "", filename }) { try { const { isDuplicate, reason } = this.tracker.isDuplicate( this.name, { file_content, filename } ); if (isDuplicate) { this.super.handlerProps.log( `${this.name} was called, but exited early because ${reason}.` ); return `${filename} file has been saved successfully!`; } this.super.socket.send("fileDownload", { filename, b64Content: "data:text/plain;base64," + Buffer.from(file_content, "utf8").toString("base64"), }); this.super.introspect(`${this.caller}: Saving file ${filename}.`); this.tracker.trackRun(this.name, { file_content, filename }); return `${filename} file has been saved successfully and will be downloaded automatically to the users browser.`; } catch (error) { this.super.handlerProps.log( `save-file-to-browser raised an error. ${error.message}` ); return `Let the user know this action was not successful. An error was raised while saving a file to the browser. ${error.message}`; } }, }); }, }; }, }; module.exports = { saveFileInBrowser, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/chat-history.js
server/utils/agents/aibitat/plugins/chat-history.js
const { WorkspaceChats } = require("../../../../models/workspaceChats"); /** * Plugin to save chat history to AnythingLLM DB. */ const chatHistory = { name: "chat-history", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup: function (aibitat) { aibitat.onMessage(async () => { try { const lastResponses = aibitat.chats.slice(-2); if (lastResponses.length !== 2) return; const [prev, last] = lastResponses; // We need a full conversation reply with prev being from // the USER and the last being from anyone other than the user. if (prev.from !== "USER" || last.from === "USER") return; // If we have a post-reply flow we should save the chat using this special flow // so that post save cleanup and other unique properties can be run as opposed to regular chat. if (aibitat.hasOwnProperty("_replySpecialAttributes")) { await this._storeSpecial(aibitat, { prompt: prev.content, response: last.content, options: aibitat._replySpecialAttributes, }); delete aibitat._replySpecialAttributes; return; } await this._store(aibitat, { prompt: prev.content, response: last.content, }); } catch {} }); }, _store: async function (aibitat, { prompt, response } = {}) { const invocation = aibitat.handlerProps.invocation; await WorkspaceChats.new({ workspaceId: Number(invocation.workspace_id), prompt, response: { text: response, sources: [], type: "chat", }, user: { id: invocation?.user_id || null }, threadId: invocation?.thread_id || null, }); }, _storeSpecial: async function ( aibitat, { prompt, response, options = {} } = {} ) { const invocation = aibitat.handlerProps.invocation; await WorkspaceChats.new({ workspaceId: Number(invocation.workspace_id), prompt, response: { sources: options?.sources ?? [], // when we have a _storeSpecial called the options param can include a storedResponse() function // that will override the text property to store extra information in, depending on the special type of chat. text: options.hasOwnProperty("storedResponse") ? options.storedResponse(response) : response, type: options?.saveAsType ?? "chat", }, user: { id: invocation?.user_id || null }, threadId: invocation?.thread_id || null, }); options?.postSave(); }, }; }, }; module.exports = { chatHistory };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/rechart.js
server/utils/agents/aibitat/plugins/rechart.js
const { safeJsonParse } = require("../../../http"); const { Deduplicator } = require("../utils/dedupe"); const rechart = { name: "create-chart", startupConfig: { params: {}, }, plugin: function () { return { name: this.name, setup(aibitat) { // Scrape a website and summarize the content based on objective if the content is too large.', aibitat.function({ super: aibitat, name: this.name, tracker: new Deduplicator(), description: "Generates the JSON data required to generate a RechartJS chart to the user based on their prompt and available data.", parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { type: { type: "string", enum: [ "area", "bar", "line", "composed", "scatter", "pie", "radar", "radialBar", "treemap", "funnel", ], description: "The type of chart to be generated.", }, title: { type: "string", description: "Title of the chart. There MUST always be a title. Do not leave it blank.", }, dataset: { type: "string", description: `Valid JSON in which each element is an object for Recharts API for the 'type' of chart defined WITHOUT new line characters. Strictly using this FORMAT and naming: { "name": "a", "value": 12 }]. Make sure field "name" always stays named "name". Instead of naming value field value in JSON, name it based on user metric and make it the same across every item. Make sure the format use double quotes and property names are string literals. Provide JSON data only.`, }, }, additionalProperties: false, }, required: ["type", "title", "dataset"], handler: async function ({ type, dataset, title }) { try { if (this.tracker.isMarkedUnique(this.name)) { this.super.handlerProps.log( `${this.name} has been called for this chat response already. It can only be called once per chat.` ); return "The chart was generated and returned to the user. This function completed successfully. Do not call this function again."; } const data = safeJsonParse(dataset, null); if (data === null) { this.super.introspect( `${this.caller}: ${this.name} provided invalid JSON data - so we cant make a ${type} chart.` ); return "Invalid JSON provided. Please only provide valid RechartJS JSON to generate a chart."; } this.super.introspect(`${this.caller}: Rendering ${type} chart.`); this.super.socket.send("rechartVisualize", { type, dataset, title, }); this.super._replySpecialAttributes = { saveAsType: "rechartVisualize", storedResponse: (additionalText = "") => JSON.stringify({ type, dataset, title, caption: additionalText, }), postSave: () => this.tracker.removeUniqueConstraint(this.name), }; this.tracker.markUnique(this.name); return "The chart was generated and returned to the user. This function completed successfully. Do not make another chart."; } catch (error) { this.super.handlerProps.log( `create-chart raised an error. ${error.message}` ); return `Let the user know this action was not successful. An error was raised while generating the chart. ${error.message}`; } }, }); }, }; }, }; module.exports = { rechart, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/list-table.js
server/utils/agents/aibitat/plugins/sql-agent/list-table.js
module.exports.SqlAgentListTables = { name: "sql-list-tables", plugin: function () { const { listSQLConnections, getDBClient, } = require("./SQLConnectors/index.js"); return { name: "sql-list-tables", setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, description: "List all available tables in a database via its `database_id`.", examples: [ { prompt: "What tables are there in the `access-logs` database?", call: JSON.stringify({ database_id: "access-logs" }), }, { prompt: "What information can you access in the customer_accts postgres db?", call: JSON.stringify({ database_id: "customer_accts" }), }, { prompt: "Can you tell me what is in the primary-logs db?", call: JSON.stringify({ database_id: "primary-logs" }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { database_id: { type: "string", description: "The database identifier for which we will list all tables for. This is a required parameter", }, }, additionalProperties: false, }, required: ["database_id"], handler: async function ({ database_id = "" }) { try { this.super.handlerProps.log(`Using the sql-list-tables tool.`); const databaseConfig = (await listSQLConnections()).find( (db) => db.database_id === database_id ); if (!databaseConfig) { this.super.handlerProps.log( `sql-list-tables failed to find config!`, database_id ); return `No database connection for ${database_id} was found!`; } const db = getDBClient(databaseConfig.engine, databaseConfig); this.super.introspect( `${this.caller}: Checking what are the available tables in the ${databaseConfig.database_id} database.` ); this.super.introspect(`Running SQL: ${db.getTablesSql()}`); const result = await db.runQuery(db.getTablesSql(database_id)); if (result.error) { this.super.handlerProps.log( `sql-list-tables tool reported error`, result.error ); this.super.introspect(`Error: ${result.error}`); return `There was an error running the query: ${result.error}`; } return JSON.stringify(result); } catch (e) { console.error(e); return e.message; } }, }); }, }; }, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/get-table-schema.js
server/utils/agents/aibitat/plugins/sql-agent/get-table-schema.js
module.exports.SqlAgentGetTableSchema = { name: "sql-get-table-schema", plugin: function () { const { listSQLConnections, getDBClient, } = require("./SQLConnectors/index.js"); return { name: "sql-get-table-schema", setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, description: "Gets the table schema in SQL for a given `table` and `database_id`", examples: [ { prompt: "What does the customers table in access-logs look like?", call: JSON.stringify({ database_id: "access-logs", table_name: "customers", }), }, { prompt: "Get me the full name of a company in records-main, the table should be call comps", call: JSON.stringify({ database_id: "records-main", table_name: "comps", }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { database_id: { type: "string", description: "The database identifier for which we will connect to to query the table schema. This is a required field.", }, table_name: { type: "string", description: "The database identifier for the table name we want the schema for. This is a required field.", }, }, additionalProperties: false, }, required: ["database_id", "table_name"], handler: async function ({ database_id = "", table_name = "" }) { this.super.handlerProps.log(`Using the sql-get-table-schema tool.`); try { const databaseConfig = (await listSQLConnections()).find( (db) => db.database_id === database_id ); if (!databaseConfig) { this.super.handlerProps.log( `sql-get-table-schema to find config!`, database_id ); return `No database connection for ${database_id} was found!`; } const db = getDBClient(databaseConfig.engine, databaseConfig); this.super.introspect( `${this.caller}: Querying the table schema for ${table_name} in the ${databaseConfig.database_id} database.` ); this.super.introspect( `Running SQL: ${db.getTableSchemaSql(table_name)}` ); const result = await db.runQuery( db.getTableSchemaSql(table_name) ); if (result.error) { this.super.handlerProps.log( `sql-get-table-schema tool reported error`, result.error ); this.super.introspect(`Error: ${result.error}`); return `There was an error running the query: ${result.error}`; } return JSON.stringify(result); } catch (e) { this.super.handlerProps.log( `sql-get-table-schema raised an error. ${e.message}` ); return e.message; } }, }); }, }; }, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/index.js
server/utils/agents/aibitat/plugins/sql-agent/index.js
const { SqlAgentGetTableSchema } = require("./get-table-schema"); const { SqlAgentListDatabase } = require("./list-database"); const { SqlAgentListTables } = require("./list-table"); const { SqlAgentQuery } = require("./query"); const sqlAgent = { name: "sql-agent", startupConfig: { params: {}, }, plugin: [ SqlAgentListDatabase, SqlAgentListTables, SqlAgentGetTableSchema, SqlAgentQuery, ], }; module.exports = { sqlAgent, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/query.js
server/utils/agents/aibitat/plugins/sql-agent/query.js
module.exports.SqlAgentQuery = { name: "sql-query", plugin: function () { const { getDBClient, listSQLConnections, } = require("./SQLConnectors/index.js"); return { name: "sql-query", setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, description: "Run a read-only SQL query on a `database_id` which will return up rows of data related to the query. The query must only be SELECT statements which do not modify the table data. There should be a reasonable LIMIT on the return quantity to prevent long-running or queries which crash the db.", examples: [ { prompt: "How many customers are in dvd-rentals?", call: JSON.stringify({ database_id: "dvd-rentals", sql_query: "SELECT * FROM customers", }), }, { prompt: "Can you tell me the total volume of sales last month?", call: JSON.stringify({ database_id: "sales-db", sql_query: "SELECT SUM(sale_amount) AS total_sales FROM sales WHERE sale_date >= DATEADD(month, -1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)) AND sale_date < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)", }), }, { prompt: "Do we have anyone in the staff table for our production db named 'sam'? ", call: JSON.stringify({ database_id: "production", sql_query: "SElECT * FROM staff WHERE first_name='sam%' OR last_name='sam%'", }), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { database_id: { type: "string", description: "The database identifier for which we will connect to to query the table schema. This is required to run the SQL query.", }, sql_query: { type: "string", description: "The raw SQL query to run. Should be a query which does not modify the table and will return results.", }, }, additionalProperties: false, }, required: ["database_id", "table_name"], handler: async function ({ database_id = "", sql_query = "" }) { this.super.handlerProps.log(`Using the sql-query tool.`); try { const databaseConfig = (await listSQLConnections()).find( (db) => db.database_id === database_id ); if (!databaseConfig) { this.super.handlerProps.log( `sql-query failed to find config!`, database_id ); return `No database connection for ${database_id} was found!`; } this.super.introspect( `${this.caller}: Im going to run a query on the ${database_id} to get an answer.` ); const db = getDBClient(databaseConfig.engine, databaseConfig); this.super.introspect(`Running SQL: ${sql_query}`); const result = await db.runQuery(sql_query); if (result.error) { this.super.handlerProps.log( `sql-query tool reported error`, result.error ); this.super.introspect(`Error: ${result.error}`); return `There was an error running the query: ${result.error}`; } return JSON.stringify(result); } catch (e) { console.error(e); return e.message; } }, }); }, }; }, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/list-database.js
server/utils/agents/aibitat/plugins/sql-agent/list-database.js
module.exports.SqlAgentListDatabase = { name: "sql-list-databases", plugin: function () { const { listSQLConnections } = require("./SQLConnectors"); return { name: "sql-list-databases", setup(aibitat) { aibitat.function({ super: aibitat, name: this.name, description: "List all available databases via `list_databases` you currently have access to. Returns a unique string identifier `database_id` that can be used for future calls.", examples: [ { prompt: "What databases can you access?", call: JSON.stringify({}), }, { prompt: "What databases can you tell me about?", call: JSON.stringify({}), }, { prompt: "Is there a database named erp-logs you can access?", call: JSON.stringify({}), }, ], parameters: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: {}, additionalProperties: false, }, handler: async function () { this.super.handlerProps.log(`Using the sql-list-databases tool.`); this.super.introspect( `${this.caller}: Checking what are the available databases.` ); const connections = (await listSQLConnections()).map((conn) => { const { connectionString, ...rest } = conn; return rest; }); return JSON.stringify(connections); }, }); }, }; }, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/MSSQL.js
server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/MSSQL.js
const mssql = require("mssql"); const { ConnectionStringParser } = require("./utils"); class MSSQLConnector { #connected = false; database_id = ""; connectionConfig = { user: null, password: null, database: null, server: null, port: null, pool: { max: 10, min: 0, idleTimeoutMillis: 30000, }, options: { encrypt: false, trustServerCertificate: true, }, }; constructor( config = { // we will force into RFC-3986 from DB // eg: mssql://user:password@server:port/database?{...opts} connectionString: null, // we will force into RFC-3986 } ) { this.className = "MSSQLConnector"; this.connectionString = config.connectionString; this._client = null; this.#parseDatabase(); } #parseDatabase() { const connectionParser = new ConnectionStringParser({ scheme: "mssql" }); const parsed = connectionParser.parse(this.connectionString); this.database_id = parsed?.endpoint; this.connectionConfig = { ...this.connectionConfig, user: parsed?.username, password: parsed?.password, database: parsed?.endpoint, server: parsed?.hosts?.[0]?.host, port: parsed?.hosts?.[0]?.port, options: { ...this.connectionConfig.options, encrypt: parsed?.options?.encrypt === "true", }, }; } async connect() { this._client = await mssql.connect(this.connectionConfig); this.#connected = true; return this._client; } /** * * @param {string} queryString the SQL query to be run * @returns {Promise<import(".").QueryResult>} */ async runQuery(queryString = "") { const result = { rows: [], count: 0, error: null }; try { if (!this.#connected) await this.connect(); const query = await this._client.query(queryString); result.rows = query.recordset; result.count = query.rowsAffected.reduce((sum, a) => sum + a, 0); } catch (err) { console.log(this.className, err); result.error = err.message; } finally { // Check client is connected before closing since we use this for validation if (this._client) { await this._client.close(); this.#connected = false; } } return result; } async validateConnection() { try { const result = await this.runQuery("SELECT 1"); return { success: !result.error, error: result.error }; } catch (error) { return { success: false, error: error.message }; } } getTablesSql() { return `SELECT name FROM sysobjects WHERE xtype='U';`; } getTableSchemaSql(table_name) { return `SELECT COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='${table_name}'`; } } module.exports.MSSQLConnector = MSSQLConnector;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js
server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/index.js
const { SystemSettings } = require("../../../../../../models/systemSettings"); const { safeJsonParse } = require("../../../../../http"); /** * @typedef {('postgresql'|'mysql'|'sql-server')} SQLEngine */ /** * @typedef {Object} QueryResult * @property {[number]} rows - The query result rows * @property {number} count - Number of rows the query returned/changed * @property {string|null} error - Error string if there was an issue */ /** * A valid database SQL connection object * @typedef {Object} SQLConnection * @property {string} database_id - Unique identifier of the database connection * @property {SQLEngine} engine - Engine used by connection * @property {string} connectionString - RFC connection string for db */ /** * @param {SQLEngine} identifier * @param {object} connectionConfig * @returns Database Connection Engine Class for SQLAgent or throws error */ function getDBClient(identifier = "", connectionConfig = {}) { switch (identifier) { case "mysql": const { MySQLConnector } = require("./MySQL"); return new MySQLConnector(connectionConfig); case "postgresql": const { PostgresSQLConnector } = require("./Postgresql"); return new PostgresSQLConnector(connectionConfig); case "sql-server": const { MSSQLConnector } = require("./MSSQL"); return new MSSQLConnector(connectionConfig); default: throw new Error( `There is no supported database connector for ${identifier}` ); } } /** * Lists all of the known database connection that can be used by the agent. * @returns {Promise<[SQLConnection]>} */ async function listSQLConnections() { return safeJsonParse( (await SystemSettings.get({ label: "agent_sql_connections" }))?.value, [] ); } /** * Validates a SQL connection by attempting to connect and run a simple query * @param {SQLEngine} identifier - The SQL engine type * @param {object} connectionConfig - The connection configuration * @returns {Promise<{success: boolean, error: string|null}>} */ async function validateConnection(identifier = "", connectionConfig = {}) { try { const client = getDBClient(identifier, connectionConfig); return await client.validateConnection(); } catch (error) { console.log(`Failed to connect to ${identifier} database.`); return { success: false, error: `Unable to connect to ${identifier}. Please verify your connection details.`, }; } } module.exports = { getDBClient, listSQLConnections, validateConnection, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/Postgresql.js
server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/Postgresql.js
const pgSql = require("pg"); class PostgresSQLConnector { #connected = false; constructor( config = { connectionString: null, schema: null, } ) { this.className = "PostgresSQLConnector"; this.connectionString = config.connectionString; this.schema = config.schema || "public"; this._client = new pgSql.Client({ connectionString: this.connectionString, }); } async connect() { await this._client.connect(); this.#connected = true; return this._client; } /** * * @param {string} queryString the SQL query to be run * @returns {Promise<import(".").QueryResult>} */ async runQuery(queryString = "") { const result = { rows: [], count: 0, error: null }; try { if (!this.#connected) await this.connect(); const query = await this._client.query(queryString); result.rows = query.rows; result.count = query.rowCount; } catch (err) { console.log(this.className, err); result.error = err.message; } finally { // Check client is connected before closing since we use this for validation if (this._client) { await this._client.end(); this.#connected = false; } } return result; } async validateConnection() { try { const result = await this.runQuery("SELECT 1"); return { success: !result.error, error: result.error }; } catch (error) { return { success: false, error: error.message }; } } getTablesSql() { return `SELECT * FROM pg_catalog.pg_tables WHERE schemaname = '${this.schema}'`; } getTableSchemaSql(table_name) { return ` select column_name, data_type, character_maximum_length, column_default, is_nullable from INFORMATION_SCHEMA.COLUMNS where table_name = '${table_name}' AND table_schema = '${this.schema}'`; } } module.exports.PostgresSQLConnector = PostgresSQLConnector;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/MySQL.js
server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/MySQL.js
const mysql = require("mysql2/promise"); const { ConnectionStringParser } = require("./utils"); class MySQLConnector { #connected = false; database_id = ""; constructor( config = { connectionString: null, } ) { this.className = "MySQLConnector"; this.connectionString = config.connectionString; this._client = null; this.database_id = this.#parseDatabase(); } #parseDatabase() { const connectionParser = new ConnectionStringParser({ scheme: "mysql" }); const parsed = connectionParser.parse(this.connectionString); return parsed?.endpoint; } async connect() { this._client = await mysql.createConnection({ uri: this.connectionString }); this.#connected = true; return this._client; } /** * * @param {string} queryString the SQL query to be run * @returns {Promise<import(".").QueryResult>} */ async runQuery(queryString = "") { const result = { rows: [], count: 0, error: null }; try { if (!this.#connected) await this.connect(); const [query] = await this._client.query(queryString); result.rows = query; result.count = query?.length; } catch (err) { console.log(this.className, err); result.error = err.message; } finally { // Check client is connected before closing since we use this for validation if (this._client) { await this._client.end(); this.#connected = false; } } return result; } async validateConnection() { try { const result = await this.runQuery("SELECT 1"); return { success: !result.error, error: result.error }; } catch (error) { return { success: false, error: error.message }; } } getTablesSql() { return `SELECT table_name FROM information_schema.tables WHERE table_schema = '${this.database_id}'`; } getTableSchemaSql(table_name) { return `SHOW COLUMNS FROM ${this.database_id}.${table_name};`; } } module.exports.MySQLConnector = MySQLConnector;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js
server/utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils.js
// Credit: https://github.com/sindilevich/connection-string-parser /** * @typedef {Object} ConnectionStringParserOptions * @property {'mssql' | 'mysql' | 'postgresql' | 'db'} [scheme] - The scheme of the connection string */ /** * @typedef {Object} ConnectionStringObject * @property {string} scheme - The scheme of the connection string eg: mongodb, mssql, mysql, postgresql, etc. * @property {string} username - The username of the connection string * @property {string} password - The password of the connection string * @property {{host: string, port: number}[]} hosts - The hosts of the connection string * @property {string} endpoint - The endpoint (database name) of the connection string * @property {Object} options - The options of the connection string */ class ConnectionStringParser { static DEFAULT_SCHEME = "db"; /** * @param {ConnectionStringParserOptions} options */ constructor(options = {}) { this.scheme = (options && options.scheme) || ConnectionStringParser.DEFAULT_SCHEME; } /** * Takes a connection string object and returns a URI string of the form: * * scheme://[username[:password]@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[endpoint]][?options] * @param {Object} connectionStringObject The object that describes connection string parameters */ format(connectionStringObject) { if (!connectionStringObject) { return this.scheme + "://localhost"; } if ( this.scheme && connectionStringObject.scheme && this.scheme !== connectionStringObject.scheme ) { throw new Error(`Scheme not supported: ${connectionStringObject.scheme}`); } let uri = (this.scheme || connectionStringObject.scheme || ConnectionStringParser.DEFAULT_SCHEME) + "://"; if (connectionStringObject.username) { uri += encodeURIComponent(connectionStringObject.username); // Allow empty passwords if (connectionStringObject.password) { uri += ":" + encodeURIComponent(connectionStringObject.password); } uri += "@"; } uri += this._formatAddress(connectionStringObject); // Only put a slash when there is an endpoint if (connectionStringObject.endpoint) { uri += "/" + encodeURIComponent(connectionStringObject.endpoint); } if ( connectionStringObject.options && Object.keys(connectionStringObject.options).length > 0 ) { uri += "?" + Object.keys(connectionStringObject.options) .map( (option) => encodeURIComponent(option) + "=" + encodeURIComponent(connectionStringObject.options[option]) ) .join("&"); } return uri; } /** * Where scheme and hosts will always be present. Other fields will only be present in the result if they were * present in the input. * @param {string} uri The connection string URI * @returns {ConnectionStringObject} The connection string object */ parse(uri) { const connectionStringParser = new RegExp( "^\\s*" + // Optional whitespace padding at the beginning of the line "([^:]+)://" + // Scheme (Group 1) "(?:([^:@,/?=&]+)(?::([^:@,/?=&]+))?@)?" + // User (Group 2) and Password (Group 3) "([^@/?=&]+)" + // Host address(es) (Group 4) "(?:/([^:@,/?=&]+)?)?" + // Endpoint (Group 5) "(?:\\?([^:@,/?]+)?)?" + // Options (Group 6) "\\s*$", // Optional whitespace padding at the end of the line "gi" ); const connectionStringObject = {}; if (!uri.includes("://")) { throw new Error(`No scheme found in URI ${uri}`); } const tokens = connectionStringParser.exec(uri); if (Array.isArray(tokens)) { connectionStringObject.scheme = tokens[1]; if (this.scheme && this.scheme !== connectionStringObject.scheme) { throw new Error(`URI must start with '${this.scheme}://'`); } connectionStringObject.username = tokens[2] ? decodeURIComponent(tokens[2]) : tokens[2]; connectionStringObject.password = tokens[3] ? decodeURIComponent(tokens[3]) : tokens[3]; connectionStringObject.hosts = this._parseAddress(tokens[4]); connectionStringObject.endpoint = tokens[5] ? decodeURIComponent(tokens[5]) : tokens[5]; connectionStringObject.options = tokens[6] ? this._parseOptions(tokens[6]) : tokens[6]; } return connectionStringObject; } /** * Formats the address portion of a connection string * @param {Object} connectionStringObject The object that describes connection string parameters */ _formatAddress(connectionStringObject) { return connectionStringObject.hosts .map( (address) => encodeURIComponent(address.host) + (address.port ? ":" + encodeURIComponent(address.port.toString(10)) : "") ) .join(","); } /** * Parses an address * @param {string} addresses The address(es) to process */ _parseAddress(addresses) { return addresses.split(",").map((address) => { const i = address.indexOf(":"); return i >= 0 ? { host: decodeURIComponent(address.substring(0, i)), port: +address.substring(i + 1), } : { host: decodeURIComponent(address) }; }); } /** * Parses options * @param {string} options The options to process */ _parseOptions(options) { const result = {}; options.split("&").forEach((option) => { const i = option.indexOf("="); if (i >= 0) { result[decodeURIComponent(option.substring(0, i))] = decodeURIComponent( option.substring(i + 1) ); } }); return result; } } module.exports = { ConnectionStringParser };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/gemini.js
server/utils/agents/aibitat/providers/gemini.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const { RetryError } = require("../error.js"); const { safeJsonParse } = require("../../../http"); const { v4 } = require("uuid"); /** * The agent provider for the Gemini provider. * We wrap Gemini in UnTooled because its tool-calling is not supported via the dedicated OpenAI API. */ class GeminiProvider extends Provider { model; constructor(config = {}) { const { model = "gemini-2.0-flash-lite" } = config; super(); this.className = "GeminiProvider"; const client = new OpenAI({ baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/", apiKey: process.env.GEMINI_API_KEY, maxRetries: 0, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsToolCalling() { if (!this.model.startsWith("gemini")) return false; return true; } get supportsAgentStreaming() { // Tool call streaming results in a 400/503 error for all non-gemini models // using the compatible v1beta/openai/ endpoint if (!this.model.startsWith("gemini")) { this.providerLog( `Gemini: ${this.model} does not support tool call streaming.` ); return false; } return true; } /** * Gemini specifcally will throw an error if the tool call's function name * starts with a non-alpha character. So we need to prefix the function names * with a valid prefix to ensure they are always valid and then strip them back * so they may properly be used in the tool call. * * So for all tools, we force the prefix to be gtc__ to avoid issues * Agent flows are already prefixed with flow__ but since we strip the prefix * anyway pre and post-reply, we do it anyway to ensure consistency across all tools. * * This specifically impacts the custom Agent Skills since they can be a short alphanumeric * and cant definitely start with a number. eg: '12xdaya31bas' -> invalid in gemini tools. * * Even if the tool is never called, if it is in the `tools` array and this prefix * patch is not applied, gemini will throw an error. * * This is undocumented by google, but it is the only way to ensure that tool calls * are valid. * * @param {string} functionName - The name of the function to prefix. * @param {'add' | 'strip'} action - The action to take. * @returns {string} The prefixed function name. * @returns {string} The prefix to use for tool call ids. */ prefixToolCall(functionName, action = "add") { if (action === "add") return `gtc__${functionName}`; // must start with gtc__ to be valid and we only strip the first instance return functionName.startsWith("gtc__") ? functionName.split("gtc__")[1] : functionName; } /** * Format the messages to the Gemini API Responses format. * - Gemini has some loosely documented format for tool calls and it can change at any time. * - We need to map the function call to the correct id and Gemini will throw an error if it does not. * @param {any[]} messages - The messages to format. * @returns {OpenAI.OpenAI.Responses.ResponseInput[]} The formatted messages. */ #formatMessages(messages) { let formattedMessages = []; messages.forEach((message) => { if (message.role === "function") { // If the message does not have an originalFunctionCall we cannot // map it to a function call id and Gemini will throw an error. // so if this does not carry over - log and skip if (!message.hasOwnProperty("originalFunctionCall")) { this.providerLog( "[Gemini.#formatMessages]: message did not pass back the originalFunctionCall. We need this to map the function call to the correct id.", { message: JSON.stringify(message, null, 2) } ); return; } formattedMessages.push( { role: "assistant", tool_calls: [ { type: "function", function: { arguments: JSON.stringify( message.originalFunctionCall.arguments ), name: message.originalFunctionCall.name, }, id: message.originalFunctionCall.id, }, ], }, { role: "tool", tool_call_id: message.originalFunctionCall.id, content: message.content, } ); return; } formattedMessages.push({ role: message.role, content: message.content, }); }); return formattedMessages; } #formatFunctions(functions) { return functions.map((func) => ({ type: "function", function: { name: this.prefixToolCall(func.name, "add"), description: func.description, parameters: func.parameters, }, })); } async stream(messages, functions = [], eventHandler = null) { if (!this.supportsToolCalling) throw new Error(`Gemini: ${this.model} does not support tool calling.`); this.providerLog("Gemini.stream - will process this chat completion."); try { const msgUUID = v4(); /** @type {OpenAI.OpenAI.Chat.ChatCompletion} */ const response = await this.client.chat.completions.create({ model: this.model, messages: this.#formatMessages(messages), stream: true, ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions), tool_choice: "auto" } : {}), }); const completion = { content: "", /** @type {null|{name: string, call_id: string, arguments: string|object}} */ functionCall: null, }; for await (const streamEvent of response) { /** @type {OpenAI.OpenAI.Chat.ChatCompletionChunk} */ const chunk = streamEvent; const { content, tool_calls } = chunk?.choices?.[0]?.delta || {}; if (content) { completion.content += content; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content, }); } if (tool_calls) { const toolCall = tool_calls[0]; completion.functionCall = { name: this.prefixToolCall(toolCall.function.name, "strip"), call_id: toolCall.id, arguments: toolCall.function.arguments, }; eventHandler?.("reportStreamEvent", { type: "toolCallInvocation", uuid: `${msgUUID}:tool_call_invocation`, content: `Assembling Tool Call: ${completion.functionCall.name}(${completion.functionCall.arguments})`, }); } } if (completion.functionCall) { completion.functionCall.arguments = safeJsonParse( completion.functionCall.arguments, {} ); return { textResponse: completion.content, functionCall: { id: completion.functionCall.call_id, name: completion.functionCall.name, arguments: completion.functionCall.arguments, }, cost: this.getCost(), }; } return { textResponse: completion.content, functionCall: null, cost: this.getCost(), }; } catch (error) { if (error instanceof OpenAI.AuthenticationError) throw error; if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the Gemini API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { if (!this.supportsToolCalling) throw new Error(`Gemini: ${this.model} does not support tool calling.`); this.providerLog("Gemini.complete - will process this chat completion."); try { const response = await this.client.chat.completions.create({ model: this.model, stream: false, messages: this.#formatMessages(messages), ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions), tool_choice: "auto" } : {}), }); /** @type {OpenAI.OpenAI.Chat.ChatCompletionMessage} */ const completion = response.choices[0].message; const cost = this.getCost(response.usage); if (completion?.tool_calls?.length > 0) { const toolCall = completion.tool_calls[0]; let functionArgs = safeJsonParse(toolCall.function.arguments, {}); return { textResponse: null, functionCall: { name: this.prefixToolCall(toolCall.function.name, "strip"), arguments: functionArgs, id: toolCall.id, }, cost, }; } return { textResponse: completion.content, cost, }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof OpenAI.AuthenticationError) throw error; if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = GeminiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/foundry.js
server/utils/agents/aibitat/providers/foundry.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { parseFoundryBasePath, FoundryLLM, } = require("../../../AiProviders/foundry/index.js"); /** * The agent provider for the Foundry provider. * Uses untooled because it doesn't support tool calling. */ class FoundryProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = process.env.FOUNDRY_MODEL_PREF } = config; super(); const client = new OpenAI({ baseURL: parseFoundryBasePath(process.env.FOUNDRY_BASE_PATH), apiKey: null, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } /** * Get the client. * @returns {OpenAI.OpenAI} */ get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { await FoundryLLM.cacheContextWindows(); return await this.client.chat.completions .create({ model: this.model, messages, max_completion_tokens: FoundryLLM.promptWindowLimit(this.model), }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Microsoft Foundry Local chat: No results!"); if (result.choices.length === 0) throw new Error("Microsoft Foundry Local chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { await FoundryLLM.cacheContextWindows(); return await this.client.chat.completions.create({ model: this.model, stream: true, messages, max_completion_tokens: FoundryLLM.promptWindowLimit(this.model), }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = FoundryProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/togetherai.js
server/utils/agents/aibitat/providers/togetherai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the TogetherAI provider. */ class TogetherAIProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "mistralai/Mistral-7B-Instruct-v0.1" } = config; super(); const client = new OpenAI({ baseURL: "https://api.together.xyz/v1", apiKey: process.env.TOGETHER_AI_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("LMStudio chat: No results!"); if (result.choices.length === 0) throw new Error("LMStudio chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LMStudio has no cost basis. */ getCost(_usage) { return 0; } } module.exports = TogetherAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/deepseek.js
server/utils/agents/aibitat/providers/deepseek.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { toValidNumber } = require("../../../http/index.js"); class DeepSeekProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = "deepseek-chat" } = config; const client = new OpenAI({ baseURL: "https://api.deepseek.com/v1", apiKey: process.env.DEEPSEEK_API_KEY ?? null, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; this.maxTokens = process.env.DEEPSEEK_MAX_TOKENS ? toValidNumber(process.env.DEEPSEEK_MAX_TOKENS, 1024) : 1024; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, max_tokens: this.maxTokens, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("DeepSeek chat: No results!"); if (result.choices.length === 0) throw new Error("DeepSeek chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = DeepSeekProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/genericOpenAi.js
server/utils/agents/aibitat/providers/genericOpenAi.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { toValidNumber } = require("../../../http/index.js"); const { getAnythingLLMUserAgent } = require("../../../../endpoints/utils"); /** * The agent provider for the Generic OpenAI provider. * Since we cannot promise the generic provider even supports tool calling * which is nearly 100% likely it does not, we can just wrap it in untooled * which often is far better anyway. */ class GenericOpenAiProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = "gpt-3.5-turbo" } = config; const client = new OpenAI({ baseURL: process.env.GENERIC_OPEN_AI_BASE_PATH, apiKey: process.env.GENERIC_OPEN_AI_API_KEY ?? null, maxRetries: 3, defaultHeaders: { "User-Agent": getAnythingLLMUserAgent(), }, }); this._client = client; this.model = model; this.verbose = true; this.maxTokens = process.env.GENERIC_OPEN_AI_MAX_TOKENS ? toValidNumber(process.env.GENERIC_OPEN_AI_MAX_TOKENS, 1024) : 1024; } get client() { return this._client; } get supportsAgentStreaming() { // Honor streaming being disabled via ENV via user preference. if (process.env.GENERIC_OPENAI_STREAMING_DISABLED === "true") return false; return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, temperature: 0, messages, max_tokens: this.maxTokens, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Generic OpenAI chat: No results!"); if (result.choices.length === 0) throw new Error("Generic OpenAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = GenericOpenAiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/zai.js
server/utils/agents/aibitat/providers/zai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); class ZAIProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "glm-4.5" } = config; super(); const client = new OpenAI({ baseURL: "https://api.z.ai/api/paas/v4", apiKey: process.env.ZAI_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the API. * @param functions * @returns The completion. */ get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Z.AI chat: No results!"); if (result.choices.length === 0) throw new Error("Z.AI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } getCost(_usage) { return 0; } } module.exports = ZAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/fireworksai.js
server/utils/agents/aibitat/providers/fireworksai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the FireworksAI provider. * We wrap FireworksAI in UnTooled because its tool-calling may not be supported for specific models and this normalizes that. */ class FireworksAIProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "accounts/fireworks/models/llama-v3p1-8b-instruct" } = config; super(); const client = new OpenAI({ baseURL: "https://api.fireworks.ai/inference/v1", apiKey: process.env.FIREWORKS_AI_LLM_API_KEY, maxRetries: 0, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("FireworksAI chat: No results!"); if (result.choices.length === 0) throw new Error("FireworksAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = FireworksAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/ollama.js
server/utils/agents/aibitat/providers/ollama.js
const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { OllamaAILLM } = require("../../../AiProviders/ollama"); const { Ollama } = require("ollama"); const { v4 } = require("uuid"); const { safeJsonParse } = require("../../../http"); /** * The agent provider for the Ollama provider. */ class OllamaProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { // options = {}, model = null, } = config; super(); const headers = process.env.OLLAMA_AUTH_TOKEN ? { Authorization: `Bearer ${process.env.OLLAMA_AUTH_TOKEN}` } : {}; this._client = new Ollama({ host: process.env.OLLAMA_BASE_PATH, headers: headers, }); this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } get performanceMode() { return process.env.OLLAMA_PERFORMANCE_MODE || "base"; } get queryOptions() { return { ...(this.performanceMode === "base" ? {} : { num_ctx: OllamaAILLM.promptWindowLimit(this.model) }), }; } /** * Handle a chat completion with tool calling * * @param messages * @returns {Promise<string|null>} The completion. */ async #handleFunctionCallChat({ messages = [] }) { await OllamaAILLM.cacheContextWindows(); const response = await this.client.chat({ model: this.model, messages, options: this.queryOptions, }); return response?.message?.content || null; } async #handleFunctionCallStream({ messages = [] }) { await OllamaAILLM.cacheContextWindows(); return await this.client.chat({ model: this.model, messages, stream: true, options: this.queryOptions, }); } async streamingFunctionCall( messages, functions, chatCb = null, eventHandler = null ) { const history = [...messages].filter((msg) => ["user", "assistant"].includes(msg.role) ); if (history[history.length - 1].role !== "user") return null; const msgUUID = v4(); let token = ""; let textResponse = ""; let reasoningText = ""; const historyMessages = this.buildToolCallMessages(history, functions); const stream = await chatCb({ messages: historyMessages }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Agent is thinking...", }); for await (const chunk of stream) { if (!chunk.hasOwnProperty("message")) continue; const content = chunk.message?.content; const reasoningToken = chunk.message?.thinking; if (reasoningToken) { if (reasoningText.length === 0) { reasoningText = `Thinking:\n\n${reasoningToken}`; token = reasoningText; } else { reasoningText += reasoningToken; token = reasoningToken; } } else if (content.length > 0) { if (reasoningText.length > 0) { token = `\n\nDone thinking.\n\n${content}`; reasoningText = ""; } else { token = content; } textResponse += content; } eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: msgUUID, content: token, }); } const call = safeJsonParse(textResponse, null); if (call === null) return { toolCall: null, text: textResponse, uuid: msgUUID }; // failed to parse, so must be regular text response. const { valid, reason } = this.validFuncCall(call, functions); if (!valid) { this.providerLog(`Invalid function tool call: ${reason}.`); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model attempted to make an invalid function call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } const { isDuplicate, reason: duplicateReason } = this.deduplicator.isDuplicate(call.name, call.arguments); if (isDuplicate) { this.providerLog( `Cannot call ${call.name} again because ${duplicateReason}.` ); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model tried to call a function with the same arguments as a previous call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } eventHandler?.("reportStreamEvent", { uuid: `${msgUUID}:tool_call_invocation`, type: "toolCallInvocation", content: `Parsed Tool Call: ${call.name}(${JSON.stringify(call.arguments)})`, }); return { toolCall: call, text: null, uuid: msgUUID }; } /** * Stream a chat completion from the LLM with tool calling * This is overriding the inherited `stream` method since Ollamas * SDK has different response structures to other OpenAI. * * @param messages A list of messages to send to the API. * @param functions * @param eventHandler * @returns The completion. */ async stream(messages, functions = [], eventHandler = null) { this.providerLog( "OllamaProvider.complete - will process this chat completion." ); try { let completion = { content: "" }; if (functions.length > 0) { const { toolCall, text, uuid: msgUUID, } = await this.streamingFunctionCall( messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments, { cooldown: this.isMCPTool(toolCall, functions), }); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } if (text) { this.providerLog( `No tool call found in the response - will send as a full text response.` ); completion.content = text; eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "No tool call found in the response", }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); eventHandler?.("reportStreamEvent", { type: "fullTextResponse", uuid: v4(), content: text, }); } } if (!completion?.content) { eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); this.providerLog( "Will assume chat completion without tool call inputs." ); const msgUUID = v4(); completion = { content: "" }; let reasoningText = ""; let token = ""; const stream = await this.#handleFunctionCallStream({ messages: this.cleanMsgs(messages), }); for await (const chunk of stream) { if (!chunk.hasOwnProperty("message")) continue; const content = chunk.message?.content; const reasoningToken = chunk.message?.thinking; if (reasoningToken) { if (reasoningText.length === 0) { reasoningText = `<think>${reasoningToken}`; token = `<think>${reasoningToken}`; } else { reasoningText += reasoningToken; token = reasoningToken; } } else if (content.length > 0) { if (reasoningText.length > 0) { token = `</think>${content}`; reasoningText = ""; } else { token = content; } } completion.content += token; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: token, }); } } // The UnTooled class inherited Deduplicator is mostly useful to prevent the agent // from calling the exact same function over and over in a loop within a single chat exchange // _but_ we should enable it to call previously used tools in a new chat interaction. this.deduplicator.reset("runs"); return { textResponse: completion.content, cost: 0, }; } catch (error) { throw error; } } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { this.providerLog( "OllamaProvider.complete - will process this chat completion." ); try { let completion = { content: "" }; if (functions.length > 0) { const { toolCall, text } = await this.functionCall( messages, functions, this.#handleFunctionCallChat.bind(this) ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments, { cooldown: this.isMCPTool(toolCall, functions), }); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } completion.content = text; } if (!completion?.content) { this.providerLog( "Will assume chat completion without tool call inputs." ); const textResponse = await this.#handleFunctionCallChat({ messages: this.cleanMsgs(messages), }); completion.content = textResponse; } // The UnTooled class inherited Deduplicator is mostly useful to prevent the agent // from calling the exact same function over and over in a loop within a single chat exchange // _but_ we should enable it to call previously used tools in a new chat interaction. this.deduplicator.reset("runs"); return { textResponse: completion.content, cost: 0, }; } catch (error) { throw error; } } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LMStudio has no cost basis. */ getCost(_usage) { return 0; } } module.exports = OllamaProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/dellProAiStudio.js
server/utils/agents/aibitat/providers/dellProAiStudio.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { DellProAiStudioLLM, } = require("../../../AiProviders/dellProAiStudio/index.js"); /** * The agent provider for Dell Pro AI Studio. */ class DellProAiStudioProvider extends InheritMultiple([Provider, UnTooled]) { model; /** * * @param {{model?: string}} config */ constructor(config = {}) { super(); const model = config?.model || process.env.DPAIS_LLM_MODEL_PREF; const client = new OpenAI({ baseURL: DellProAiStudioLLM.parseBasePath(), // Will use process.env.DPAIS_LLM_BASE_PATH if not provided apiKey: null, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("DellProAiStudio chat: No results!"); if (result.choices.length === 0) throw new Error("DellProAiStudio chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LMStudio has no cost basis. */ getCost(_usage) { return 0; } } module.exports = DellProAiStudioProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/koboldcpp.js
server/utils/agents/aibitat/providers/koboldcpp.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the KoboldCPP provider. */ class KoboldCPPProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(_config = {}) { super(); const model = process.env.KOBOLD_CPP_MODEL_PREF ?? null; const client = new OpenAI({ baseURL: process.env.KOBOLD_CPP_BASE_PATH?.replace(/\/+$/, ""), apiKey: null, maxRetries: 3, }); this._client = client; this.model = model; this.maxTokens = Number(process.env.KOBOLD_CPP_MAX_TOKENS) || 2048; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, max_tokens: this.maxTokens, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("KoboldCPP chat: No results!"); if (result.choices.length === 0) throw new Error("KoboldCPP chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, max_tokens: this.maxTokens, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since KoboldCPP has no cost basis. */ getCost(_usage) { return 0; } } module.exports = KoboldCPPProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/perplexity.js
server/utils/agents/aibitat/providers/perplexity.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the Perplexity provider. */ class PerplexityProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = "sonar-small-online" } = config; const client = new OpenAI({ baseURL: "https://api.perplexity.ai", apiKey: process.env.PERPLEXITY_API_KEY ?? null, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Perplexity chat: No results!"); if (result.choices.length === 0) throw new Error("Perplexity chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = PerplexityProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/index.js
server/utils/agents/aibitat/providers/index.js
const OpenAIProvider = require("./openai.js"); const AnthropicProvider = require("./anthropic.js"); const LMStudioProvider = require("./lmstudio.js"); const OllamaProvider = require("./ollama.js"); const GroqProvider = require("./groq.js"); const TogetherAIProvider = require("./togetherai.js"); const AzureOpenAiProvider = require("./azure.js"); const KoboldCPPProvider = require("./koboldcpp.js"); const LocalAIProvider = require("./localai.js"); const OpenRouterProvider = require("./openrouter.js"); const MistralProvider = require("./mistral.js"); const GenericOpenAiProvider = require("./genericOpenAi.js"); const PerplexityProvider = require("./perplexity.js"); const TextWebGenUiProvider = require("./textgenwebui.js"); const AWSBedrockProvider = require("./bedrock.js"); const FireworksAIProvider = require("./fireworksai.js"); const DeepSeekProvider = require("./deepseek.js"); const LiteLLMProvider = require("./litellm.js"); const ApiPieProvider = require("./apipie.js"); const XAIProvider = require("./xai.js"); const ZAIProvider = require("./zai.js"); const NovitaProvider = require("./novita.js"); const NvidiaNimProvider = require("./nvidiaNim.js"); const PPIOProvider = require("./ppio.js"); const GeminiProvider = require("./gemini.js"); const DellProAiStudioProvider = require("./dellProAiStudio.js"); const MoonshotAiProvider = require("./moonshotAi.js"); const CometApiProvider = require("./cometapi.js"); const FoundryProvider = require("./foundry.js"); const GiteeAIProvider = require("./giteeai.js"); const CohereProvider = require("./cohere.js"); module.exports = { OpenAIProvider, AnthropicProvider, LMStudioProvider, OllamaProvider, GroqProvider, TogetherAIProvider, AzureOpenAiProvider, KoboldCPPProvider, LocalAIProvider, OpenRouterProvider, MistralProvider, GenericOpenAiProvider, DeepSeekProvider, PerplexityProvider, TextWebGenUiProvider, AWSBedrockProvider, FireworksAIProvider, LiteLLMProvider, ApiPieProvider, XAIProvider, ZAIProvider, NovitaProvider, CometApiProvider, NvidiaNimProvider, PPIOProvider, GeminiProvider, DellProAiStudioProvider, MoonshotAiProvider, FoundryProvider, GiteeAIProvider, CohereProvider, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/litellm.js
server/utils/agents/aibitat/providers/litellm.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for LiteLLM. */ class LiteLLMProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = null } = config; const client = new OpenAI({ baseURL: process.env.LITE_LLM_BASE_PATH, apiKey: process.env.LITE_LLM_API_KEY ?? null, maxRetries: 3, }); this._client = client; this.model = model || process.env.LITE_LLM_MODEL_PREF; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("LiteLLM chat: No results!"); if (result.choices.length === 0) throw new Error("LiteLLM chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } getCost(_usage) { return 0; } } module.exports = LiteLLMProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/azure.js
server/utils/agents/aibitat/providers/azure.js
const { OpenAI } = require("openai"); const { AzureOpenAiLLM } = require("../../../AiProviders/azureOpenAi"); const Provider = require("./ai-provider.js"); const { RetryError } = require("../error.js"); /** * The agent provider for the Azure OpenAI API. */ class AzureOpenAiProvider extends Provider { model; constructor(config = { model: null }) { const client = new OpenAI({ apiKey: process.env.AZURE_OPENAI_KEY, baseURL: AzureOpenAiLLM.formatBaseUrl(process.env.AZURE_OPENAI_ENDPOINT), }); super(client); this.model = config.model ?? process.env.OPEN_MODEL_PREF; this.verbose = true; } get supportsAgentStreaming() { return true; } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the OpenAI API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { try { const response = await this.client.chat.completions.create({ model: this.model, stream: false, messages, ...(Array.isArray(functions) && functions?.length > 0 ? { functions } : {}), }); // Right now, we only support one completion, // so we just take the first one in the list const completion = response.choices[0].message; const cost = this.getCost(response.usage); // treat function calls if (completion.function_call) { let functionArgs = {}; try { functionArgs = JSON.parse(completion.function_call.arguments); } catch (error) { // call the complete function again in case it gets a json error return this.complete( [ ...messages, { role: "function", name: completion.function_call.name, function_call: completion.function_call, content: error?.message, }, ], functions ); } // console.log(completion, { functionArgs }) return { textResponse: null, functionCall: { name: completion.function_call.name, arguments: functionArgs, }, cost, }; } return { textResponse: completion.content, cost, }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof OpenAI.AuthenticationError) throw error; if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Get the cost of the completion. * Stubbed since Azure OpenAI has no public cost basis. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = AzureOpenAiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/ppio.js
server/utils/agents/aibitat/providers/ppio.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the PPIO AI provider. */ class PPIOProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "qwen/qwen2.5-32b-instruct" } = config; super(); const client = new OpenAI({ baseURL: "https://api.ppinfra.com/v3/openai", apiKey: process.env.PPIO_API_KEY, maxRetries: 3, defaultHeaders: { "HTTP-Referer": "https://anythingllm.com", "X-API-Source": "anythingllm", }, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return false; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!Object.prototype.hasOwnProperty.call(result, "choices")) throw new Error("PPIO chat: No results!"); if (result.choices.length === 0) throw new Error("PPIO chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since PPIO has no cost basis. */ getCost() { return 0; } } module.exports = PPIOProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/openai.js
server/utils/agents/aibitat/providers/openai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const { RetryError } = require("../error.js"); const { v4 } = require("uuid"); const { safeJsonParse } = require("../../../http"); /** * The agent provider for the OpenAI API. * By default, the model is set to 'gpt-3.5-turbo'. */ class OpenAIProvider extends Provider { model; constructor(config = {}) { const { options = { apiKey: process.env.OPEN_AI_KEY, maxRetries: 3, }, model = "gpt-4o", } = config; const client = new OpenAI(options); super(client); this.model = model; } get supportsAgentStreaming() { return true; } /** * Format the messages to the OpenAI API Responses format. * - If the message is our internal `function` type, then we need to map it to a function call + output format * - Otherwise, map it to the input text format for user, system, and assistant messages * * @param {any[]} messages - The messages to format. * @returns {OpenAI.OpenAI.Responses.ResponseInput[]} The formatted messages. */ #formatToResponsesInput(messages) { let formattedMessages = []; messages.forEach((message) => { if (message.role === "function") { // If the message does not have an originalFunctionCall we cannot // map it to a function call id and OpenAI will throw an error. // so if this does not carry over - log and skip if (!message.hasOwnProperty("originalFunctionCall")) { this.providerLog( "[OpenAI.#formatToResponsesInput]: message did not pass back the originalFunctionCall. We need this to map the function call to the correct id.", { message: JSON.stringify(message, null, 2) } ); return; } formattedMessages.push( { type: "function_call", name: message.originalFunctionCall.name, call_id: message.originalFunctionCall.id, arguments: JSON.stringify(message.originalFunctionCall.arguments), }, { type: "function_call_output", call_id: message.originalFunctionCall.id, output: message.content, } ); return; } formattedMessages.push({ role: message.role, content: [ { type: message.role === "assistant" ? "output_text" : "input_text", text: message.content, }, ], }); }); return formattedMessages; } /** * Format the functions to the OpenAI API Responses format. * * @param {any[]} functions - The functions to format. * @returns {{ * type: "function", * name: string, * description: string, * parameters: object, * strict: boolean, * }[]} The formatted functions. */ #formatFunctions(functions) { return functions.map((func) => ({ type: "function", name: func.name, description: func.description, parameters: func.parameters, strict: false, })); } /** * Stream a chat completion from the LLM with tool calling * Note: This using the OpenAI API Responses SDK and its implementation is specific to OpenAI models. * Do not re-use this code for providers that do not EXACTLY implement the OpenAI API Responses SDK. * * @param {any[]} messages - The messages to send to the LLM. * @param {any[]} functions - The functions to use in the LLM. * @param {function} eventHandler - The event handler to use to report stream events. * @returns {Promise<{ functionCall: any, textResponse: string }>} - The result of the chat completion. */ async stream(messages, functions = [], eventHandler = null) { this.providerLog("OpenAI.stream - will process this chat completion."); try { const msgUUID = v4(); /** @type {OpenAI.OpenAI.Responses.Response} */ const response = await this.client.responses.create({ model: this.model, input: this.#formatToResponsesInput(messages), stream: true, store: false, parallel_tool_calls: false, ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions) } : {}), }); const completion = { content: "", /** @type {null|{name: string, call_id: string, arguments: string|object}} */ functionCall: null, }; for await (const streamEvent of response) { /** @type {OpenAI.OpenAI.Responses.ResponseStreamEvent} */ const chunk = streamEvent; if (chunk.type === "response.output_text.delta") { completion.content += chunk.delta; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: chunk.delta, }); continue; } if ( chunk.type === "response.output_item.added" && chunk.item.type === "function_call" ) { completion.functionCall = { name: chunk.item.name, call_id: chunk.item.call_id, arguments: chunk.item.arguments, }; eventHandler?.("reportStreamEvent", { type: "toolCallInvocation", uuid: `${msgUUID}:tool_call_invocation`, content: `Assembling Tool Call: ${completion.functionCall.name}(${completion.functionCall.arguments})`, }); continue; } if (chunk.type === "response.function_call_arguments.delta") { completion.functionCall.arguments += chunk.delta; eventHandler?.("reportStreamEvent", { type: "toolCallInvocation", uuid: `${msgUUID}:tool_call_invocation`, content: `Assembling Tool Call: ${completion.functionCall.name}(${completion.functionCall.arguments})`, }); continue; } } if (completion.functionCall) { completion.functionCall.arguments = safeJsonParse( completion.functionCall.arguments, {} ); return { textResponse: completion.content, functionCall: { id: completion.functionCall.call_id, name: completion.functionCall.name, arguments: completion.functionCall.arguments, }, cost: this.getCost(), }; } return { textResponse: completion.content, functionCall: null, cost: this.getCost(), }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof OpenAI.AuthenticationError) throw error; if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the OpenAI API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { this.providerLog("OpenAI.complete - will process this chat completion."); try { const completion = { content: "", functionCall: null, }; /** @type {OpenAI.OpenAI.Responses.Response} */ const response = await this.client.responses.create({ model: this.model, stream: false, store: false, parallel_tool_calls: false, input: this.#formatToResponsesInput(messages), ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions) } : {}), }); for (const outputBlock of response.output) { // Grab intermediate text output if it exists // If no tools are used, this will be returned to the aibitat handler // Otherwise, this text will never be shown to the user if (outputBlock.type === "message") { if (outputBlock.content[0]?.type === "output_text") { completion.content = outputBlock.content[0].text; } } // Grab function call output if it exists if (outputBlock.type === "function_call") { completion.functionCall = { name: outputBlock.name, call_id: outputBlock.call_id, arguments: outputBlock.arguments, }; } } if (completion.functionCall) { completion.functionCall.arguments = safeJsonParse( completion.functionCall.arguments, {} ); return { textResponse: completion.content, functionCall: { // For OpenAI, the id is the call_id and we need it in followup requests // so we can match the function call output to its invocation in the message history. id: completion.functionCall.call_id, name: completion.functionCall.name, arguments: completion.functionCall.arguments, }, cost: this.getCost(), }; } return { textResponse: completion.content, functionCall: null, cost: this.getCost(), }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof OpenAI.AuthenticationError) throw error; if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost() { return 0; } } module.exports = OpenAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/nvidiaNim.js
server/utils/agents/aibitat/providers/nvidiaNim.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { parseNvidiaNimBasePath } = require("../../../AiProviders/nvidiaNim"); /** * The agent provider for the Nvidia NIM provider. * We wrap Nvidia NIM in UnTooled because its tool-calling may not be supported for specific models and this normalizes that. */ class NvidiaNimProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model } = config; super(); const client = new OpenAI({ baseURL: parseNvidiaNimBasePath(process.env.NVIDIA_NIM_LLM_BASE_PATH), apiKey: null, maxRetries: 0, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("NVIDIA NIM chat: No results!"); if (result.choices.length === 0) throw new Error("NVIDIA NIM chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = NvidiaNimProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/cometapi.js
server/utils/agents/aibitat/providers/cometapi.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the CometAPI provider. */ class CometApiProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "gpt-5-mini" } = config; super(); const client = new OpenAI({ baseURL: "https://api.cometapi.com/v1", apiKey: process.env.COMETAPI_LLM_API_KEY, maxRetries: 3, defaultHeaders: { "HTTP-Referer": "https://anythingllm.com", "X-CometAPI-Source": "anythingllm", }, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return false; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("CometAPI chat: No results!"); if (result.choices.length === 0) throw new Error("CometAPI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since CometAPI has no cost basis. */ getCost() { return 0; } } module.exports = CometApiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/lmstudio.js
server/utils/agents/aibitat/providers/lmstudio.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { LMStudioLLM, parseLMStudioBasePath, } = require("../../../AiProviders/lmStudio/index.js"); /** * The agent provider for the LMStudio. */ class LMStudioProvider extends InheritMultiple([Provider, UnTooled]) { model; /** * * @param {{model?: string}} config */ constructor(config = {}) { super(); const model = config?.model || process.env.LMSTUDIO_MODEL_PREF || "Loaded from Chat UI"; const client = new OpenAI({ baseURL: parseLMStudioBasePath(process.env.LMSTUDIO_BASE_PATH), apiKey: null, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { await LMStudioLLM.cacheContextWindows(); return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("LMStudio chat: No results!"); if (result.choices.length === 0) throw new Error("LMStudio chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { await LMStudioLLM.cacheContextWindows(); return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LMStudio has no cost basis. */ getCost(_usage) { return 0; } } module.exports = LMStudioProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/ai-provider.js
server/utils/agents/aibitat/providers/ai-provider.js
/** * A service that provides an AI client to create a completion. */ /** * @typedef {Object} LangChainModelConfig * @property {(string|null)} baseURL - Override the default base URL process.env for this provider * @property {(string|null)} apiKey - Override the default process.env for this provider * @property {(number|null)} temperature - Override the default temperature * @property {(string|null)} model - Overrides model used for provider. */ const { v4 } = require("uuid"); const { ChatOpenAI } = require("@langchain/openai"); const { ChatAnthropic } = require("@langchain/anthropic"); const { ChatCohere } = require("@langchain/cohere"); const { ChatOllama } = require("@langchain/community/chat_models/ollama"); const { toValidNumber, safeJsonParse } = require("../../../http"); const { getLLMProviderClass } = require("../../../helpers"); const { parseLMStudioBasePath } = require("../../../AiProviders/lmStudio"); const { parseFoundryBasePath } = require("../../../AiProviders/foundry"); const { SystemPromptVariables, } = require("../../../../models/systemPromptVariables"); const { createBedrockChatClient, } = require("../../../AiProviders/bedrock/utils"); const DEFAULT_WORKSPACE_PROMPT = "You are a helpful ai assistant who can assist the user and use tools available to help answer the users prompts and questions."; class Provider { _client; /** * The invocation object containing the user ID and other invocation details. * @type {import("@prisma/client").workspace_agent_invocations} */ invocation = {}; /** * The user ID for the chat completion to send to the LLM provider for user tracking. * In order for this to be set, the handler props must be attached to the provider after instantiation. * ex: this.attachHandlerProps({ ..., invocation: { ..., user_id: 123 } }); * eg: `user_123` * @type {string} */ executingUserId = ""; constructor(client) { if (this.constructor == Provider) { return; } this._client = client; } providerLog(text, ...args) { console.log( `\x1b[36m[AgentLLM${this?.model ? ` - ${this.model}` : ""}]\x1b[0m ${text}`, ...args ); } /** * Attaches handler props to the provider for reuse in the provider. * - Explicitly sets the invocation object. * - Explicitly sets the executing user ID from the invocation object. * @param {Object} handlerProps - The handler props to attach to the provider. */ attachHandlerProps(handlerProps = {}) { this.invocation = handlerProps?.invocation || {}; this.executingUserId = this.invocation?.user_id ? `user_${this.invocation.user_id}` : ""; } get client() { return this._client; } /** * * @param {string} provider - the string key of the provider LLM being loaded. * @param {LangChainModelConfig} config - Config to be used to override default connection object. * @returns */ static LangChainChatModel(provider = "openai", config = {}) { switch (provider) { // Cloud models case "openai": return new ChatOpenAI({ apiKey: process.env.OPEN_AI_KEY, ...config, }); case "anthropic": return new ChatAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, ...config, }); case "groq": return new ChatOpenAI({ configuration: { baseURL: "https://api.groq.com/openai/v1", }, apiKey: process.env.GROQ_API_KEY, ...config, }); case "mistral": return new ChatOpenAI({ configuration: { baseURL: "https://api.mistral.ai/v1", }, apiKey: process.env.MISTRAL_API_KEY ?? null, ...config, }); case "openrouter": return new ChatOpenAI({ configuration: { baseURL: "https://openrouter.ai/api/v1", defaultHeaders: { "HTTP-Referer": "https://anythingllm.com", "X-Title": "AnythingLLM", }, }, apiKey: process.env.OPENROUTER_API_KEY ?? null, ...config, }); case "perplexity": return new ChatOpenAI({ configuration: { baseURL: "https://api.perplexity.ai", }, apiKey: process.env.PERPLEXITY_API_KEY ?? null, ...config, }); case "togetherai": return new ChatOpenAI({ configuration: { baseURL: "https://api.together.xyz/v1", }, apiKey: process.env.TOGETHER_AI_API_KEY ?? null, ...config, }); case "generic-openai": return new ChatOpenAI({ configuration: { baseURL: process.env.GENERIC_OPEN_AI_BASE_PATH, }, apiKey: process.env.GENERIC_OPEN_AI_API_KEY, maxTokens: toValidNumber( process.env.GENERIC_OPEN_AI_MAX_TOKENS, 1024 ), ...config, }); case "bedrock": return createBedrockChatClient(config); case "fireworksai": return new ChatOpenAI({ apiKey: process.env.FIREWORKS_AI_LLM_API_KEY, ...config, }); case "apipie": return new ChatOpenAI({ configuration: { baseURL: "https://apipie.ai/v1", }, apiKey: process.env.APIPIE_LLM_API_KEY ?? null, ...config, }); case "deepseek": return new ChatOpenAI({ configuration: { baseURL: "https://api.deepseek.com/v1", }, apiKey: process.env.DEEPSEEK_API_KEY ?? null, ...config, }); case "xai": return new ChatOpenAI({ configuration: { baseURL: "https://api.x.ai/v1", }, apiKey: process.env.XAI_LLM_API_KEY ?? null, ...config, }); case "zai": return new ChatOpenAI({ configuration: { baseURL: "https://api.z.ai/api/paas/v4", }, apiKey: process.env.ZAI_API_KEY ?? null, ...config, }); case "novita": return new ChatOpenAI({ configuration: { baseURL: "https://api.novita.ai/v3/openai", }, apiKey: process.env.NOVITA_LLM_API_KEY ?? null, ...config, }); case "ppio": return new ChatOpenAI({ configuration: { baseURL: "https://api.ppinfra.com/v3/openai", }, apiKey: process.env.PPIO_API_KEY ?? null, ...config, }); case "gemini": return new ChatOpenAI({ configuration: { baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/", }, apiKey: process.env.GEMINI_API_KEY ?? null, ...config, }); case "moonshotai": return new ChatOpenAI({ configuration: { baseURL: "https://api.moonshot.ai/v1", }, apiKey: process.env.MOONSHOT_AI_API_KEY ?? null, ...config, }); case "cometapi": return new ChatOpenAI({ configuration: { baseURL: "https://api.cometapi.com/v1", }, apiKey: process.env.COMETAPI_LLM_API_KEY ?? null, ...config, }); case "giteeai": return new ChatOpenAI({ configuration: { baseURL: "https://ai.gitee.com/v1", }, apiKey: process.env.GITEE_AI_API_KEY ?? null, ...config, }); case "cohere": return new ChatCohere({ apiKey: process.env.COHERE_API_KEY ?? null, ...config, }); // OSS Model Runners // case "anythingllm_ollama": // return new ChatOllama({ // baseUrl: process.env.PLACEHOLDER, // ...config, // }); case "ollama": return new ChatOllama({ baseUrl: process.env.OLLAMA_BASE_PATH, ...config, }); case "lmstudio": return new ChatOpenAI({ configuration: { baseURL: parseLMStudioBasePath(process.env.LMSTUDIO_BASE_PATH), }, apiKey: "not-used", // Needs to be specified or else will assume OpenAI ...config, }); case "koboldcpp": return new ChatOpenAI({ configuration: { baseURL: process.env.KOBOLD_CPP_BASE_PATH, }, apiKey: "not-used", ...config, }); case "localai": return new ChatOpenAI({ configuration: { baseURL: process.env.LOCAL_AI_BASE_PATH, }, apiKey: process.env.LOCAL_AI_API_KEY ?? "not-used", ...config, }); case "textgenwebui": return new ChatOpenAI({ configuration: { baseURL: process.env.TEXT_GEN_WEB_UI_BASE_PATH, }, apiKey: process.env.TEXT_GEN_WEB_UI_API_KEY ?? "not-used", ...config, }); case "litellm": return new ChatOpenAI({ configuration: { baseURL: process.env.LITE_LLM_BASE_PATH, }, apiKey: process.env.LITE_LLM_API_KEY ?? null, ...config, }); case "nvidia-nim": return new ChatOpenAI({ configuration: { baseURL: process.env.NVIDIA_NIM_LLM_BASE_PATH, }, apiKey: null, ...config, }); case "foundry": { return new ChatOpenAI({ configuration: { baseURL: parseFoundryBasePath(process.env.FOUNDRY_BASE_PATH), }, apiKey: null, ...config, }); } default: throw new Error(`Unsupported provider ${provider} for this task.`); } } /** * Get the context limit for a provider/model combination using static method in AIProvider class. * @param {string} provider * @param {string} modelName * @returns {number} */ static contextLimit(provider = "openai", modelName) { const llm = getLLMProviderClass({ provider }); if (!llm || !llm.hasOwnProperty("promptWindowLimit")) return 8_000; return llm.promptWindowLimit(modelName); } static defaultSystemPromptForProvider(provider = null) { switch (provider) { case "lmstudio": return "You are a helpful ai assistant who can assist the user and use tools available to help answer the users prompts and questions. Tools will be handled by another assistant and you will simply receive their responses to help answer the user prompt - always try to answer the user's prompt the best you can with the context available to you and your general knowledge."; default: return DEFAULT_WORKSPACE_PROMPT; } } /** * Get the system prompt for a provider. * @param {string} provider * @param {import("@prisma/client").workspaces | null} workspace * @param {import("@prisma/client").users | null} user * @returns {Promise<string>} */ static async systemPrompt({ provider = null, workspace = null, user = null, }) { if (!workspace?.openAiPrompt) return Provider.defaultSystemPromptForProvider(provider); return await SystemPromptVariables.expandSystemPromptVariables( workspace.openAiPrompt, user?.id || null, workspace.id ); } /** * Whether the provider supports agent streaming. * Disabled by default and needs to be explicitly enabled in the provider * This is temporary while we migrate all providers to support agent streaming * @returns {boolean} */ get supportsAgentStreaming() { return false; } /** * Stream a chat completion from the LLM with tool calling * Note: This using the OpenAI API format and may need to be adapted for other providers. * * @param {any[]} messages - The messages to send to the LLM. * @param {any[]} functions - The functions to use in the LLM. * @param {function} eventHandler - The event handler to use to report stream events. * @returns {Promise<{ functionCall: any, textResponse: string }>} - The result of the chat completion. */ async stream(messages, functions = [], eventHandler = null) { this.providerLog("Provider.stream - will process this chat completion."); const msgUUID = v4(); const stream = await this.client.chat.completions.create({ model: this.model, stream: true, messages, ...(Array.isArray(functions) && functions?.length > 0 ? { functions } : {}), }); const result = { functionCall: null, textResponse: "", }; for await (const chunk of stream) { if (!chunk?.choices?.[0]) continue; // Skip if no choices const choice = chunk.choices[0]; if (choice.delta?.content) { result.textResponse += choice.delta.content; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: choice.delta.content, }); } if (choice.delta?.function_call) { // accumulate the function call if (result.functionCall) result.functionCall.arguments += choice.delta.function_call.arguments; else result.functionCall = choice.delta.function_call; eventHandler?.("reportStreamEvent", { uuid: `${msgUUID}:tool_call_invocation`, type: "toolCallInvocation", content: `Assembling Tool Call: ${result.functionCall.name}(${result.functionCall.arguments})`, }); } } // If there are arguments, parse them as json so that the tools can use them if (!!result.functionCall?.arguments) result.functionCall.arguments = safeJsonParse( result.functionCall.arguments, {} ); return { textResponse: result.textResponse, functionCall: result.functionCall, }; } } module.exports = Provider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/cohere.js
server/utils/agents/aibitat/providers/cohere.js
const { CohereClient } = require("cohere-ai"); const Provider = require("./ai-provider"); const InheritMultiple = require("./helpers/classes"); const UnTooled = require("./helpers/untooled"); const { v4 } = require("uuid"); const { safeJsonParse } = require("../../../http"); class CohereProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = process.env.COHERE_MODEL_PREF || "command-r-08-2024" } = config; super(); const client = new CohereClient({ token: process.env.COHERE_API_KEY, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } #convertChatHistoryCohere(chatHistory = []) { let cohereHistory = []; chatHistory.forEach((message) => { switch (message.role) { case "SYSTEM": case "system": cohereHistory.push({ role: "SYSTEM", message: message.content }); break; case "USER": case "user": cohereHistory.push({ role: "USER", message: message.content }); break; case "CHATBOT": case "assistant": cohereHistory.push({ role: "CHATBOT", message: message.content }); break; } }); return cohereHistory; } async #handleFunctionCallStream({ messages = [] }) { const userPrompt = messages[messages.length - 1]?.content || ""; const history = messages.slice(0, -1); return await this.client.chatStream({ model: this.model, chatHistory: this.#convertChatHistoryCohere(history), message: userPrompt, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async streamingFunctionCall( messages, functions, chatCb = null, eventHandler = null ) { const history = [...messages].filter((msg) => ["user", "assistant"].includes(msg.role) ); if (history[history.length - 1]?.role !== "user") return null; const msgUUID = v4(); let textResponse = ""; const historyMessages = this.buildToolCallMessages(history, functions); const stream = await chatCb({ messages: historyMessages }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Agent is thinking...", }); for await (const event of stream) { if (event.eventType !== "text-generation") continue; textResponse += event.text; eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: msgUUID, content: event.text, }); } const call = safeJsonParse(textResponse, null); if (call === null) return { toolCall: null, text: textResponse, uuid: msgUUID }; const { valid, reason } = this.validFuncCall(call, functions); if (!valid) { this.providerLog(`Invalid function tool call: ${reason}.`); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model attempted to make an invalid function call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } const { isDuplicate, reason: duplicateReason } = this.deduplicator.isDuplicate(call.name, call.arguments); if (isDuplicate) { this.providerLog( `Cannot call ${call.name} again because ${duplicateReason}.` ); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model tried to call a function with the same arguments as a previous call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } eventHandler?.("reportStreamEvent", { uuid: `${msgUUID}:tool_call_invocation`, type: "toolCallInvocation", content: `Parsed Tool Call: ${call.name}(${JSON.stringify(call.arguments)})`, }); return { toolCall: call, text: null, uuid: msgUUID }; } /** * Stream a chat completion from the LLM with tool calling * Override the inherited `stream` method since Cohere uses a different API format. * * @param {any[]} messages - The messages to send to the LLM. * @param {any[]} functions - The functions to use in the LLM. * @param {function} eventHandler - The event handler to use to report stream events. * @returns {Promise<{ functionCall: any, textResponse: string }>} - The result of the chat completion. */ async stream(messages, functions = [], eventHandler = null) { this.providerLog( "CohereProvider.stream - will process this chat completion." ); try { let completion = { content: "" }; if (functions.length > 0) { const { toolCall, text, uuid: msgUUID, } = await this.streamingFunctionCall( messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments, { cooldown: this.isMCPTool(toolCall, functions), }); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } if (text) { this.providerLog( `No tool call found in the response - will send as a full text response.` ); completion.content = text; eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "No tool call found in the response", }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); eventHandler?.("reportStreamEvent", { type: "fullTextResponse", uuid: v4(), content: text, }); } } if (!completion?.content) { eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); this.providerLog( "Will assume chat completion without tool call inputs." ); const msgUUID = v4(); completion = { content: "" }; const stream = await this.#handleFunctionCallStream({ messages: this.cleanMsgs(messages), }); for await (const chunk of stream) { if (chunk.eventType !== "text-generation") continue; completion.content += chunk.text; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: chunk.text, }); } } this.deduplicator.reset("runs"); return { textResponse: completion.content, cost: 0, }; } catch (error) { throw error; } } getCost(_usage) { return 0; } } module.exports = CohereProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/openrouter.js
server/utils/agents/aibitat/providers/openrouter.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the OpenRouter provider. * @extends {Provider} * @extends {UnTooled} */ class OpenRouterProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "openrouter/auto" } = config; super(); const client = new OpenAI({ baseURL: "https://openrouter.ai/api/v1", apiKey: process.env.OPENROUTER_API_KEY, maxRetries: 3, defaultHeaders: { "HTTP-Referer": "https://anythingllm.com", "X-Title": "AnythingLLM", }, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, user: this.executingUserId, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("OpenRouter chat: No results!"); if (result.choices.length === 0) throw new Error("OpenRouter chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, user: this.executingUserId, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since OpenRouter has no cost basis. */ getCost(_usage) { return 0; } } module.exports = OpenRouterProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/apipie.js
server/utils/agents/aibitat/providers/apipie.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the OpenRouter provider. */ class ApiPieProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "openrouter/llama-3.1-8b-instruct" } = config; super(); const client = new OpenAI({ baseURL: "https://apipie.ai/v1", apiKey: process.env.APIPIE_LLM_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("ApiPie chat: No results!"); if (result.choices.length === 0) throw new Error("ApiPie chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = ApiPieProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/anthropic.js
server/utils/agents/aibitat/providers/anthropic.js
const Anthropic = require("@anthropic-ai/sdk"); const { RetryError } = require("../error.js"); const Provider = require("./ai-provider.js"); const { v4 } = require("uuid"); const { safeJsonParse } = require("../../../http"); /** * The agent provider for the Anthropic API. * By default, the model is set to 'claude-2'. */ class AnthropicProvider extends Provider { model; constructor(config = {}) { const { options = { apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 3, }, model = "claude-3-5-sonnet-20240620", } = config; const client = new Anthropic(options); super(client); this.model = model; } /** * Parses the cache control ENV variable * * If caching is enabled, we can pass less than 1024 tokens and Anthropic will just * ignore it unless it is above the model's minimum. Since this feature is opt-in * we can safely assume that if caching is enabled that we should just pass the content as is. * https://docs.claude.com/en/docs/build-with-claude/prompt-caching#cache-limitations * * @param {string} value - The ENV value (5m or 1h) * @returns {null|{type: "ephemeral", ttl: "5m" | "1h"}} Cache control configuration */ get cacheControl() { // Store result in instance variable to avoid recalculating if (this._cacheControl) return this._cacheControl; if (!process.env.ANTHROPIC_CACHE_CONTROL) this._cacheControl = null; else { const normalized = process.env.ANTHROPIC_CACHE_CONTROL.toLowerCase().trim(); if (["5m", "1h"].includes(normalized)) this._cacheControl = { type: "ephemeral", ttl: normalized }; else this._cacheControl = null; } return this._cacheControl; } get supportsAgentStreaming() { return true; } /** * Builds system parameter with cache control if applicable * @param {string} systemContent - The system prompt content * @returns {string|array} System parameter for API call */ #buildSystemPrompt(systemContent) { if (!systemContent || !this.cacheControl) return systemContent; return [ { type: "text", text: systemContent, cache_control: this.cacheControl, }, ]; } #prepareMessages(messages = []) { // Extract system prompt and filter out any system messages from the main chat. let systemPrompt = "You are a helpful ai assistant who can assist the user and use tools available to help answer the users prompts and questions."; const chatMessages = messages.filter((msg) => { if (msg.role === "system") { systemPrompt = msg.content; return false; } return true; }); const processedMessages = chatMessages.reduce( (processedMessages, message, index) => { // Normalize `function` role to Anthropic's `tool_result` format. if (message.role === "function") { const prevMessage = chatMessages[index - 1]; if (prevMessage?.role === "assistant") { const toolUse = prevMessage.content.find( (item) => item.type === "tool_use" ); if (toolUse) { processedMessages.push({ role: "user", content: [ { type: "tool_result", tool_use_id: toolUse.id, content: message.content ? String(message.content) : "Tool executed successfully.", }, ], }); } } return processedMessages; } // Ensure message content is in array format and filter out empty text blocks. let content = Array.isArray(message.content) ? message.content : [{ type: "text", text: message.content }]; content = content.filter( (item) => item.type !== "text" || (item.text && item.text.trim().length > 0) ); if (content.length === 0) return processedMessages; // Add a text block to assistant messages with tool use if one doesn't exist. if ( message.role === "assistant" && content.some((item) => item.type === "tool_use") && !content.some((item) => item.type === "text") ) { content.unshift({ type: "text", text: "I'll use a tool to help answer this question.", }); } const lastMessage = processedMessages[processedMessages.length - 1]; if (lastMessage && lastMessage.role === message.role) { // Merge consecutive messages from the same role. lastMessage.content.push(...content); } else { processedMessages.push({ ...message, content }); } return processedMessages; }, [] ); // The first message must be from the user. if (processedMessages.length > 0 && processedMessages[0].role !== "user") { processedMessages.shift(); } return [systemPrompt, processedMessages]; } // Anthropic does not use the regular schema for functions so here we need to ensure it is in there specific format // so that the call can run correctly. #formatFunctions(functions = []) { return functions.map((func) => { const { name, description, parameters, required } = func; const { type, properties } = parameters; return { name, description, input_schema: { type, properties, required, }, }; }); } /** * Stream a chat completion from the LLM with tool calling * Note: This using the Anthropic API SDK and its implementation is specific to Anthropic. * * @param {any[]} messages - The messages to send to the LLM. * @param {any[]} functions - The functions to use in the LLM. * @param {function} eventHandler - The event handler to use to report stream events. * @returns {Promise<{ functionCall: any, textResponse: string }>} - The result of the chat completion. */ async stream(messages, functions = [], eventHandler = null) { try { const msgUUID = v4(); const [systemPrompt, chats] = this.#prepareMessages(messages); const response = await this.client.messages.create( { model: this.model, max_tokens: 4096, system: this.#buildSystemPrompt(systemPrompt), messages: chats, stream: true, ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions) } : {}), }, { headers: { "anthropic-beta": "tools-2024-04-04" } } // Required to we can use tools. ); const result = { functionCall: null, textResponse: "", }; for await (const chunk of response) { if (chunk.type === "content_block_start") { if (chunk.content_block.type === "text") { result.textResponse += chunk.content_block.text; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: chunk.content_block.text, }); } if (chunk.content_block.type === "tool_use") { result.functionCall = { id: chunk.content_block.id, name: chunk.content_block.name, // The initial arguments are empty {} (object) so we need to set it to an empty string. // It is unclear if this is ALWAYS empty on the tool_use block or if it can possible be populated. // This is a workaround to ensure the tool call is valid. arguments: "", }; eventHandler?.("reportStreamEvent", { type: "toolCallInvocation", uuid: `${msgUUID}:tool_call_invocation`, content: `Assembling Tool Call: ${result.functionCall.name}(${result.functionCall.arguments})`, }); } } if (chunk.type === "content_block_delta") { if (chunk.delta.type === "text_delta") { result.textResponse += chunk.delta.text; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: chunk.delta.text, }); } if (chunk.delta.type === "input_json_delta") { result.functionCall.arguments += chunk.delta.partial_json; eventHandler?.("reportStreamEvent", { type: "toolCallInvocation", uuid: `${msgUUID}:tool_call_invocation`, content: `Assembling Tool Call: ${result.functionCall.name}(${result.functionCall.arguments})`, }); } } } if (result.functionCall) { result.functionCall.arguments = safeJsonParse( result.functionCall.arguments, {} ); messages.push({ role: "assistant", content: [ { type: "text", text: result.textResponse }, { type: "tool_use", id: result.functionCall.id, name: result.functionCall.name, input: result.functionCall.arguments, }, ], }); return { textResponse: result.textResponse, functionCall: { name: result.functionCall.name, arguments: result.functionCall.arguments, }, cost: 0, }; } return { textResponse: result.textResponse, functionCall: null, cost: 0, }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof Anthropic.AuthenticationError) throw error; if ( error instanceof Anthropic.RateLimitError || error instanceof Anthropic.InternalServerError || error instanceof Anthropic.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the Anthropic API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { try { const [systemPrompt, chats] = this.#prepareMessages(messages); const response = await this.client.messages.create( { model: this.model, max_tokens: 4096, system: this.#buildSystemPrompt(systemPrompt), messages: chats, stream: false, ...(Array.isArray(functions) && functions?.length > 0 ? { tools: this.#formatFunctions(functions) } : {}), }, { headers: { "anthropic-beta": "tools-2024-04-04" } } // Required to we can use tools. ); // We know that we need to call a tool. So we are about to recurse through completions/handleExecution // https://docs.anthropic.com/claude/docs/tool-use#how-tool-use-works if (response.stop_reason === "tool_use") { // Get the tool call explicitly. const toolCall = response.content.find( (res) => res.type === "tool_use" ); // Here we need the chain of thought the model may or may not have generated alongside the call. // this needs to be in a very specific format so we always ensure there is a 2-item content array // so that we can ensure the tool_call content is correct. For anthropic all text items must not // be empty, but the api will still return empty text so we need to make 100% sure text is not empty // or the tool call will fail. // wtf. let thought = response.content.find((res) => res.type === "text"); thought = thought?.content?.length > 0 ? { role: thought.role, content: [ { type: "text", text: thought.content }, { ...toolCall }, ], } : { role: "assistant", content: [ { type: "text", text: `Okay, im going to use ${toolCall.name} to help me.`, }, { ...toolCall }, ], }; // Modify messages forcefully by adding system thought so that tool_use/tool_result // messaging works with Anthropic's disastrous tool calling API. messages.push(thought); const functionArgs = toolCall.input; return { result: null, functionCall: { name: toolCall.name, arguments: functionArgs, }, cost: 0, }; } const completion = response.content.find((msg) => msg.type === "text"); return { textResponse: completion?.text ?? "The model failed to complete the task and return back a valid response.", cost: 0, }; } catch (error) { // If invalid Auth error we need to abort because no amount of waiting // will make auth better. if (error instanceof Anthropic.AuthenticationError) throw error; if ( error instanceof Anthropic.RateLimitError || error instanceof Anthropic.InternalServerError || error instanceof Anthropic.APIError // Also will catch AuthenticationError!!! ) { throw new RetryError(error.message); } throw error; } } } module.exports = AnthropicProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/giteeai.js
server/utils/agents/aibitat/providers/giteeai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); class GiteeAIProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = "DeepSeek-R1" } = config; this._client = new OpenAI({ baseURL: "https://ai.gitee.com/v1", apiKey: process.env.GITEE_AI_API_KEY ?? null, maxRetries: 3, }); this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("GiteeAI chat: No results!"); if (result.choices.length === 0) throw new Error("GiteeAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = GiteeAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/moonshotAi.js
server/utils/agents/aibitat/providers/moonshotAi.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); class MoonshotAiProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "moonshot-v1-32k" } = config; super(); const client = new OpenAI({ baseURL: "https://api.moonshot.ai/v1", apiKey: process.env.MOONSHOT_AI_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the API. * @param functions * @returns The completion. */ get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Moonshot chat: No results!"); if (result.choices.length === 0) throw new Error("Moonshot chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } getCost(_usage) { return 0; } } module.exports = MoonshotAiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/bedrock.js
server/utils/agents/aibitat/providers/bedrock.js
const { createBedrockCredentials, getBedrockAuthMethod, createBedrockChatClient, } = require("../../../AiProviders/bedrock/utils.js"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); const { HumanMessage, SystemMessage, AIMessage, } = require("@langchain/core/messages"); /** * The agent provider for the AWS Bedrock provider. */ class AWSBedrockProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(_config = {}) { super(); const model = process.env.AWS_BEDROCK_LLM_MODEL_PREFERENCE ?? null; const client = createBedrockChatClient( {}, this.authMethod, this.credentials, model ); this._client = client; this.model = model; this.verbose = true; } /** * Gets the credentials for the AWS Bedrock LLM based on the authentication method provided. * @returns {object} The credentials object. */ get credentials() { return createBedrockCredentials(this.authMethod); } /** * Gets the configured AWS authentication method ('iam' or 'sessionToken'). * Defaults to 'iam' if the environment variable is invalid. * @returns {"iam" | "iam_role" | "sessionToken"} The authentication method. */ get authMethod() { return getBedrockAuthMethod(); } get client() { return this._client; } // For streaming we use Langchain's wrapper to handle weird chunks // or otherwise absorb headaches that can arise from Ollama models #convertToLangchainPrototypes(chats = []) { const langchainChats = []; const roleToMessageMap = { system: SystemMessage, user: HumanMessage, assistant: AIMessage, }; for (const chat of chats) { if (!roleToMessageMap.hasOwnProperty(chat.role)) continue; const MessageClass = roleToMessageMap[chat.role]; langchainChats.push(new MessageClass({ content: chat.content })); } return langchainChats; } async #handleFunctionCallChat({ messages = [] }) { const response = await this.client .invoke(this.#convertToLangchainPrototypes(messages)) .then((res) => res) .catch((e) => { console.error(e); return null; }); return response?.content; } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the API. * @param functions * @returns The completion. */ async complete(messages, functions = []) { try { let completion; if (functions.length > 0) { const { toolCall, text } = await this.functionCall( messages, functions, this.#handleFunctionCallChat.bind(this) ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } completion = { content: text }; } if (!completion?.content) { this.providerLog( "Will assume chat completion without tool call inputs." ); const response = await this.client.invoke( this.#convertToLangchainPrototypes(this.cleanMsgs(messages)) ); completion = response; } // The UnTooled class inherited Deduplicator is mostly useful to prevent the agent // from calling the exact same function over and over in a loop within a single chat exchange // _but_ we should enable it to call previously used tools in a new chat interaction. this.deduplicator.reset("runs"); return { result: completion.content, cost: 0, }; } catch (error) { throw error; } } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since KoboldCPP has no cost basis. */ getCost(_usage) { return 0; } } module.exports = AWSBedrockProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/textgenwebui.js
server/utils/agents/aibitat/providers/textgenwebui.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the Oobabooga provider. */ class TextWebGenUiProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(_config = {}) { super(); const client = new OpenAI({ baseURL: process.env.TEXT_GEN_WEB_UI_BASE_PATH, apiKey: process.env.TEXT_GEN_WEB_UI_API_KEY ?? null, maxRetries: 3, }); this._client = client; this.model = "text-generation-webui"; // text-web-gen-ui does not have a model pref, but we need a placeholder this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Oobabooga chat: No results!"); if (result.choices.length === 0) throw new Error("Oobabooga chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since KoboldCPP has no cost basis. */ getCost(_usage) { return 0; } } module.exports = TextWebGenUiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/novita.js
server/utils/agents/aibitat/providers/novita.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the Novita AI provider. */ class NovitaProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "deepseek/deepseek-r1" } = config; super(); const client = new OpenAI({ baseURL: "https://api.novita.ai/v3/openai", apiKey: process.env.NOVITA_LLM_API_KEY, maxRetries: 3, defaultHeaders: { "HTTP-Referer": "https://anythingllm.com", "X-Novita-Source": "anythingllm", }, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("Novita chat: No results!"); if (result.choices.length === 0) throw new Error("Novita chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since Novita AI has no cost basis. */ getCost() { return 0; } } module.exports = NovitaProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/mistral.js
server/utils/agents/aibitat/providers/mistral.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the Mistral provider. * Mistral limits what models can call tools and even when using those * the model names change and dont match docs. When you do have the right model * it still fails and is not truly OpenAI compatible so its easier to just wrap * this with Untooled which 100% works since its just text & works far more reliably */ class MistralProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { super(); const { model = "mistral-medium" } = config; const client = new OpenAI({ baseURL: "https://api.mistral.ai/v1", apiKey: process.env.MISTRAL_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("LMStudio chat: No results!"); if (result.choices.length === 0) throw new Error("LMStudio chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = MistralProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/localai.js
server/utils/agents/aibitat/providers/localai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the LocalAI provider. */ class LocalAiProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = null } = config; super(); const client = new OpenAI({ baseURL: process.env.LOCAL_AI_BASE_PATH, apiKey: process.env.LOCAL_AI_API_KEY ?? null, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("LocalAI chat: No results!"); if (result.choices.length === 0) throw new Error("LocalAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LocalAI has no cost basis. */ getCost(_usage) { return 0; } } module.exports = LocalAiProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/groq.js
server/utils/agents/aibitat/providers/groq.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the GroqAI provider. * We wrap Groq in UnTooled because its tool-calling built in is quite bad and wasteful. */ class GroqProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "llama3-8b-8192" } = config; super(); const client = new OpenAI({ baseURL: "https://api.groq.com/openai/v1", apiKey: process.env.GROQ_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("GroqAI chat: No results!"); if (result.choices.length === 0) throw new Error("GroqAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. * Stubbed since LMStudio has no cost basis. */ getCost(_usage) { return 0; } } module.exports = GroqProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/xai.js
server/utils/agents/aibitat/providers/xai.js
const OpenAI = require("openai"); const Provider = require("./ai-provider.js"); const InheritMultiple = require("./helpers/classes.js"); const UnTooled = require("./helpers/untooled.js"); /** * The agent provider for the xAI provider. */ class XAIProvider extends InheritMultiple([Provider, UnTooled]) { model; constructor(config = {}) { const { model = "grok-beta" } = config; super(); const client = new OpenAI({ baseURL: "https://api.x.ai/v1", apiKey: process.env.XAI_LLM_API_KEY, maxRetries: 3, }); this._client = client; this.model = model; this.verbose = true; } get client() { return this._client; } get supportsAgentStreaming() { return true; } async #handleFunctionCallChat({ messages = [] }) { return await this.client.chat.completions .create({ model: this.model, messages, }) .then((result) => { if (!result.hasOwnProperty("choices")) throw new Error("xAI chat: No results!"); if (result.choices.length === 0) throw new Error("xAI chat: No results length!"); return result.choices[0].message.content; }) .catch((_) => { return null; }); } async #handleFunctionCallStream({ messages = [] }) { return await this.client.chat.completions.create({ model: this.model, stream: true, messages, }); } async stream(messages, functions = [], eventHandler = null) { return await UnTooled.prototype.stream.call( this, messages, functions, this.#handleFunctionCallStream.bind(this), eventHandler ); } async complete(messages, functions = []) { return await UnTooled.prototype.complete.call( this, messages, functions, this.#handleFunctionCallChat.bind(this) ); } /** * Get the cost of the completion. * * @param _usage The completion to get the cost for. * @returns The cost of the completion. */ getCost(_usage) { return 0; } } module.exports = XAIProvider;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/helpers/classes.js
server/utils/agents/aibitat/providers/helpers/classes.js
function InheritMultiple(bases = []) { class Bases { constructor() { bases.forEach((base) => Object.assign(this, new base())); } } bases.forEach((base) => { Object.getOwnPropertyNames(base.prototype) .filter((prop) => prop != "constructor") .forEach((prop) => (Bases.prototype[prop] = base.prototype[prop])); }); return Bases; } module.exports = InheritMultiple;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/providers/helpers/untooled.js
server/utils/agents/aibitat/providers/helpers/untooled.js
const { safeJsonParse } = require("../../../../http"); const { Deduplicator } = require("../../utils/dedupe"); const { v4 } = require("uuid"); // Useful inheritance class for a model which supports OpenAi schema for API requests // but does not have tool-calling or JSON output support. class UnTooled { constructor() { this.deduplicator = new Deduplicator(); } cleanMsgs(messages) { const modifiedMessages = []; messages.forEach((msg) => { if (msg.role === "function") { const prevMsg = modifiedMessages[modifiedMessages.length - 1].content; modifiedMessages[modifiedMessages.length - 1].content = `${prevMsg}\n${msg.content}`; return; } modifiedMessages.push(msg); }); return modifiedMessages; } showcaseFunctions(functions = []) { let output = ""; functions.forEach((def) => { let shotExample = `----------- Function name: ${def.name} Function Description: ${def.description} Function parameters in JSON format: ${JSON.stringify(def.parameters.properties, null, 4)}\n`; if (Array.isArray(def.examples)) { def.examples.forEach(({ prompt, call }) => { shotExample += `Query: "${prompt}"\nJSON: ${JSON.stringify({ name: def.name, arguments: safeJsonParse(call, {}), })}\n`; }); } output += `${shotExample}-----------\n`; }); return output; } /** * Check if a function call is an MCP tool. * We do this because some MCP tools dont return values and will cause infinite loops in calling for Untooled to call the same function over and over again. * Any MCP tool is automatically marked with a cooldown to prevent infinite loops of the same function over and over again. * * This can lead to unexpected behavior if you want a model using Untooled to call a repeat action multiple times. * eg: Create 3 Jira tickets about x, y, and z. -> will skip y and z if you don't disable the cooldown. * * You can disable this check by setting the `MCP_NO_COOLDOWN` flag to any value in the ENV. * * @param {{name: string, arguments: Object}} functionCall - The function call to check. * @param {Object[]} functions - The list of functions definitions to check against. * @return {boolean} - True if the function call is an MCP tool, false otherwise. */ isMCPTool(functionCall = {}, functions = []) { if (process.env.MCP_NO_COOLDOWN) return false; const foundFunc = functions.find( (def) => def?.name?.toLowerCase() === functionCall.name?.toLowerCase() ); if (!foundFunc) return false; return foundFunc?.isMCPTool || false; } /** * Validate a function call against a list of functions. * @param {{name: string, arguments: Object}} functionCall - The function call to validate. * @param {Object[]} functions - The list of functions definitions to validate against. * @return {{valid: boolean, reason: string|null}} - The validation result. */ validFuncCall(functionCall = {}, functions = []) { if ( !functionCall || !functionCall?.hasOwnProperty("name") || !functionCall?.hasOwnProperty("arguments") ) { return { valid: false, reason: "Missing name or arguments in function call.", }; } const foundFunc = functions.find((def) => def.name === functionCall.name); if (!foundFunc) return { valid: false, reason: "Function name does not exist." }; const schemaProps = Object.keys(foundFunc?.parameters?.properties || {}); const requiredProps = foundFunc?.parameters?.required || []; const providedProps = Object.keys(functionCall.arguments); for (const requiredProp of requiredProps) { if (!providedProps.includes(requiredProp)) { return { valid: false, reason: `Missing required argument: ${requiredProp}`, }; } } // Ensure all provided arguments are valid for the schema // This is to prevent the model from hallucinating or providing invalid additional arguments. for (const providedProp of providedProps) { if (!schemaProps.includes(providedProp)) { return { valid: false, reason: `Unknown argument: ${providedProp} provided but not in schema.`, }; } } return { valid: true, reason: null }; } buildToolCallMessages(history = [], functions = []) { return [ { content: `You are a program which picks the most optimal function and parameters to call. DO NOT HAVE TO PICK A FUNCTION IF IT WILL NOT HELP ANSWER OR FULFILL THE USER'S QUERY. When a function is selection, respond in JSON with no additional text. When there is no relevant function to call - return with a regular chat text response. Your task is to pick a **single** function that we will use to call, if any seem useful or relevant for the user query. All JSON responses should have two keys. 'name': this is the name of the function name to call. eg: 'web-scraper', 'rag-memory', etc.. 'arguments': this is an object with the function properties to invoke the function. DO NOT INCLUDE ANY OTHER KEYS IN JSON RESPONSES. Here are the available tools you can use an examples of a query and response so you can understand how each one works. ${this.showcaseFunctions(functions)} Now pick a function if there is an appropriate one to use given the last user message and the given conversation so far.`, role: "system", }, ...history, ]; } async functionCall(messages, functions, chatCb = null) { const history = [...messages].filter((msg) => ["user", "assistant"].includes(msg.role) ); if (history[history.length - 1].role !== "user") return null; const historyMessages = this.buildToolCallMessages(history, functions); const response = await chatCb({ messages: historyMessages }); const call = safeJsonParse(response, null); if (call === null) return { toolCall: null, text: response }; // failed to parse, so must be text. const { valid, reason } = this.validFuncCall(call, functions); if (!valid) { this.providerLog(`Invalid function tool call: ${reason}.`); return { toolCall: null, text: null }; } const { isDuplicate, reason: duplicateReason } = this.deduplicator.isDuplicate(call.name, call.arguments); if (isDuplicate) { this.providerLog( `Cannot call ${call.name} again because ${duplicateReason}.` ); return { toolCall: null, text: null }; } return { toolCall: call, text: null }; } async streamingFunctionCall( messages, functions, chatCb = null, eventHandler = null ) { const history = [...messages].filter((msg) => ["user", "assistant"].includes(msg.role) ); if (history[history.length - 1].role !== "user") return null; const msgUUID = v4(); let textResponse = ""; const historyMessages = this.buildToolCallMessages(history, functions); const stream = await chatCb({ messages: historyMessages }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Agent is thinking...", }); for await (const chunk of stream) { if (!chunk?.choices?.[0]) continue; // Skip if no choices const choice = chunk.choices[0]; if (choice.delta?.content) { textResponse += choice.delta.content; eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: msgUUID, content: choice.delta.content, }); } } const call = safeJsonParse(textResponse, null); if (call === null) return { toolCall: null, text: textResponse, uuid: msgUUID }; // failed to parse, so must be regular text response. const { valid, reason } = this.validFuncCall(call, functions); if (!valid) { this.providerLog(`Invalid function tool call: ${reason}.`); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model attempted to make an invalid function call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } const { isDuplicate, reason: duplicateReason } = this.deduplicator.isDuplicate(call.name, call.arguments); if (isDuplicate) { this.providerLog( `Cannot call ${call.name} again because ${duplicateReason}.` ); eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "The model tried to call a function with the same arguments as a previous call - it was ignored.", }); return { toolCall: null, text: null, uuid: msgUUID }; } eventHandler?.("reportStreamEvent", { uuid: `${msgUUID}:tool_call_invocation`, type: "toolCallInvocation", content: `Parsed Tool Call: ${call.name}(${JSON.stringify(call.arguments)})`, }); return { toolCall: call, text: null, uuid: msgUUID }; } /** * Stream a chat completion from the LLM with tool calling * Note: This using the OpenAI API format and may need to be adapted for other providers. * * @param {any[]} messages - The messages to send to the LLM. * @param {any[]} functions - The functions to use in the LLM. * @param {function} chatCallback - A callback function to handle the chat completion. * @param {function} eventHandler - The event handler to use to report stream events. * @returns {Promise<{ functionCall: any, textResponse: string }>} - The result of the chat completion. */ async stream( messages, functions = [], chatCallback = null, eventHandler = null ) { this.providerLog("Untooled.stream - will process this chat completion."); try { let completion = { content: "" }; if (functions.length > 0) { const { toolCall, text, uuid: msgUUID, } = await this.streamingFunctionCall( messages, functions, chatCallback, eventHandler ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments, { cooldown: this.isMCPTool(toolCall, functions), }); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } if (text) { this.providerLog( `No tool call found in the response - will send as a full text response.` ); completion.content = text; eventHandler?.("reportStreamEvent", { type: "removeStatusResponse", uuid: msgUUID, content: "No tool call found in the response", }); eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); eventHandler?.("reportStreamEvent", { type: "fullTextResponse", uuid: v4(), content: text, }); } } if (!completion?.content) { eventHandler?.("reportStreamEvent", { type: "statusResponse", uuid: v4(), content: "Done thinking.", }); this.providerLog( "Will assume chat completion without tool call inputs." ); const msgUUID = v4(); completion = { content: "" }; const stream = await chatCallback({ messages: this.cleanMsgs(messages), }); for await (const chunk of stream) { if (!chunk?.choices?.[0]) continue; // Skip if no choices const choice = chunk.choices[0]; if (choice.delta?.content) { completion.content += choice.delta.content; eventHandler?.("reportStreamEvent", { type: "textResponseChunk", uuid: msgUUID, content: choice.delta.content, }); } } } // The UnTooled class inherited Deduplicator is mostly useful to prevent the agent // from calling the exact same function over and over in a loop within a single chat exchange // _but_ we should enable it to call previously used tools in a new chat interaction. this.deduplicator.reset("runs"); return { textResponse: completion.content, cost: 0, }; } catch (error) { throw error; } } /** * Create a completion based on the received messages. * * @param messages A list of messages to send to the API. * @param functions * @param chatCallback - A callback function to handle the chat completion. * @returns The completion. */ async complete(messages, functions = [], chatCallback = null) { this.providerLog("Untooled.complete - will process this chat completion."); try { let completion = { content: "" }; if (functions.length > 0) { const { toolCall, text } = await this.functionCall( messages, functions, chatCallback ); if (toolCall !== null) { this.providerLog(`Valid tool call found - running ${toolCall.name}.`); this.deduplicator.trackRun(toolCall.name, toolCall.arguments, { cooldown: this.isMCPTool(toolCall, functions), }); return { result: null, functionCall: { name: toolCall.name, arguments: toolCall.arguments, }, cost: 0, }; } completion.content = text; } // If there are no functions, we want to run a normal chat completion. if (!completion?.content) { this.providerLog( "Will assume chat completion without tool call inputs." ); const response = await chatCallback({ messages: this.cleanMsgs(messages), }); // If the response from the callback is the raw OpenAI Spec response object, we can use that directly. // Otherwise, we will assume the response is just the string output we wanted (see: `#handleFunctionCallChat` which returns the content only) // This handles both streaming and non-streaming completions. completion = typeof response === "string" ? { content: response } : response.choices?.[0]?.message; } // The UnTooled class inherited Deduplicator is mostly useful to prevent the agent // from calling the exact same function over and over in a loop within a single chat exchange // _but_ we should enable it to call previously used tools in a new chat interaction. this.deduplicator.reset("runs"); return { textResponse: completion.content, cost: 0, }; } catch (error) { throw error; } } } module.exports = UnTooled;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/example/blog-post-coding.js
server/utils/agents/aibitat/example/blog-post-coding.js
const AIbitat = require("../index.js"); const { cli, webBrowsing, fileHistory, webScraping, } = require("../plugins/index.js"); require("dotenv").config({ path: `../../../../.env.development` }); const aibitat = new AIbitat({ model: "gpt-4o", }) .use(cli.plugin()) .use(fileHistory.plugin()) .use(webBrowsing.plugin()) // Does not have introspect so will fail. .use(webScraping.plugin()) .agent("researcher", { role: `You are a Researcher. Conduct thorough research to gather all necessary information about the topic you are writing about. Collect data, facts, and statistics. Analyze competitor blogs for insights. Provide accurate and up-to-date information that supports the blog post's content to @copywriter.`, functions: ["web-browsing"], }) .agent("copywriter", { role: `You are a Copywriter. Interpret the draft as general idea and write the full blog post using markdown, ensuring it is tailored to the target audience's preferences, interests, and demographics. Apply genre-specific writing techniques relevant to the author's genre. Add code examples when needed. Code must be written in Typescript. Always mention references. Revisit and edit the post for clarity, coherence, and correctness based on the feedback provided. Ask for feedbacks to the channel when you are done`, }) .agent("pm", { role: `You are a Project Manager. Coordinate the project, ensure tasks are completed on time and within budget. Communicate with team members and stakeholders.`, interrupt: "ALWAYS", }) .channel("content-team", ["researcher", "copywriter", "pm"]); async function main() { if (!process.env.OPEN_AI_KEY) throw new Error( "This example requires a valid OPEN_AI_KEY in the env.development file" ); await aibitat.start({ from: "pm", to: "content-team", content: `We have got this draft of the new blog post, let us start working on it. --- BEGIN DRAFT OF POST --- Maui is a beautiful island in the state of Hawaii and is world-renowned for its whale watching season. Here are 2 additional things to do in Maui, HI: --- END DRAFT OF POST --- `, }); } main();
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/example/beginner-chat.js
server/utils/agents/aibitat/example/beginner-chat.js
// You must execute this example from within the example folder. const AIbitat = require("../index.js"); const { cli } = require("../plugins/cli.js"); const { NodeHtmlMarkdown } = require("node-html-markdown"); require("dotenv").config({ path: `../../../../.env.development` }); const Agent = { HUMAN: "🧑", AI: "🤖", }; const aibitat = new AIbitat({ provider: "openai", model: "gpt-4o", }) .use(cli.plugin()) .function({ name: "aibitat-documentations", description: "The documentation about aibitat AI project.", parameters: { type: "object", properties: {}, }, handler: async () => { return await fetch( "https://raw.githubusercontent.com/wladiston/aibitat/main/README.md" ) .then((res) => res.text()) .then((html) => NodeHtmlMarkdown.translate(html)) .catch((e) => { console.error(e.message); return "FAILED TO FETCH"; }); }, }) .agent(Agent.HUMAN, { interrupt: "ALWAYS", role: "You are a human assistant.", }) .agent(Agent.AI, { functions: ["aibitat-documentations"], }); async function main() { if (!process.env.OPEN_AI_KEY) throw new Error( "This example requires a valid OPEN_AI_KEY in the env.development file" ); await aibitat.start({ from: Agent.HUMAN, to: Agent.AI, content: `Please, talk about the documentation of AIbitat.`, }); } main();
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/example/websocket/websock-multi-turn-chat.js
server/utils/agents/aibitat/example/websocket/websock-multi-turn-chat.js
// You can only run this example from within the websocket/ directory. // NODE_ENV=development node websock-multi-turn-chat.js // Scraping is enabled, but search requires AGENT_GSE_* keys. const express = require("express"); const chalk = require("chalk"); const AIbitat = require("../../index.js"); const { websocket, webBrowsing, webScraping, } = require("../../plugins/index.js"); const path = require("path"); const port = 3000; const app = express(); require("@mintplex-labs/express-ws").default(app); // load WebSockets in non-SSL mode. require("dotenv").config({ path: `../../../../../.env.development` }); // Debugging echo function if this is working for you. // app.ws('/echo', function (ws, req) { // ws.on('message', function (msg) { // ws.send(msg); // }); // }); // Set up WSS sockets for listening. app.ws("/ws", function (ws, _response) { try { ws.on("message", function (msg) { if (ws?.handleFeedback) ws.handleFeedback(msg); }); ws.on("close", function () { console.log("Socket killed"); return; }); console.log("Socket online and waiting..."); runAIbitat(ws).catch((error) => { ws.send( JSON.stringify({ from: Agent.AI, to: Agent.HUMAN, content: error.message, }) ); }); } catch (error) {} }); app.all("*", function (_, response) { response.sendFile(path.join(__dirname, "index.html")); }); app.listen(port, () => { console.log(`Testing HTTP/WSS server listening at http://localhost:${port}`); }); const Agent = { HUMAN: "🧑", AI: "🤖", }; async function runAIbitat(socket) { if (!process.env.OPEN_AI_KEY) throw new Error( "This example requires a valid OPEN_AI_KEY in the env.development file" ); console.log(chalk.blue("Booting AIbitat class & starting agent(s)")); const aibitat = new AIbitat({ provider: "openai", model: "gpt-4o", }) .use(websocket.plugin({ socket })) .use(webBrowsing.plugin()) .use(webScraping.plugin()) .agent(Agent.HUMAN, { interrupt: "ALWAYS", role: "You are a human assistant.", }) .agent(Agent.AI, { role: "You are a helpful ai assistant who likes to chat with the user who an also browse the web for questions it does not know or have real-time access to.", functions: ["web-browsing"], }); await aibitat.start({ from: Agent.HUMAN, to: Agent.AI, content: `How are you doing today?`, }); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agents/aibitat/example/websocket/websock-branding-collab.js
server/utils/agents/aibitat/example/websocket/websock-branding-collab.js
// You can only run this example from within the websocket/ directory. // NODE_ENV=development node websock-branding-collab.js // Scraping is enabled, but search requires AGENT_GSE_* keys. const express = require("express"); const chalk = require("chalk"); const AIbitat = require("../../index.js"); const { websocket, webBrowsing, webScraping, } = require("../../plugins/index.js"); const path = require("path"); const port = 3000; const app = express(); require("@mintplex-labs/express-ws").default(app); // load WebSockets in non-SSL mode. require("dotenv").config({ path: `../../../../../.env.development` }); // Debugging echo function if this is working for you. // app.ws('/echo', function (ws, req) { // ws.on('message', function (msg) { // ws.send(msg); // }); // }); // Set up WSS sockets for listening. app.ws("/ws", function (ws, _response) { try { ws.on("message", function (msg) { if (ws?.handleFeedback) ws.handleFeedback(msg); }); ws.on("close", function () { console.log("Socket killed"); return; }); console.log("Socket online and waiting..."); runAIbitat(ws).catch((error) => { ws.send( JSON.stringify({ from: "AI", to: "HUMAN", content: error.message, }) ); }); } catch (error) {} }); app.all("*", function (_, response) { response.sendFile(path.join(__dirname, "index.html")); }); app.listen(port, () => { console.log(`Testing HTTP/WSS server listening at http://localhost:${port}`); }); async function runAIbitat(socket) { console.log(chalk.blue("Booting AIbitat class & starting agent(s)")); const aibitat = new AIbitat({ provider: "openai", model: "gpt-4", }) .use(websocket.plugin({ socket })) .use(webBrowsing.plugin()) .use(webScraping.plugin()) .agent("creativeDirector", { role: `You are a Creative Director. Your role is overseeing the entire branding project, ensuring the client's brief is met, and maintaining consistency across all brand elements, developing the brand strategy, guiding the visual and conceptual direction, and providing overall creative leadership.`, }) .agent("marketResearcher", { role: `You do competitive market analysis via searching on the internet and learning about comparative products and services. You can search by using keywords and phrases that you think will lead to competitor research that can help find the unique angle and market of the idea.`, functions: ["web-browsing"], }) .agent("PM", { role: `You are the Project Coordinator. Your role is overseeing the project's progress, timeline, and budget. Ensure effective communication and coordination among team members, client, and stakeholders. Your tasks include planning and scheduling project milestones, tracking tasks, and managing any risks or issues that arise.`, interrupt: "ALWAYS", }) .channel("<b>#branding</b>", [ "creativeDirector", "marketResearcher", "PM", ]); await aibitat.start({ from: "PM", to: "<b>#branding</b>", content: `I have an idea for a muslim focused meetup called Chai & Vibes. I want to focus on professionals that are muslim and are in their 18-30 year old range who live in big cities. Does anything like this exist? How can we differentiate?`, }); }
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/validWorkspace.js
server/utils/middleware/validWorkspace.js
const { Workspace } = require("../../models/workspace"); const { WorkspaceThread } = require("../../models/workspaceThread"); const { userFromSession, multiUserMode } = require("../http"); // Will pre-validate and set the workspace for a request if the slug is provided in the URL path. async function validWorkspaceSlug(request, response, next) { const { slug } = request.params; const user = await userFromSession(request, response); const workspace = multiUserMode(response) ? await Workspace.getWithUser(user, { slug }) : await Workspace.get({ slug }); if (!workspace) { response.status(404).send("Workspace does not exist."); return; } response.locals.workspace = workspace; next(); } // Will pre-validate and set the workspace AND a thread for a request if the slugs are provided in the URL path. async function validWorkspaceAndThreadSlug(request, response, next) { const { slug, threadSlug } = request.params; const user = await userFromSession(request, response); const workspace = multiUserMode(response) ? await Workspace.getWithUser(user, { slug }) : await Workspace.get({ slug }); if (!workspace) { response.status(404).send("Workspace does not exist."); return; } const thread = await WorkspaceThread.get({ slug: threadSlug, user_id: user?.id || null, }); if (!thread) { response.status(404).send("Workspace thread does not exist."); return; } response.locals.workspace = workspace; response.locals.thread = thread; next(); } module.exports = { validWorkspaceSlug, validWorkspaceAndThreadSlug, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/isSupportedRepoProviders.js
server/utils/middleware/isSupportedRepoProviders.js
// Middleware to validate that a repo provider URL is supported. const REPO_PLATFORMS = ["github", "gitlab"]; function isSupportedRepoProvider(request, response, next) { const { repo_platform = null } = request.params; if (!repo_platform || !REPO_PLATFORMS.includes(repo_platform)) return response .status(500) .text(`Unsupported repo platform ${repo_platform}`); next(); } module.exports = { isSupportedRepoProvider };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/communityHubDownloadsEnabled.js
server/utils/middleware/communityHubDownloadsEnabled.js
const { CommunityHub } = require("../../models/communityHub"); const { reqBody } = require("../http"); /** * ### Must be called after `communityHubItem` * Checks if community hub bundle downloads are enabled. The reason this functionality is disabled * by default is that since AgentSkills, Workspaces, and DataConnectors are all imported from the * community hub via unzipping a bundle - it would be possible for a malicious user to craft and * download a malicious bundle and import it into their own hosted instance. To avoid this, this * functionality is disabled by default and must be enabled manually by the system administrator. * * On hosted systems, this would not be an issue since the user cannot modify this setting, but those * who self-host can still unlock this feature manually by setting the environment variable * which would require someone who likely has the capacity to understand the risks and the * implications of importing unverified items that can run code on their system, container, or instance. * @see {@link https://docs.anythingllm.com/docs/community-hub/import} * @param {import("express").Request} request * @param {import("express").Response} response * @param {import("express").NextFunction} next * @returns {void} */ function communityHubDownloadsEnabled(request, response, next) { if (!("COMMUNITY_HUB_BUNDLE_DOWNLOADS_ENABLED" in process.env)) { return response.status(422).json({ error: "Community Hub bundle downloads are not enabled. The system administrator must enable this feature manually to allow this instance to download these types of items. See https://docs.anythingllm.com/configuration#anythingllm-hub-agent-skills", }); } // If the admin specifically did not set the system to `allow_all` then downloads are limited to verified items or private items only. // This is to prevent users from downloading unverified items and importing them into their own instance without understanding the risks. const item = response.locals.bundleItem; if ( !item.verified && item.visibility !== "private" && process.env.COMMUNITY_HUB_BUNDLE_DOWNLOADS_ENABLED !== "allow_all" ) { return response.status(422).json({ error: "Community hub bundle downloads are limited to verified public items or private team items only. Please contact the system administrator to review or modify this setting. See https://docs.anythingllm.com/configuration#anythingllm-hub-agent-skills", }); } next(); } /** * Fetch the bundle item from the community hub. * Sets `response.locals.bundleItem` and `response.locals.bundleUrl`. */ async function communityHubItem(request, response, next) { const { importId } = reqBody(request); if (!importId) return response.status(500).json({ success: false, error: "Import ID is required", }); const { url, item, error: fetchError, } = await CommunityHub.getBundleItem(importId); if (fetchError) return response.status(500).json({ success: false, error: fetchError, }); response.locals.bundleItem = item; response.locals.bundleUrl = url; next(); } module.exports = { communityHubItem, communityHubDownloadsEnabled, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/featureFlagEnabled.js
server/utils/middleware/featureFlagEnabled.js
const { SystemSettings } = require("../../models/systemSettings"); // Explicitly check that a specific feature flag is enabled. // This should match the key in the SystemSetting label. function featureFlagEnabled(featureFlagKey = null) { return async (_, response, next) => { if (!featureFlagKey) return response.sendStatus(401).end(); const flagValue = ( await SystemSettings.get({ label: String(featureFlagKey) }) )?.value; if (!flagValue) return response.sendStatus(401).end(); if (flagValue === "enabled") { next(); return; } return response.sendStatus(401).end(); }; } module.exports = { featureFlagEnabled, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/validApiKey.js
server/utils/middleware/validApiKey.js
const { ApiKey } = require("../../models/apiKeys"); const { SystemSettings } = require("../../models/systemSettings"); async function validApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json({ error: "No valid api key found.", }); return; } if (!(await ApiKey.get({ secret: bearerKey }))) { response.status(403).json({ error: "No valid api key found.", }); return; } next(); } module.exports = { validApiKey, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/chatHistoryViewable.js
server/utils/middleware/chatHistoryViewable.js
/** * A simple middleware that validates that the chat history is viewable. * via the `DISABLE_VIEW_CHAT_HISTORY` environment variable being set AT ALL. * @param {Request} request - The request object. * @param {Response} response - The response object. * @param {NextFunction} next - The next function. */ function chatHistoryViewable(_request, response, next) { if ("DISABLE_VIEW_CHAT_HISTORY" in process.env) return response .status(422) .send("This feature has been disabled by the administrator."); next(); } module.exports = { chatHistoryViewable, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/embedMiddleware.js
server/utils/middleware/embedMiddleware.js
const { v4: uuidv4, validate } = require("uuid"); const { VALID_CHAT_MODE } = require("../chats/stream"); const { EmbedChats } = require("../../models/embedChats"); const { EmbedConfig } = require("../../models/embedConfig"); const { reqBody } = require("../http"); // Finds or Aborts request for a /:embedId/ url. This should always // be the first middleware and the :embedID should be in the URL. async function validEmbedConfig(request, response, next) { const { embedId } = request.params; const embed = await EmbedConfig.getWithWorkspace({ uuid: embedId }); if (!embed) { response.sendStatus(404).end(); return; } response.locals.embedConfig = embed; next(); } function setConnectionMeta(request, response, next) { response.locals.connection = { host: request.headers?.origin, ip: request?.ip, }; next(); } async function validEmbedConfigId(request, response, next) { const { embedId } = request.params; const embed = await EmbedConfig.get({ id: Number(embedId) }); if (!embed) { response.sendStatus(404).end(); return; } response.locals.embedConfig = embed; next(); } async function canRespond(request, response, next) { try { const embed = response.locals.embedConfig; if (!embed) { response.sendStatus(404).end(); return; } // Block if disabled by admin. if (!embed.enabled) { response.status(503).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "This chat has been disabled by the administrator - try again later.", }); return; } // Check if requester hostname is in the valid allowlist of domains. const host = request.headers.origin ?? ""; const allowedHosts = EmbedConfig.parseAllowedHosts(embed); if (allowedHosts !== null && !allowedHosts.includes(host)) { response.status(401).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "Invalid request.", }); return; } const { sessionId, message } = reqBody(request); if (typeof sessionId !== "string" || !validate(String(sessionId))) { response.status(404).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "Invalid session ID.", }); return; } if (!message?.length || !VALID_CHAT_MODE.includes(embed.chat_mode)) { response.status(400).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: !message?.length ? "Message is empty." : `${embed.chat_mode} is not a valid mode.`, }); return; } if ( !isNaN(embed.max_chats_per_day) && Number(embed.max_chats_per_day) > 0 ) { const dailyChatCount = await EmbedChats.count({ embed_id: embed.id, createdAt: { gte: new Date(new Date() - 24 * 60 * 60 * 1000), }, }); if (dailyChatCount >= Number(embed.max_chats_per_day)) { response.status(429).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "Rate limit exceeded", errorMsg: "The quota for this chat has been reached. Try again later or contact the site owner.", }); return; } } if ( !isNaN(embed.max_chats_per_session) && Number(embed.max_chats_per_session) > 0 ) { const dailySessionCount = await EmbedChats.count({ embed_id: embed.id, session_id: sessionId, createdAt: { gte: new Date(new Date() - 24 * 60 * 60 * 1000), }, }); if (dailySessionCount >= Number(embed.max_chats_per_session)) { response.status(429).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "Your quota for this chat has been reached. Try again later or contact the site owner.", }); return; } } next(); } catch (e) { response.status(500).json({ id: uuidv4(), type: "abort", textResponse: null, sources: [], close: true, error: "Invalid request.", }); return; } } module.exports = { setConnectionMeta, validEmbedConfig, validEmbedConfigId, canRespond, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/simpleSSOEnabled.js
server/utils/middleware/simpleSSOEnabled.js
const { SystemSettings } = require("../../models/systemSettings"); /** * Checks if simple SSO is enabled for issuance of temporary auth tokens. * Note: This middleware must be called after `validApiKey`. * @param {import("express").Request} request * @param {import("express").Response} response * @param {import("express").NextFunction} next * @returns {void} */ async function simpleSSOEnabled(_, response, next) { if (!("SIMPLE_SSO_ENABLED" in process.env)) { return response .status(403) .send( "Simple SSO is not enabled. It must be enabled to validate or issue temporary auth tokens." ); } // If the multi-user mode response local is not set, we need to check if it's enabled. if (!("multiUserMode" in response.locals)) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; } if (!response.locals.multiUserMode) { return response .status(403) .send( "Multi-User mode is not enabled. It must be enabled to use Simple SSO." ); } next(); } /** * Checks if simple SSO login is disabled by checking if the * SIMPLE_SSO_NO_LOGIN environment variable is set as well as * SIMPLE_SSO_ENABLED is set. * * This check should only be run when in multi-user mode when used. * @returns {boolean} */ function simpleSSOLoginDisabled() { return ( "SIMPLE_SSO_ENABLED" in process.env && "SIMPLE_SSO_NO_LOGIN" in process.env ); } /** * Middleware that checks if simple SSO login is disabled by checking if the * SIMPLE_SSO_NO_LOGIN environment variable is set as well as * SIMPLE_SSO_ENABLED is set. * * This middleware will 403 if SSO is enabled and no login is allowed and * the system is in multi-user mode. Otherwise, it will call next. * * @param {import("express").Request} request * @param {import("express").Response} response * @param {import("express").NextFunction} next * @returns {void} */ async function simpleSSOLoginDisabledMiddleware(_, response, next) { if (!("multiUserMode" in response.locals)) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; } if (response.locals.multiUserMode && simpleSSOLoginDisabled()) { response.status(403).json({ success: false, error: "Login via credentials has been disabled by the administrator.", }); return; } next(); } module.exports = { simpleSSOEnabled, simpleSSOLoginDisabled, simpleSSOLoginDisabledMiddleware, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/validatedRequest.js
server/utils/middleware/validatedRequest.js
const { SystemSettings } = require("../../models/systemSettings"); const { User } = require("../../models/user"); const { EncryptionManager } = require("../EncryptionManager"); const { decodeJWT } = require("../http"); const EncryptionMgr = new EncryptionManager(); async function validatedRequest(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; if (multiUserMode) return await validateMultiUserRequest(request, response, next); // When in development passthrough auth token for ease of development. // Or if the user simply did not set an Auth token or JWT Secret if ( process.env.NODE_ENV === "development" || !process.env.AUTH_TOKEN || !process.env.JWT_SECRET ) { next(); return; } if (!process.env.AUTH_TOKEN) { response.status(401).json({ error: "You need to set an AUTH_TOKEN environment variable.", }); return; } const auth = request.header("Authorization"); const token = auth ? auth.split(" ")[1] : null; if (!token) { response.status(401).json({ error: "No auth token found.", }); return; } const bcrypt = require("bcryptjs"); const { p } = decodeJWT(token); if (p === null || !/\w{32}:\w{32}/.test(p)) { response.status(401).json({ error: "Token expired or failed validation.", }); return; } // Since the blame of this comment we have been encrypting the `p` property of JWTs with the persistent // encryptionManager PEM's. This prevents us from storing the `p` unencrypted in the JWT itself, which could // be unsafe. As a consequence, existing JWTs with invalid `p` values that do not match the regex // in ln:44 will be marked invalid so they can be logged out and forced to log back in and obtain an encrypted token. // This kind of methodology only applies to single-user password mode. if ( !bcrypt.compareSync( EncryptionMgr.decrypt(p), bcrypt.hashSync(process.env.AUTH_TOKEN, 10) ) ) { response.status(401).json({ error: "Invalid auth credentials.", }); return; } next(); } async function validateMultiUserRequest(request, response, next) { const auth = request.header("Authorization"); const token = auth ? auth.split(" ")[1] : null; if (!token) { response.status(401).json({ error: "No auth token found.", }); return; } const valid = decodeJWT(token); if (!valid || !valid.id) { response.status(401).json({ error: "Invalid auth token.", }); return; } const user = await User.get({ id: valid.id }); if (!user) { response.status(401).json({ error: "Invalid auth for user.", }); return; } if (user.suspended) { response.status(401).json({ error: "User is suspended from system", }); return; } response.locals.user = user; next(); } module.exports = { validatedRequest, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/multiUserProtected.js
server/utils/middleware/multiUserProtected.js
const { SystemSettings } = require("../../models/systemSettings"); const { userFromSession } = require("../http"); const ROLES = { all: "<all>", admin: "admin", manager: "manager", default: "default", }; const DEFAULT_ROLES = [ROLES.admin, ROLES.admin]; /** * Explicitly check that multi user mode is enabled as well as that the * requesting user has the appropriate role to modify or call the URL. * @param {string[]} allowedRoles - The roles that are allowed to access the route * @returns {function} */ function strictMultiUserRoleValid(allowedRoles = DEFAULT_ROLES) { return async (request, response, next) => { // If the access-control is allowable for all - skip validations and continue; if (allowedRoles.includes(ROLES.all)) { next(); return; } const multiUserMode = response.locals?.multiUserMode ?? (await SystemSettings.isMultiUserMode()); if (!multiUserMode) return response.sendStatus(401).end(); const user = response.locals?.user ?? (await userFromSession(request, response)); if (allowedRoles.includes(user?.role)) { next(); return; } return response.sendStatus(401).end(); }; } /** * Apply role permission checks IF the current system is in multi-user mode. * This is relevant for routes that are shared between MUM and single-user mode. * @param {string[]} allowedRoles - The roles that are allowed to access the route * @returns {function} */ function flexUserRoleValid(allowedRoles = DEFAULT_ROLES) { return async (request, response, next) => { // If the access-control is allowable for all - skip validations and continue; // It does not matter if multi-user or not. if (allowedRoles.includes(ROLES.all)) { next(); return; } // Bypass if not in multi-user mode const multiUserMode = response.locals?.multiUserMode ?? (await SystemSettings.isMultiUserMode()); if (!multiUserMode) { next(); return; } const user = response.locals?.user ?? (await userFromSession(request, response)); if (allowedRoles.includes(user?.role)) { next(); return; } return response.sendStatus(401).end(); }; } // Middleware check on a public route if the instance is in a valid // multi-user set up. async function isMultiUserSetup(_request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); if (!multiUserMode) { response.status(403).json({ error: "Invalid request", }); return; } next(); return; } module.exports = { ROLES, strictMultiUserRoleValid, flexUserRoleValid, isMultiUserSetup, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/middleware/validBrowserExtensionApiKey.js
server/utils/middleware/validBrowserExtensionApiKey.js
const { BrowserExtensionApiKey, } = require("../../models/browserExtensionApiKey"); const { SystemSettings } = require("../../models/systemSettings"); const { User } = require("../../models/user"); async function validBrowserExtensionApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json({ error: "No valid API key found.", }); return; } const apiKey = await BrowserExtensionApiKey.validate(bearerKey); if (!apiKey) { response.status(403).json({ error: "No valid API key found.", }); return; } if (multiUserMode) { response.locals.user = await User.get({ id: apiKey.user_id }); } response.locals.apiKey = apiKey; next(); } module.exports = { validBrowserExtensionApiKey };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/index.js
server/utils/agentFlows/index.js
const fs = require("fs"); const path = require("path"); const { v4: uuidv4 } = require("uuid"); const { FlowExecutor, FLOW_TYPES } = require("./executor"); const { normalizePath } = require("../files"); const { safeJsonParse } = require("../http"); /** * @typedef {Object} LoadedFlow * @property {string} name - The name of the flow * @property {string} uuid - The UUID of the flow * @property {Object} config - The flow configuration details * @property {string} config.description - The description of the flow * @property {Array<{type: string, config: Object, [key: string]: any}>} config.steps - The steps of the flow. Each step has at least a type and config */ class AgentFlows { static flowsDir = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "plugins", "agent-flows") : path.join(process.cwd(), "storage", "plugins", "agent-flows"); constructor() {} /** * Ensure flows directory exists * @returns {Boolean} True if directory exists, false otherwise */ 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; } } /** * Helper to get all flow files with their contents * @returns {Object} Map of flow UUID to flow config */ 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; } /** * 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 */ 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; } } /** * 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 */ 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 }; } } /** * List all available flows * @returns {Array} Array of flow summaries */ 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 []; } } /** * Delete a flow by UUID * @param {string} uuid - The UUID of the flow to delete * @returns {Object} Result of the delete operation */ 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 }; } } /** * 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 */ 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); } /** * Get all active flows as plugins that can be loaded into the agent * @returns {string[]} Array of flow names in @@flow_{uuid} format */ static activeFlowPlugins() { const flows = AgentFlows.getAllFlows(); return Object.entries(flows) .filter(([_, flow]) => flow.active !== false) .map(([uuid]) => `@@flow_${uuid}`); } /** * 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 */ 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, }; } /** * 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 */ static stringifyResult(input) { return typeof input === "object" ? JSON.stringify(input) : String(input); } } module.exports.AgentFlows = AgentFlows;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/executor.js
server/utils/agentFlows/executor.js
const { FLOW_TYPES } = require("./flowTypes"); const executeApiCall = require("./executors/api-call"); const executeLLMInstruction = require("./executors/llm-instruction"); const executeWebScraping = require("./executors/web-scraping"); const { Telemetry } = require("../../models/telemetry"); const { safeJsonParse } = require("../http"); class FlowExecutor { constructor() { this.variables = {}; this.introspect = (...args) => console.log("[introspect] ", ...args); this.logger = console.info; this.aibitat = null; } attachLogging(introspectFn = null, loggerFn = null) { this.introspect = introspectFn || ((...args) => console.log("[introspect] ", ...args)); this.logger = loggerFn || console.info; } /** * 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(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; } /** * 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(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); } /** * Executes a single step of the flow * @param {Object} step - The step to execute * @returns {Promise<Object>} The result of the step */ 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; } /** * 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 */ 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, }; } } module.exports = { FlowExecutor, FLOW_TYPES, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/flowTypes.js
server/utils/agentFlows/flowTypes.js
const FLOW_TYPES = { START: { type: "start", description: "Initialize flow variables", parameters: { variables: { type: "array", description: "List of variables to initialize", }, }, }, API_CALL: { type: "apiCall", description: "Make an HTTP request to an API endpoint", parameters: { url: { type: "string", description: "The URL to make the request to" }, method: { type: "string", description: "HTTP method (GET, POST, etc.)" }, headers: { type: "array", description: "Request headers as key-value pairs", }, bodyType: { type: "string", description: "Type of request body (json, form)", }, body: { type: "string", description: "Request body content. If body type is json, always return a valid json object. If body type is form, always return a valid form data object.", }, formData: { type: "array", description: "Form data as key-value pairs" }, responseVariable: { type: "string", description: "Variable to store the response", }, directOutput: { type: "boolean", description: "Whether to return the response directly to the user without LLM processing", }, }, examples: [ { url: "https://api.example.com/data", method: "GET", headers: [{ key: "Authorization", value: "Bearer 1234567890" }], }, ], }, LLM_INSTRUCTION: { type: "llmInstruction", description: "Process data using LLM instructions", parameters: { instruction: { type: "string", description: "The instruction for the LLM to follow", }, resultVariable: { type: "string", description: "Variable to store the processed result", }, }, }, WEB_SCRAPING: { type: "webScraping", description: "Scrape content from a webpage", parameters: { url: { type: "string", description: "The URL of the webpage to scrape", }, resultVariable: { type: "string", description: "Variable to store the scraped content", }, directOutput: { type: "boolean", description: "Whether to return the scraped content directly to the user without LLM processing", }, }, }, }; module.exports.FLOW_TYPES = FLOW_TYPES;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/executors/llm-instruction.js
server/utils/agentFlows/executors/llm-instruction.js
/** * 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 */ 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.textResponse; } catch (error) { logger(`LLM processing failed: ${error.message}`, error); throw new Error(`LLM processing failed: ${error.message}`); } } module.exports = executeLLMInstruction;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/executors/web-scraping.js
server/utils/agentFlows/executors/web-scraping.js
/** * 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 */ 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; } /** * 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 */ 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 }; } module.exports = executeWebScraping;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/agentFlows/executors/api-call.js
server/utils/agentFlows/executors/api-call.js
const { safeJsonParse } = require("../../http"); /** * 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 */ 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}`); } } module.exports = executeApiCall;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorStore/resetAllVectorStores.js
server/utils/vectorStore/resetAllVectorStores.js
const { Workspace } = require("../../models/workspace"); const { Document } = require("../../models/documents"); const { DocumentVectors } = require("../../models/vectors"); const { EventLogs } = require("../../models/eventLogs"); const { purgeEntireVectorCache } = require("../files"); const { getVectorDbClass } = require("../helpers"); /** * Resets all vector database and associated content: * - Purges the entire vector-cache folder. * - Deletes all document vectors from the database. * - Deletes all documents from the database. * - Deletes all vector db namespaces for each workspace. * - Logs an event indicating the reset. * @param {string} vectorDbKey - The _previous_ vector database provider name that we will be resetting. * @returns {Promise<boolean>} - True if successful, false otherwise. */ async function resetAllVectorStores({ vectorDbKey }) { try { const workspaces = await Workspace.where(); purgeEntireVectorCache(); // Purges the entire vector-cache folder. await DocumentVectors.delete(); // Deletes all document vectors from the database. await Document.delete(); // Deletes all documents from the database. await EventLogs.logEvent("workspace_vectors_reset", { reason: "System vector configuration changed", }); console.log( "Resetting anythingllm managed vector namespaces for", vectorDbKey ); const VectorDb = getVectorDbClass(vectorDbKey); if (vectorDbKey === "pgvector") { /* pgvector has a reset method that drops the entire embedding table which is required since if this function is called we will need to reset the embedding column VECTOR dimension value and you cannot change the dimension value of an existing vector column. */ await VectorDb.reset(); } else { for (const workspace of workspaces) { try { await VectorDb["delete-namespace"]({ namespace: workspace.slug }); } catch (e) { console.error(e.message); } } } return true; } catch (error) { console.error("Failed to reset vector stores:", error); return false; } } module.exports = { resetAllVectorStores };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/DocumentManager/index.js
server/utils/DocumentManager/index.js
const fs = require("fs"); const path = require("path"); const documentsPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../storage/documents`) : path.resolve(process.env.STORAGE_DIR, `documents`); class DocumentManager { constructor({ workspace = null, maxTokens = null }) { this.workspace = workspace; this.maxTokens = maxTokens || Number.POSITIVE_INFINITY; this.documentStoragePath = documentsPath; } log(text, ...args) { console.log(`\x1b[36m[DocumentManager]\x1b[0m ${text}`, ...args); } async pinnedDocuments() { if (!this.workspace) return []; const { Document } = require("../../models/documents"); return await Document.where({ workspaceId: Number(this.workspace.id), pinned: true, }); } async pinnedDocs() { if (!this.workspace) return []; const docPaths = (await this.pinnedDocuments()).map((doc) => doc.docpath); if (docPaths.length === 0) return []; let tokens = 0; const pinnedDocs = []; for await (const docPath of docPaths) { try { const filePath = path.resolve(this.documentStoragePath, docPath); const data = JSON.parse( fs.readFileSync(filePath, { encoding: "utf-8" }) ); if ( !data.hasOwnProperty("pageContent") || !data.hasOwnProperty("token_count_estimate") ) { this.log( `Skipping document - Could not find page content or token_count_estimate in pinned source.` ); continue; } if (tokens >= this.maxTokens) { this.log( `Skipping document - Token limit of ${this.maxTokens} has already been exceeded by pinned documents.` ); continue; } pinnedDocs.push(data); tokens += data.token_count_estimate || 0; } catch {} } this.log( `Found ${pinnedDocs.length} pinned sources - prepending to content with ~${tokens} tokens of content.` ); return pinnedDocs; } } module.exports.DocumentManager = DocumentManager;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EncryptionManager/index.js
server/utils/EncryptionManager/index.js
const crypto = require("crypto"); const { dumpENV } = require("../helpers/updateENV"); // Class that is used to arbitrarily encrypt/decrypt string data via a persistent passphrase/salt that // is either user defined or is created and saved to the ENV on creation. class EncryptionManager { #keyENV = "SIG_KEY"; #saltENV = "SIG_SALT"; #encryptionKey; #encryptionSalt; constructor({ key = null, salt = null } = {}) { this.#loadOrCreateKeySalt(key, salt); this.key = crypto.scryptSync(this.#encryptionKey, this.#encryptionSalt, 32); this.algorithm = "aes-256-cbc"; this.separator = ":"; // Used to send key to collector process to be able to decrypt data since they do not share ENVs // this value should use the CommunicationKey.encrypt process before sending anywhere outside the // server process so it is never sent in its raw format. this.xPayload = this.key.toString("base64"); } log(text, ...args) { console.log(`\x1b[36m[EncryptionManager]\x1b[0m ${text}`, ...args); } #loadOrCreateKeySalt(_key = null, _salt = null) { if (!!_key && !!_salt) { this.log( "Pre-assigned key & salt for encrypting arbitrary data was used." ); this.#encryptionKey = _key; this.#encryptionSalt = _salt; return; } if (!process.env[this.#keyENV] || !process.env[this.#saltENV]) { this.log("Self-assigning key & salt for encrypting arbitrary data."); process.env[this.#keyENV] = crypto.randomBytes(32).toString("hex"); process.env[this.#saltENV] = crypto.randomBytes(32).toString("hex"); if (process.env.NODE_ENV === "production") dumpENV(); } else this.log("Loaded existing key & salt for encrypting arbitrary data."); this.#encryptionKey = process.env[this.#keyENV]; this.#encryptionSalt = process.env[this.#saltENV]; return; } encrypt(plainTextString = null) { try { if (!plainTextString) throw new Error("Empty string is not valid for this method."); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv(this.algorithm, this.key, iv); const encrypted = cipher.update(plainTextString, "utf8", "hex"); return [ encrypted + cipher.final("hex"), Buffer.from(iv).toString("hex"), ].join(this.separator); } catch (e) { this.log(e); return null; } } decrypt(encryptedString) { try { const [encrypted, iv] = encryptedString.split(this.separator); if (!iv) throw new Error("IV not found"); const decipher = crypto.createDecipheriv( this.algorithm, this.key, Buffer.from(iv, "hex") ); return decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8"); } catch (e) { this.log(e); return null; } } } module.exports = { EncryptionManager };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/weaviate/index.js
server/utils/vectorDbProviders/weaviate/index.js
const { default: weaviate } = require("weaviate-ts-client"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { camelCase } = require("../../helpers/camelcase"); const { sourceIdentifier } = require("../../chats"); const Weaviate = { name: "Weaviate", connect: async function () { if (process.env.VECTOR_DB !== "weaviate") throw new Error("Weaviate::Invalid ENV settings"); const weaviateUrl = new URL(process.env.WEAVIATE_ENDPOINT); const options = { scheme: weaviateUrl.protocol?.replace(":", "") || "http", host: weaviateUrl?.host, ...(process.env?.WEAVIATE_API_KEY?.length > 0 ? { apiKey: new weaviate.ApiKey(process.env?.WEAVIATE_API_KEY) } : {}), }; const client = weaviate.client(options); const isAlive = await await client.misc.liveChecker().do(); if (!isAlive) throw new Error( "Weaviate::Invalid Alive signal received - is the service online?" ); return { client }; }, heartbeat: async function () { await this.connect(); return { heartbeat: Number(new Date()) }; }, totalVectors: async function () { const { client } = await this.connect(); const collectionNames = await this.allNamespaces(client); var totalVectors = 0; for (const name of collectionNames) { totalVectors += await this.namespaceCountWithClient(client, name); } return totalVectors; }, namespaceCountWithClient: async function (client, namespace) { try { const response = await client.graphql .aggregate() .withClassName(camelCase(namespace)) .withFields("meta { count }") .do(); return ( response?.data?.Aggregate?.[camelCase(namespace)]?.[0]?.meta?.count || 0 ); } catch (e) { console.error(`Weaviate:namespaceCountWithClient`, e.message); return 0; } }, namespaceCount: async function (namespace = null) { try { const { client } = await this.connect(); const response = await client.graphql .aggregate() .withClassName(camelCase(namespace)) .withFields("meta { count }") .do(); return ( response?.data?.Aggregate?.[camelCase(namespace)]?.[0]?.meta?.count || 0 ); } catch (e) { console.error(`Weaviate:namespaceCountWithClient`, e.message); return 0; } }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const weaviateClass = await this.namespace(client, namespace); const fields = weaviateClass.properties?.map((prop) => prop.name)?.join(" ") ?? ""; const queryResponse = await client.graphql .get() .withClassName(camelCase(namespace)) .withFields(`${fields} _additional { id certainty }`) .withNearVector({ vector: queryVector }) .withLimit(topN) .do(); const responses = queryResponse?.data?.Get?.[camelCase(namespace)]; responses.forEach((response) => { // In Weaviate we have to pluck id from _additional and spread it into the rest // of the properties. const { _additional: { id, certainty }, ...rest } = response; if (certainty < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(rest))) { console.log( "Weaviate: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(rest.text); result.sourceDocuments.push({ ...rest, id, score: certainty }); result.scores.push(certainty); }); return result; }, allNamespaces: async function (client) { try { const { classes = [] } = await client.schema.getter().do(); return classes.map((classObj) => classObj.class); } catch (e) { console.error("Weaviate::AllNamespace", e); return []; } }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); if (!(await this.namespaceExists(client, namespace))) return null; const weaviateClass = await client.schema .classGetter() .withClassName(camelCase(namespace)) .do(); return { ...weaviateClass, vectorCount: await this.namespaceCount(namespace), }; }, addVectors: async function (client, vectors = []) { const response = { success: true, errors: new Set([]) }; const results = await client.batch .objectsBatcher() .withObjects(...vectors) .do(); results.forEach((res) => { const { status, errors = [] } = res.result; if (status === "SUCCESS" || errors.length === 0) return; response.success = false; response.errors.add(errors.error?.[0]?.message || null); }); response.errors = [...response.errors]; return response; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); const weaviateClasses = await this.allNamespaces(client); return weaviateClasses.includes(camelCase(namespace)); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const weaviateClasses = await this.allNamespaces(client); return weaviateClasses.includes(camelCase(namespace)); }, deleteVectorsInNamespace: async function (client, namespace = null) { await client.schema.classDeleter().withClassName(camelCase(namespace)).do(); return true; }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { const { pageContent, docId, id: _id, // Weaviate will abort if `id` is present in properties ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const weaviateClassExits = await this.hasNamespace(namespace); if (!weaviateClassExits) { await client.schema .classCreator() .withClass({ class: camelCase(namespace), description: `Class created by AnythingLLM named ${camelCase( namespace )}`, vectorizer: "none", }) .do(); } const { chunks } = cacheResult; const documentVectors = []; const vectors = []; for (const chunk of chunks) { // Before sending to Weaviate and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. chunk.forEach((chunk) => { const id = uuidv4(); const flattenedMetadata = this.flattenObjectForWeaviate( chunk.properties ?? chunk.metadata ); documentVectors.push({ docId, vectorId: id }); const vectorRecord = { id, class: camelCase(namespace), vector: chunk.vector || chunk.values || [], properties: { ...flattenedMetadata }, }; vectors.push(vectorRecord); }); const { success: additionResult, errors = [] } = await this.addVectors(client, vectors); if (!additionResult) { console.error("Weaviate::addVectors failed to insert", errors); throw new Error("Error embedding into Weaviate"); } } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `Chroma.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); const submission = { ids: [], vectors: [], properties: [], }; if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { const flattenedMetadata = this.flattenObjectForWeaviate(metadata); const vectorRecord = { class: camelCase(namespace), id: uuidv4(), vector: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. // https://github.com/hwchase17/langchainjs/blob/5485c4af50c063e257ad54f4393fa79e0aff6462/langchain/src/vectorstores/weaviate.ts#L133 properties: { ...flattenedMetadata, text: textChunks[i] }, }; submission.ids.push(vectorRecord.id); submission.vectors.push(vectorRecord.values); submission.properties.push(metadata); vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } const { client } = await this.connect(); const weaviateClassExits = await this.hasNamespace(namespace); if (!weaviateClassExits) { await client.schema .classCreator() .withClass({ class: camelCase(namespace), description: `Class created by AnythingLLM named ${camelCase( namespace )}`, vectorizer: "none", }) .do(); } if (vectors.length > 0) { const chunks = []; for (const chunk of toChunks(vectors, 500)) chunks.push(chunk); console.log("Inserting vectorized chunks into Weaviate collection."); const { success: additionResult, errors = [] } = await this.addVectors( client, vectors ); if (!additionResult) { console.error("Weaviate::addVectors failed to insert", errors); throw new Error("Error embedding into Weaviate"); } await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) return; const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; for (const doc of knownDocuments) { await client.data .deleter() .withClassName(camelCase(namespace)) .withId(doc.vectorId) .do(); } const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((metadata, i) => { return { ...metadata, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); const details = await this.namespace(client, namespace); await this.deleteVectorsInNamespace(client, namespace); return { message: `Namespace ${camelCase(namespace)} was deleted along with ${ details?.vectorCount } vectors.`, }; }, reset: async function () { const { client } = await this.connect(); const weaviateClasses = await this.allNamespaces(client); for (const weaviateClass of weaviateClasses) { await client.schema.classDeleter().withClassName(weaviateClass).do(); } return { reset: true }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { if (Object.keys(source).length > 0) { const metadata = source.hasOwnProperty("metadata") ? source.metadata : source; documents.push({ ...metadata }); } } return documents; }, flattenObjectForWeaviate: function (obj = {}) { // Note this function is not generic, it is designed specifically for Weaviate // https://weaviate.io/developers/weaviate/config-refs/datatypes#introduction // Credit to LangchainJS // https://github.com/hwchase17/langchainjs/blob/5485c4af50c063e257ad54f4393fa79e0aff6462/langchain/src/vectorstores/weaviate.ts#L11C1-L50C3 const flattenedObject = {}; for (const key in obj) { if (!Object.hasOwn(obj, key) || key === "id") { continue; } const value = obj[key]; if (typeof obj[key] === "object" && !Array.isArray(value)) { const recursiveResult = this.flattenObjectForWeaviate(value); for (const deepKey in recursiveResult) { if (Object.hasOwn(obj, key)) { flattenedObject[`${key}_${deepKey}`] = recursiveResult[deepKey]; } } } else if (Array.isArray(value)) { if ( value.length > 0 && typeof value[0] !== "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any value.every((el) => typeof el === typeof value[0]) ) { // Weaviate only supports arrays of primitive types, // where all elements are of the same type flattenedObject[key] = value; } } else { flattenedObject[key] = value; } } return flattenedObject; }, }; module.exports.Weaviate = Weaviate;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/pgvector/index.js
server/utils/vectorDbProviders/pgvector/index.js
const pgsql = require("pg"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { TextSplitter } = require("../../TextSplitter"); const { v4: uuidv4 } = require("uuid"); const { sourceIdentifier } = require("../../chats"); /* Embedding Table Schema (table name defined by user) - id: UUID PRIMARY KEY - namespace: TEXT - embedding: vector(xxxx) - metadata: JSONB - created_at: TIMESTAMP */ const PGVector = { name: "PGVector", connectionTimeout: 30_000, /** * Get the table name for the PGVector database. * - Defaults to "anythingllm_vectors" if no table name is provided. * @returns {string} */ tableName: () => process.env.PGVECTOR_TABLE_NAME || "anythingllm_vectors", /** * Get the connection string for the PGVector database. * - Requires a connection string to be present in the environment variables. * @returns {string | null} */ connectionString: () => process.env.PGVECTOR_CONNECTION_STRING, // Possible for this to be a user-configurable option in the future. // Will require a handler per operator to ensure scores are normalized. operator: { l2: "<->", innerProduct: "<#>", cosine: "<=>", l1: "<+>", hamming: "<~>", jaccard: "<%>", }, getTablesSql: "SELECT * FROM pg_catalog.pg_tables WHERE schemaname = 'public'", getEmbeddingTableSchemaSql: "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = $1", createExtensionSql: "CREATE EXTENSION IF NOT EXISTS vector;", createTableSql: (dimensions) => `CREATE TABLE IF NOT EXISTS "${PGVector.tableName()}" (id UUID PRIMARY KEY, namespace TEXT, embedding vector(${Number(dimensions)}), metadata JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)`, log: function (message = null, ...args) { console.log(`\x1b[35m[PGVectorDb]\x1b[0m ${message}`, ...args); }, /** * Recursively sanitize values intended for JSONB to prevent Postgres errors * like "unsupported Unicode escape sequence". This primarily removes the * NUL character (\u0000) and other disallowed control characters from * strings. Arrays and objects are traversed and sanitized deeply. * @param {any} value * @returns {any} */ sanitizeForJsonb: function (value) { // Fast path for null/undefined and primitives that do not need changes if (value === null || value === undefined) return value; // Strings: strip NUL and unsafe C0 control characters except common whitespace if (typeof value === "string") { // Build a sanitized string by excluding C0 control characters except // horizontal tab (9), line feed (10), and carriage return (13). let sanitized = ""; for (let i = 0; i < value.length; i++) { const code = value.charCodeAt(i); if (code === 9 || code === 10 || code === 13 || code >= 0x20) { sanitized += value[i]; } } return sanitized; } // Arrays: sanitize each element if (Array.isArray(value)) { return value.map((item) => this.sanitizeForJsonb(item)); } // Dates: keep as ISO string if (value instanceof Date) { return value.toISOString(); } // Objects: sanitize each property value if (typeof value === "object") { const result = {}; for (const [k, v] of Object.entries(value)) { result[k] = this.sanitizeForJsonb(v); } return result; } // Numbers, booleans, etc. return value; }, client: function (connectionString = null) { return new pgsql.Client({ connectionString: connectionString || PGVector.connectionString(), }); }, /** * Validate the existing embedding table schema. * @param {pgsql.Client} pgClient * @param {string} tableName * @returns {Promise<boolean>} */ validateExistingEmbeddingTableSchema: async function (pgClient, tableName) { const result = await pgClient.query(this.getEmbeddingTableSchemaSql, [ tableName, ]); // Minimum expected schema for an embedding table. // Extra columns are allowed but the minimum exact columns are required // to be present in the table. const expectedSchema = [ { column_name: "id", expected: "uuid", validation: function (dataType) { return dataType.toLowerCase() === this.expected; }, }, { column_name: "namespace", expected: "text", validation: function (dataType) { return dataType.toLowerCase() === this.expected; }, }, { column_name: "embedding", expected: "vector", validation: function (dataType) { return !!dataType; }, }, // just check if it exists { column_name: "metadata", expected: "jsonb", validation: function (dataType) { return dataType.toLowerCase() === this.expected; }, }, { column_name: "created_at", expected: "timestamp", validation: function (dataType) { return dataType.toLowerCase().includes(this.expected); }, }, ]; if (result.rows.length === 0) throw new Error( `The table '${tableName}' was found but does not contain any columns or cannot be accessed by role. It cannot be used as an embedding table in AnythingLLM.` ); for (const rowDef of expectedSchema) { const column = result.rows.find( (c) => c.column_name === rowDef.column_name ); if (!column) throw new Error( `The column '${rowDef.column_name}' was expected but not found in the table '${tableName}'.` ); if (!rowDef.validation(column.data_type)) throw new Error( `Invalid data type for column: '${column.column_name}'. Got '${column.data_type}' but expected '${rowDef.expected}'` ); } this.log( `✅ The pgvector table '${tableName}' was found and meets the minimum expected schema for an embedding table.` ); return true; }, /** * Validate the connection to the database and verify that the table does not already exist. * so that anythingllm can manage the table directly. * * @param {{connectionString: string | null, tableName: string | null}} params * @returns {Promise<{error: string | null, success: boolean}>} */ validateConnection: async function ({ connectionString = null, tableName = null, }) { if (!connectionString) throw new Error("No connection string provided"); try { const timeoutPromise = new Promise((resolve) => { setTimeout(() => { resolve({ error: `Connection timeout (${(PGVector.connectionTimeout / 1000).toFixed(0)}s). Please check your connection string and try again.`, success: false, }); }, PGVector.connectionTimeout); }); const connectionPromise = new Promise(async (resolve) => { let pgClient = null; try { pgClient = this.client(connectionString); await pgClient.connect(); const result = await pgClient.query(this.getTablesSql); if (result.rows.length !== 0 && !!tableName) { const tableExists = result.rows.some( (row) => row.tablename === tableName ); if (tableExists) await this.validateExistingEmbeddingTableSchema( pgClient, tableName ); } resolve({ error: null, success: true }); } catch (err) { resolve({ error: err.message, success: false }); } finally { if (pgClient) await pgClient.end(); } }); // Race the connection attempt against the timeout const result = await Promise.race([connectionPromise, timeoutPromise]); return result; } catch (err) { this.log("Validation Error:", err.message); let readableError = err.message; switch (true) { case err.message.includes("ECONNREFUSED"): readableError = "The host could not be reached. Please check your connection string and try again."; break; default: break; } return { error: readableError, success: false }; } }, /** * Test the connection to the database directly. * @returns {{error: string | null, success: boolean}} */ testConnectionToDB: async function () { try { const pgClient = await this.connect(); await pgClient.query(this.getTablesSql); await pgClient.end(); return { error: null, success: true }; } catch (err) { return { error: err.message, success: false }; } }, /** * Connect to the database. * - Throws an error if the connection string or table name is not provided. * @returns {Promise<pgsql.Client>} */ connect: async function () { if (!PGVector.connectionString()) throw new Error("No connection string provided"); if (!PGVector.tableName()) throw new Error("No table name provided"); const client = this.client(); await client.connect(); return client; }, /** * Test the connection to the database with already set credentials via ENV * @returns {{error: string | null, success: boolean}} */ heartbeat: async function () { return this.testConnectionToDB(); }, /** * Check if the anythingllm embedding table exists in the database * @returns {Promise<boolean>} */ dbTableExists: async function () { let connection = null; try { connection = await this.connect(); const tables = await connection.query(this.getTablesSql); if (tables.rows.length === 0) return false; const tableExists = tables.rows.some( (row) => row.tablename === PGVector.tableName() ); return !!tableExists; } catch (err) { return false; } finally { if (connection) await connection.end(); } }, totalVectors: async function () { if (!(await this.dbTableExists())) return 0; let connection = null; try { connection = await this.connect(); const result = await connection.query( `SELECT COUNT(id) FROM "${PGVector.tableName()}"` ); return result.rows[0].count; } catch (err) { return 0; } finally { if (connection) await connection.end(); } }, // Distance for cosine is just the distance for pgvector. distanceToSimilarity: function (distance = null) { if (distance === null || typeof distance !== "number") return 0.0; if (distance >= 1.0) return 1; if (distance < 0) return 1 - Math.abs(distance); return 1 - distance; }, namespaceCount: async function (namespace = null) { if (!(await this.dbTableExists())) return 0; let connection = null; try { connection = await this.connect(); const result = await connection.query( `SELECT COUNT(id) FROM "${PGVector.tableName()}" WHERE namespace = $1`, [namespace] ); return result.rows[0].count; } catch (err) { return 0; } finally { if (connection) await connection.end(); } }, /** * Performs a SimilaritySearch on a given PGVector namespace. * @param {Object} params * @param {pgsql.Client} params.client * @param {string} params.namespace * @param {number[]} params.queryVector * @param {number} params.similarityThreshold * @param {number} params.topN * @param {string[]} params.filterIdentifiers * @returns */ similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const embedding = `[${queryVector.map(Number).join(",")}]`; const response = await client.query( `SELECT embedding ${this.operator.cosine} $1 AS _distance, metadata FROM "${PGVector.tableName()}" WHERE namespace = $2 ORDER BY _distance ASC LIMIT $3`, [embedding, namespace, topN] ); response.rows.forEach((item) => { if (this.distanceToSimilarity(item._distance) < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(item.metadata))) { this.log( "A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(item.metadata.text); result.sourceDocuments.push({ ...item.metadata, score: this.distanceToSimilarity(item._distance), }); result.scores.push(this.distanceToSimilarity(item._distance)); }); return result; }, normalizeVector: function (vector) { const magnitude = Math.sqrt( vector.reduce((sum, val) => sum + val * val, 0) ); if (magnitude === 0) return vector; // Avoid division by zero return vector.map((val) => val / magnitude); }, /** * Update or create a collection in the database * @param {Object} params * @param {pgsql.Connection} params.connection * @param {{id: number, vector: number[], metadata: Object}[]} params.submissions * @param {string} params.namespace * @param {number} params.dimensions * @returns {Promise<boolean>} */ updateOrCreateCollection: async function ({ connection, submissions, namespace, dimensions = 384, }) { await this.createTableIfNotExists(connection, dimensions); this.log(`Updating or creating collection ${namespace}`); try { // Create a transaction of all inserts await connection.query(`BEGIN`); for (const submission of submissions) { const embedding = `[${submission.vector.map(Number).join(",")}]`; // stringify the vector for pgvector const sanitizedMetadata = this.sanitizeForJsonb(submission.metadata); await connection.query( `INSERT INTO "${PGVector.tableName()}" (id, namespace, embedding, metadata) VALUES ($1, $2, $3, $4)`, [submission.id, namespace, embedding, sanitizedMetadata] ); } this.log(`Committing ${submissions.length} vectors to ${namespace}`); await connection.query(`COMMIT`); } catch (err) { this.log( `Rolling back ${submissions.length} vectors to ${namespace}`, err ); await connection.query(`ROLLBACK`); } return true; }, /** * create a table if it doesn't exist * @param {pgsql.Client} connection * @param {number} dimensions * @returns */ createTableIfNotExists: async function (connection, dimensions = 384) { this.log(`Creating embedding table with ${dimensions} dimensions`); await connection.query(this.createExtensionSql); await connection.query(this.createTableSql(dimensions)); return true; }, /** * Get the namespace from the database * @param {pgsql.Client} connection * @param {string} namespace * @returns {Promise<{name: string, vectorCount: number}>} */ namespace: async function (connection, namespace = null) { if (!namespace) throw new Error("No namespace provided"); const result = await connection.query( `SELECT COUNT(id) FROM "${PGVector.tableName()}" WHERE namespace = $1`, [namespace] ); return { name: namespace, vectorCount: result.rows[0].count }; }, /** * Check if the namespace exists in the database * @param {string} namespace * @returns {Promise<boolean>} */ hasNamespace: async function (namespace = null) { if (!namespace) throw new Error("No namespace provided"); let connection = null; try { connection = await this.connect(); return await this.namespaceExists(connection, namespace); } catch (err) { return false; } finally { if (connection) await connection.end(); } }, /** * Check if the namespace exists in the database * @param {pgsql.Client} connection * @param {string} namespace * @returns {Promise<boolean>} */ namespaceExists: async function (connection, namespace = null) { if (!namespace) throw new Error("No namespace provided"); const result = await connection.query( `SELECT COUNT(id) FROM "${PGVector.tableName()}" WHERE namespace = $1 LIMIT 1`, [namespace] ); return result.rows[0].count > 0; }, /** * Delete all vectors in the namespace * @param {pgsql.Client} connection * @param {string} namespace * @returns {Promise<boolean>} */ deleteVectorsInNamespace: async function (connection, namespace = null) { if (!namespace) throw new Error("No namespace provided"); await connection.query( `DELETE FROM "${PGVector.tableName()}" WHERE namespace = $1`, [namespace] ); return true; }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); const { storeVectorResult, cachedVectorInformation, } = require("../../files"); let connection = null; try { const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; connection = await this.connect(); this.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); let vectorDimensions; if (cacheResult.exists) { const { chunks } = cacheResult; const documentVectors = []; const submissions = []; for (const chunk of chunks.flat()) { if (!vectorDimensions) vectorDimensions = chunk.values.length; const id = uuidv4(); const { id: _id, ...metadata } = chunk.metadata; documentVectors.push({ docId, vectorId: id }); submissions.push({ id: id, vector: chunk.values, metadata }); } await this.updateOrCreateCollection({ connection, submissions, namespace, dimensions: vectorDimensions, }); await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `xyz.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. const { SystemSettings } = require("../../../models/systemSettings"); const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); this.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const submissions = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); let vectorDimensions; if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { if (!vectorDimensions) vectorDimensions = vector.length; const vectorRecord = { id: uuidv4(), values: vector, metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); submissions.push({ id: vectorRecord.id, vector: vectorRecord.values, metadata: vectorRecord.metadata, }); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } if (vectors.length > 0) { const chunks = []; for (const chunk of toChunks(vectors, 500)) chunks.push(chunk); this.log("Inserting vectorized chunks into PGVector collection."); await this.updateOrCreateCollection({ connection, submissions, namespace, dimensions: vectorDimensions, }); await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (err) { this.log("addDocumentToNamespace", err.message); return { vectorized: false, error: err.message }; } finally { if (connection) await connection.end(); } }, /** * Delete a document from the namespace * @param {string} namespace * @param {string} docId * @returns {Promise<boolean>} */ deleteDocumentFromNamespace: async function (namespace, docId) { if (!namespace) throw new Error("No namespace provided"); if (!docId) throw new Error("No docId provided"); let connection = null; try { connection = await this.connect(); const exists = await this.namespaceExists(connection, namespace); if (!exists) throw new Error( `PGVector:deleteDocumentFromNamespace - namespace ${namespace} does not exist.` ); const { DocumentVectors } = require("../../../models/vectors"); const vectorIds = (await DocumentVectors.where({ docId })).map( (record) => record.vectorId ); if (vectorIds.length === 0) return; try { await connection.query(`BEGIN`); for (const vectorId of vectorIds) await connection.query( `DELETE FROM "${PGVector.tableName()}" WHERE id = $1`, [vectorId] ); await connection.query(`COMMIT`); } catch (err) { await connection.query(`ROLLBACK`); throw err; } this.log( `Deleted ${vectorIds.length} vectors from namespace ${namespace}` ); return true; } catch (err) { this.log( `Error deleting document from namespace ${namespace}: ${err.message}` ); return false; } finally { if (connection) await connection.end(); } }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { let connection = null; if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); try { connection = await this.connect(); const exists = await this.namespaceExists(connection, namespace); if (!exists) { this.log( `The namespace ${namespace} does not exist or has no vectors. Returning empty results.` ); return { contextTexts: [], sources: [], message: null, }; } const queryVector = await LLMConnector.embedTextInput(input); const result = await this.similarityResponse({ client: connection, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const { contextTexts, sourceDocuments } = result; const sources = sourceDocuments.map((metadata, i) => { return { metadata: { ...metadata, text: contextTexts[i] } }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; } catch (err) { return { error: err.message, success: false }; } finally { if (connection) await connection.end(); } }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); if (!(await this.dbTableExists())) return { message: "No table found in database" }; let connection = null; try { connection = await this.connect(); if (!(await this.namespaceExists(connection, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(connection, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; } catch (err) { return { message: `Error fetching stats for namespace ${namespace}: ${err.message}`, }; } finally { if (connection) await connection.end(); } }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("No namespace provided"); let connection = null; try { const existingCount = await this.namespaceCount(namespace); if (existingCount === 0) return { message: `Namespace ${namespace} does not exist or has no vectors.`, }; connection = await this.connect(); await this.deleteVectorsInNamespace(connection, namespace); return { message: `Namespace ${namespace} was deleted along with ${existingCount} vectors.`, }; } catch (err) { return { message: `Error deleting namespace ${namespace}: ${err.message}`, }; } finally { if (connection) await connection.end(); } }, /** * Reset the entire vector database table associated with anythingllm * @returns {Promise<{reset: boolean}>} */ reset: async function () { let connection = null; try { connection = await this.connect(); await connection.query(`DROP TABLE IF EXISTS "${PGVector.tableName()}"`); return { reset: true }; } catch (err) { return { reset: false }; } finally { if (connection) await connection.end(); } }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { text, vector: _v, _distance: _d, ...rest } = source; const metadata = rest.hasOwnProperty("metadata") ? rest.metadata : rest; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(text ? { text } : {}), }); } } return documents; }, }; module.exports.PGVector = PGVector;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/astra/index.js
server/utils/vectorDbProviders/astra/index.js
const { AstraDB: AstraClient } = require("@datastax/astra-db-ts"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { sourceIdentifier } = require("../../chats"); const sanitizeNamespace = (namespace) => { // If namespace already starts with ns_, don't add it again if (namespace.startsWith("ns_")) return namespace; // Remove any invalid characters, ensure starts with letter return `ns_${namespace.replace(/[^a-zA-Z0-9_]/g, "_")}`; }; // Add this helper method to check if collection exists more reliably const collectionExists = async function (client, namespace) { try { const collections = await AstraDB.allNamespaces(client); if (collections) { return collections.includes(namespace); } } catch (error) { console.log("Astra::collectionExists check error", error?.message || error); return false; // Return false for any error to allow creation attempt } }; const AstraDB = { name: "AstraDB", connect: async function () { if (process.env.VECTOR_DB !== "astra") throw new Error("AstraDB::Invalid ENV settings"); const client = new AstraClient( process?.env?.ASTRA_DB_APPLICATION_TOKEN, process?.env?.ASTRA_DB_ENDPOINT ); return { client }; }, heartbeat: async function () { return { heartbeat: Number(new Date()) }; }, // Astra interface will return a valid collection object even if the collection // does not actually exist. So we run a simple check which will always throw // when the table truly does not exist. Faster than iterating all collections. isRealCollection: async function (astraCollection = null) { if (!astraCollection) return false; return await astraCollection .countDocuments() .then(() => true) .catch(() => false); }, totalVectors: async function () { const { client } = await this.connect(); const collectionNames = await this.allNamespaces(client); var totalVectors = 0; for (const name of collectionNames) { const collection = await client.collection(name).catch(() => null); const count = await collection.countDocuments().catch(() => 0); totalVectors += count ? count : 0; } return totalVectors; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const namespace = await this.namespace(client, _namespace); return namespace?.vectorCount || 0; }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const sanitizedNamespace = sanitizeNamespace(namespace); const collection = await client .collection(sanitizedNamespace) .catch(() => null); if (!(await this.isRealCollection(collection))) return null; const count = await collection.countDocuments().catch((e) => { console.error("Astra::namespaceExists", e.message); return null; }); return { name: namespace, ...collection, vectorCount: typeof count === "number" ? count : 0, }; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); return await this.namespaceExists(client, namespace); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const sanitizedNamespace = sanitizeNamespace(namespace); const collection = await client.collection(sanitizedNamespace); return await this.isRealCollection(collection); }, deleteVectorsInNamespace: async function (client, namespace = null) { const sanitizedNamespace = sanitizeNamespace(namespace); await client.dropCollection(sanitizedNamespace); return true; }, // AstraDB requires a dimension aspect for collection creation // we pass this in from the first chunk to infer the dimensions like other // providers do. getOrCreateCollection: async function (client, namespace, dimensions = null) { const sanitizedNamespace = sanitizeNamespace(namespace); try { const exists = await collectionExists(client, sanitizedNamespace); if (!exists) { if (!dimensions) { throw new Error( `AstraDB:getOrCreateCollection Unable to infer vector dimension from input. Open an issue on Github for support.` ); } // Create new collection await client.createCollection(sanitizedNamespace, { vector: { dimension: dimensions, metric: "cosine", }, }); // Get the newly created collection return await client.collection(sanitizedNamespace); } return await client.collection(sanitizedNamespace); } catch (error) { console.error( "Astra::getOrCreateCollection error", error?.message || error ); throw error; } }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { let vectorDimension = null; const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const { chunks } = cacheResult; const documentVectors = []; vectorDimension = chunks[0][0].values.length || null; const collection = await this.getOrCreateCollection( client, namespace, vectorDimension ); if (!(await this.isRealCollection(collection))) throw new Error("Failed to create new AstraDB collection!", { namespace, }); for (const chunk of chunks) { // Before sending to Astra and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. const newChunks = chunk.map((chunk) => { const _id = uuidv4(); documentVectors.push({ docId, vectorId: _id }); return { _id: _id, $vector: chunk.values, metadata: chunk.metadata || {}, }; }); await collection.insertMany(newChunks); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: Math.min( 7500, TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ) ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { if (!vectorDimension) vectorDimension = vector.length; const vectorRecord = { _id: uuidv4(), $vector: vector, metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord._id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } const { client } = await this.connect(); const collection = await this.getOrCreateCollection( client, namespace, vectorDimension ); if (!(await this.isRealCollection(collection))) throw new Error("Failed to create new AstraDB collection!", { namespace, }); if (vectors.length > 0) { const chunks = []; console.log("Inserting vectorized chunks into Astra DB."); // AstraDB has maximum upsert size of 20 records per-request so we have to use a lower chunk size here // in order to do the queries - this takes a lot more time than other providers but there // is no way around it. This will save the vector-cache with the same layout, so we don't // have to chunk again for cached files. for (const chunk of toChunks(vectors, 20)) { chunks.push( chunk.map((c) => { return { id: c._id, values: c.$vector, metadata: c.metadata }; }) ); await collection.insertMany(chunk); } await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); namespace = sanitizeNamespace(namespace); if (!(await this.namespaceExists(client, namespace))) throw new Error( "Invalid namespace - has it been collected and populated yet?" ); const collection = await client.collection(namespace); const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); for (const id of vectorIds) { await collection.deleteMany({ _id: id, }); } const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); // Sanitize namespace before checking existence const sanitizedNamespace = sanitizeNamespace(namespace); if (!(await this.namespaceExists(client, sanitizedNamespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no namespace found for workspace in vector db!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client, namespace: sanitizedNamespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((metadata, i) => { return { ...metadata, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; // Namespace should already be sanitized, but let's be defensive const sanitizedNamespace = sanitizeNamespace(namespace); const collection = await client.collection(sanitizedNamespace); const responses = await collection .find( {}, { sort: { $vector: queryVector }, limit: topN, includeSimilarity: true, } ) .toArray(); responses.forEach((response) => { if (response.$similarity < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(response.metadata))) { console.log( "AstraDB: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(response.metadata.text); result.sourceDocuments.push({ ...response.metadata, score: response.$similarity, }); result.scores.push(response.$similarity); }); return result; }, allNamespaces: async function (client) { try { let header = new Headers(); header.append("Token", client?.httpClient?.applicationToken); header.append("Content-Type", "application/json"); let raw = JSON.stringify({ findCollections: {}, }); let requestOptions = { method: "POST", headers: header, body: raw, redirect: "follow", }; const call = await fetch(client?.httpClient?.baseUrl, requestOptions); const resp = await call?.text(); const collections = resp ? JSON.parse(resp)?.status?.collections : []; return collections; } catch (e) { console.error("Astra::AllNamespace", e); return []; } }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const details = await this.namespace(client, namespace); await this.deleteVectorsInNamespace(client, namespace); return { message: `Namespace ${namespace} was deleted along with ${ details?.vectorCount || "all" } vectors.`, }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { if (Object.keys(source).length > 0) { const metadata = source.hasOwnProperty("metadata") ? source.metadata : source; documents.push({ ...metadata, }); } } return documents; }, }; module.exports.AstraDB = AstraDB;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/pinecone/index.js
server/utils/vectorDbProviders/pinecone/index.js
const { Pinecone } = require("@pinecone-database/pinecone"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { sourceIdentifier } = require("../../chats"); const PineconeDB = { name: "Pinecone", connect: async function () { if (process.env.VECTOR_DB !== "pinecone") throw new Error("Pinecone::Invalid ENV settings"); const client = new Pinecone({ apiKey: process.env.PINECONE_API_KEY, }); const pineconeIndex = client.Index(process.env.PINECONE_INDEX); const { status } = await client.describeIndex(process.env.PINECONE_INDEX); if (!status.ready) throw new Error("Pinecone::Index not ready."); return { client, pineconeIndex, indexName: process.env.PINECONE_INDEX }; }, totalVectors: async function () { const { pineconeIndex } = await this.connect(); const { namespaces } = await pineconeIndex.describeIndexStats(); return Object.values(namespaces).reduce( (a, b) => a + (b?.recordCount || 0), 0 ); }, namespaceCount: async function (_namespace = null) { const { pineconeIndex } = await this.connect(); const namespace = await this.namespace(pineconeIndex, _namespace); return namespace?.recordCount || 0; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const pineconeNamespace = client.namespace(namespace); const response = await pineconeNamespace.query({ vector: queryVector, topK: topN, includeMetadata: true, }); response.matches.forEach((match) => { if (match.score < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(match.metadata))) { console.log( "Pinecone: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(match.metadata.text); result.sourceDocuments.push({ ...match.metadata, score: match.score, }); result.scores.push(match.score); }); return result; }, namespace: async function (index, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const { namespaces } = await index.describeIndexStats(); return namespaces.hasOwnProperty(namespace) ? namespaces[namespace] : null; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { pineconeIndex } = await this.connect(); return await this.namespaceExists(pineconeIndex, namespace); }, namespaceExists: async function (index, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const { namespaces } = await index.describeIndexStats(); return namespaces.hasOwnProperty(namespace); }, deleteVectorsInNamespace: async function (index, namespace = null) { const pineconeNamespace = index.namespace(namespace); await pineconeNamespace.deleteAll(); return true; }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { pineconeIndex } = await this.connect(); const pineconeNamespace = pineconeIndex.namespace(namespace); const { chunks } = cacheResult; const documentVectors = []; for (const chunk of chunks) { // Before sending to Pinecone and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. const newChunks = chunk.map((chunk) => { const id = uuidv4(); documentVectors.push({ docId, vectorId: id }); return { ...chunk, id }; }); await pineconeNamespace.upsert([...newChunks]); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `PineconeStore.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. // https://github.com/hwchase17/langchainjs/blob/2def486af734c0ca87285a48f1a04c057ab74bdf/langchain/src/vectorstores/pinecone.ts#L167 const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { const vectorRecord = { id: uuidv4(), values: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. // https://github.com/hwchase17/langchainjs/blob/2def486af734c0ca87285a48f1a04c057ab74bdf/langchain/src/vectorstores/pinecone.ts#L64 metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } if (vectors.length > 0) { const chunks = []; const { pineconeIndex } = await this.connect(); const pineconeNamespace = pineconeIndex.namespace(namespace); console.log("Inserting vectorized chunks into Pinecone."); for (const chunk of toChunks(vectors, 100)) { chunks.push(chunk); await pineconeNamespace.upsert([...chunk]); } await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { pineconeIndex } = await this.connect(); if (!(await this.namespaceExists(pineconeIndex, namespace))) return; const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); const pineconeNamespace = pineconeIndex.namespace(namespace); for (const batchOfVectorIds of toChunks(vectorIds, 1000)) { await pineconeNamespace.deleteMany(batchOfVectorIds); } const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); return true; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { pineconeIndex } = await this.connect(); if (!(await this.namespaceExists(pineconeIndex, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(pineconeIndex, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { pineconeIndex } = await this.connect(); if (!(await this.namespaceExists(pineconeIndex, namespace))) throw new Error("Namespace by that name does not exist."); const details = await this.namespace(pineconeIndex, namespace); await this.deleteVectorsInNamespace(pineconeIndex, namespace); return { message: `Namespace ${namespace} was deleted along with ${details.vectorCount} vectors.`, }; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { pineconeIndex } = await this.connect(); if (!(await this.namespaceExists(pineconeIndex, namespace))) throw new Error( "Invalid namespace - has it been collected and populated yet?" ); const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client: pineconeIndex, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((doc, i) => { return { metadata: doc, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { metadata = {} } = source; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(source.hasOwnProperty("pageContent") ? { text: source.pageContent } : {}), }); } } return documents; }, }; module.exports.Pinecone = PineconeDB;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/lance/index.js
server/utils/vectorDbProviders/lance/index.js
const lancedb = require("@lancedb/lancedb"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { sourceIdentifier } = require("../../chats"); const { NativeEmbeddingReranker } = require("../../EmbeddingRerankers/native"); /** * LancedDB Client connection object * @typedef {import('@lancedb/lancedb').Connection} LanceClient */ const LanceDb = { uri: `${ !!process.env.STORAGE_DIR ? `${process.env.STORAGE_DIR}/` : "./storage/" }lancedb`, name: "LanceDb", /** @returns {Promise<{client: LanceClient}>} */ connect: async function () { const client = await lancedb.connect(this.uri); return { client }; }, distanceToSimilarity: function (distance = null) { if (distance === null || typeof distance !== "number") return 0.0; if (distance >= 1.0) return 1; if (distance < 0) return 1 - Math.abs(distance); return 1 - distance; }, heartbeat: async function () { await this.connect(); return { heartbeat: Number(new Date()) }; }, tables: async function () { const { client } = await this.connect(); return await client.tableNames(); }, totalVectors: async function () { const { client } = await this.connect(); const tables = await client.tableNames(); let count = 0; for (const tableName of tables) { const table = await client.openTable(tableName); count += await table.countRows(); } return count; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const exists = await this.namespaceExists(client, _namespace); if (!exists) return 0; const table = await client.openTable(_namespace); return (await table.countRows()) || 0; }, /** * Performs a SimilaritySearch + Reranking on a namespace. * @param {Object} params - The parameters for the rerankedSimilarityResponse. * @param {Object} params.client - The vectorDB client. * @param {string} params.namespace - The namespace to search in. * @param {string} params.query - The query to search for (plain text). * @param {number[]} params.queryVector - The vector of the query. * @param {number} params.similarityThreshold - The threshold for similarity. * @param {number} params.topN - the number of results to return from this process. * @param {string[]} params.filterIdentifiers - The identifiers of the documents to filter out. * @returns */ rerankedSimilarityResponse: async function ({ client, namespace, query, queryVector, topN = 4, similarityThreshold = 0.25, filterIdentifiers = [], }) { const reranker = new NativeEmbeddingReranker(); const collection = await client.openTable(namespace); const totalEmbeddings = await this.namespaceCount(namespace); const result = { contextTexts: [], sourceDocuments: [], scores: [], }; /** * For reranking, we want to work with a larger number of results than the topN. * This is because the reranker can only rerank the results it it given and we dont auto-expand the results. * We want to give the reranker a larger number of results to work with. * * However, we cannot make this boundless as reranking is expensive and time consuming. * So we limit the number of results to a maximum of 50 and a minimum of 10. * This is a good balance between the number of results to rerank and the cost of reranking * and ensures workspaces with 10K embeddings will still rerank within a reasonable timeframe on base level hardware. * * Benchmarks: * On Intel Mac: 2.6 GHz 6-Core Intel Core i7 - 20 docs reranked in ~5.2 sec */ const searchLimit = Math.max( 10, Math.min(50, Math.ceil(totalEmbeddings * 0.1)) ); const vectorSearchResults = await collection .vectorSearch(queryVector) .distanceType("cosine") .limit(searchLimit) .toArray(); await reranker .rerank(query, vectorSearchResults, { topK: topN }) .then((rerankResults) => { rerankResults.forEach((item) => { if (this.distanceToSimilarity(item._distance) < similarityThreshold) return; const { vector: _, ...rest } = item; if (filterIdentifiers.includes(sourceIdentifier(rest))) { console.log( "LanceDB: A source was filtered from context as it's parent document is pinned." ); return; } const score = item?.rerank_score || this.distanceToSimilarity(item._distance); result.contextTexts.push(rest.text); result.sourceDocuments.push({ ...rest, score, }); result.scores.push(score); }); }) .catch((e) => { console.error(e); console.error("LanceDB::rerankedSimilarityResponse", e.message); }); return result; }, /** * Performs a SimilaritySearch on a give LanceDB namespace. * @param {Object} params * @param {LanceClient} params.client * @param {string} params.namespace * @param {number[]} params.queryVector * @param {number} params.similarityThreshold * @param {number} params.topN * @param {string[]} params.filterIdentifiers * @returns */ similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const collection = await client.openTable(namespace); const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const response = await collection .vectorSearch(queryVector) .distanceType("cosine") .limit(topN) .toArray(); response.forEach((item) => { if (this.distanceToSimilarity(item._distance) < similarityThreshold) return; const { vector: _, ...rest } = item; if (filterIdentifiers.includes(sourceIdentifier(rest))) { console.log( "LanceDB: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(rest.text); result.sourceDocuments.push({ ...rest, score: this.distanceToSimilarity(item._distance), }); result.scores.push(this.distanceToSimilarity(item._distance)); }); return result; }, /** * * @param {LanceClient} client * @param {string} namespace * @returns */ namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client.openTable(namespace).catch(() => false); if (!collection) return null; return { ...collection, }; }, /** * * @param {LanceClient} client * @param {number[]} data * @param {string} namespace * @returns */ updateOrCreateCollection: async function (client, data = [], namespace) { const hasNamespace = await this.hasNamespace(namespace); if (hasNamespace) { const collection = await client.openTable(namespace); await collection.add(data); return true; } await client.createTable(namespace, data); return true; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); const exists = await this.namespaceExists(client, namespace); return exists; }, /** * * @param {LanceClient} client * @param {string} namespace * @returns */ namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collections = await client.tableNames(); return collections.includes(namespace); }, /** * * @param {LanceClient} client * @param {string} namespace * @returns */ deleteVectorsInNamespace: async function (client, namespace = null) { await client.dropTable(namespace); return true; }, deleteDocumentFromNamespace: async function (namespace, docId) { const { client } = await this.connect(); const exists = await this.namespaceExists(client, namespace); if (!exists) { console.error( `LanceDB:deleteDocumentFromNamespace - namespace ${namespace} does not exist.` ); return; } const { DocumentVectors } = require("../../../models/vectors"); const table = await client.openTable(namespace); const vectorIds = (await DocumentVectors.where({ docId })).map( (record) => record.vectorId ); if (vectorIds.length === 0) return; await table.delete(`id IN (${vectorIds.map((v) => `'${v}'`).join(",")})`); return true; }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const { chunks } = cacheResult; const documentVectors = []; const submissions = []; for (const chunk of chunks) { chunk.forEach((chunk) => { const id = uuidv4(); const { id: _id, ...metadata } = chunk.metadata; documentVectors.push({ docId, vectorId: id }); submissions.push({ id: id, vector: chunk.values, ...metadata }); }); } await this.updateOrCreateCollection(client, submissions, namespace); await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `xyz.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const submissions = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { const vectorRecord = { id: uuidv4(), values: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. // https://github.com/hwchase17/langchainjs/blob/2def486af734c0ca87285a48f1a04c057ab74bdf/langchain/src/vectorstores/pinecone.ts#L64 metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); submissions.push({ ...vectorRecord.metadata, id: vectorRecord.id, vector: vectorRecord.values, }); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } if (vectors.length > 0) { const chunks = []; for (const chunk of toChunks(vectors, 500)) chunks.push(chunk); console.log("Inserting vectorized chunks into LanceDB collection."); const { client } = await this.connect(); await this.updateOrCreateCollection(client, submissions, namespace); await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], rerank = false, }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const result = rerank ? await this.rerankedSimilarityResponse({ client, namespace, query: input, queryVector, similarityThreshold, topN, filterIdentifiers, }) : await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const { contextTexts, sourceDocuments } = result; const sources = sourceDocuments.map((metadata, i) => { return { metadata: { ...metadata, text: contextTexts[i] } }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); await this.deleteVectorsInNamespace(client, namespace); return { message: `Namespace ${namespace} was deleted.`, }; }, reset: async function () { const { client } = await this.connect(); const fs = require("fs"); fs.rm(`${client.uri}`, { recursive: true }, () => null); return { reset: true }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { text, vector: _v, _distance: _d, ...rest } = source; const metadata = rest.hasOwnProperty("metadata") ? rest.metadata : rest; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(text ? { text } : {}), }); } } return documents; }, }; module.exports.LanceDb = LanceDb;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/zilliz/index.js
server/utils/vectorDbProviders/zilliz/index.js
const { DataType, MetricType, IndexType, MilvusClient, } = require("@zilliz/milvus2-sdk-node"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { v4: uuidv4 } = require("uuid"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { sourceIdentifier } = require("../../chats"); // Zilliz is basically a copy of Milvus DB class with a different constructor // to connect to the cloud const Zilliz = { name: "Zilliz", // Milvus/Zilliz only allows letters, numbers, and underscores in collection names // so we need to enforce that by re-normalizing the names when communicating with // the DB. // If the first char of the collection is not an underscore or letter the collection name will be invalid. normalize: function (inputString) { let normalized = inputString.replace(/[^a-zA-Z0-9_]/g, "_"); if (new RegExp(/^[a-zA-Z_]/).test(normalized.slice(0, 1))) normalized = `anythingllm_${normalized}`; return normalized; }, connect: async function () { if (process.env.VECTOR_DB !== "zilliz") throw new Error("Zilliz::Invalid ENV settings"); const client = new MilvusClient({ address: process.env.ZILLIZ_ENDPOINT, token: process.env.ZILLIZ_API_TOKEN, }); const { isHealthy } = await client.checkHealth(); if (!isHealthy) throw new Error( "Zilliz::Invalid Heartbeat received - is the instance online?" ); return { client }; }, heartbeat: async function () { await this.connect(); return { heartbeat: Number(new Date()) }; }, totalVectors: async function () { const { client } = await this.connect(); const { collection_names } = await client.listCollections(); const total = collection_names.reduce(async (acc, collection_name) => { const statistics = await client.getCollectionStatistics({ collection_name: this.normalize(collection_name), }); return Number(acc) + Number(statistics?.data?.row_count ?? 0); }, 0); return total; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const statistics = await client.getCollectionStatistics({ collection_name: this.normalize(_namespace), }); return Number(statistics?.data?.row_count ?? 0); }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client .getCollectionStatistics({ collection_name: this.normalize(namespace) }) .catch(() => null); return collection; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); return await this.namespaceExists(client, namespace); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const { value } = await client .hasCollection({ collection_name: this.normalize(namespace) }) .catch((e) => { console.error("Zilliz::namespaceExists", e.message); return { value: false }; }); return value; }, deleteVectorsInNamespace: async function (client, namespace = null) { await client.dropCollection({ collection_name: this.normalize(namespace) }); return true; }, // Zilliz requires a dimension aspect for collection creation // we pass this in from the first chunk to infer the dimensions like other // providers do. getOrCreateCollection: async function (client, namespace, dimensions = null) { const isExists = await this.namespaceExists(client, namespace); if (!isExists) { if (!dimensions) throw new Error( `Zilliz:getOrCreateCollection Unable to infer vector dimension from input. Open an issue on GitHub for support.` ); await client.createCollection({ collection_name: this.normalize(namespace), fields: [ { name: "id", description: "id", data_type: DataType.VarChar, max_length: 255, is_primary_key: true, }, { name: "vector", description: "vector", data_type: DataType.FloatVector, dim: dimensions, }, { name: "metadata", description: "metadata", data_type: DataType.JSON, }, ], }); await client.createIndex({ collection_name: this.normalize(namespace), field_name: "vector", index_type: IndexType.AUTOINDEX, metric_type: MetricType.COSINE, }); await client.loadCollectionSync({ collection_name: this.normalize(namespace), }); } }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { let vectorDimension = null; const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const { chunks } = cacheResult; const documentVectors = []; vectorDimension = chunks[0][0].values.length || null; await this.getOrCreateCollection(client, namespace, vectorDimension); for (const chunk of chunks) { // Before sending to Pinecone and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. const newChunks = chunk.map((chunk) => { const id = uuidv4(); documentVectors.push({ docId, vectorId: id }); return { id, vector: chunk.values, metadata: chunk.metadata }; }); const insertResult = await client.insert({ collection_name: this.normalize(namespace), data: newChunks, }); if (insertResult?.status.error_code !== "Success") { throw new Error( `Error embedding into Zilliz! Reason:${insertResult?.status.reason}` ); } } await DocumentVectors.bulkInsert(documentVectors); await client.flushSync({ collection_names: [this.normalize(namespace)], }); return { vectorized: true, error: null }; } } const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { if (!vectorDimension) vectorDimension = vector.length; const vectorRecord = { id: uuidv4(), values: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } if (vectors.length > 0) { const chunks = []; const { client } = await this.connect(); await this.getOrCreateCollection(client, namespace, vectorDimension); console.log("Inserting vectorized chunks into Zilliz."); for (const chunk of toChunks(vectors, 100)) { chunks.push(chunk); const insertResult = await client.insert({ collection_name: this.normalize(namespace), data: chunk.map((item) => ({ id: item.id, vector: item.values, metadata: item.metadata, })), }); if (insertResult?.status.error_code !== "Success") { throw new Error( `Error embedding into Zilliz! Reason:${insertResult?.status.reason}` ); } } await storeVectorResult(chunks, fullFilePath); await client.flushSync({ collection_names: [this.normalize(namespace)], }); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) return; const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); const queryIn = vectorIds.map((v) => `'${v}'`).join(","); await client.deleteEntities({ collection_name: this.normalize(namespace), expr: `id in [${queryIn}]`, }); const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); // Even after flushing Zilliz can take some time to re-calc the count // so all we can hope to do is flushSync so that the count can be correct // on a later call. await client.flushSync({ collection_names: [this.normalize(namespace)] }); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((doc, i) => { return { metadata: doc, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const response = await client.search({ collection_name: this.normalize(namespace), vectors: queryVector, limit: topN, }); response.results.forEach((match) => { if (match.score < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(match.metadata))) { console.log( "Zilliz: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(match.metadata.text); result.sourceDocuments.push({ ...match.metadata, score: match.score, }); result.scores.push(match.score); }); return result; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const statistics = await this.namespace(client, namespace); await this.deleteVectorsInNamespace(client, namespace); const vectorCount = Number(statistics?.data?.row_count ?? 0); return { message: `Namespace ${namespace} was deleted along with ${vectorCount} vectors.`, }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { metadata = {} } = source; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(source.text ? { text: source.text } : {}), }); } } return documents; }, }; module.exports.Zilliz = Zilliz;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/chromacloud/index.js
server/utils/vectorDbProviders/chromacloud/index.js
const { CloudClient } = require("chromadb"); const { Chroma } = require("../chroma"); const { toChunks } = require("../../helpers"); /** * ChromaCloud works nearly the same as Chroma so we can just extend the * Chroma class and override the connect method to use the CloudClient for major differences in API functionality. */ const ChromaCloud = { ...Chroma, name: "ChromaCloud", /** * Basic quota/limitations for Chroma Cloud for accounts. Does not lookup client-specific limits. * @see https://docs.trychroma.com/cloud/quotas-limits */ limits: { maxEmbeddingDim: 4_096, maxDocumentBytes: 16_384, maxMetadataBytes: 4_096, maxRecordsPerWrite: 300, }, connect: async function () { if (process.env.VECTOR_DB !== "chromacloud") throw new Error("ChromaCloud::Invalid ENV settings"); const client = new CloudClient({ apiKey: process.env.CHROMACLOUD_API_KEY, tenant: process.env.CHROMACLOUD_TENANT, database: process.env.CHROMACLOUD_DATABASE, }); const isAlive = await client.heartbeat(); if (!isAlive) throw new Error( "ChromaCloud::Invalid Heartbeat received - is the instance online?" ); return { client }; }, /** * Chroma Cloud has some basic limitations on upserts to protect performance and latency. * Local deployments do not have these limitations since they are self-hosted. * * This method, if cloud, will do some simple logic/heuristics to ensure that the upserts are not too large. * Otherwise, it may throw a 422. * @param {import("chromadb").Collection} collection * @param {{ids: string[], embeddings: number[], metadatas: Record<string, any>[], documents: string[]}[]} submissions * @returns {Promise<boolean>} True if the upsert was successful, false otherwise. * If the upsert was not successful, the error message will be returned. */ smartAdd: async function (collection, submission) { const testSubmission = { id: submission.ids[0], embedding: submission.embeddings[0], metadata: submission.metadatas[0], document: submission.documents[0], }; if (testSubmission.embedding.length > this.limits.maxEmbeddingDim) console.warn( `ChromaCloud::Embedding dimension too large (default max is ${this.limits.maxEmbeddingDim}). Got ${testSubmission.embedding.length}. Upsert may fail!` ); if (testSubmission.document.length > this.limits.maxDocumentBytes) console.warn( `ChromaCloud::Document length too large (default max is ${this.limits.maxDocumentBytes}). Got ${testSubmission.document.length}. Upsert may fail!` ); if ( JSON.stringify(testSubmission.metadata).length > this.limits.maxMetadataBytes ) console.warn( `ChromaCloud::Metadata length too large (default max is ${this.limits.maxMetadataBytes}). Got ${JSON.stringify(testSubmission.metadata).length}. Upsert may fail!` ); // If the submissions are not too large, just add them directly. if (submission.ids.length <= this.limits.maxRecordsPerWrite) { await collection.add(submission); return true; } console.log( `ChromaCloud::Upsert Payload is too large (max is ${this.limits.maxRecordsPerWrite} records). Splitting into chunks of ${this.limits.maxRecordsPerWrite} records.` ); const chunks = []; let chunkedSubmission = { ids: [], embeddings: [], metadatas: [], documents: [], }; for (let i = 0; i < submission.ids.length; i++) { chunkedSubmission.ids.push(submission.ids[i]); chunkedSubmission.embeddings.push(submission.embeddings[i]); chunkedSubmission.metadatas.push(submission.metadatas[i]); chunkedSubmission.documents.push(submission.documents[i]); if (chunkedSubmission.ids.length === this.limits.maxRecordsPerWrite) { console.log( `ChromaCloud::Adding chunk payload ${chunks.length + 1} of ${Math.ceil(submission.ids.length / this.limits.maxRecordsPerWrite)}` ); chunks.push(chunkedSubmission); chunkedSubmission = { ids: [], embeddings: [], metadatas: [], documents: [], }; } } // Push remaining submissions to the last chunk if (chunkedSubmission.ids.length > 0) chunks.push(chunkedSubmission); let counter = 1; for (const chunk of chunks) { await collection.add(chunk); counter++; } return true; }, /** * This method is a wrapper around the ChromaCollection.delete method. * It will return the result of the delete method directly. * Chroma Cloud has some basic limitations on deletes to protect performance and latency. * Local deployments do not have these limitations since they are self-hosted. * * This method, if cloud, will do some simple logic/heuristics to ensure that the deletes are not too large. * Otherwise, it may throw a 422. * @param {import("chromadb").Collection} collection * @param {string[]} vectorIds * @returns {Promise<boolean>} True if the delete was successful, false otherwise. */ smartDelete: async function (collection, vectorIds) { if (vectorIds.length <= this.limits.maxRecordsPerWrite) return await collection.delete({ ids: vectorIds }); console.log( `ChromaCloud::Delete Payload is too large (max is ${this.limits.maxRecordsPerWrite} records). Splitting into chunks of ${this.limits.maxRecordsPerWrite} records.` ); const chunks = toChunks(vectorIds, this.limits.maxRecordsPerWrite); let counter = 1; for (const chunk of chunks) { console.log(`ChromaCloud::Deleting chunk ${counter} of ${chunks.length}`); await collection.delete({ ids: chunk }); counter++; } return true; }, }; module.exports.ChromaCloud = ChromaCloud;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/chroma/index.js
server/utils/vectorDbProviders/chroma/index.js
const { ChromaClient } = require("chromadb"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { parseAuthHeader } = require("../../http"); const { sourceIdentifier } = require("../../chats"); const COLLECTION_REGEX = new RegExp( /^(?!\d+\.\d+\.\d+\.\d+$)(?!.*\.\.)(?=^[a-zA-Z0-9][a-zA-Z0-9_-]{1,61}[a-zA-Z0-9]$).{3,63}$/ ); const Chroma = { name: "Chroma", // Chroma DB has specific requirements for collection names: // (1) Must contain 3-63 characters // (2) Must start and end with an alphanumeric character // (3) Can only contain alphanumeric characters, underscores, or hyphens // (4) Cannot contain two consecutive periods (..) // (5) Cannot be a valid IPv4 address // We need to enforce these rules by normalizing the collection names // before communicating with the Chroma DB. normalize: function (inputString) { if (COLLECTION_REGEX.test(inputString)) return inputString; let normalized = inputString.replace(/[^a-zA-Z0-9_-]/g, "-"); // Replace consecutive periods with a single period (if any) normalized = normalized.replace(/\.\.+/g, "."); // Ensure the name doesn't start with a non-alphanumeric character if (normalized[0] && !/^[a-zA-Z0-9]$/.test(normalized[0])) { normalized = "anythingllm-" + normalized.slice(1); } // Ensure the name doesn't end with a non-alphanumeric character if ( normalized[normalized.length - 1] && !/^[a-zA-Z0-9]$/.test(normalized[normalized.length - 1]) ) { normalized = normalized.slice(0, -1); } // Ensure the length is between 3 and 63 characters if (normalized.length < 3) { normalized = `anythingllm-${normalized}`; } else if (normalized.length > 63) { // Recheck the norm'd name if sliced since its ending can still be invalid. normalized = this.normalize(normalized.slice(0, 63)); } // Ensure the name is not an IPv4 address if (/^\d+\.\d+\.\d+\.\d+$/.test(normalized)) { normalized = "-" + normalized.slice(1); } return normalized; }, connect: async function () { if (process.env.VECTOR_DB !== "chroma") throw new Error("Chroma::Invalid ENV settings"); const client = new ChromaClient({ path: process.env.CHROMA_ENDPOINT, // if not set will fallback to localhost:8000 ...(!!process.env.CHROMA_API_HEADER && !!process.env.CHROMA_API_KEY ? { fetchOptions: { headers: parseAuthHeader( process.env.CHROMA_API_HEADER || "X-Api-Key", process.env.CHROMA_API_KEY ), }, } : {}), }); const isAlive = await client.heartbeat(); if (!isAlive) throw new Error( "ChromaDB::Invalid Heartbeat received - is the instance online?" ); return { client }; }, heartbeat: async function () { const { client } = await this.connect(); return { heartbeat: await client.heartbeat() }; }, totalVectors: async function () { const { client } = await this.connect(); const collections = await client.listCollections(); var totalVectors = 0; for (const collectionObj of collections) { const collection = await client .getCollection({ name: collectionObj.name }) .catch(() => null); if (!collection) continue; totalVectors += await collection.count(); } return totalVectors; }, distanceToSimilarity: function (distance = null) { if (distance === null || typeof distance !== "number") return 0.0; if (distance >= 1.0) return 1; if (distance < 0) return 1 - Math.abs(distance); return 1 - distance; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const namespace = await this.namespace(client, this.normalize(_namespace)); return namespace?.vectorCount || 0; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const collection = await client.getCollection({ name: this.normalize(namespace), }); const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const response = await collection.query({ queryEmbeddings: queryVector, nResults: topN, }); response.ids[0].forEach((_, i) => { const similarity = this.distanceToSimilarity(response.distances[0][i]); if (similarity < similarityThreshold) return; if ( filterIdentifiers.includes(sourceIdentifier(response.metadatas[0][i])) ) { console.log( "Chroma: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(response.documents[0][i]); result.sourceDocuments.push(response.metadatas[0][i]); result.scores.push(similarity); }); return result; }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client .getCollection({ name: this.normalize(namespace) }) .catch(() => null); if (!collection) return null; return { ...collection, vectorCount: await collection.count(), }; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); return await this.namespaceExists(client, this.normalize(namespace)); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client .getCollection({ name: this.normalize(namespace) }) .catch((e) => { console.error("ChromaDB::namespaceExists", e.message); return null; }); return !!collection; }, deleteVectorsInNamespace: async function (client, namespace = null) { await client.deleteCollection({ name: this.normalize(namespace) }); return true; }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const collection = await client.getOrCreateCollection({ name: this.normalize(namespace), // returns [-1, 1] unit vector metadata: { "hnsw:space": "cosine" }, }); const { chunks } = cacheResult; const documentVectors = []; for (const chunk of chunks) { const submission = { ids: [], embeddings: [], metadatas: [], documents: [], }; // Before sending to Chroma and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. chunk.forEach((chunk) => { const id = uuidv4(); const { id: _id, ...metadata } = chunk.metadata; documentVectors.push({ docId, vectorId: id }); submission.ids.push(id); submission.embeddings.push(chunk.values); submission.metadatas.push(metadata); submission.documents.push(metadata.text); }); await this.smartAdd(collection, submission); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `Chroma.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); const submission = { ids: [], embeddings: [], metadatas: [], documents: [], }; if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { const vectorRecord = { id: uuidv4(), values: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. // https://github.com/hwchase17/langchainjs/blob/2def486af734c0ca87285a48f1a04c057ab74bdf/langchain/src/vectorstores/pinecone.ts#L64 metadata: { ...metadata, text: textChunks[i] }, }; submission.ids.push(vectorRecord.id); submission.embeddings.push(vectorRecord.values); submission.metadatas.push(metadata); submission.documents.push(textChunks[i]); vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } const { client } = await this.connect(); const collection = await client.getOrCreateCollection({ name: this.normalize(namespace), metadata: { "hnsw:space": "cosine" }, }); if (vectors.length > 0) { const chunks = []; console.log("Inserting vectorized chunks into Chroma collection."); for (const chunk of toChunks(vectors, 500)) chunks.push(chunk); try { await this.smartAdd(collection, submission); console.log( `Successfully added ${submission.ids.length} vectors to collection ${this.normalize(namespace)}` ); } catch (error) { console.error("Error adding to ChromaDB:", error); throw new Error(`Error embedding into ChromaDB: ${error.message}`); } await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) return; const collection = await client.getCollection({ name: this.normalize(namespace), }); const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); await this.smartDelete(collection, vectorIds); const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, this.normalize(namespace)))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments, scores } = await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((metadata, i) => ({ metadata: { ...metadata, text: contextTexts[i], score: scores?.[i] || null, }, })); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, this.normalize(namespace)))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, this.normalize(namespace)); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, this.normalize(namespace)))) throw new Error("Namespace by that name does not exist."); const details = await this.namespace(client, this.normalize(namespace)); await this.deleteVectorsInNamespace(client, this.normalize(namespace)); return { message: `Namespace ${namespace} was deleted along with ${details?.vectorCount} vectors.`, }; }, reset: async function () { const { client } = await this.connect(); await client.reset(); return { reset: true }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { metadata = {} } = source; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(source.hasOwnProperty("pageContent") ? { text: source.pageContent } : {}), }); } } return documents; }, /** * This method is a wrapper around the ChromaCollection.add method. * It will return true if the add was successful, false otherwise. * For local deployments, this will be the same as calling the add method directly since there are no limitations. * @param {import("chromadb").Collection} collection * @param {{ids: string[], embeddings: number[], metadatas: Record<string, any>[], documents: string[]}[]} submissions * @returns {Promise<boolean>} True if the add was successful, false otherwise. */ smartAdd: async function (collection, submissions) { await collection.add(submissions); return true; }, /** * This method is a wrapper around the ChromaCollection.delete method. * It will return the result of the delete method directly. * For local deployments, this will be the same as calling the delete method directly since there are no limitations. * @param {import("chromadb").Collection} collection * @param {string[]} vectorIds * @returns {Promise<boolean>} True if the delete was successful, false otherwise. */ smartDelete: async function (collection, vectorIds) { await collection.delete({ ids: vectorIds }); return true; }, }; module.exports.Chroma = Chroma;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/qdrant/index.js
server/utils/vectorDbProviders/qdrant/index.js
const { QdrantClient } = require("@qdrant/js-client-rest"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { v4: uuidv4 } = require("uuid"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { sourceIdentifier } = require("../../chats"); const QDrant = { name: "QDrant", connect: async function () { if (process.env.VECTOR_DB !== "qdrant") throw new Error("QDrant::Invalid ENV settings"); const client = new QdrantClient({ url: process.env.QDRANT_ENDPOINT, ...(process.env.QDRANT_API_KEY ? { apiKey: process.env.QDRANT_API_KEY } : {}), }); const isAlive = (await client.api("cluster")?.clusterStatus())?.ok || false; if (!isAlive) throw new Error( "QDrant::Invalid Heartbeat received - is the instance online?" ); return { client }; }, heartbeat: async function () { await this.connect(); return { heartbeat: Number(new Date()) }; }, totalVectors: async function () { const { client } = await this.connect(); const { collections } = await client.getCollections(); var totalVectors = 0; for (const collection of collections) { if (!collection || !collection.name) continue; totalVectors += (await this.namespace(client, collection.name))?.vectorCount || 0; } return totalVectors; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const namespace = await this.namespace(client, _namespace); return namespace?.vectorCount || 0; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const responses = await client.search(namespace, { vector: queryVector, limit: topN, with_payload: true, }); responses.forEach((response) => { if (response.score < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(response?.payload))) { console.log( "QDrant: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(response?.payload?.text || ""); result.sourceDocuments.push({ ...(response?.payload || {}), id: response.id, score: response.score, }); result.scores.push(response.score); }); return result; }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client.getCollection(namespace).catch(() => null); if (!collection) return null; return { name: namespace, ...collection, vectorCount: (await client.count(namespace, { exact: true })).count, }; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); return await this.namespaceExists(client, namespace); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client.getCollection(namespace).catch((e) => { console.error("QDrant::namespaceExists", e.message); return null; }); return !!collection; }, deleteVectorsInNamespace: async function (client, namespace = null) { await client.deleteCollection(namespace); return true; }, // QDrant requires a dimension aspect for collection creation // we pass this in from the first chunk to infer the dimensions like other // providers do. getOrCreateCollection: async function (client, namespace, dimensions = null) { if (await this.namespaceExists(client, namespace)) { return await client.getCollection(namespace); } if (!dimensions) throw new Error( `Qdrant:getOrCreateCollection Unable to infer vector dimension from input. Open an issue on GitHub for support.` ); await client.createCollection(namespace, { vectors: { size: dimensions, distance: "Cosine", }, }); return await client.getCollection(namespace); }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { let vectorDimension = null; const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const { chunks } = cacheResult; const documentVectors = []; vectorDimension = chunks[0][0]?.vector?.length ?? chunks[0][0]?.values?.length ?? null; const collection = await this.getOrCreateCollection( client, namespace, vectorDimension ); if (!collection) throw new Error("Failed to create new QDrant collection!", { namespace, }); for (const chunk of chunks) { const submission = { ids: [], vectors: [], payloads: [], }; // Before sending to Qdrant and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. // The id property must be defined or else it will be unable to be managed by ALLM. chunk.forEach((chunk) => { const id = uuidv4(); if (chunk?.payload?.hasOwnProperty("id")) { const { id: _id, ...payload } = chunk.payload; documentVectors.push({ docId, vectorId: id }); submission.ids.push(id); submission.vectors.push(chunk.vector); submission.payloads.push(payload); } else { console.error( "The 'id' property is not defined in chunk.payload - it will be omitted from being inserted in QDrant collection." ); } }); const additionResult = await client.upsert(namespace, { wait: true, batch: { ...submission }, }); if (additionResult?.status !== "completed") throw new Error("Error embedding into QDrant", additionResult); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } } // If we are here then we are going to embed and store a novel document. // We have to do this manually as opposed to using LangChains `Qdrant.fromDocuments` // because we then cannot atomically control our namespace to granularly find/remove documents // from vectordb. const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); const submission = { ids: [], vectors: [], payloads: [], }; if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { if (!vectorDimension) vectorDimension = vector.length; const vectorRecord = { id: uuidv4(), vector: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. // https://github.com/hwchase17/langchainjs/blob/2def486af734c0ca87285a48f1a04c057ab74bdf/langchain/src/vectorstores/pinecone.ts#L64 payload: { ...metadata, text: textChunks[i] }, }; submission.ids.push(vectorRecord.id); submission.vectors.push(vectorRecord.vector); submission.payloads.push(vectorRecord.payload); vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } const { client } = await this.connect(); const collection = await this.getOrCreateCollection( client, namespace, vectorDimension ); if (!collection) throw new Error("Failed to create new QDrant collection!", { namespace, }); if (vectors.length > 0) { const chunks = []; console.log("Inserting vectorized chunks into QDrant collection."); for (const chunk of toChunks(vectors, 500)) { const batchIds = [], batchVectors = [], batchPayloads = []; chunks.push(chunk); chunk.forEach((v) => { batchIds.push(v.id); batchVectors.push(v.vector); batchPayloads.push(v.payload); }); const additionResult = await client.upsert(namespace, { wait: true, batch: { ids: batchIds, vectors: batchVectors, payloads: batchPayloads, }, }); if (additionResult?.status !== "completed") throw new Error("Error embedding into QDrant", additionResult); } await storeVectorResult(chunks, fullFilePath); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) return; const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); await client.delete(namespace, { wait: true, points: vectorIds, }); const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((metadata, i) => { return { ...metadata, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const details = await this.namespace(client, namespace); await this.deleteVectorsInNamespace(client, namespace); return { message: `Namespace ${namespace} was deleted along with ${details?.vectorCount} vectors.`, }; }, reset: async function () { const { client } = await this.connect(); const response = await client.getCollections(); for (const collection of response.collections) { await client.deleteCollection(collection.name); } return { reset: true }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { if (Object.keys(source).length > 0) { const metadata = source.hasOwnProperty("metadata") ? source.metadata : source; documents.push({ ...metadata, }); } } return documents; }, }; module.exports.QDrant = QDrant;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/vectorDbProviders/milvus/index.js
server/utils/vectorDbProviders/milvus/index.js
const { DataType, MetricType, IndexType, MilvusClient, } = require("@zilliz/milvus2-sdk-node"); const { TextSplitter } = require("../../TextSplitter"); const { SystemSettings } = require("../../../models/systemSettings"); const { v4: uuidv4 } = require("uuid"); const { storeVectorResult, cachedVectorInformation } = require("../../files"); const { toChunks, getEmbeddingEngineSelection } = require("../../helpers"); const { sourceIdentifier } = require("../../chats"); const Milvus = { name: "Milvus", // Milvus/Zilliz only allows letters, numbers, and underscores in collection names // so we need to enforce that by re-normalizing the names when communicating with // the DB. // If the first char of the collection is not an underscore or letter the collection name will be invalid. normalize: function (inputString) { let normalized = inputString.replace(/[^a-zA-Z0-9_]/g, "_"); if (new RegExp(/^[a-zA-Z_]/).test(normalized.slice(0, 1))) normalized = `anythingllm_${normalized}`; return normalized; }, connect: async function () { if (process.env.VECTOR_DB !== "milvus") throw new Error("Milvus::Invalid ENV settings"); const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS, username: process.env.MILVUS_USERNAME, password: process.env.MILVUS_PASSWORD, }); const { isHealthy } = await client.checkHealth(); if (!isHealthy) throw new Error( "MilvusDB::Invalid Heartbeat received - is the instance online?" ); return { client }; }, heartbeat: async function () { await this.connect(); return { heartbeat: Number(new Date()) }; }, totalVectors: async function () { const { client } = await this.connect(); const { collection_names } = await client.listCollections(); const total = collection_names.reduce(async (acc, collection_name) => { const statistics = await client.getCollectionStatistics({ collection_name: this.normalize(collection_name), }); return Number(acc) + Number(statistics?.data?.row_count ?? 0); }, 0); return total; }, namespaceCount: async function (_namespace = null) { const { client } = await this.connect(); const statistics = await client.getCollectionStatistics({ collection_name: this.normalize(_namespace), }); return Number(statistics?.data?.row_count ?? 0); }, namespace: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const collection = await client .getCollectionStatistics({ collection_name: this.normalize(namespace) }) .catch(() => null); return collection; }, hasNamespace: async function (namespace = null) { if (!namespace) return false; const { client } = await this.connect(); return await this.namespaceExists(client, namespace); }, namespaceExists: async function (client, namespace = null) { if (!namespace) throw new Error("No namespace value provided."); const { value } = await client .hasCollection({ collection_name: this.normalize(namespace) }) .catch((e) => { console.error("MilvusDB::namespaceExists", e.message); return { value: false }; }); return value; }, deleteVectorsInNamespace: async function (client, namespace = null) { await client.dropCollection({ collection_name: this.normalize(namespace) }); return true; }, // Milvus requires a dimension aspect for collection creation // we pass this in from the first chunk to infer the dimensions like other // providers do. getOrCreateCollection: async function (client, namespace, dimensions = null) { const isExists = await this.namespaceExists(client, namespace); if (!isExists) { if (!dimensions) throw new Error( `Milvus:getOrCreateCollection Unable to infer vector dimension from input. Open an issue on GitHub for support.` ); await client.createCollection({ collection_name: this.normalize(namespace), fields: [ { name: "id", description: "id", data_type: DataType.VarChar, max_length: 255, is_primary_key: true, }, { name: "vector", description: "vector", data_type: DataType.FloatVector, dim: dimensions, }, { name: "metadata", description: "metadata", data_type: DataType.JSON, }, ], }); await client.createIndex({ collection_name: this.normalize(namespace), field_name: "vector", index_type: IndexType.AUTOINDEX, metric_type: MetricType.COSINE, }); await client.loadCollectionSync({ collection_name: this.normalize(namespace), }); } }, addDocumentToNamespace: async function ( namespace, documentData = {}, fullFilePath = null, skipCache = false ) { const { DocumentVectors } = require("../../../models/vectors"); try { let vectorDimension = null; const { pageContent, docId, ...metadata } = documentData; if (!pageContent || pageContent.length == 0) return false; console.log("Adding new vectorized document into namespace", namespace); if (!skipCache) { const cacheResult = await cachedVectorInformation(fullFilePath); if (cacheResult.exists) { const { client } = await this.connect(); const { chunks } = cacheResult; const documentVectors = []; vectorDimension = chunks[0][0].values.length || null; await this.getOrCreateCollection(client, namespace, vectorDimension); try { for (const chunk of chunks) { // Before sending to Milvus and saving the records to our db // we need to assign the id of each chunk that is stored in the cached file. const newChunks = chunk.map((chunk) => { const id = uuidv4(); documentVectors.push({ docId, vectorId: id }); return { id, vector: chunk.values, metadata: chunk.metadata }; }); const insertResult = await client.insert({ collection_name: this.normalize(namespace), data: newChunks, }); if (insertResult?.status.error_code !== "Success") { throw new Error( `Error embedding into Milvus! Reason:${insertResult?.status.reason}` ); } } await DocumentVectors.bulkInsert(documentVectors); await client.flushSync({ collection_names: [this.normalize(namespace)], }); return { vectorized: true, error: null }; } catch (insertError) { console.error( "Error inserting cached chunks:", insertError.message ); return { vectorized: false, error: insertError.message }; } } } const EmbedderEngine = getEmbeddingEngineSelection(); const textSplitter = new TextSplitter({ chunkSize: TextSplitter.determineMaxChunkSize( await SystemSettings.getValueOrFallback({ label: "text_splitter_chunk_size", }), EmbedderEngine?.embeddingMaxChunkLength ), chunkOverlap: await SystemSettings.getValueOrFallback( { label: "text_splitter_chunk_overlap" }, 20 ), chunkHeaderMeta: TextSplitter.buildHeaderMeta(metadata), chunkPrefix: EmbedderEngine?.embeddingPrefix, }); const textChunks = await textSplitter.splitText(pageContent); console.log("Snippets created from document:", textChunks.length); const documentVectors = []; const vectors = []; const vectorValues = await EmbedderEngine.embedChunks(textChunks); if (!!vectorValues && vectorValues.length > 0) { for (const [i, vector] of vectorValues.entries()) { if (!vectorDimension) vectorDimension = vector.length; const vectorRecord = { id: uuidv4(), values: vector, // [DO NOT REMOVE] // LangChain will be unable to find your text if you embed manually and dont include the `text` key. metadata: { ...metadata, text: textChunks[i] }, }; vectors.push(vectorRecord); documentVectors.push({ docId, vectorId: vectorRecord.id }); } } else { throw new Error( "Could not embed document chunks! This document will not be recorded." ); } if (vectors.length > 0) { const chunks = []; const { client } = await this.connect(); await this.getOrCreateCollection(client, namespace, vectorDimension); console.log("Inserting vectorized chunks into Milvus."); for (const chunk of toChunks(vectors, 100)) { chunks.push(chunk); const insertResult = await client.insert({ collection_name: this.normalize(namespace), data: chunk.map((item) => ({ id: item.id, vector: item.values, metadata: item.metadata, })), }); if (insertResult?.status.error_code !== "Success") { throw new Error( `Error embedding into Milvus! Reason:${insertResult?.status.reason}` ); } } await storeVectorResult(chunks, fullFilePath); await client.flushSync({ collection_names: [this.normalize(namespace)], }); } await DocumentVectors.bulkInsert(documentVectors); return { vectorized: true, error: null }; } catch (e) { console.error("addDocumentToNamespace", e.message); return { vectorized: false, error: e.message }; } }, deleteDocumentFromNamespace: async function (namespace, docId) { const { DocumentVectors } = require("../../../models/vectors"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) return; const knownDocuments = await DocumentVectors.where({ docId }); if (knownDocuments.length === 0) return; const vectorIds = knownDocuments.map((doc) => doc.vectorId); const queryIn = vectorIds.map((v) => `'${v}'`).join(","); await client.deleteEntities({ collection_name: this.normalize(namespace), expr: `id in [${queryIn}]`, }); const indexes = knownDocuments.map((doc) => doc.id); await DocumentVectors.deleteIds(indexes); // Even after flushing Milvus can take some time to re-calc the count // so all we can hope to do is flushSync so that the count can be correct // on a later call. await client.flushSync({ collection_names: [this.normalize(namespace)] }); return true; }, performSimilaritySearch: async function ({ namespace = null, input = "", LLMConnector = null, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { if (!namespace || !input || !LLMConnector) throw new Error("Invalid request to performSimilaritySearch."); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) { return { contextTexts: [], sources: [], message: "Invalid query - no documents found for workspace!", }; } const queryVector = await LLMConnector.embedTextInput(input); const { contextTexts, sourceDocuments } = await this.similarityResponse({ client, namespace, queryVector, similarityThreshold, topN, filterIdentifiers, }); const sources = sourceDocuments.map((doc, i) => { return { metadata: doc, text: contextTexts[i] }; }); return { contextTexts, sources: this.curateSources(sources), message: false, }; }, similarityResponse: async function ({ client, namespace, queryVector, similarityThreshold = 0.25, topN = 4, filterIdentifiers = [], }) { const result = { contextTexts: [], sourceDocuments: [], scores: [], }; const response = await client.search({ collection_name: this.normalize(namespace), vectors: queryVector, limit: topN, }); response.results.forEach((match) => { if (match.score < similarityThreshold) return; if (filterIdentifiers.includes(sourceIdentifier(match.metadata))) { console.log( "Milvus: A source was filtered from context as it's parent document is pinned." ); return; } result.contextTexts.push(match.metadata.text); result.sourceDocuments.push({ ...match.metadata, score: match.score, }); result.scores.push(match.score); }); return result; }, "namespace-stats": async function (reqBody = {}) { const { namespace = null } = reqBody; if (!namespace) throw new Error("namespace required"); const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const stats = await this.namespace(client, namespace); return stats ? stats : { message: "No stats were able to be fetched from DB for namespace" }; }, "delete-namespace": async function (reqBody = {}) { const { namespace = null } = reqBody; const { client } = await this.connect(); if (!(await this.namespaceExists(client, namespace))) throw new Error("Namespace by that name does not exist."); const statistics = await this.namespace(client, namespace); await this.deleteVectorsInNamespace(client, namespace); const vectorCount = Number(statistics?.data?.row_count ?? 0); return { message: `Namespace ${namespace} was deleted along with ${vectorCount} vectors.`, }; }, curateSources: function (sources = []) { const documents = []; for (const source of sources) { const { metadata = {} } = source; if (Object.keys(metadata).length > 0) { documents.push({ ...metadata, ...(source.text ? { text: source.text } : {}), }); } } return documents; }, }; module.exports.Milvus = Milvus;
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/comKey/index.js
server/utils/comKey/index.js
const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const keyPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../storage/comkey`) : path.resolve( process.env.STORAGE_DIR ?? path.resolve(__dirname, `../../storage`), `comkey` ); // What does this class do? // This class generates a hashed version of some text (typically a JSON payload) using a rolling RSA key // that can then be appended as a header value to do integrity checking on a payload. Given the // nature of this class and that keys are rolled constantly, this protects the request // integrity of requests sent to the collector as only the server can sign these requests. // This keeps accidental misconfigurations of AnythingLLM that leaving port 8888 open from // being abused or SSRF'd by users scraping malicious sites who have a loopback embedded in a <script>, for example. // Since each request to the collector must be signed to be valid, unsigned requests directly to the collector // will be dropped and must go through the /server endpoint directly. class CommunicationKey { #privKeyName = "ipc-priv.pem"; #pubKeyName = "ipc-pub.pem"; #storageLoc = keyPath; // Init the class and determine if keys should be rolled. // This typically occurs on boot up so key is fresh each boot. constructor(generate = false) { if (generate) this.#generate(); } log(text, ...args) { console.log(`\x1b[36m[CommunicationKey]\x1b[0m ${text}`, ...args); } #readPrivateKey() { return fs.readFileSync(path.resolve(this.#storageLoc, this.#privKeyName)); } #generate() { const keyPair = crypto.generateKeyPairSync("rsa", { modulusLength: 2048, publicKeyEncoding: { type: "pkcs1", format: "pem", }, privateKeyEncoding: { type: "pkcs1", format: "pem", }, }); if (!fs.existsSync(this.#storageLoc)) fs.mkdirSync(this.#storageLoc, { recursive: true }); fs.writeFileSync( `${path.resolve(this.#storageLoc, this.#privKeyName)}`, keyPair.privateKey ); fs.writeFileSync( `${path.resolve(this.#storageLoc, this.#pubKeyName)}`, keyPair.publicKey ); this.log( "RSA key pair generated for signed payloads within AnythingLLM services." ); } // This instance of ComKey on server is intended for generation of Priv/Pub key for signing and decoding. // this resource is shared with /collector/ via a class of the same name in /utils which does decoding/verification only // while this server class only does signing with the private key. sign(textData = "") { return crypto .sign("RSA-SHA256", Buffer.from(textData), this.#readPrivateKey()) .toString("hex"); } // Use the rolling priv-key to encrypt arbitrary data that is text // returns the encrypted content as a base64 string. encrypt(textData = "") { return crypto .privateEncrypt(this.#readPrivateKey(), Buffer.from(textData, "utf-8")) .toString("base64"); } } module.exports = { CommunicationKey };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/agents.js
server/utils/chats/agents.js
const pluralize = require("pluralize"); const { WorkspaceAgentInvocation, } = require("../../models/workspaceAgentInvocation"); const { writeResponseChunk } = require("../helpers/chat/responses"); async function grepAgents({ uuid, response, message, workspace, user = null, thread = null, }) { const agentHandles = WorkspaceAgentInvocation.parseAgents(message); if (agentHandles.length > 0) { const { invocation: newInvocation } = await WorkspaceAgentInvocation.new({ prompt: message, workspace: workspace, user: user, thread: thread, }); if (!newInvocation) { writeResponseChunk(response, { id: uuid, type: "statusResponse", textResponse: `${pluralize( "Agent", agentHandles.length )} ${agentHandles.join( ", " )} could not be called. Chat will be handled as default chat.`, sources: [], close: true, animate: false, error: null, }); return; } writeResponseChunk(response, { id: uuid, type: "agentInitWebsocketConnection", textResponse: null, sources: [], close: false, error: null, websocketUUID: newInvocation.uuid, }); // Close HTTP stream-able chunk response method because we will swap to agents now. writeResponseChunk(response, { id: uuid, type: "statusResponse", textResponse: `${pluralize( "Agent", agentHandles.length )} ${agentHandles.join( ", " )} invoked.\nSwapping over to agent chat. Type /exit to exit agent execution loop early.`, sources: [], close: true, error: null, animate: true, }); return true; } return false; } module.exports = { grepAgents };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/openaiCompatible.js
server/utils/chats/openaiCompatible.js
const { v4: uuidv4 } = require("uuid"); const { DocumentManager } = require("../DocumentManager"); const { WorkspaceChats } = require("../../models/workspaceChats"); const { getVectorDbClass, getLLMProvider } = require("../helpers"); const { writeResponseChunk } = require("../helpers/chat/responses"); const { chatPrompt, sourceIdentifier } = require("./index"); const { PassThrough } = require("stream"); async function chatSync({ workspace, systemPrompt = null, history = [], prompt = null, attachments = [], temperature = null, }) { const uuid = uuidv4(); const chatMode = workspace?.chatMode ?? "chat"; const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const hasVectorizedSpace = await VectorDb.hasNamespace(workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(workspace.slug); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: textResponse, sources: [], type: chatMode, attachments, }, include: false, }); return formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, }, { model: workspace.slug, finish_reason: "abort" } ); } // If we are here we know that we are in a workspace that is: // 1. Chatting in "chat" mode and may or may _not_ have embeddings // 2. Chatting in "query" mode and has at least 1 embedding let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; await new DocumentManager({ workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: workspace.slug, input: String(prompt), LLMConnector, similarityThreshold: workspace?.similarityThreshold, topN: workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { return formatJSON( { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: vectorSearchResults.message, }, { model: workspace.slug, finish_reason: "abort" } ); } // For OpenAI Compatible chats, we cannot do backfilling so we simply aggregate results here. contextTexts = [...contextTexts, ...vectorSearchResults.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no context chunks are found from search, backfill, or pins - do not // let the LLM try to hallucinate a response or use general knowledge and exit early if (chatMode === "query" && contextTexts.length === 0) { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: textResponse, sources: [], type: chatMode, attachments, }, include: false, }); return formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, }, { model: workspace.slug, finish_reason: "no_content" } ); } // Compress & Assemble message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages({ systemPrompt: systemPrompt ?? (await chatPrompt(workspace)), userPrompt: String(prompt), contextTexts, chatHistory: history, attachments, }); // Send the text completion. const { textResponse, metrics } = await LLMConnector.getChatCompletion( messages, { temperature: temperature ?? workspace?.openAiTemp ?? LLMConnector.defaultTemp, } ); if (!textResponse) { return formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: "No text completion could be completed with this input.", textResponse: null, }, { model: workspace.slug, finish_reason: "no_content", usage: metrics } ); } const { chat } = await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: textResponse, sources, type: chatMode, metrics, attachments, }, }); return formatJSON( { id: uuid, type: "textResponse", close: true, error: null, chatId: chat.id, textResponse, sources, }, { model: workspace.slug, finish_reason: "stop", usage: metrics } ); } async function streamChat({ workspace, response, systemPrompt = null, history = [], prompt = null, attachments = [], temperature = null, }) { const uuid = uuidv4(); const chatMode = workspace?.chatMode ?? "chat"; const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const hasVectorizedSpace = await VectorDb.hasNamespace(workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(workspace.slug); // We don't want to write a new method for every LLM to support openAI calls // via the `handleStreamResponseV2` method handler. So here we create a passthrough // that on writes to the main response, transforms the chunk to OpenAI format. // The chunk is coming in the format from `writeResponseChunk` but in the AnythingLLM // response chunk schema, so we here we mutate each chunk. const responseInterceptor = new PassThrough({}); responseInterceptor.on("data", (chunk) => { try { const originalData = JSON.parse(chunk.toString().split("data: ")[1]); const modified = formatJSON(originalData, { chunked: true, model: workspace.slug, }); // rewrite to OpenAI format response.write(`data: ${JSON.stringify(modified)}\n\n`); } catch (e) { console.error(e); } }); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: textResponse, sources: [], type: chatMode, attachments, }, include: false, }); writeResponseChunk( response, formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, }, { chunked: true, model: workspace.slug, finish_reason: "abort" } ) ); return; } // If we are here we know that we are in a workspace that is: // 1. Chatting in "chat" mode and may or may _not_ have embeddings // 2. Chatting in "query" mode and has at least 1 embedding let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; await new DocumentManager({ workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: workspace.slug, input: String(prompt), LLMConnector, similarityThreshold: workspace?.similarityThreshold, topN: workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { writeResponseChunk( response, formatJSON( { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: vectorSearchResults.message, }, { chunked: true, model: workspace.slug, finish_reason: "abort" } ) ); return; } // For OpenAI Compatible chats, we cannot do backfilling so we simply aggregate results here. contextTexts = [...contextTexts, ...vectorSearchResults.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no context chunks are found from search, backfill, or pins - do not // let the LLM try to hallucinate a response or use general knowledge and exit early if (chatMode === "query" && contextTexts.length === 0) { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: textResponse, sources: [], type: chatMode, attachments, }, include: false, }); writeResponseChunk( response, formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, }, { chunked: true, model: workspace.slug, finish_reason: "no_content" } ) ); return; } // Compress & Assemble message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages({ systemPrompt: systemPrompt ?? (await chatPrompt(workspace)), userPrompt: String(prompt), contextTexts, chatHistory: history, attachments, }); if (!LLMConnector.streamingEnabled()) { writeResponseChunk( response, formatJSON( { id: uuid, type: "textResponse", sources: [], close: true, error: "Streaming is not available for the connected LLM Provider", textResponse: null, }, { chunked: true, model: workspace.slug, finish_reason: "streaming_disabled", } ) ); return; } const stream = await LLMConnector.streamGetChatCompletion(messages, { temperature: temperature ?? workspace?.openAiTemp ?? LLMConnector.defaultTemp, }); const completeText = await LLMConnector.handleStream( responseInterceptor, stream, { uuid, sources, } ); if (completeText?.length > 0) { const { chat } = await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(prompt), response: { text: completeText, sources, type: chatMode, metrics: stream.metrics, attachments, }, }); writeResponseChunk( response, formatJSON( { uuid, type: "finalizeResponseStream", close: true, error: false, chatId: chat.id, textResponse: "", }, { chunked: true, model: workspace.slug, finish_reason: "stop", usage: stream.metrics, } ) ); return; } writeResponseChunk( response, formatJSON( { uuid, type: "finalizeResponseStream", close: true, error: false, textResponse: "", }, { chunked: true, model: workspace.slug, finish_reason: "stop", usage: stream.metrics, } ) ); return; } function formatJSON( chat, { chunked = false, model, finish_reason = null, usage = {} } ) { const data = { id: chat.uuid ?? chat.id, object: "chat.completion", created: Math.floor(Number(new Date()) / 1000), model: model, choices: [ { index: 0, [chunked ? "delta" : "message"]: { role: "assistant", content: chat.textResponse, }, logprobs: null, finish_reason: finish_reason, }, ], usage, }; return data; } module.exports.OpenAICompatibleChat = { chatSync, streamChat, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/index.js
server/utils/chats/index.js
const { v4: uuidv4 } = require("uuid"); const { WorkspaceChats } = require("../../models/workspaceChats"); const { resetMemory } = require("./commands/reset"); const { convertToPromptHistory } = require("../helpers/chat/responses"); const { SlashCommandPresets } = require("../../models/slashCommandsPresets"); const { SystemPromptVariables } = require("../../models/systemPromptVariables"); const VALID_COMMANDS = { "/reset": resetMemory, }; async function grepCommand(message, user = null) { const userPresets = await SlashCommandPresets.getUserPresets(user?.id); const availableCommands = Object.keys(VALID_COMMANDS); // Check if the message starts with any built-in command for (let i = 0; i < availableCommands.length; i++) { const cmd = availableCommands[i]; const re = new RegExp(`^(${cmd})`, "i"); if (re.test(message)) { return cmd; } } // Replace all preset commands with their corresponding prompts // Allows multiple commands in one message let updatedMessage = message; for (const preset of userPresets) { const regex = new RegExp( `(?:\\b\\s|^)(${preset.command})(?:\\b\\s|$)`, "g" ); updatedMessage = updatedMessage.replace(regex, preset.prompt); } return updatedMessage; } /** * @description This function will do recursive replacement of all slash commands with their corresponding prompts. * @notice This function is used for API calls and is not user-scoped. THIS FUNCTION DOES NOT SUPPORT PRESET COMMANDS. * @returns {Promise<string>} */ async function grepAllSlashCommands(message) { const allPresets = await SlashCommandPresets.where({}); // Replace all preset commands with their corresponding prompts // Allows multiple commands in one message let updatedMessage = message; for (const preset of allPresets) { const regex = new RegExp( `(?:\\b\\s|^)(${preset.command})(?:\\b\\s|$)`, "g" ); updatedMessage = updatedMessage.replace(regex, preset.prompt); } return updatedMessage; } async function recentChatHistory({ user = null, workspace, thread = null, messageLimit = 20, apiSessionId = null, }) { const rawHistory = ( await WorkspaceChats.where( { workspaceId: workspace.id, user_id: user?.id || null, thread_id: thread?.id || null, api_session_id: apiSessionId || null, include: true, }, messageLimit, { id: "desc" } ) ).reverse(); return { rawHistory, chatHistory: convertToPromptHistory(rawHistory) }; } /** * Returns the base prompt for the chat. This method will also do variable * substitution on the prompt if there are any defined variables in the prompt. * @param {Object|null} workspace - the workspace object * @param {Object|null} user - the user object * @returns {Promise<string>} - the base prompt */ async function chatPrompt(workspace, user = null) { const { SystemSettings } = require("../../models/systemSettings"); const basePrompt = workspace?.openAiPrompt ?? SystemSettings.saneDefaultSystemPrompt; return await SystemPromptVariables.expandSystemPromptVariables( basePrompt, user?.id, workspace?.id ); } // We use this util function to deduplicate sources from similarity searching // if the document is already pinned. // Eg: You pin a csv, if we RAG + full-text that you will get the same data // points both in the full-text and possibly from RAG - result in bad results // even if the LLM was not even going to hallucinate. function sourceIdentifier(sourceDocument) { if (!sourceDocument?.title || !sourceDocument?.published) return uuidv4(); return `title:${sourceDocument.title}-timestamp:${sourceDocument.published}`; } module.exports = { sourceIdentifier, recentChatHistory, chatPrompt, grepCommand, grepAllSlashCommands, VALID_COMMANDS, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/apiChatHandler.js
server/utils/chats/apiChatHandler.js
const { v4: uuidv4 } = require("uuid"); const { DocumentManager } = require("../DocumentManager"); const { WorkspaceChats } = require("../../models/workspaceChats"); const { getVectorDbClass, getLLMProvider } = require("../helpers"); const { writeResponseChunk } = require("../helpers/chat/responses"); const { chatPrompt, sourceIdentifier, recentChatHistory, grepAllSlashCommands, } = require("./index"); const { EphemeralAgentHandler, EphemeralEventListener, } = require("../agents/ephemeral"); const { Telemetry } = require("../../models/telemetry"); const { CollectorApi } = require("../collectorApi"); const fs = require("fs"); const path = require("path"); const { hotdirPath, normalizePath, isWithin } = require("../files"); /** * @typedef ResponseObject * @property {string} id - uuid of response * @property {string} type - Type of response * @property {string|null} textResponse - full text response * @property {object[]} sources * @property {boolean} close * @property {string|null} error * @property {object} metrics */ /** * Users can pass in documents as attachments to the chat API. * The name of the document is the name of the attachment and must include the file extension. * the mime type for documents is `application/anythingllm-document` - anything else is assumed to be an image. * @param {{name: string, mime: string, contentString: string}[]} attachments * @returns {Promise<{parsedDocuments: Object[], imageAttachments: {name: string; mime: string; contentString: string}[]}>} */ async function processDocumentAttachments(attachments = []) { if (!Array.isArray(attachments) || attachments.length === 0) return { parsedDocuments: [], imageAttachments: [] }; const documentAttachments = []; const imageAttachments = []; for (const attachment of attachments) { if ( attachment && attachment.contentString && attachment.mime && attachment.mime.toLowerCase() === "application/anythingllm-document" ) documentAttachments.push(attachment); else imageAttachments.push(attachment); } if (documentAttachments.length === 0) return { parsedDocuments: [], imageAttachments }; const Collector = new CollectorApi(); const processingOnline = await Collector.online(); if (!processingOnline) { console.warn( "Collector API is not online, skipping document attachment processing" ); return { parsedDocuments: [], imageAttachments }; } if (!fs.existsSync(hotdirPath)) fs.mkdirSync(hotdirPath, { recursive: true }); const parsedDocuments = []; for (const attachment of documentAttachments) { try { let base64Data = attachment.contentString; const dataUriMatch = base64Data.match(/^data:[^;]+;base64,(.+)$/); if (dataUriMatch) base64Data = dataUriMatch[1]; const buffer = Buffer.from(base64Data, "base64"); const filename = normalizePath( attachment.name || `attachment-${uuidv4()}` ); const filePath = normalizePath(path.join(hotdirPath, filename)); if (!isWithin(hotdirPath, filePath)) throw new Error(`Invalid file path for attachment ${filename}`); fs.writeFileSync(filePath, buffer); const { success, reason, documents } = await Collector.parseDocument(filename); if (success && documents?.length > 0) parsedDocuments.push(...documents); else console.warn(`Failed to parse attachment ${filename}:`, reason); } catch (error) { console.error( `Error processing attachment ${attachment.name}:`, error.message ); } } return { parsedDocuments, imageAttachments }; } /** * Handle synchronous chats with your workspace via the developer API endpoint * @param {{ * workspace: import("@prisma/client").workspaces, * message:string, * mode: "chat"|"query", * user: import("@prisma/client").users|null, * thread: import("@prisma/client").workspace_threads|null, * sessionId: string|null, * attachments: { name: string; mime: string; contentString: string }[], * reset: boolean, * }} parameters * @returns {Promise<ResponseObject>} */ async function chatSync({ workspace, message = null, mode = "chat", user = null, thread = null, sessionId = null, attachments = [], reset = false, }) { const uuid = uuidv4(); const chatMode = mode ?? "chat"; // If the user wants to reset the chat history we do so pre-flight // and continue execution. If no message is provided then the user intended // to reset the chat history only and we can exit early with a confirmation. if (reset) { await WorkspaceChats.markThreadHistoryInvalidV2({ workspaceId: workspace.id, user_id: user?.id, thread_id: thread?.id, api_session_id: sessionId, }); if (!message?.length) { return { id: uuid, type: "textResponse", textResponse: "Chat history was reset!", sources: [], close: true, error: null, metrics: {}, }; } } // Process slash commands // Since preset commands are not supported in API calls, we can just process the message here const processedMessage = await grepAllSlashCommands(message); message = processedMessage; if (EphemeralAgentHandler.isAgentInvocation({ message })) { await Telemetry.sendTelemetry("agent_chat_started"); // Initialize the EphemeralAgentHandler to handle non-continuous // conversations with agents since this is over REST. const agentHandler = new EphemeralAgentHandler({ uuid, workspace, prompt: message, userId: user?.id || null, threadId: thread?.id || null, sessionId, }); // Establish event listener that emulates websocket calls // in Aibitat so that we can keep the same interface in Aibitat // but use HTTP. const eventListener = new EphemeralEventListener(); await agentHandler.init(); await agentHandler.createAIbitat({ handler: eventListener }); agentHandler.startAgentCluster(); // The cluster has started and now we wait for close event since // this is a synchronous call for an agent, so we return everything at once. // After this, we conclude the call as we normally do. return await eventListener .waitForClose() .then(async ({ thoughts, textResponse }) => { await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(message), response: { text: textResponse, sources: [], attachments, type: chatMode, thoughts, }, include: false, apiSessionId: sessionId, }); return { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, thoughts, }; }); } const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const messageLimit = workspace?.openAiHistory || 20; const hasVectorizedSpace = await VectorDb.hasNamespace(workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(workspace.slug); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(message), response: { text: textResponse, sources: [], attachments: attachments, type: chatMode, metrics: {}, }, include: false, apiSessionId: sessionId, }); return { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, metrics: {}, }; } // If we are here we know that we are in a workspace that is: // 1. Chatting in "chat" mode and may or may _not_ have embeddings // 2. Chatting in "query" mode and has at least 1 embedding let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; const { rawHistory, chatHistory } = await recentChatHistory({ user, workspace, thread, messageLimit, apiSessionId: sessionId, }); await new DocumentManager({ workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); const processedAttachments = await processDocumentAttachments(attachments); const parsedAttachments = processedAttachments.parsedDocuments; attachments = processedAttachments.imageAttachments; parsedAttachments.forEach((doc) => { if (doc.pageContent) { contextTexts.push(doc.pageContent); const { pageContent, ...metadata } = doc; sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); } }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: workspace.slug, input: message, LLMConnector, similarityThreshold: workspace?.similarityThreshold, topN: workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { return { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: vectorSearchResults.message, metrics: {}, }; } const { fillSourceWindow } = require("../helpers/chat"); const filledSources = fillSourceWindow({ nDocs: workspace?.topN || 4, searchResults: vectorSearchResults.sources, history: rawHistory, filterIdentifiers: pinnedDocIdentifiers, }); // Why does contextTexts get all the info, but sources only get current search? // This is to give the ability of the LLM to "comprehend" a contextual response without // populating the Citations under a response with documents the user "thinks" are irrelevant // due to how we manage backfilling of the context to keep chats with the LLM more correct in responses. // If a past citation was used to answer the question - that is visible in the history so it logically makes sense // and does not appear to the user that a new response used information that is otherwise irrelevant for a given prompt. // TLDR; reduces GitHub issues for "LLM citing document that has no answer in it" while keep answers highly accurate. contextTexts = [...contextTexts, ...filledSources.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no context chunks are found from search, backfill, or pins - do not // let the LLM try to hallucinate a response or use general knowledge and exit early if (chatMode === "query" && contextTexts.length === 0) { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources: [], attachments: attachments, type: chatMode, metrics: {}, }, threadId: thread?.id || null, include: false, apiSessionId: sessionId, user, }); return { id: uuid, type: "textResponse", sources: [], close: true, error: null, textResponse, metrics: {}, }; } // Compress & Assemble message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages( { systemPrompt: await chatPrompt(workspace, user), userPrompt: message, contextTexts, chatHistory, attachments, }, rawHistory ); // Send the text completion. const { textResponse, metrics: performanceMetrics } = await LLMConnector.getChatCompletion(messages, { temperature: workspace?.openAiTemp ?? LLMConnector.defaultTemp, user: user, }); if (!textResponse) { return { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: "No text completion could be completed with this input.", metrics: performanceMetrics, }; } const { chat } = await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources, attachments, type: chatMode, metrics: performanceMetrics, }, threadId: thread?.id || null, apiSessionId: sessionId, user, }); return { id: uuid, type: "textResponse", close: true, error: null, chatId: chat.id, textResponse, sources, metrics: performanceMetrics, }; } /** * Handle streamable HTTP chunks for chats with your workspace via the developer API endpoint * @param {{ * response: import("express").Response, * workspace: import("@prisma/client").workspaces, * message:string, * mode: "chat"|"query", * user: import("@prisma/client").users|null, * thread: import("@prisma/client").workspace_threads|null, * sessionId: string|null, * attachments: { name: string; mime: string; contentString: string }[], * reset: boolean, * }} parameters * @returns {Promise<VoidFunction>} */ async function streamChat({ response, workspace, message = null, mode = "chat", user = null, thread = null, sessionId = null, attachments = [], reset = false, }) { const uuid = uuidv4(); const chatMode = mode ?? "chat"; // If the user wants to reset the chat history we do so pre-flight // and continue execution. If no message is provided then the user intended // to reset the chat history only and we can exit early with a confirmation. if (reset) { await WorkspaceChats.markThreadHistoryInvalidV2({ workspaceId: workspace.id, user_id: user?.id, thread_id: thread?.id, api_session_id: sessionId, }); if (!message?.length) { writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse: "Chat history was reset!", sources: [], attachments: [], close: true, error: null, metrics: {}, }); return; } } // Check for and process slash commands // Since preset commands are not supported in API calls, we can just process the message here const processedMessage = await grepAllSlashCommands(message); message = processedMessage; if (EphemeralAgentHandler.isAgentInvocation({ message })) { await Telemetry.sendTelemetry("agent_chat_started"); // Initialize the EphemeralAgentHandler to handle non-continuous // conversations with agents since this is over REST. const agentHandler = new EphemeralAgentHandler({ uuid, workspace, prompt: message, userId: user?.id || null, threadId: thread?.id || null, sessionId, }); // Establish event listener that emulates websocket calls // in Aibitat so that we can keep the same interface in Aibitat // but use HTTP. const eventListener = new EphemeralEventListener(); await agentHandler.init(); await agentHandler.createAIbitat({ handler: eventListener }); agentHandler.startAgentCluster(); // The cluster has started and now we wait for close event since // and stream back any results we get from agents as they come in. return eventListener .streamAgentEvents(response, uuid) .then(async ({ thoughts, textResponse }) => { await WorkspaceChats.new({ workspaceId: workspace.id, prompt: String(message), response: { text: textResponse, sources: [], attachments: attachments, type: chatMode, thoughts, }, include: true, threadId: thread?.id || null, apiSessionId: sessionId, }); writeResponseChunk(response, { uuid, type: "finalizeResponseStream", textResponse, thoughts, close: true, error: false, }); }); } const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const messageLimit = workspace?.openAiHistory || 20; const hasVectorizedSpace = await VectorDb.hasNamespace(workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(workspace.slug); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse, sources: [], attachments: [], close: true, error: null, metrics: {}, }); await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources: [], attachments: attachments, type: chatMode, metrics: {}, }, threadId: thread?.id || null, apiSessionId: sessionId, include: false, user, }); return; } // If we are here we know that we are in a workspace that is: // 1. Chatting in "chat" mode and may or may _not_ have embeddings // 2. Chatting in "query" mode and has at least 1 embedding let completeText; let metrics = {}; let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; const { rawHistory, chatHistory } = await recentChatHistory({ user, workspace, thread, messageLimit, apiSessionId: sessionId, }); // Look for pinned documents and see if the user decided to use this feature. We will also do a vector search // as pinning is a supplemental tool but it should be used with caution since it can easily blow up a context window. // However we limit the maximum of appended context to 80% of its overall size, mostly because if it expands beyond this // it will undergo prompt compression anyway to make it work. If there is so much pinned that the context here is bigger than // what the model can support - it would get compressed anyway and that really is not the point of pinning. It is really best // suited for high-context models. await new DocumentManager({ workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); const processedAttachments = await processDocumentAttachments(attachments); const parsedAttachments = processedAttachments.parsedDocuments; attachments = processedAttachments.imageAttachments; parsedAttachments.forEach((doc) => { if (doc.pageContent) { contextTexts.push(doc.pageContent); const { pageContent, ...metadata } = doc; sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); } }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: workspace.slug, input: message, LLMConnector, similarityThreshold: workspace?.similarityThreshold, topN: workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { writeResponseChunk(response, { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: vectorSearchResults.message, metrics: {}, }); return; } const { fillSourceWindow } = require("../helpers/chat"); const filledSources = fillSourceWindow({ nDocs: workspace?.topN || 4, searchResults: vectorSearchResults.sources, history: rawHistory, filterIdentifiers: pinnedDocIdentifiers, }); // Why does contextTexts get all the info, but sources only get current search? // This is to give the ability of the LLM to "comprehend" a contextual response without // populating the Citations under a response with documents the user "thinks" are irrelevant // due to how we manage backfilling of the context to keep chats with the LLM more correct in responses. // If a past citation was used to answer the question - that is visible in the history so it logically makes sense // and does not appear to the user that a new response used information that is otherwise irrelevant for a given prompt. // TLDR; reduces GitHub issues for "LLM citing document that has no answer in it" while keep answers highly accurate. contextTexts = [...contextTexts, ...filledSources.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no context chunks are found from search, backfill, or pins - do not // let the LLM try to hallucinate a response or use general knowledge and exit early if (chatMode === "query" && contextTexts.length === 0) { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse, sources: [], close: true, error: null, metrics: {}, }); await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources: [], attachments: attachments, type: chatMode, metrics: {}, }, threadId: thread?.id || null, apiSessionId: sessionId, include: false, user, }); return; } // Compress & Assemble message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages( { systemPrompt: await chatPrompt(workspace, user), userPrompt: message, contextTexts, chatHistory, attachments, }, rawHistory ); // If streaming is not explicitly enabled for connector // we do regular waiting of a response and send a single chunk. if (LLMConnector.streamingEnabled() !== true) { console.log( `\x1b[31m[STREAMING DISABLED]\x1b[0m Streaming is not available for ${LLMConnector.constructor.name}. Will use regular chat method.` ); const { textResponse, metrics: performanceMetrics } = await LLMConnector.getChatCompletion(messages, { temperature: workspace?.openAiTemp ?? LLMConnector.defaultTemp, user: user, }); completeText = textResponse; metrics = performanceMetrics; writeResponseChunk(response, { uuid, sources, type: "textResponseChunk", textResponse: completeText, close: true, error: false, metrics, }); } else { const stream = await LLMConnector.streamGetChatCompletion(messages, { temperature: workspace?.openAiTemp ?? LLMConnector.defaultTemp, user: user, }); completeText = await LLMConnector.handleStream(response, stream, { uuid }); metrics = stream.metrics; } if (completeText?.length > 0) { const { chat } = await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: completeText, sources, type: chatMode, metrics, attachments, }, threadId: thread?.id || null, apiSessionId: sessionId, user, }); writeResponseChunk(response, { uuid, type: "finalizeResponseStream", close: true, error: false, chatId: chat.id, metrics, sources, }); return; } writeResponseChunk(response, { uuid, type: "finalizeResponseStream", close: true, error: false, }); return; } module.exports.ApiChatHandler = { chatSync, streamChat, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/stream.js
server/utils/chats/stream.js
const { v4: uuidv4 } = require("uuid"); const { DocumentManager } = require("../DocumentManager"); const { WorkspaceChats } = require("../../models/workspaceChats"); const { WorkspaceParsedFiles } = require("../../models/workspaceParsedFiles"); const { getVectorDbClass, getLLMProvider } = require("../helpers"); const { writeResponseChunk } = require("../helpers/chat/responses"); const { grepAgents } = require("./agents"); const { grepCommand, VALID_COMMANDS, chatPrompt, recentChatHistory, sourceIdentifier, } = require("./index"); const VALID_CHAT_MODE = ["chat", "query"]; async function streamChatWithWorkspace( response, workspace, message, chatMode = "chat", user = null, thread = null, attachments = [] ) { const uuid = uuidv4(); const updatedMessage = await grepCommand(message, user); if (Object.keys(VALID_COMMANDS).includes(updatedMessage)) { const data = await VALID_COMMANDS[updatedMessage]( workspace, message, uuid, user, thread ); writeResponseChunk(response, data); return; } // If is agent enabled chat we will exit this flow early. const isAgentChat = await grepAgents({ uuid, response, message: updatedMessage, user, workspace, thread, }); if (isAgentChat) return; const LLMConnector = getLLMProvider({ provider: workspace?.chatProvider, model: workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const messageLimit = workspace?.openAiHistory || 20; const hasVectorizedSpace = await VectorDb.hasNamespace(workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(workspace.slug); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse, sources: [], attachments, close: true, error: null, }); await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources: [], type: chatMode, attachments, }, threadId: thread?.id || null, include: false, user, }); return; } // If we are here we know that we are in a workspace that is: // 1. Chatting in "chat" mode and may or may _not_ have embeddings // 2. Chatting in "query" mode and has at least 1 embedding let completeText; let metrics = {}; let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; const { rawHistory, chatHistory } = await recentChatHistory({ user, workspace, thread, messageLimit, }); // Look for pinned documents and see if the user decided to use this feature. We will also do a vector search // as pinning is a supplemental tool but it should be used with caution since it can easily blow up a context window. // However we limit the maximum of appended context to 80% of its overall size, mostly because if it expands beyond this // it will undergo prompt compression anyway to make it work. If there is so much pinned that the context here is bigger than // what the model can support - it would get compressed anyway and that really is not the point of pinning. It is really best // suited for high-context models. await new DocumentManager({ workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); // Inject any parsed files for this workspace/thread/user const parsedFiles = await WorkspaceParsedFiles.getContextFiles( workspace, thread || null, user || null ); parsedFiles.forEach((doc) => { const { pageContent, ...metadata } = doc; contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: workspace.slug, input: updatedMessage, LLMConnector, similarityThreshold: workspace?.similarityThreshold, topN: workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { writeResponseChunk(response, { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: vectorSearchResults.message, }); return; } const { fillSourceWindow } = require("../helpers/chat"); const filledSources = fillSourceWindow({ nDocs: workspace?.topN || 4, searchResults: vectorSearchResults.sources, history: rawHistory, filterIdentifiers: pinnedDocIdentifiers, }); // Why does contextTexts get all the info, but sources only get current search? // This is to give the ability of the LLM to "comprehend" a contextual response without // populating the Citations under a response with documents the user "thinks" are irrelevant // due to how we manage backfilling of the context to keep chats with the LLM more correct in responses. // If a past citation was used to answer the question - that is visible in the history so it logically makes sense // and does not appear to the user that a new response used information that is otherwise irrelevant for a given prompt. // TLDR; reduces GitHub issues for "LLM citing document that has no answer in it" while keep answers highly accurate. contextTexts = [...contextTexts, ...filledSources.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no context chunks are found from search, backfill, or pins - do not // let the LLM try to hallucinate a response or use general knowledge and exit early if (chatMode === "query" && contextTexts.length === 0) { const textResponse = workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query."; writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse, sources: [], close: true, error: null, }); await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: textResponse, sources: [], type: chatMode, attachments, }, threadId: thread?.id || null, include: false, user, }); return; } // Compress & Assemble message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages( { systemPrompt: await chatPrompt(workspace, user), userPrompt: updatedMessage, contextTexts, chatHistory, attachments, }, rawHistory ); // If streaming is not explicitly enabled for connector // we do regular waiting of a response and send a single chunk. if (LLMConnector.streamingEnabled() !== true) { console.log( `\x1b[31m[STREAMING DISABLED]\x1b[0m Streaming is not available for ${LLMConnector.constructor.name}. Will use regular chat method.` ); const { textResponse, metrics: performanceMetrics } = await LLMConnector.getChatCompletion(messages, { temperature: workspace?.openAiTemp ?? LLMConnector.defaultTemp, user: user, }); completeText = textResponse; metrics = performanceMetrics; writeResponseChunk(response, { uuid, sources, type: "textResponseChunk", textResponse: completeText, close: true, error: false, metrics, }); } else { const stream = await LLMConnector.streamGetChatCompletion(messages, { temperature: workspace?.openAiTemp ?? LLMConnector.defaultTemp, user: user, }); completeText = await LLMConnector.handleStream(response, stream, { uuid, sources, }); metrics = stream.metrics; } if (completeText?.length > 0) { const { chat } = await WorkspaceChats.new({ workspaceId: workspace.id, prompt: message, response: { text: completeText, sources, type: chatMode, attachments, metrics, }, threadId: thread?.id || null, user, }); writeResponseChunk(response, { uuid, type: "finalizeResponseStream", close: true, error: false, chatId: chat.id, metrics, }); return; } writeResponseChunk(response, { uuid, type: "finalizeResponseStream", close: true, error: false, metrics, }); return; } module.exports = { VALID_CHAT_MODE, streamChatWithWorkspace, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/embed.js
server/utils/chats/embed.js
const { v4: uuidv4 } = require("uuid"); const { getVectorDbClass, getLLMProvider } = require("../helpers"); const { chatPrompt, sourceIdentifier } = require("./index"); const { EmbedChats } = require("../../models/embedChats"); const { convertToPromptHistory, writeResponseChunk, } = require("../helpers/chat/responses"); const { DocumentManager } = require("../DocumentManager"); async function streamChatWithForEmbed( response, /** @type {import("@prisma/client").embed_configs & {workspace?: import("@prisma/client").workspaces}} */ embed, /** @type {String} */ message, /** @type {String} */ sessionId, { promptOverride, modelOverride, temperatureOverride, username } ) { const chatMode = embed.chat_mode; const chatModel = embed.allow_model_override ? modelOverride : null; // If there are overrides in request & they are permitted, override the default workspace ref information. if (embed.allow_prompt_override) embed.workspace.openAiPrompt = promptOverride; if (embed.allow_temperature_override) embed.workspace.openAiTemp = parseFloat(temperatureOverride); const uuid = uuidv4(); const LLMConnector = getLLMProvider({ provider: embed?.workspace?.chatProvider, model: chatModel ?? embed.workspace?.chatModel, }); const VectorDb = getVectorDbClass(); const messageLimit = embed.message_limit ?? 20; const hasVectorizedSpace = await VectorDb.hasNamespace(embed.workspace.slug); const embeddingsCount = await VectorDb.namespaceCount(embed.workspace.slug); // User is trying to query-mode chat a workspace that has no data in it - so // we should exit early as no information can be found under these conditions. if ((!hasVectorizedSpace || embeddingsCount === 0) && chatMode === "query") { writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse: "I do not have enough information to answer that. Try another question.", sources: [], close: true, error: null, }); return; } let completeText; let metrics = {}; let contextTexts = []; let sources = []; let pinnedDocIdentifiers = []; const { rawHistory, chatHistory } = await recentEmbedChatHistory( sessionId, embed, messageLimit ); // See stream.js comment for more information on this implementation. await new DocumentManager({ workspace: embed.workspace, maxTokens: LLMConnector.promptWindowLimit(), }) .pinnedDocs() .then((pinnedDocs) => { pinnedDocs.forEach((doc) => { const { pageContent, ...metadata } = doc; pinnedDocIdentifiers.push(sourceIdentifier(doc)); contextTexts.push(doc.pageContent); sources.push({ text: pageContent.slice(0, 1_000) + "...continued on in source document...", ...metadata, }); }); }); const vectorSearchResults = embeddingsCount !== 0 ? await VectorDb.performSimilaritySearch({ namespace: embed.workspace.slug, input: message, LLMConnector, similarityThreshold: embed.workspace?.similarityThreshold, topN: embed.workspace?.topN, filterIdentifiers: pinnedDocIdentifiers, rerank: embed.workspace?.vectorSearchMode === "rerank", }) : { contextTexts: [], sources: [], message: null, }; // Failed similarity search if it was run at all and failed. if (!!vectorSearchResults.message) { writeResponseChunk(response, { id: uuid, type: "abort", textResponse: null, sources: [], close: true, error: "Failed to connect to vector database provider.", }); return; } const { fillSourceWindow } = require("../helpers/chat"); const filledSources = fillSourceWindow({ nDocs: embed.workspace?.topN || 4, searchResults: vectorSearchResults.sources, history: rawHistory, filterIdentifiers: pinnedDocIdentifiers, }); // Why does contextTexts get all the info, but sources only get current search? // This is to give the ability of the LLM to "comprehend" a contextual response without // populating the Citations under a response with documents the user "thinks" are irrelevant // due to how we manage backfilling of the context to keep chats with the LLM more correct in responses. // If a past citation was used to answer the question - that is visible in the history so it logically makes sense // and does not appear to the user that a new response used information that is otherwise irrelevant for a given prompt. // TLDR; reduces GitHub issues for "LLM citing document that has no answer in it" while keep answers highly accurate. contextTexts = [...contextTexts, ...filledSources.contextTexts]; sources = [...sources, ...vectorSearchResults.sources]; // If in query mode and no sources are found in current search or backfilled from history, do not // let the LLM try to hallucinate a response or use general knowledge if (chatMode === "query" && contextTexts.length === 0) { writeResponseChunk(response, { id: uuid, type: "textResponse", textResponse: embed.workspace?.queryRefusalResponse ?? "There is no relevant information in this workspace to answer your query.", sources: [], close: true, error: null, }); return; } // Compress message to ensure prompt passes token limit with room for response // and build system messages based on inputs and history. const messages = await LLMConnector.compressMessages( { systemPrompt: await chatPrompt(embed.workspace, username), userPrompt: message, contextTexts, chatHistory, }, rawHistory ); // If streaming is not explicitly enabled for connector // we do regular waiting of a response and send a single chunk. if (LLMConnector.streamingEnabled() !== true) { console.log( `\x1b[31m[STREAMING DISABLED]\x1b[0m Streaming is not available for ${LLMConnector.constructor.name}. Will use regular chat method.` ); const { textResponse, metrics: performanceMetrics } = await LLMConnector.getChatCompletion(messages, { temperature: embed.workspace?.openAiTemp ?? LLMConnector.defaultTemp, }); completeText = textResponse; metrics = performanceMetrics; writeResponseChunk(response, { uuid, sources: [], type: "textResponseChunk", textResponse: completeText, close: true, error: false, }); } else { const stream = await LLMConnector.streamGetChatCompletion(messages, { temperature: embed.workspace?.openAiTemp ?? LLMConnector.defaultTemp, }); completeText = await LLMConnector.handleStream(response, stream, { uuid, sources: [], }); metrics = stream.metrics; } await EmbedChats.new({ embedId: embed.id, prompt: message, response: { text: completeText, type: chatMode, sources, metrics }, connection_information: response.locals.connection ? { ...response.locals.connection, username: !!username ? String(username) : null, } : { username: !!username ? String(username) : null }, sessionId, }); return; } /** * @param {string} sessionId the session id of the user from embed widget * @param {Object} embed the embed config object * @param {Number} messageLimit the number of messages to return * @returns {Promise<{rawHistory: import("@prisma/client").embed_chats[], chatHistory: {role: string, content: string, attachments?: Object[]}[]}> */ async function recentEmbedChatHistory(sessionId, embed, messageLimit = 20) { const rawHistory = ( await EmbedChats.forEmbedByUser(embed.id, sessionId, messageLimit, { id: "desc", }) ).reverse(); return { rawHistory, chatHistory: convertToPromptHistory(rawHistory) }; } module.exports = { streamChatWithForEmbed, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/chats/commands/reset.js
server/utils/chats/commands/reset.js
const { WorkspaceChats } = require("../../../models/workspaceChats"); async function resetMemory( workspace, _message, msgUUID, user = null, thread = null ) { // If thread is present we are wanting to reset this specific thread. Not the whole workspace. thread ? await WorkspaceChats.markThreadHistoryInvalid( workspace.id, user, thread.id ) : await WorkspaceChats.markHistoryInvalid(workspace.id, user); return { uuid: msgUUID, type: "textResponse", textResponse: "Workspace chat memory was reset!", sources: [], close: true, error: false, action: "reset_chat", }; } module.exports = { resetMemory, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/files/index.js
server/utils/files/index.js
const fs = require("fs"); const path = require("path"); const { v5: uuidv5 } = require("uuid"); const { Document } = require("../../models/documents"); const { DocumentSyncQueue } = require("../../models/documentSyncQueue"); const documentsPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../storage/documents`) : path.resolve(process.env.STORAGE_DIR, `documents`); const directUploadsPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../storage/direct-uploads`) : path.resolve(process.env.STORAGE_DIR, `direct-uploads`); const vectorCachePath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../storage/vector-cache`) : path.resolve(process.env.STORAGE_DIR, `vector-cache`); const hotdirPath = process.env.NODE_ENV === "development" ? path.resolve(__dirname, `../../../collector/hotdir`) : path.resolve(process.env.STORAGE_DIR, `../../collector/hotdir`); // Should take in a folder that is a subfolder of documents // eg: youtube-subject/video-123.json async function fileData(filePath = null) { if (!filePath) throw new Error("No docPath provided in request"); const fullFilePath = path.resolve(documentsPath, normalizePath(filePath)); if (!fs.existsSync(fullFilePath) || !isWithin(documentsPath, fullFilePath)) return null; const data = fs.readFileSync(fullFilePath, "utf8"); return JSON.parse(data); } async function viewLocalFiles() { if (!fs.existsSync(documentsPath)) fs.mkdirSync(documentsPath); const liveSyncAvailable = await DocumentSyncQueue.enabled(); const directory = { name: "documents", type: "folder", items: [], }; for (const file of fs.readdirSync(documentsPath)) { if (path.extname(file) === ".md") continue; const folderPath = path.resolve(documentsPath, file); const isFolder = fs.lstatSync(folderPath).isDirectory(); if (isFolder) { const subdocs = { name: file, type: "folder", items: [], }; const subfiles = fs.readdirSync(folderPath); const filenames = {}; const filePromises = []; for (let i = 0; i < subfiles.length; i++) { const subfile = subfiles[i]; const cachefilename = `${file}/${subfile}`; if (path.extname(subfile) !== ".json") continue; filePromises.push( fileToPickerData({ pathToFile: path.join(folderPath, subfile), liveSyncAvailable, cachefilename, }) ); filenames[cachefilename] = subfile; } const results = await Promise.all(filePromises) .then((results) => results.filter((i) => !!i)) // Remove null results .then((results) => results.filter((i) => hasRequiredMetadata(i))); // Remove invalid file structures subdocs.items.push(...results); // Grab the pinned workspaces and watched documents for this folder's documents // at the time of the query so we don't have to re-query the database for each file const pinnedWorkspacesByDocument = await getPinnedWorkspacesByDocument(filenames); const watchedDocumentsFilenames = await getWatchedDocumentFilenames(filenames); for (const item of subdocs.items) { item.pinnedWorkspaces = pinnedWorkspacesByDocument[item.name] || []; item.watched = watchedDocumentsFilenames.hasOwnProperty(item.name) || false; } directory.items.push(subdocs); } } // Make sure custom-documents is always the first folder in picker directory.items = [ directory.items.find((folder) => folder.name === "custom-documents"), ...directory.items.filter((folder) => folder.name !== "custom-documents"), ].filter((i) => !!i); return directory; } /** * Gets the documents by folder name. * @param {string} folderName - The name of the folder to get the documents from. * @returns {Promise<{folder: string, documents: any[], code: number, error: string}>} - The documents by folder name. */ async function getDocumentsByFolder(folderName = "") { if (!folderName) { return { folder: folderName, documents: [], code: 400, error: "Folder name must be provided.", }; } const folderPath = path.resolve(documentsPath, normalizePath(folderName)); if ( !isWithin(documentsPath, folderPath) || !fs.existsSync(folderPath) || !fs.lstatSync(folderPath).isDirectory() ) { return { folder: folderName, documents: [], code: 404, error: `Folder "${folderName}" does not exist.`, }; } const documents = []; const filenames = {}; const files = fs.readdirSync(folderPath); for (const file of files) { if (path.extname(file) !== ".json") continue; const filePath = path.join(folderPath, file); const rawData = fs.readFileSync(filePath, "utf8"); const cachefilename = `${folderName}/${file}`; const { pageContent, ...metadata } = JSON.parse(rawData); documents.push({ name: file, type: "file", ...metadata, cached: await cachedVectorInformation(cachefilename, true), }); filenames[cachefilename] = file; } // Get pinned and watched information for each document in the folder const pinnedWorkspacesByDocument = await getPinnedWorkspacesByDocument(filenames); const watchedDocumentsFilenames = await getWatchedDocumentFilenames(filenames); for (let doc of documents) { doc.pinnedWorkspaces = pinnedWorkspacesByDocument[doc.name] || []; doc.watched = Object.prototype.hasOwnProperty.call( watchedDocumentsFilenames, doc.name ); } return { folder: folderName, documents, code: 200, error: null }; } /** * Searches the vector-cache folder for existing information so we dont have to re-embed a * document and can instead push directly to vector db. * @param {string} filename - the filename to check for cached vector information * @param {boolean} checkOnly - if true, only check if the file exists, do not return the cached data * @returns {Promise<{exists: boolean, chunks: any[]}>} - a promise that resolves to an object containing the existence of the file and its cached chunks */ async function cachedVectorInformation(filename = null, checkOnly = false) { if (!filename) return checkOnly ? false : { exists: false, chunks: [] }; const digest = uuidv5(filename, uuidv5.URL); const file = path.resolve(vectorCachePath, `${digest}.json`); const exists = fs.existsSync(file); if (checkOnly) return exists; if (!exists) return { exists, chunks: [] }; console.log( `Cached vectorized results of ${filename} found! Using cached data to save on embed costs.` ); const rawData = fs.readFileSync(file, "utf8"); return { exists: true, chunks: JSON.parse(rawData) }; } // vectorData: pre-chunked vectorized data for a given file that includes the proper metadata and chunk-size limit so it can be iterated and dumped into Pinecone, etc // filename is the fullpath to the doc so we can compare by filename to find cached matches. async function storeVectorResult(vectorData = [], filename = null) { if (!filename) return; console.log( `Caching vectorized results of ${filename} to prevent duplicated embedding.` ); if (!fs.existsSync(vectorCachePath)) fs.mkdirSync(vectorCachePath); const digest = uuidv5(filename, uuidv5.URL); const writeTo = path.resolve(vectorCachePath, `${digest}.json`); fs.writeFileSync(writeTo, JSON.stringify(vectorData), "utf8"); return; } // Purges a file from the documents/ folder. async function purgeSourceDocument(filename = null) { if (!filename) return; const filePath = path.resolve(documentsPath, normalizePath(filename)); if ( !fs.existsSync(filePath) || !isWithin(documentsPath, filePath) || !fs.lstatSync(filePath).isFile() ) return; console.log(`Purging source document of ${filename}.`); fs.rmSync(filePath); return; } // Purges a vector-cache file from the vector-cache/ folder. async function purgeVectorCache(filename = null) { if (!filename) return; const digest = uuidv5(filename, uuidv5.URL); const filePath = path.resolve(vectorCachePath, `${digest}.json`); if (!fs.existsSync(filePath) || !fs.lstatSync(filePath).isFile()) return; console.log(`Purging vector-cache of ${filename}.`); fs.rmSync(filePath); return; } // Search for a specific document by its unique name in the entire `documents` // folder via iteration of all folders and checking if the expected file exists. async function findDocumentInDocuments(documentName = null) { if (!documentName) return null; for (const folder of fs.readdirSync(documentsPath)) { const isFolder = fs .lstatSync(path.join(documentsPath, folder)) .isDirectory(); if (!isFolder) continue; const targetFilename = normalizePath(documentName); const targetFileLocation = path.join(documentsPath, folder, targetFilename); if ( !fs.existsSync(targetFileLocation) || !isWithin(documentsPath, targetFileLocation) ) continue; const fileData = fs.readFileSync(targetFileLocation, "utf8"); const cachefilename = `${folder}/${targetFilename}`; const { pageContent, ...metadata } = JSON.parse(fileData); return { name: targetFilename, type: "file", ...metadata, cached: await cachedVectorInformation(cachefilename, true), }; } return null; } /** * 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. */ function isWithin(outer, inner) { if (outer === inner) return false; const rel = path.relative(outer, inner); return !rel.startsWith("../") && rel !== ".."; } function normalizePath(filepath = "") { const result = path .normalize(filepath.trim()) .replace(/^(\.\.(\/|\\|$))+/, "") .trim(); if (["..", ".", "/"].includes(result)) throw new Error("Invalid path."); return result; } // Check if the vector-cache folder is empty or not // useful for it the user is changing embedders as this will // break the previous cache. function hasVectorCachedFiles() { try { return ( fs.readdirSync(vectorCachePath)?.filter((name) => name.endsWith(".json")) .length !== 0 ); } catch {} return false; } /** * @param {string[]} filenames - array of filenames to check for pinned workspaces * @returns {Promise<Record<string, string[]>>} - a record of filenames and their corresponding workspaceIds */ async function getPinnedWorkspacesByDocument(filenames = []) { return ( await Document.where( { docpath: { in: Object.keys(filenames), }, pinned: true, }, null, null, null, { workspaceId: true, docpath: true, } ) ).reduce((result, { workspaceId, docpath }) => { const filename = filenames[docpath]; if (!result[filename]) result[filename] = []; if (!result[filename].includes(workspaceId)) result[filename].push(workspaceId); return result; }, {}); } /** * Get a record of filenames and their corresponding workspaceIds that have watched a document * that will be used to determine if a document should be displayed in the watched documents sidebar * @param {string[]} filenames - array of filenames to check for watched workspaces * @returns {Promise<Record<string, string[]>>} - a record of filenames and their corresponding workspaceIds */ async function getWatchedDocumentFilenames(filenames = []) { return ( await Document.where( { docpath: { in: Object.keys(filenames) }, watched: true, }, null, null, null, { workspaceId: true, docpath: true } ) ).reduce((result, { workspaceId, docpath }) => { const filename = filenames[docpath]; result[filename] = workspaceId; return result; }, {}); } /** * Purges the entire vector-cache folder and recreates it. * @returns {void} */ function purgeEntireVectorCache() { fs.rmSync(vectorCachePath, { recursive: true, force: true }); fs.mkdirSync(vectorCachePath); return; } /** * File size threshold for files that are too large to be read into memory (MB) * * If the file is larger than this, we will stream it and parse it in chunks * This is to prevent us from using too much memory when parsing large files * or loading the files in the file picker. * @TODO - When lazy loading for folders is implemented, we should increase this threshold (512MB) * since it will always be faster to readSync than to stream the file and parse it in chunks. */ const FILE_READ_SIZE_THRESHOLD = 150 * (1024 * 1024); /** * Converts a file to picker data * @param {string} pathToFile - The path to the file to convert * @param {boolean} liveSyncAvailable - Whether live sync is available * @returns {Promise<{name: string, type: string, [string]: any, cached: boolean, canWatch: boolean}>} - The picker data */ async function fileToPickerData({ pathToFile, liveSyncAvailable = false, cachefilename = null, }) { let metadata = {}; const filename = path.basename(pathToFile); const fileStats = fs.statSync(pathToFile); const cachedStatus = await cachedVectorInformation(cachefilename, true); if (fileStats.size < FILE_READ_SIZE_THRESHOLD) { const rawData = fs.readFileSync(pathToFile, "utf8"); try { metadata = JSON.parse(rawData); // Remove the pageContent field from the metadata - it is large and not needed for the picker delete metadata.pageContent; } catch (err) { console.error("Error parsing file", err); return null; } return { name: filename, type: "file", ...metadata, cached: cachedStatus, canWatch: liveSyncAvailable ? DocumentSyncQueue.canWatch(metadata) : false, // pinnedWorkspaces: [], // This is the list of workspaceIds that have pinned this document // watched: false, // boolean to indicate if this document is watched in ANY workspace }; } console.log( `Stream-parsing ${path.basename(pathToFile)} because it exceeds the ${FILE_READ_SIZE_THRESHOLD} byte limit.` ); const stream = fs.createReadStream(pathToFile, { encoding: "utf8" }); try { let fileContent = ""; metadata = await new Promise((resolve, reject) => { stream .on("data", (chunk) => { fileContent += chunk; }) .on("end", () => { metadata = JSON.parse(fileContent); // Remove the pageContent field from the metadata - it is large and not needed for the picker delete metadata.pageContent; resolve(metadata); }) .on("error", (err) => { console.error("Error parsing file", err); reject(null); }); }).catch((err) => { console.error("Error parsing file", err); }); } catch (err) { console.error("Error parsing file", err); metadata = null; } finally { stream.destroy(); } // If the metadata is empty or something went wrong, return null if (!metadata || !Object.keys(metadata)?.length) { console.log(`Stream-parsing failed for ${path.basename(pathToFile)}`); return null; } return { name: filename, type: "file", ...metadata, cached: cachedStatus, canWatch: liveSyncAvailable ? DocumentSyncQueue.canWatch(metadata) : false, }; } const REQUIRED_FILE_OBJECT_FIELDS = [ "name", "type", "url", "title", "docAuthor", "description", "docSource", "chunkSource", "published", "wordCount", "token_count_estimate", ]; /** * Checks if a given metadata object has all the required fields * @param {{name: string, type: string, url: string, title: string, docAuthor: string, description: string, docSource: string, chunkSource: string, published: string, wordCount: number, token_count_estimate: number}} metadata - The metadata object to check (fileToPickerData) * @returns {boolean} - Returns true if the metadata object has all the required fields, false otherwise */ function hasRequiredMetadata(metadata = {}) { return REQUIRED_FILE_OBJECT_FIELDS.every((field) => metadata.hasOwnProperty(field) ); } module.exports = { findDocumentInDocuments, cachedVectorInformation, viewLocalFiles, purgeSourceDocument, purgeVectorCache, storeVectorResult, fileData, normalizePath, isWithin, documentsPath, directUploadsPath, hasVectorCachedFiles, purgeEntireVectorCache, getDocumentsByFolder, hotdirPath, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/files/logo.js
server/utils/files/logo.js
const path = require("path"); const fs = require("fs"); const { getType } = require("mime"); const { v4 } = require("uuid"); const { SystemSettings } = require("../../models/systemSettings"); const { normalizePath, isWithin } = require("."); const LOGO_FILENAME = "anything-llm.png"; const LOGO_FILENAME_DARK = "anything-llm-dark.png"; /** * Checks if the filename is the default logo filename for dark or light mode. * @param {string} filename - The filename to check. * @returns {boolean} Whether the filename is the default logo filename. */ function isDefaultFilename(filename) { return [LOGO_FILENAME, LOGO_FILENAME_DARK].includes(filename); } function validFilename(newFilename = "") { return !isDefaultFilename(newFilename); } /** * Shows the logo for the current theme. In dark mode, it shows the light logo * and vice versa. * @param {boolean} darkMode - Whether the logo should be for dark mode. * @returns {string} The filename of the logo. */ function getDefaultFilename(darkMode = true) { return darkMode ? LOGO_FILENAME : LOGO_FILENAME_DARK; } async function determineLogoFilepath(defaultFilename = LOGO_FILENAME) { const currentLogoFilename = await SystemSettings.currentLogoFilename(); const basePath = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets") : path.join(__dirname, "../../storage/assets"); const defaultFilepath = path.join(basePath, defaultFilename); if (currentLogoFilename && validFilename(currentLogoFilename)) { customLogoPath = path.join(basePath, normalizePath(currentLogoFilename)); if (!isWithin(path.resolve(basePath), path.resolve(customLogoPath))) return defaultFilepath; return fs.existsSync(customLogoPath) ? customLogoPath : defaultFilepath; } return defaultFilepath; } function fetchLogo(logoPath) { if (!fs.existsSync(logoPath)) { return { found: false, buffer: null, size: 0, mime: "none/none", }; } const mime = getType(logoPath); const buffer = fs.readFileSync(logoPath); return { found: true, buffer, size: buffer.length, mime, }; } async function renameLogoFile(originalFilename = null) { const extname = path.extname(originalFilename) || ".png"; const newFilename = `${v4()}${extname}`; const assetsDirectory = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets") : path.join(__dirname, `../../storage/assets`); const originalFilepath = path.join( assetsDirectory, normalizePath(originalFilename) ); if (!isWithin(path.resolve(assetsDirectory), path.resolve(originalFilepath))) throw new Error("Invalid file path."); // The output always uses a random filename. const outputFilepath = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets", normalizePath(newFilename)) : path.join(__dirname, `../../storage/assets`, normalizePath(newFilename)); fs.renameSync(originalFilepath, outputFilepath); return newFilename; } async function removeCustomLogo(logoFilename = LOGO_FILENAME) { if (!logoFilename || !validFilename(logoFilename)) return false; const assetsDirectory = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets") : path.join(__dirname, `../../storage/assets`); const logoPath = path.join(assetsDirectory, normalizePath(logoFilename)); if (!isWithin(path.resolve(assetsDirectory), path.resolve(logoPath))) throw new Error("Invalid file path."); if (fs.existsSync(logoPath)) fs.unlinkSync(logoPath); return true; } module.exports = { fetchLogo, renameLogoFile, removeCustomLogo, validFilename, getDefaultFilename, determineLogoFilepath, isDefaultFilename, LOGO_FILENAME, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/files/purgeDocument.js
server/utils/files/purgeDocument.js
const fs = require("fs"); const path = require("path"); const { purgeVectorCache, purgeSourceDocument, normalizePath, isWithin, documentsPath, } = require("."); const { Document } = require("../../models/documents"); const { Workspace } = require("../../models/workspace"); async function purgeDocument(filename = null) { if (!filename || !normalizePath(filename)) return; await purgeVectorCache(filename); await purgeSourceDocument(filename); const workspaces = await Workspace.where(); for (const workspace of workspaces) { await Document.removeDocuments(workspace, [filename]); } return; } /** * Purge a folder and all its contents. This will also remove all vector-cache files and workspace document associations * for the documents within the folder. * @notice This function is not recursive. It only purges the contents of the specified folder. * @notice You cannot purge the `custom-documents` folder. * @param {string} folderName - The name/path of the folder to purge. * @returns {Promise<void>} */ async function purgeFolder(folderName = null) { if (!folderName) return; const subFolder = normalizePath(folderName); const subFolderPath = path.resolve(documentsPath, subFolder); const validRemovableSubFolders = fs .readdirSync(documentsPath) .map((folder) => { // Filter out any results which are not folders or // are the protected custom-documents folder. if (folder === "custom-documents") return null; const subfolderPath = path.resolve(documentsPath, folder); if (!fs.lstatSync(subfolderPath).isDirectory()) return null; return folder; }) .filter((subFolder) => !!subFolder); if ( !validRemovableSubFolders.includes(subFolder) || !fs.existsSync(subFolderPath) || !isWithin(documentsPath, subFolderPath) ) return; const filenames = fs .readdirSync(subFolderPath) .map((file) => path.join(subFolderPath, file).replace(documentsPath + "/", "") ); const workspaces = await Workspace.where(); const purgePromises = []; // Remove associated Vector-cache files for (const filename of filenames) { const rmVectorCache = () => new Promise((resolve) => purgeVectorCache(filename).then(() => resolve(true)) ); purgePromises.push(rmVectorCache); } // Remove workspace document associations for (const workspace of workspaces) { const rmWorkspaceDoc = () => new Promise((resolve) => Document.removeDocuments(workspace, filenames).then(() => resolve(true)) ); purgePromises.push(rmWorkspaceDoc); } await Promise.all(purgePromises.flat().map((f) => f())); fs.rmSync(subFolderPath, { recursive: true }); // Delete target document-folder and source files. return; } module.exports = { purgeDocument, purgeFolder, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false
Mintplex-Labs/anything-llm
https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/files/pfp.js
server/utils/files/pfp.js
const path = require("path"); const fs = require("fs"); const { getType } = require("mime"); const { User } = require("../../models/user"); const { normalizePath, isWithin } = require("."); const { Workspace } = require("../../models/workspace"); function fetchPfp(pfpPath) { if (!fs.existsSync(pfpPath)) { return { found: false, buffer: null, size: 0, mime: "none/none", }; } const mime = getType(pfpPath); const buffer = fs.readFileSync(pfpPath); return { found: true, buffer, size: buffer.length, mime, }; } async function determinePfpFilepath(id) { const numberId = Number(id); const user = await User.get({ id: numberId }); const pfpFilename = user?.pfpFilename || null; if (!pfpFilename) return null; const basePath = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets/pfp") : path.join(__dirname, "../../storage/assets/pfp"); const pfpFilepath = path.join(basePath, normalizePath(pfpFilename)); if (!isWithin(path.resolve(basePath), path.resolve(pfpFilepath))) return null; if (!fs.existsSync(pfpFilepath)) return null; return pfpFilepath; } async function determineWorkspacePfpFilepath(slug) { const workspace = await Workspace.get({ slug }); const pfpFilename = workspace?.pfpFilename || null; if (!pfpFilename) return null; const basePath = process.env.STORAGE_DIR ? path.join(process.env.STORAGE_DIR, "assets/pfp") : path.join(__dirname, "../../storage/assets/pfp"); const pfpFilepath = path.join(basePath, normalizePath(pfpFilename)); if (!isWithin(path.resolve(basePath), path.resolve(pfpFilepath))) return null; if (!fs.existsSync(pfpFilepath)) return null; return pfpFilepath; } module.exports = { fetchPfp, determinePfpFilepath, determineWorkspacePfpFilepath, };
javascript
MIT
e287fab56089cf8fcea9ba579a3ecdeca0daa313
2026-01-04T14:57:11.963777Z
false