Member Junction
    Preparing search index...

    Hierarchy (View Summary)

    Index

    Constructors

    Accessors

    • get DefaultPromptTimeoutMS(): number

      Engine-level default model-call timeout, in milliseconds, applied when the caller supplies no AIPromptParams.timeoutMS. undefined (the default) means NO implicit bound — a prompt run with neither a timeout nor a cancellation token stays unbounded, exactly as before, so this change is behavior-preserving for existing callers.

      Subclasses (or a host application's runner subclass) can override this to impose a global safety ceiling on every prompt call.

      Returns number

    • get ParallelCoordinator(): IParallelExecutionCoordinator

      Lazily resolves the parallel execution coordinator.

      The coordinator is a SUBCLASS of AIPromptRunner — it inherits executeModel and the rest of the battle-tested execution path so there is a single source of truth for credential / driver / ChatParams / streaming resolution. That subclass relationship means the base cannot statically new it without a hard circular import, so we resolve it through the ClassFactory instead (the coordinator self-registers via @RegisterClass(AIPromptRunner, PARALLEL_COORDINATOR_KEY)). Created once per runner and reused; the runner's Provider override is propagated. Throws a clear error if the coordinator class was never loaded/registered — otherwise ClassFactory would silently fall back to a plain AIPromptRunner that lacks the parallel methods.

      Returns IParallelExecutionCoordinator

    Methods

    • Calculates the delay before the next failover attempt.

      Parameters

      • attemptNumber: number

        The current attempt number (1-based)

      • baseDelaySeconds: number

        The base delay in seconds from configuration

      Returns number

      Delay in milliseconds before the next attempt

      Implements exponential backoff with jitter by default. The delay increases exponentially with each attempt and includes random jitter to prevent thundering herd problems. Override this method to implement custom delay logic.

    • Composes the caller-supplied cancellation token with the resolved model-call timeout into a single AbortSignal that bounds one model call. NEITHER bound is discarded:

      • caller token only → the caller's signal is used directly (behavior unchanged)
      • timeout only → an internal controller aborts after the timeout elapses
      • both → an internal controller relays the caller's abort AND fires on timeout; whichever happens first wins
      • neither → Signal is undefined and the call runs unbounded (legacy behavior)

      Implemented with an AbortController + relay listener rather than AbortSignal.any() so it works on Node 18 (where AbortSignal.any does not exist — it landed in Node 20.3).

      Parameters

      Returns ExecutionBound

    • Executes the AI model with the rendered prompt.

      protected so the parallel coordinator subclass reuses this exact code path — credential resolution, driver selection, ChatParams construction, prefill, media handling, and streaming all live here ONCE. Do not duplicate this logic elsewhere.

      Parameters

      Returns Promise<ChatResult>

    • Executes the AI model with failover support

      Parameters

      Returns Promise<ChatResult>

      This method wraps the core executeModel functionality with intelligent failover capabilities. It will attempt to execute with different models/vendors according to the configured failover strategy when errors occur.

      The method calls several smaller, focused helper methods:

      • buildFailoverCandidates: Creates candidate models based on type restrictions
      • createCandidatesFromModels: Converts models to vendor-specific candidates
      • updatePromptRunWithFailoverSuccess: Records successful failover metadata
      • updatePromptRunWithFailoverFailure: Records failed failover metadata
      • createFailoverErrorResult: Creates standardized error response
    • Executes an AI prompt with full support for templates, model selection, and validation.

      Type Parameters

      • T = unknown

      Parameters

      Returns Promise<AIPromptRunResult<T>>

      Promise<AIPromptRunResult> The execution result with tracking information

      // Execute with specific result type
      interface AnalysisResult {
      sentiment: string;
      score: number;
      keywords: string[];
      }

      const result = await promptRunner.ExecutePrompt<AnalysisResult>({
      prompt: sentimentPrompt,
      data: { text: "Customer feedback text" }
      });

      if (result.success && result.result) {
      // result.result is typed as AnalysisResult
      console.log(`Sentiment: ${result.result.sentiment}, Score: ${result.result.score}`);
      }
    • Resolves the per-model-call timeout: the caller's AIPromptParams.timeoutMS, else the runner's DefaultPromptTimeoutMS. Non-positive / non-numeric values mean "no timeout".

      The bound is applied PER MODEL CALL (not per prompt execution), which mirrors the parallel path's existing taskTimeoutMS semantics: each failover candidate / validation retry gets a fresh budget rather than sharing one wall-clock window.

      NOTE (issue #3064): there is deliberately NO prompt-entity source here yet — the AIPrompt table has no TimeoutMS column today. Once a migration adds one and CodeGen regenerates the entity, this becomes prompt.TimeoutMS ?? params.timeoutMS ?? this.DefaultPromptTimeoutMS and every bound below starts honoring the per-prompt configuration with no other change.

      Parameters

      Returns number

    • Retrieves failover configuration from the prompt entity.

      Parameters

      Returns FailoverConfiguration

      FailoverConfiguration object with strategy and settings

      This method extracts failover configuration from the prompt entity and provides default values when configuration is not specified. Override this method to implement custom failover configuration logic.

    • Helper method for enhanced error logging with metadata

      Parameters

      • error: string | Error
      • Optionaloptions: {
            category?: string;
            maxErrorLength?: number;
            metadata?: Record<string, any>;
            model?: MJAIModelEntityExtended;
            prompt?: MJAIPromptEntityExtended;
            severity?: "error" | "warning" | "critical";
        }

      Returns void

    • Logs a failover attempt for tracking and debugging.

      Parameters

      • promptId: string

        The ID of the prompt being executed

      • attempt: FailoverAttempt

        The failover attempt details

      • willRetry: boolean

        Whether another attempt will be made

      Returns void

      This method logs detailed information about each failover attempt to help with debugging and monitoring. Override this method to implement custom logging or integrate with external monitoring systems.

    • Internal logging helper that wraps LogStatusEx with verbose control

      Parameters

      • message: string

        The message to log

      • verboseOnly: boolean = false

        Whether this is a verbose-only message

      • Optionalparams: AIPromptParams

        Optional prompt parameters for custom verbose check

      Returns void

    • Selects candidate models for failover based on the strategy and current failure.

      Parameters

      • currentModel: MJAIModelEntityExtended

        The model that just failed

      • currentVendorId: string

        The vendor ID that just failed

      • strategy: "None" | "SameModelDifferentVendor" | "NextBestModel" | "PowerRank"

        The failover strategy to use

      • modelStrategy: "PreferSameModel" | "PreferDifferentModel" | "RequireSameModel"

        The model selection preference

      • allCandidates: ModelVendorCandidate[]

        All available model-vendor candidates

      • attemptHistory: FailoverAttempt[]

        History of previous failover attempts

      Returns ModelVendorCandidate[]

      Array of candidates sorted by priority (highest first)

      This method implements different strategies for selecting failover candidates:

      • SameModelDifferentVendor: Try the same model with different vendors
      • NextBestModel: Try different models in order of preference
      • PowerRank: Use the global power ranking of models

      Override this method to implement custom candidate selection logic.

    • Determines whether a failover attempt should be made based on the error and configuration.

      Parameters

      • error: Error

        The error that occurred during execution

      • config: FailoverConfiguration

        The failover configuration

      • attemptNumber: number

        The current attempt number (1-based)

      Returns boolean

      True if failover should be attempted, false otherwise

      This method uses the ErrorAnalyzer to classify errors and determine if they are eligible for failover based on the configured error scope. Override this method to implement custom failover decision logic.

    • Awaits all in-flight prompt-run saves queued by this runner instance. The normal execution path does NOT call this — prompt-run persistence is intentionally fire-and-forget. Exposed for tests and for callers that need the AIPromptRun rows durably written before proceeding.

      Returns Promise<void>