LibreChat/api/server/services/Runs/RunMananger.js
Danny Avila ea1dd59ef4
refactor(api): Central Logging 📜 (#1348)
* WIP: initial logging changes
add several transports in ~/config/winston
omit messages in logs, truncate long strings
add short blurb in dotenv for debug logging
GoogleClient: using logger
OpenAIClient: using logger, handleOpenAIErrors
Adding typedef for payload message
bumped winston and using winston-daily-rotate-file
moved config for server paths to ~/config dir
Added `DEBUG_LOGGING=true` to .env.example

* WIP: Refactor logging statements in code

* WIP: Refactor logging statements and import configurations

* WIP: Refactor logging statements and import configurations

* refactor: broadcast Redis initialization message with `info` not `debug`

* refactor: complete Refactor logging statements and import configurations

* chore: delete unused tools

* fix: circular dependencies due to accessing logger

* refactor(handleText): handle booleans and write tests

* refactor: redact sensitive values, better formatting

* chore: improve log formatting, avoid passing strings to 2nd arg

* fix(ci): fix jest tests due to logger changes

* refactor(getAvailablePluginsController): cache plugins as they are static and avoids async addOpenAPISpecs call every time

* chore: update docs

* chore: update docs

* chore: create separate meiliSync logger, clean up logs to avoid being unnecessarily verbose

* chore: spread objects where they are commonly logged to allow string truncation

* chore: improve error log formatting
2023-12-14 07:49:27 -05:00

99 lines
3.9 KiB
JavaScript

const { logger } = require('~/config');
/**
* @typedef {import('openai').OpenAI} OpenAI
* @typedef {import('../AssistantService').RunStep} RunStep
* @callback StepHandler
* @param {RunStep} step - A single run step to be processed.
*/
/**
* @typedef {Object} RunManager
* Manages the retrieval and processing of run steps based on run status.
* @property {Set<string>} seenSteps - A set of IDs for steps that have already been seen.
* @property {Object.<string, Promise<RunStep[]>>} stepsByStatus - Steps organized by run status.
* @property {Object.<string, StepHandler>} handlers - Handlers for different run statuses.
* @property {Object.<string, Promise>} lastStepPromiseByStatus - Last processed step's promise by run status.
* @property {Function} fetchRunSteps - Fetches run steps based on run status.
* @property {Function} handleStep - Handles a run step based on its status.
*/
/**
* Manages the retrieval and processing of run steps based on run status.
*/
class RunManager {
/**
* Initializes the RunManager instance.
* @param {Object.<string, StepHandler>} handlers - An object containing handler functions for different run statuses.
*/
constructor(handlers = {}) {
this.seenSteps = new Set();
this.stepsByStatus = {};
this.handlers = handlers;
this.lastStepPromiseByStatus = {};
}
/**
* Fetches run steps once and filters out already seen steps.
* @param {Object} params - The parameters for fetching run steps.
* @param {OpenAI} params.openai - The OpenAI client instance.
* @param {string} params.thread_id - The ID of the thread associated with the run.
* @param {string} params.run_id - The ID of the run to retrieve steps for.
* @param {string} params.runStatus - The status of the run.
* @param {boolean} [params.final] - The end of the run polling loop, due to `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or `expired` statuses.
*/
async fetchRunSteps({ openai, thread_id, run_id, runStatus, final = false }) {
// const { data: steps, first_id, last_id, has_more } = await openai.beta.threads.runs.steps.list(thread_id, run_id);
const { data: _steps } = await openai.beta.threads.runs.steps.list(thread_id, run_id);
const steps = _steps.sort((a, b) => a.created_at - b.created_at);
for (const [i, step] of steps.entries()) {
if (this.seenSteps.has(step.id)) {
continue;
}
const isLast = i === steps.length - 1;
this.seenSteps.add(step.id);
this.stepsByStatus[runStatus] = this.stepsByStatus[runStatus] || [];
const currentStepPromise = (async () => {
await (this.lastStepPromiseByStatus[runStatus] || Promise.resolve());
return this.handleStep({ step, runStatus, final, isLast });
})();
if (final && isLast) {
return await currentStepPromise;
}
this.lastStepPromiseByStatus[runStatus] = currentStepPromise;
this.stepsByStatus[runStatus].push(currentStepPromise);
}
}
/**
* Handles a run step based on its status.
* @param {Object} params - The parameters for handling a run step.
* @param {RunStep} params.step - The run step to handle.
* @param {string} params.runStatus - The status of the run step.
* @param {string} params.final - The final run status (no further polling will occur)
* @param {boolean} params.isLast - Whether the current step is the last step of the list.
*/
async handleStep({ step, runStatus, final, isLast }) {
if (this.handlers[runStatus]) {
return this.handlers[runStatus]({ step, final, isLast });
}
if (final && isLast && this.handlers['final']) {
return await this.handlers['final']({ step, runStatus, stepsByStatus: this.stepsByStatus });
}
logger.debug(`[RunManager] Default handler for ${step.id} with status \`${runStatus}\``, {
step,
runStatus,
final,
isLast,
});
return step;
}
}
module.exports = RunManager;