* implement native embedder job queue * persist embedding progress across renders * add development worker timeouts * change to static method * native reranker * remove useless return * lint * simplify * make embedding worker timeout value configurable by admin * add event emission for missing data * lint * remove onProgress callback argument * make rerank to rerankDirect * persists progress state across app reloads * remove chunk level progress reporting * remove unuse dvariable * make NATIVE_RERANKING_WORKER_TIMEOUT user configurable * remove dead code * scope embedding progress per-user and clear stale state on SSE reconnect * lint * revert vector databases and embedding engines to call their original methods * simplify rerank * simplify progress fetching by removing updateProgressFromApi * remove duplicate jsdoc * replace sessionStorage persistence with server-side history replay for embedding progress * fix old comment * fix: ignore premature SSE all_complete when embedding hasn't started yet The SSE connection opens before the embedding API call fires, so the server sees no buffered history and immediately sends all_complete. Firefox dispatches this eagerly enough that it closes the EventSource before real progress events arrive, causing the progress UI to clear and fall back to the loading spinner. Chrome's EventSource timing masks the race. Track slugs where startEmbedding was called but no real progress event has arrived yet via awaitingProgressRef. Ignore the first all_complete for those slugs and keep the connection open for the real events. * reduce duplication with progress emissions * remove dead code * refactor: streamline embedding progress handling Removed unnecessary tracking of slugs for premature all_complete events in the EmbeddingProgressProvider. Updated the server-side logic to avoid sending all_complete when no embedding is in progress, allowing the connection to remain open for real events. Adjusted the embedding initiation flow to ensure the server processes the job before the SSE connection opens, improving the reliability of progress updates. * fix stale comment * remove unused function * fix event emissions for document creation failure * refactor: move Reranking Worker Idle Timeout input to LanceDBOptions component Extracted the Reranking Worker Idle Timeout input from GeneralEmbeddingPreference and integrated it into the LanceDBOptions component. This change enhances modularity and maintains a cleaner structure for the settings interface. * lint * remove unused hadHistory vars * refactor workspace directory by hoisting component and converting into functions * moved EmbeddingProgressProvider to wrap Document Manager Modal * refactor embed progress SSE connection to use fetchEventSource instead of native EventSource API. * refactor message handlng into a function and reduce duplication * refactor: utilize writeResponseChunk for event emissions in document embedding progress SSE * refactor: explicit in-proc embedding and rerank methods that are called by workers instead of process.send checks * Abstract EmbeddingProgressBus and Worker Queue into modules * remove error and toast messages on embed process result * use safeJsonParse * add chunk-level progress events with per-document progress bar in UI * remove unused parameter * rename all worker timeout references to use ttl | remove ttl updating from UI * refactor: pass embedding context through job payload instead of global state * lint * add graceful shutdown for workers * apply figma styles * refactor embedding worker to use bree * use existing WorkerQueue class as the management layer for jobs * lint * revert all reranking worker changes back to master state Removes the reranking worker queue, rerankViaWorker/rerankInProcess renames, and NATIVE_RERANKING_WORKER_TTL config so this branch only contains the embedding worker job queue feature. * remove breeManaged flag — WorkerQueue always spawns via Bree * fix prompt embedding bug * have embedTextInput call embedChunksInProcess * add message field to `process.send()` * remove nullish check and error throw * remove bespoke graceful shutdown logix * add spawnWorker method and asbtract redudant flows into helper methods * remove unneeded comment * remove recomputation of TTL value * frontend cleanup and refactor * wip on backend refactor * backend overhaul * small lint * second pass * add logging, update endpoint * simple refactor * add reporting to all embedder providers * fix styles --------- Co-authored-by: Timothy Carambat <rambat1010@gmail.com>
129 lines
4.4 KiB
JavaScript
129 lines
4.4 KiB
JavaScript
const {
|
|
toChunks,
|
|
maximumChunkLength,
|
|
reportEmbeddingProgress,
|
|
} = require("../../helpers");
|
|
|
|
class GenericOpenAiEmbedder {
|
|
constructor() {
|
|
if (!process.env.EMBEDDING_BASE_PATH)
|
|
throw new Error(
|
|
"GenericOpenAI must have a valid base path to use for the api."
|
|
);
|
|
this.className = "GenericOpenAiEmbedder";
|
|
const { OpenAI: OpenAIApi } = require("openai");
|
|
this.basePath = process.env.EMBEDDING_BASE_PATH;
|
|
this.openai = new OpenAIApi({
|
|
baseURL: this.basePath,
|
|
apiKey: process.env.GENERIC_OPEN_AI_EMBEDDING_API_KEY ?? null,
|
|
});
|
|
this.model = process.env.EMBEDDING_MODEL_PREF ?? null;
|
|
this.embeddingMaxChunkLength = maximumChunkLength();
|
|
|
|
// this.maxConcurrentChunks is delegated to the getter below.
|
|
// Refer to your specific model and provider you use this class with to determine a valid maxChunkLength
|
|
this.log(`Initialized ${this.model}`, {
|
|
baseURL: this.basePath,
|
|
maxConcurrentChunks: this.maxConcurrentChunks,
|
|
embeddingMaxChunkLength: this.embeddingMaxChunkLength,
|
|
});
|
|
}
|
|
|
|
log(text, ...args) {
|
|
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
|
|
}
|
|
|
|
/**
|
|
* returns the `GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS` env variable as a number or null if the env variable is not set or is not a number.
|
|
* The minimum delay is 500ms.
|
|
*
|
|
* For some implementation this is necessary to avoid 429 errors due to rate limiting or
|
|
* hardware limitations where a single-threaded process is not able to handle the requests fast enough.
|
|
* @returns {number}
|
|
*/
|
|
get apiRequestDelay() {
|
|
if (!("GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS" in process.env)) return null;
|
|
if (isNaN(Number(process.env.GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS)))
|
|
return null;
|
|
const delayTimeout = Number(
|
|
process.env.GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS
|
|
);
|
|
if (delayTimeout < 500) return 500; // minimum delay of 500ms
|
|
return delayTimeout;
|
|
}
|
|
|
|
/**
|
|
* runs the delay if it is set and valid.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async runDelay() {
|
|
if (!this.apiRequestDelay) return;
|
|
this.log(`Delaying new batch request for ${this.apiRequestDelay}ms`);
|
|
await new Promise((resolve) => setTimeout(resolve, this.apiRequestDelay));
|
|
}
|
|
|
|
/**
|
|
* returns the `GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS` env variable as a number
|
|
* or 500 if the env variable is not set or is not a number.
|
|
* @returns {number}
|
|
*/
|
|
get maxConcurrentChunks() {
|
|
if (!process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS)
|
|
return 500;
|
|
if (
|
|
isNaN(Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS))
|
|
)
|
|
return 500;
|
|
return Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS);
|
|
}
|
|
|
|
async embedTextInput(textInput) {
|
|
const result = await this.embedChunks(
|
|
Array.isArray(textInput) ? textInput : [textInput]
|
|
);
|
|
return result?.[0] || [];
|
|
}
|
|
|
|
async embedChunks(textChunks = []) {
|
|
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
|
|
// we sequentially execute each max batch of text chunks possible.
|
|
// Refer to constructor maxConcurrentChunks for more info.
|
|
const allResults = [];
|
|
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
|
|
const { data = [], error = null } = await new Promise((resolve) => {
|
|
this.openai.embeddings
|
|
.create({
|
|
model: this.model,
|
|
input: chunk,
|
|
})
|
|
.then((result) => resolve({ data: result?.data, error: null }))
|
|
.catch((e) => {
|
|
e.type =
|
|
e?.response?.data?.error?.code ||
|
|
e?.response?.status ||
|
|
"failed_to_embed";
|
|
e.message = e?.response?.data?.error?.message || e.message;
|
|
resolve({ data: [], error: e });
|
|
});
|
|
});
|
|
|
|
// If any errors were returned from OpenAI abort the entire sequence because the embeddings
|
|
// will be incomplete.
|
|
if (error)
|
|
throw new Error(`GenericOpenAI Failed to embed: ${error.message}`);
|
|
allResults.push(...(data || []));
|
|
reportEmbeddingProgress(allResults.length, textChunks.length);
|
|
if (this.apiRequestDelay) await this.runDelay();
|
|
}
|
|
|
|
return allResults.length > 0 &&
|
|
allResults.every((embd) => embd.hasOwnProperty("embedding"))
|
|
? allResults.map((embd) => embd.embedding)
|
|
: null;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
GenericOpenAiEmbedder,
|
|
};
|