Member Junction
    Preparing search index...

    Server specific sub-class that handles the automatic creation and updating of Templates and Template Contents entity records linked to the AI Prompt. This class extends the MJAIPromptEntityExtended class and overrides the Save() method and also provides additional utility functionality that is used within Save() and can be overridden by subclasses to provide custom logic for creating or updating the linked Template and Template Contents, etc.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    Accessors

    Methods

    AfterEntityAIAction BeforeEntityAIAction CascadeDeleteChildRecord CheckForChildRecords CheckPermissions ClearRestoreContext Config CopyFrom CreateLinkedTemplateAndTemplateContents createRootTemplateCategory Delete EmbedTextLocal EnforceDisjointSubtype EnsureDeleteComplete EnsureLoadComplete EnsureSaveComplete From GenerateEmbedding GenerateEmbeddingByFieldName GenerateEmbeddings GenerateEmbeddingsByFieldName Get GetAll GetChangesSinceLastSave GetDataObject GetDataObjectJSON GetFieldByCodeName GetFieldByName getOrCreateRootTemplateCategoryID GetRecordName GetRelatedEntityData GetRelatedEntityDataExt getTemplateContentTypeID GetTemplateParams Hydrate InitializeChildEntity InitializeParentEntity InnerLoad Load LoadFromData LoadRelatedEntities LoadTemplateParams LoadTemplateText NewRecord PropagateTransactionToParents RaiseEvent RaiseReadyForTransaction Refresh RegisterEventHandler RegisterResultHistoryEntry RegisterTransactionPreprocessing ResetVectors Revert Save Set SetMany SetRestoreContext SupportsEmbedTextLocal ThrowPermissionError To UpdateLinkedTemplateContents Validate ValidateAsync ValidateCacheSimilarityThresholdBetweenZeroAndOne ValidateCacheSimilarityThresholdRequiredForVectorMatchType ValidateCacheTTLSecondsIsPositive ValidateEffortLevelIsBetween1And100 ValidateOutputExampleRequiredWhenOutputTypeIsObject ValidateParallelConfigParamRequiredForConfigParamMode ValidateParallelCountRequiredForStaticCount ValidateResultSelectorPromptIDNotEqualID GetRecordChanges ResolveLeafEntity

    Constructors

    Properties

    _originalTemplateText: string

    private property to hold the template text.

    MAX_RESULT_HISTORY: 50

    Maximum number of BaseEntityResult entries retained in _resultHistory per entity instance. Set to 50 — enough for diagnostic context while bounding worst-case memory for entities that survive thousands of Save/Delete cycles.

    Accessors

    • get __mj_CreatedAt(): Date
      • Field Name: __mj_CreatedAt
      • Display Name: Created At
      • SQL Data Type: datetimeoffset
      • Default Value: getutcdate()

      Returns Date

    • get __mj_UpdatedAt(): Date
      • Field Name: __mj_UpdatedAt
      • Display Name: Updated At
      • SQL Data Type: datetimeoffset
      • Default Value: getutcdate()

      Returns Date

    • get ActiveUser(): UserInfo

      Internal helper method for the class and sub-classes - used to easily get the Active User which is either the ContextCurrentUser, if defined, or the Metadata.Provider.CurrentUser if not.

      Returns UserInfo

    • get AIModelType(): string
      • Field Name: AIModelType
      • Display Name: AI Model Type Name
      • SQL Data Type: nvarchar(50)

      Returns string

    • get AIModelTypeID(): string
      • Field Name: AIModelTypeID
      • Display Name: AI Model Type
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Model Types (vwAIModelTypes.ID)
      • Description: References the type of AI model this prompt is designed for (LLM, Image, Audio, etc.).

      Returns string

    • set AIModelTypeID(value: string): void

      Parameters

      • value: string

      Returns void

    • get AssistantPrefill(): string
      • Field Name: AssistantPrefill
      • Display Name: Assistant Prefill
      • SQL Data Type: nvarchar(MAX)
      • Description: Optional text to prefill the assistant response. The model will continue generating from where this text ends. Used with StopSequences for structured output extraction (e.g., prefill with ```json to get raw JSON). Only effective with providers that support prefill natively; see PrefillFallbackMode for non-supporting providers.

      Returns string

    • set AssistantPrefill(value: string): void

      Parameters

      • value: string

      Returns void

    • get CacheMatchType(): "Exact" | "Vector"
      • Field Name: CacheMatchType
      • Display Name: Cache Match Type
      • SQL Data Type: nvarchar(20)
      • Default Value: Exact
      • Value List Type: List
      • Possible Values
        • Exact
        • Vector
      • Description: Method for matching cached results: Exact (string matching) or Vector (embedding similarity).

      Returns "Exact" | "Vector"

    • set CacheMatchType(value: "Exact" | "Vector"): void

      Parameters

      • value: "Exact" | "Vector"

      Returns void

    • get CacheMustMatchAgent(): boolean
      • Field Name: CacheMustMatchAgent
      • Display Name: Cache Must Match Agent
      • SQL Data Type: bit
      • Default Value: 0
      • Description: When true, the agent context must match for a cache hit. When false, agent-specific and non-agent results can be used interchangeably.

      Returns boolean

    • set CacheMustMatchAgent(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get CacheMustMatchConfig(): boolean
      • Field Name: CacheMustMatchConfig
      • Display Name: Cache Must Match Config
      • SQL Data Type: bit
      • Default Value: 0
      • Description: When true, the configuration must match for a cache hit. When false, results from any configuration can be used.

      Returns boolean

    • set CacheMustMatchConfig(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get CacheMustMatchModel(): boolean
      • Field Name: CacheMustMatchModel
      • Display Name: Cache Must Match Model
      • SQL Data Type: bit
      • Default Value: 1
      • Description: When true, the AI model must match for a cache hit. When false, results from any model can be used.

      Returns boolean

    • set CacheMustMatchModel(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get CacheMustMatchVendor(): boolean
      • Field Name: CacheMustMatchVendor
      • Display Name: Cache Must Match Vendor
      • SQL Data Type: bit
      • Default Value: 1
      • Description: When true, the vendor must match for a cache hit. When false, results from any vendor can be used.

      Returns boolean

    • set CacheMustMatchVendor(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get CacheSimilarityThreshold(): number
      • Field Name: CacheSimilarityThreshold
      • Display Name: Cache Similarity Threshold
      • SQL Data Type: float(53)
      • Description: Threshold (0-1) for vector similarity matching. Higher values require closer matches.

      Returns number

    • set CacheSimilarityThreshold(value: number): void

      Parameters

      • value: number

      Returns void

    • get CacheTTLSeconds(): number
      • Field Name: CacheTTLSeconds
      • Display Name: Cache TTL (Seconds)
      • SQL Data Type: int
      • Description: Time-to-live in seconds for cached results. NULL means results never expire.

      Returns number

    • set CacheTTLSeconds(value: number): void

      Parameters

      • value: number

      Returns void

    • get Category(): string
      • Field Name: Category
      • Display Name: Category Name
      • SQL Data Type: nvarchar(255)

      Returns string

    • get CategoryID(): string
      • Field Name: CategoryID
      • Display Name: Category
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompt Categories (vwAIPromptCategories.ID)
      • Description: Reference to the category the prompt belongs to.

      Returns string

    • set CategoryID(value: string): void

      Parameters

      • value: string

      Returns void

    • get ContextCurrentUser(): UserInfo

      Returns UserInfo

    • set ContextCurrentUser(user: UserInfo): void

      The ContextCurrentUser is a property used to manually set the "current" user for scenarios, primarily on the server side, where the user changes per request. For situations where there is no global CurrentUser in the Metadata.Provider, you MUST set this property to the user you want to use for the current operation. If you used Metadata.GetEntityObject() to get the entity object, this property will be set automatically for you as that method has a parameter that can be provided for the ContextCurrentUser.

      Parameters

      Returns void

    • get DefaultSkipAsyncValidation(): boolean
      Protected

      Default value for whether async validation should be skipped. Subclasses can override this property to enable async validation by default. When the options object is passed to Save(), and it includes a value for the SkipAsyncValidation property, that value will take precedence over this default.

      Returns boolean

      Save

    • get Description(): string
      • Field Name: Description
      • Display Name: Description
      • SQL Data Type: nvarchar(MAX)

      Returns string

    • set Description(value: string): void

      Parameters

      • value: string

      Returns void

    • get Dirty(): boolean

      Returns true if the object is Dirty, meaning something has changed since it was last saved to the database, and false otherwise. For new records, this will always return true.

      Returns boolean

    • get EffortLevel(): number
      • Field Name: EffortLevel
      • Display Name: Effort Level
      • SQL Data Type: int
      • Description: Effort level for this specific prompt (1-100, where 1=minimal effort, 100=maximum effort). Higher values request more thorough reasoning and analysis. Can be overridden by agent DefaultPromptEffortLevel or runtime parameters.

      Returns number

    • set EffortLevel(value: number): void

      Parameters

      • value: number

      Returns void

    • get EnableCaching(): boolean
      • Field Name: EnableCaching
      • Display Name: Enable Caching
      • SQL Data Type: bit
      • Default Value: 0
      • Description: When true, results from this prompt will be cached for potential reuse.

      Returns boolean

    • set EnableCaching(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get FailoverDelaySeconds(): number
      • Field Name: FailoverDelaySeconds
      • Display Name: Failover Delay (Seconds)
      • SQL Data Type: int
      • Default Value: 5
      • Description: Initial delay in seconds between failover attempts

      Returns number

    • set FailoverDelaySeconds(value: number): void

      Parameters

      • value: number

      Returns void

    • get FailoverErrorScope(): | "All"
      | "NetworkOnly"
      | "RateLimitOnly"
      | "ServiceErrorOnly"
      • Field Name: FailoverErrorScope
      • Display Name: Failover Error Scope
      • SQL Data Type: nvarchar(50)
      • Default Value: All
      • Value List Type: List
      • Possible Values
        • All
        • All
        • NetworkOnly
        • NetworkOnly
        • RateLimitOnly
        • RateLimitOnly
        • ServiceErrorOnly
        • ServiceErrorOnly
      • Description: Types of errors that should trigger failover. Options: All, NetworkOnly, RateLimitOnly, ServiceErrorOnly

      Returns "All" | "NetworkOnly" | "RateLimitOnly" | "ServiceErrorOnly"

    • set FailoverErrorScope(
          value: "All" | "NetworkOnly" | "RateLimitOnly" | "ServiceErrorOnly",
      ): void

      Parameters

      • value: "All" | "NetworkOnly" | "RateLimitOnly" | "ServiceErrorOnly"

      Returns void

    • get FailoverMaxAttempts(): number
      • Field Name: FailoverMaxAttempts
      • Display Name: Failover Max Attempts
      • SQL Data Type: int
      • Default Value: 3
      • Description: Maximum number of failover attempts before giving up

      Returns number

    • set FailoverMaxAttempts(value: number): void

      Parameters

      • value: number

      Returns void

    • get FailoverModelStrategy(): | "PreferDifferentModel"
      | "PreferSameModel"
      | "RequireSameModel"
      • Field Name: FailoverModelStrategy
      • Display Name: Failover Model Strategy
      • SQL Data Type: nvarchar(50)
      • Default Value: PreferSameModel
      • Value List Type: List
      • Possible Values
        • PreferDifferentModel
        • PreferDifferentModel
        • PreferSameModel
        • PreferSameModel
        • RequireSameModel
        • RequireSameModel
      • Description: Strategy for selecting failover models. Options: PreferSameModel, PreferDifferentModel, RequireSameModel

      Returns "PreferDifferentModel" | "PreferSameModel" | "RequireSameModel"

    • set FailoverModelStrategy(
          value: "PreferDifferentModel" | "PreferSameModel" | "RequireSameModel",
      ): void

      Parameters

      • value: "PreferDifferentModel" | "PreferSameModel" | "RequireSameModel"

      Returns void

    • get FailoverStrategy(): | "None"
      | "NextBestModel"
      | "PowerRank"
      | "SameModelDifferentVendor"
      • Field Name: FailoverStrategy
      • Display Name: Failover Strategy
      • SQL Data Type: nvarchar(50)
      • Default Value: SameModelDifferentVendor
      • Value List Type: List
      • Possible Values
        • NextBestModel
        • NextBestModel
        • None
        • None
        • PowerRank
        • PowerRank
        • SameModelDifferentVendor
        • SameModelDifferentVendor
      • Description: Failover strategy to use when the primary model fails. Options: SameModelDifferentVendor, NextBestModel, PowerRank, None

      Returns "None" | "NextBestModel" | "PowerRank" | "SameModelDifferentVendor"

    • set FailoverStrategy(
          value:
              | "None"
              | "NextBestModel"
              | "PowerRank"
              | "SameModelDifferentVendor",
      ): void

      Parameters

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

      Returns void

    • get FrequencyPenalty(): number
      • Field Name: FrequencyPenalty
      • Display Name: Frequency Penalty
      • SQL Data Type: decimal(3, 2)
      • Description: Default frequency penalty for this prompt. Penalizes tokens based on their frequency in the text. Positive values decrease likelihood of repetition. Can be overridden at runtime.

      Returns number

    • set FrequencyPenalty(value: number): void

      Parameters

      • value: number

      Returns void

    • get ID(): string
      • Field Name: ID
      • Display Name: ID
      • SQL Data Type: uniqueidentifier
      • Default Value: newsequentialid()

      Returns string

    • set ID(value: string): void

      Parameters

      • value: string

      Returns void

    • get IncludeLogProbs(): boolean
      • Field Name: IncludeLogProbs
      • Display Name: Include Log Probabilities
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Default setting for including log probabilities in the response. Can be overridden at runtime.

      Returns boolean

    • set IncludeLogProbs(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get ISAChild(): BaseEntity<unknown>

      Returns the child entity in the IS-A composition chain, or null if this entity has no child record, hasn't been loaded yet, or is an overlapping subtype parent (use ISAChildren instead for overlapping parents).

      Example: For a MeetingEntity where a Webinar record exists with the same PK, ISAChild returns the WebinarEntity instance.

      Returns BaseEntity<unknown>

    • get ISAChildren(): { entityName: string }[]

      For overlapping subtype parents (AllowMultipleSubtypes = true), returns the list of child entity type names that have records for this PK. For disjoint parents or non-parent entities, returns null (use ISAChild instead).

      Example: For a PersonEntity with AllowMultipleSubtypes=true, might return [{entityName: 'Members'}, {entityName: 'Volunteers'}, {entityName: 'Speakers'}].

      Returns { entityName: string }[]

    • get ISAParent(): BaseEntity<unknown>

      Returns the parent entity in the IS-A composition chain, or null if this entity is not an IS-A child type.

      Example: For a MeetingEntity that IS-A ProductEntity, ISAParent returns the ProductEntity instance.

      Named with ISA prefix to avoid collision with generated entity properties (many entities have a Parent string column in the database).

      Returns BaseEntity<unknown>

    • get IsBusy(): boolean

      Returns true if any operation (Save, Delete, or Load) is currently in progress. This is a convenience property that combines IsSaving, IsDeleting, and IsLoading. Useful for disabling UI elements when any database operation is happening.

      Returns boolean

    • get IsDeleting(): boolean

      Returns true if a Delete operation is currently in progress. This is useful for UI components to show loading indicators or disable buttons while deleting.

      Returns boolean

    • get IsLoading(): boolean

      Returns true if a Load operation is currently in progress. This is useful for UI components to show loading indicators while data is being fetched.

      Returns boolean

    • get IsSaved(): boolean

      Returns true if the record has been saved to the database, false otherwise. This is a useful property to check to determine if the record is a "New Record" or an existing one.

      Returns boolean

    • get IsSaving(): boolean

      Returns true if a Save operation is currently in progress. This is useful for UI components to show loading indicators or disable buttons while saving.

      Returns boolean

    • get LeafEntity(): BaseEntity

      Returns the leaf (most-derived) entity in the IS-A chain, walking downward through child references. Returns this if no child exists.

      For overlapping subtype parents (AllowMultipleSubtypes = true), returns this because there is no single child chain to follow — the parent is the leaf from its own perspective.

      Returns BaseEntity

    • get MaxRetries(): number
      • Field Name: MaxRetries
      • Display Name: Max Retries
      • SQL Data Type: int
      • Default Value: 0
      • Description: Maximum number of retry attempts for API failures.

      Returns number

    • set MaxRetries(value: number): void

      Parameters

      • value: number

      Returns void

    • get MinP(): number
      • Field Name: MinP
      • Display Name: Min P
      • SQL Data Type: decimal(3, 2)
      • Description: Default MinP (minimum probability) for this prompt. Tokens with probability below this threshold are filtered out. Can be overridden at runtime.

      Returns number

    • set MinP(value: number): void

      Parameters

      • value: number

      Returns void

    • get MinPowerRank(): number
      • Field Name: MinPowerRank
      • Display Name: Minimum Power Rank
      • SQL Data Type: int
      • Default Value: 0
      • Description: The minimum power rank required for models to be considered for this prompt.

      Returns number

    • set MinPowerRank(value: number): void

      Parameters

      • value: number

      Returns void

    • get ModelSpecificResponseFormat(): string
      • Field Name: ModelSpecificResponseFormat
      • Display Name: Model Specific Response Format
      • SQL Data Type: nvarchar(MAX)
      • Description: A JSON-formatted string containing model-specific response format instructions. This will be parsed and provided as a JSON object to the model.

      Returns string

    • set ModelSpecificResponseFormat(value: string): void

      Parameters

      • value: string

      Returns void

    • get Name(): string
      • Field Name: Name
      • Display Name: Name
      • SQL Data Type: nvarchar(255)

      Returns string

    • set Name(value: string): void

      Parameters

      • value: string

      Returns void

    • get OutputExample(): string
      • Field Name: OutputExample
      • Display Name: Output Example
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON example output when OutputType is "object", used for validating structured outputs.

      Returns string

    • set OutputExample(value: string): void

      Parameters

      • value: string

      Returns void

    • get OutputType(): "string" | "number" | "boolean" | "object" | "date"
      • Field Name: OutputType
      • Display Name: Output Type
      • SQL Data Type: nvarchar(50)
      • Default Value: string
      • Value List Type: List
      • Possible Values
        • boolean
        • date
        • number
        • object
        • string
      • Description: The expected data type of the prompt output: string, number, boolean, date, or object.

      Returns "string" | "number" | "boolean" | "object" | "date"

    • set OutputType(value: "string" | "number" | "boolean" | "object" | "date"): void

      Parameters

      • value: "string" | "number" | "boolean" | "object" | "date"

      Returns void

    • get ParallelConfigParam(): string
      • Field Name: ParallelConfigParam
      • Display Name: Parallel Config Parameter
      • SQL Data Type: nvarchar(100)
      • Description: When ParallelizationMode is ConfigParam, specifies the name of the configuration parameter that contains the parallel count.

      Returns string

    • set ParallelConfigParam(value: string): void

      Parameters

      • value: string

      Returns void

    • get ParallelCount(): number
      • Field Name: ParallelCount
      • Display Name: Parallel Count
      • SQL Data Type: int
      • Description: When ParallelizationMode is StaticCount, specifies the number of parallel executions.

      Returns number

    • set ParallelCount(value: number): void

      Parameters

      • value: number

      Returns void

    • get ParallelizationMode(): | "None"
      | "ModelSpecific"
      | "ConfigParam"
      | "StaticCount"
      • Field Name: ParallelizationMode
      • Display Name: Parallelization Mode
      • SQL Data Type: nvarchar(20)
      • Default Value: None
      • Value List Type: List
      • Possible Values
        • ConfigParam
        • ModelSpecific
        • None
        • StaticCount
      • Description: Controls parallelization: None (no parallelization), StaticCount (use AIPrompt.ParallelCount for total runs), ConfigParam (use config param specified in ParallelConfigParam for total runs), or ModelSpecific (check each AIPromptModel's individual settings).

      Returns "None" | "ModelSpecific" | "ConfigParam" | "StaticCount"

    • set ParallelizationMode(
          value: "None" | "ModelSpecific" | "ConfigParam" | "StaticCount",
      ): void

      Parameters

      • value: "None" | "ModelSpecific" | "ConfigParam" | "StaticCount"

      Returns void

    • get PowerPreference(): "Balanced" | "Highest" | "Lowest"
      • Field Name: PowerPreference
      • Display Name: Power Preference
      • SQL Data Type: nvarchar(20)
      • Default Value: Highest
      • Value List Type: List
      • Possible Values
        • Balanced
        • Highest
        • Lowest
      • Description: When using ByPower selection strategy, determines whether to prefer highest, lowest, or balanced power models.

      Returns "Balanced" | "Highest" | "Lowest"

    • set PowerPreference(value: "Balanced" | "Highest" | "Lowest"): void

      Parameters

      • value: "Balanced" | "Highest" | "Lowest"

      Returns void

    • get PrefillFallbackMode(): "None" | "Ignore" | "SystemInstruction"
      • Field Name: PrefillFallbackMode
      • Display Name: Prefill Fallback Mode
      • SQL Data Type: nvarchar(20)
      • Default Value: Ignore
      • Value List Type: List
      • Possible Values
        • Ignore
        • None
        • SystemInstruction
      • Description: Controls behavior when the selected provider does not support native assistant prefill. Ignore = silently skip prefill, SystemInstruction = inject a system message instructing the model to start its response with the prefill text (uses fallback text from AI Model Vendor or AI Model Type), None = no fallback (prefill only works with supported providers).

      Returns "None" | "Ignore" | "SystemInstruction"

    • set PrefillFallbackMode(value: "None" | "Ignore" | "SystemInstruction"): void

      Parameters

      • value: "None" | "Ignore" | "SystemInstruction"

      Returns void

    • get PresencePenalty(): number
      • Field Name: PresencePenalty
      • Display Name: Presence Penalty
      • SQL Data Type: decimal(3, 2)
      • Description: Default presence penalty for this prompt. Penalizes tokens that have appeared in the text. Positive values increase topic diversity. Can be overridden at runtime.

      Returns number

    • set PresencePenalty(value: number): void

      Parameters

      • value: number

      Returns void

    • get PrimaryKey(): CompositeKey

      Returns the primary key for the record. The CompositeKey class is a multi-valued key that can have any number of key/value pairs within it. Always traverse the full set of key/value pairs to get the full primary key for the record.

      Returns CompositeKey

    • get PrimaryKeys(): EntityField[]

      Returns an array of all primary key fields for the entity. If the entity has a composite primary key, this method will return an array of all primary key fields. If the entity has a single primary key, this method will return an array with a single field in it.

      Returns EntityField[]

    • get PromptPosition(): "First" | "Last"
      • Field Name: PromptPosition
      • Display Name: Prompt Position
      • SQL Data Type: nvarchar(20)
      • Default Value: First
      • Value List Type: List
      • Possible Values
        • First
        • Last
      • Description: Controls message placement for User and Assistant role prompts: First (beginning of conversation) or Last (end of conversation). Not used for System role prompts which are always first

      Returns "First" | "Last"

    • set PromptPosition(value: "First" | "Last"): void

      Parameters

      • value: "First" | "Last"

      Returns void

    • get PromptRole(): "User" | "Assistant" | "System" | "SystemOrUser"
      • Field Name: PromptRole
      • Display Name: Prompt Role
      • SQL Data Type: nvarchar(20)
      • Default Value: System
      • Value List Type: List
      • Possible Values
        • Assistant
        • System
        • SystemOrUser
        • User
      • Description: Determines how the prompt is used in conversation: System (always first message), User (positioned by PromptPosition), Assistant (positioned by PromptPosition), or SystemOrUser (try system first, fallback to user last if system slot taken)

      Returns "User" | "Assistant" | "System" | "SystemOrUser"

    • set PromptRole(value: "User" | "Assistant" | "System" | "SystemOrUser"): void

      Parameters

      • value: "User" | "Assistant" | "System" | "SystemOrUser"

      Returns void

    • get ProviderTransaction(): unknown

      Gets the provider transaction handle for IS-A chain orchestration.

      Returns unknown

    • set ProviderTransaction(value: unknown): void

      Sets the provider transaction handle. Used during IS-A save/delete to share a single database transaction across the entire parent chain.

      Parameters

      • value: unknown

      Returns void

    • get RecordLoaded(): boolean

      Returns true if the record has been loaded from the database, false otherwise. This is useful to check to see if the record is in a "New Record" state or not.

      Returns boolean

    • get RequireSpecificModels(): boolean
      • Field Name: RequireSpecificModels
      • Display Name: Require Specific Models
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Only applies when SelectionStrategy is Specific. When 0 (default), if none of the explicitly configured AIPromptModel entries have valid API credentials the system automatically falls back to Default/ByPower model selection across all active models matching the prompt AIModelTypeID. When 1, the system will hard-fail with an error instead of falling back, ensuring only the explicitly configured models are ever used.

      Returns boolean

    • set RequireSpecificModels(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get ResponseFormat(): "Text" | "JSON" | "Any" | "Markdown" | "ModelSpecific"
      • Field Name: ResponseFormat
      • Display Name: Response Format
      • SQL Data Type: nvarchar(20)
      • Default Value: Any
      • Value List Type: List
      • Possible Values
        • Any
        • JSON
        • Markdown
        • ModelSpecific
        • Text
      • Description: Specifies the expected response format for the AI model. Options include Any, Text, Markdown, JSON, and ModelSpecific. Defaults to Any if not specified.

      Returns "Text" | "JSON" | "Any" | "Markdown" | "ModelSpecific"

    • set ResponseFormat(
          value: "Text" | "JSON" | "Any" | "Markdown" | "ModelSpecific",
      ): void

      Parameters

      • value: "Text" | "JSON" | "Any" | "Markdown" | "ModelSpecific"

      Returns void

    • get RestoreContext(): RestoreContext

      Returns the active restore context for the next save, if any.

      Read by the data provider when generating the RecordChange SQL: when non-null, the resulting RecordChange row is written with Source='Restore', RestoredFromID = SourceChangeID, and RestoreReason = Reason. Returns null for ordinary saves.

      Returns RestoreContext

    • get ResultHistory(): BaseEntityResult[]

      The result history shows the history of the attempted transactions (Save and Delete) for this particular entity object. This is useful for tracking the results of operations on the entity object.

      Returns BaseEntityResult[]

    • get ResultSelectorPrompt(): string
      • Field Name: ResultSelectorPrompt
      • Display Name: Result Selector Prompt Name
      • SQL Data Type: nvarchar(255)

      Returns string

    • get ResultSelectorPromptID(): string
      • Field Name: ResultSelectorPromptID
      • Display Name: Result Selector Prompt
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompts (vwAIPrompts.ID)
      • Description: References another prompt that selects the best result from multiple parallel executions.

      Returns string

    • set ResultSelectorPromptID(value: string): void

      Parameters

      • value: string

      Returns void

    • get RetryDelayMS(): number
      • Field Name: RetryDelayMS
      • Display Name: Retry Delay (ms)
      • SQL Data Type: int
      • Default Value: 0
      • Description: Delay between retry attempts in milliseconds.

      Returns number

    • set RetryDelayMS(value: number): void

      Parameters

      • value: number

      Returns void

    • get RetryStrategy(): "Exponential" | "Fixed" | "Linear"
      • Field Name: RetryStrategy
      • Display Name: Retry Strategy
      • SQL Data Type: nvarchar(20)
      • Default Value: Fixed
      • Value List Type: List
      • Possible Values
        • Exponential
        • Fixed
        • Linear
      • Description: Strategy for calculating retry delays: Fixed (same delay each time), Exponential (doubling delay), or Linear (linearly increasing delay).

      Returns "Exponential" | "Fixed" | "Linear"

    • set RetryStrategy(value: "Exponential" | "Fixed" | "Linear"): void

      Parameters

      • value: "Exponential" | "Fixed" | "Linear"

      Returns void

    • get RootResultSelectorPromptID(): string
      • Field Name: RootResultSelectorPromptID
      • Display Name: Root Result Selector Prompt
      • SQL Data Type: uniqueidentifier

      Returns string

    • get Seed(): number
      • Field Name: Seed
      • Display Name: Seed
      • SQL Data Type: int
      • Description: Default random seed for this prompt. Used for deterministic generation. Same seed produces same output. Can be overridden at runtime.

      Returns number

    • set Seed(value: number): void

      Parameters

      • value: number

      Returns void

    • get SelectionStrategy(): "Default" | "ByPower" | "Specific"
      • Field Name: SelectionStrategy
      • Display Name: Selection Strategy
      • SQL Data Type: nvarchar(20)
      • Default Value: Default
      • Value List Type: List
      • Possible Values
        • ByPower
        • Default
        • Specific
      • Description: Determines how models are selected for this prompt (Default, Specific, ByPower).

      Returns "Default" | "ByPower" | "Specific"

    • set SelectionStrategy(value: "Default" | "ByPower" | "Specific"): void

      Parameters

      • value: "Default" | "ByPower" | "Specific"

      Returns void

    • get SkipEmbeddings(): boolean

      Returns boolean

    • set SkipEmbeddings(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get Status(): "Pending" | "Active" | "Disabled"
      • Field Name: Status
      • Display Name: Status
      • SQL Data Type: nvarchar(50)
      • Value List Type: List
      • Possible Values
        • Active
        • Disabled
        • Pending

      Returns "Pending" | "Active" | "Disabled"

    • set Status(value: "Pending" | "Active" | "Disabled"): void

      Parameters

      • value: "Pending" | "Active" | "Disabled"

      Returns void

    • get StopSequences(): string
      • Field Name: StopSequences
      • Display Name: Stop Sequences
      • SQL Data Type: nvarchar(1000)
      • Description: Default stop sequences for this prompt. Comma-delimited list of sequences that will stop generation when encountered. Can be overridden at runtime.

      Returns string

    • set StopSequences(value: string): void

      Parameters

      • value: string

      Returns void

    • get Temperature(): number
      • Field Name: Temperature
      • Display Name: Temperature
      • SQL Data Type: decimal(3, 2)
      • Description: Default temperature setting for this prompt. Controls randomness in the output. 0 = more focused and deterministic, 2 = more random and creative. Can be overridden at runtime.

      Returns number

    • set Temperature(value: number): void

      Parameters

      • value: number

      Returns void

    • get Template(): string
      • Field Name: Template
      • Display Name: Template Text
      • SQL Data Type: nvarchar(255)

      Returns string

    • get TemplateID(): string
      • Field Name: TemplateID
      • Display Name: Template
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: Templates (vwTemplates.ID)
      • Description: Reference to the template used for the prompt.

      Returns string

    • set TemplateID(value: string): void

      Parameters

      • value: string

      Returns void

    • get TemplateParams(): MJTemplateParamEntity[]

      Virtual property to get the template parameters for this AI Prompt. Returns the cached parameters if available, or an empty array if not loaded yet. Call LoadTemplateParams() to ensure params are loaded.

      Returns MJTemplateParamEntity[]

    • get TemplateText(): string

      Virtual property to hold the template text. This property is used to create or update the Template and Template Contents entity records automatically whenever the AIPrompt is saved.

      Returns string

    • set TemplateText(value: string): void

      Parameters

      • value: string

      Returns void

    • get TemplateTextDirty(): boolean

      Returns boolean

    • get TopK(): number
      • Field Name: TopK
      • Display Name: Top K
      • SQL Data Type: int
      • Description: Default TopK sampling for this prompt. Only sample from the top K tokens. Lower values reduce randomness. Can be overridden at runtime.

      Returns number

    • set TopK(value: number): void

      Parameters

      • value: number

      Returns void

    • get TopLogProbs(): number
      • Field Name: TopLogProbs
      • Display Name: Top Log Probabilities
      • SQL Data Type: int
      • Description: Default number of top log probabilities to include when IncludeLogProbs is true. Can be overridden at runtime.

      Returns number

    • set TopLogProbs(value: number): void

      Parameters

      • value: number

      Returns void

    • get TopP(): number
      • Field Name: TopP
      • Display Name: Top P
      • SQL Data Type: decimal(3, 2)
      • Description: Default TopP (nucleus sampling) for this prompt. Only consider tokens with cumulative probability up to this value. 1 = consider all tokens. Can be overridden at runtime.

      Returns number

    • set TopP(value: number): void

      Parameters

      • value: number

      Returns void

    • get Type(): string
      • Field Name: Type
      • Display Name: Type Name
      • SQL Data Type: nvarchar(255)

      Returns string

    • get TypeID(): string
      • Field Name: TypeID
      • Display Name: Type
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompt Types (vwAIPromptTypes.ID)
      • Description: Reference to the type of the prompt.

      Returns string

    • set TypeID(value: string): void

      Parameters

      • value: string

      Returns void

    • get ValidationBehavior(): "None" | "Strict" | "Warn"
      • Field Name: ValidationBehavior
      • Display Name: Validation Behavior
      • SQL Data Type: nvarchar(50)
      • Default Value: Warn
      • Value List Type: List
      • Possible Values
        • None
        • Strict
        • Warn
      • Description: Determines how validation failures are handled: Strict (fail), Warn (log warning), or None (ignore).

      Returns "None" | "Strict" | "Warn"

    • set ValidationBehavior(value: "None" | "Strict" | "Warn"): void

      Parameters

      • value: "None" | "Strict" | "Warn"

      Returns void

    • get Vectors(): Map<string, number[]>

      Utility storage for vector embeddings that represent the active record. Each string in the Map can be any unique key relative to the object so you can use this to track vectors associated with

      Returns Map<string, number[]>

    • get BaseEventCode(): string

      When a BaseEntity class raises an event with MJGlobal, the eventCode property is set to this value. This is used to identify events that are raised by BaseEntity objects. Any MJGlobal event that is raised by a BaseEntity class will use a BaseEntityEvent type as the args parameter

      Returns string

    • get Provider(): IEntityDataProvider

      Static property to get/set the IEntityDataProvider that is used by all BaseEntity objects. This is a global setting that is used by all BaseEntity objects. It can be overriden for a given BaseEntity object instance by passing in a provider to the constructor of the BaseEntity object. Typically, a provider will pass itself into BaseEntity objects it creates to create a tight coupling between the provider and the BaseEntity objects it creates. This allows multiple concurrent connections to exist in the same process space without interfering with each other.

      Returns IEntityDataProvider

    • set Provider(value: IEntityDataProvider): void

      Parameters

      Returns void

    • get RootTemplateCategoryID(): string

      The root category ID in the Template Categories entity that will be used for creating new templates linked to this AI Prompt. The way it works is we automatically create new sub-categories of the root category for each AI Prompt Category. Those sub-categories are below the root category. If RootTemplateCategoryID is null when the first such operation occurs upon Save() of a given AIPrompt in a given process space, we will load a category with the name of "MJ: AI Prompts" and use that as the root category ID. If such a category does not exist, we will create it automatically.

      Returns string

      The root template category ID or null if not set.

    • set RootTemplateCategoryID(value: string): void

      Parameters

      • value: string

      Returns void

    Methods

    • Cascade-deletes an IS-A child record when the parent entity has CascadeDeletes enabled. Loads the child entity, then deletes it through the normal IS-A chain. The child's delete will cascade further down if it also has children and CascadeDeletes.

      Parameters

      • childCheck: { ChildEntityName: string; HasChildren: boolean }
      • parentOptions: EntityDeleteOptions

      Returns Promise<boolean>

    • Checks if this entity has any child records in IS-A child entity tables. Used for parent delete protection — a parent record cannot be deleted while child type records referencing it still exist.

      Returns Promise<{ ChildEntityName: string; HasChildren: boolean }>

      Object with HasChildren flag and the name of the child entity found

    • Clears any pending restore context. Safe to call when no context is set. Recommended after Save() returns so a subsequent ordinary save isn't accidentally tagged as a restore.

      Returns void

    • This method MUST be called right after the class is instantiated to provide an async/await pair for any asynchronous operations a given entity needs to do when it is first created/configured. When you call Metadata/Provider GetEntityObject() this is done automatically for you. In nearly all cases you should go through GetEntityObject() anyway and not ever directly instantiate a BaseEntity derived class.

      Parameters

      Returns Promise<void>

    • This method will copy the values from the other entity object into the current one. This is useful for things like cloning a record. This method will ONLY copy values for fields that exist in the current entity object. If the other object has fields that don't exist in the current object, they will be ignored.

      Parameters

      • other: BaseEntity

        the other entity object to copy values from

      • OptionalincludePrimaryKeys: boolean

        if true, the primary keys will be copied as well, if false, they will be ignored, defaults to false and generally you want to leave it that way

      • OptionalreplaceOldValues: boolean

        if true, the old values of the fields will be reset to the values provided in the other parameter, if false, they will be left alone, defaults to false and generally you want to leave it that way

      Returns boolean

    • Protected

      This method creates a new root template category with the given name. It will create a new Template Category entity record and return its ID.

      Parameters

      • name: string

        The name of the root template category to create.

      Returns Promise<string>

      The ID of the newly created root template category.

    • MJ: AI Prompts - Delete method override to wrap in transaction since CascadeDeletes is true. Wrapping in a transaction ensures that all cascade delete operations are handled atomically.

      Parameters

      Returns Promise<boolean>

      • true if successful, false otherwise

      MJAIPromptEntity

    • In the BaseEntity class this method is not implemented. This method shoudl be implemented only in server-side sub-classes only by calling AIEngine or other methods to generate embeddings for a given piece of text provided. Subclasses that override this method to implement embedding support should also override

      Parameters

      • textToEmbed: string

      Returns Promise<SimpleEmbeddingResult>

      SupportsEmbedTextLocal and return true

    • Enforces disjoint subtype constraint during IS-A child entity creation. A parent record can only be ONE child type at a time. Checks all sibling child types (excluding self) for records with the same PK value. Throws if a sibling child record is found.

      Only called when the parent entity has AllowMultipleSubtypes = false (default). When AllowMultipleSubtypes = true, this check is skipped entirely, allowing overlapping subtypes (e.g., a Person can be both a Member and a Volunteer).

      Only runs on Database providers — client-side (Network/GraphQL) skips this because the server-side save will perform the check authoritatively.

      Returns Promise<void>

    • Returns a promise that resolves when the current Delete operation completes. If no Delete operation is in progress, resolves immediately.

      This is useful when you need to ensure a record is deleted before performing cleanup operations or navigating away from a view.

      Returns Promise<void>

      // Ensure any in-progress delete is complete before proceeding
      await entity.EnsureDeleteComplete();
      // Now safe to navigate away or perform cleanup
      navigateToList();
    • Returns a promise that resolves when the current Load operation completes. If no Load operation is in progress, resolves immediately.

      This is useful when you need to ensure data is loaded before accessing entity properties or performing operations that depend on loaded data.

      Returns Promise<void>

      // Ensure any in-progress load is complete before proceeding
      await entity.EnsureLoadComplete();
      // Now safe to access entity data
      console.log(entity.Name);
    • Returns a promise that resolves when the current Save operation completes. If no Save operation is in progress, resolves immediately.

      This is useful when you need to ensure data is persisted before performing a dependent operation, or when coordinating between multiple components that might trigger saves.

      Returns Promise<void>

      // Ensure any in-progress save is complete before proceeding
      await entity.EnsureSaveComplete();
      // Now safe to perform operations that depend on the saved state
      await someOperationThatNeedsSavedData(entity);
    • Strongly-typed wrapper for the SetMany method.

      Type Parameters

      • K extends AnyZodObject

      Parameters

      • data: unknown
      • Optionalschema: TypeOf<K>

        the zod schema to validate the data against

      Returns boolean

      data - the data to set on the entity object

    • Generates a vector embedding for a single text field using AI engine. Only generates embeddings for new records or when the source field has changed. Stores both the vector embedding and the model ID used to generate it.

      Parameters

      • field: EntityField

        The EntityField containing the text to embed

      • vectorField: EntityField

        The EntityField to store the generated vector embedding (as JSON string)

      • modelField: EntityField

        The EntityField to store the ID of the AI model used

      Returns Promise<boolean>

      Promise that resolves to true if embedding was generated successfully, false otherwise

    • Generates a vector embedding for a single text field identified by field name. Retrieves the field objects and delegates to GenerateEmbedding method.

      Parameters

      • fieldName: string

        Name of the text field to generate embedding from

      • vectorFieldName: string

        Name of the field to store the vector embedding

      • modelFieldName: string

        Name of the field to store the model ID used for embedding

      Returns Promise<boolean>

      Promise that resolves to true if embedding was generated successfully, false otherwise

    • Generates vector embeddings for multiple text fields using EntityField objects. Processes fields in parallel for better performance.

      Parameters

      • fields: { field: EntityField; modelField: EntityField; vectorField: EntityField }[]

        Array of field configurations with EntityField objects for source, vector, and model fields

      Returns Promise<boolean>

      Promise that resolves to true if all embeddings were generated successfully, false if any failed

    • Generates vector embeddings for multiple text fields by their field names. Processes fields in parallel for better performance.

      Parameters

      • fields: { fieldName: string; modelFieldName: string; vectorFieldName: string }[]

        Array of field configurations specifying source text field, target vector field, and model ID field names

      Returns Promise<boolean>

      Promise that resolves to true if all embeddings were generated successfully, false if any failed

    • Returns the value of the field with the given name. If the field is a date, and the value is a string, it will be converted to a date object.

      For IS-A child entities, parent fields return the authoritative value from _parentEntity.Get() (recursive for N-level chains), NOT the mirrored value on the child's own Fields array.

      Parameters

      • FieldName: string

      Returns any

    • NOTE: Do not call this method directly. Use the To method instead

      Utility method to create an object and return it with properties in the newly created and returned object for each field in the entity object. This is useful for scenarios where you need to be able to persist the data in a format to send to a network call, save to a file or database, etc. This method will return an object with properties that match the field names of the entity object.

      Parameters

      • OptionaloldValues: boolean

        When set to true, the old values of the fields will be returned instead of the current values.

      • OptionalonlyDirtyFields: boolean

        When set to true, only the fields that are dirty will be returned.

      Returns any

    • Returns a partial object that contains only the fields that have changed since the last time the record was saved. This is useful for scenarios where you want to send only the changes to the server or to a client. It is also helpful for quickly finding the fields that are "dirty".

      Returns Partial<T>

    • This utility method generates a completely new object that has properties that map to the fields and values in the entity at the time it is called. It is a copy, NOT a link, so any changes made to the object after calling this method will NOT be reflected in the object that is returned. This is useful for things like sending data to a client, or for use in a view model.

      Parameters

      Returns Promise<any>

    • This utility method calls GetDataObject() internally and formats the result as a JSON string. If you want to get the data as an object instead of a string, call GetDataObject() directly.

      Parameters

      Returns Promise<string>

    • Convenience method to access a field by code name. This method is case-insensitive and will return null if the field is not found.

      Parameters

      • codeName: string

      Returns EntityField

    • Convenience method to access a field by name. This method is case-insensitive and will return null if the field is not found. You can do the same thing with more fine tune controlled by accessing the Fields property directly.

      Parameters

      • fieldName: string

      Returns EntityField

    • Protected

      This internal method can be overriden by subclasses to provide a custom way of getting or creating the root template category ID. The default implementation checks if the RootTemplateCategoryID is set, and
      if not, it attempts to find a category with the name "MJ: AI Prompts" (or you can override this with a Setting in the AI Prompts entity called "Root Template Category Name"). If such a category does not exist, it creates one and sets the RootTemplateCategoryID.

      Returns Promise<string>

      The root template category ID.

    • Utility method to return the Name of the record (the value of the column that comes back from EntityInfo.NameField) from the current object. This avoids needing a network round trip to get the record name whenever we have the object already loaded in memory.

      Returns any

    • Resets this entity to a pristine state and populates it from the provided data object.

      Unlike SetMany, which incrementally updates existing field values, Hydrate() first resets ALL internal state — fields, composite key cache, loaded/saved flags — then populates from the provided data as if loading a fresh record from the database.

      This is critical for IS-A (table-per-type) inheritance: when a child entity loads its record, parent entities in the chain must be fully reset and re-populated from the child's view data, including the shared primary key. After init(), each EntityField's _NeverSet flag is true, allowing even ReadOnly PK fields to be set exactly once via SetMany.

      After population, entities are automatically marked as saved/loaded when all PK values are present (via UpdateSavedStateFromPrimaryKeys).

      The parent chain is handled recursively: if this entity has an IS-A parent, the parent is hydrated first (deepest ancestor first) via SetMany's built-in routing.

      Parameters

      • data: Record<string, unknown>

        A plain object whose properties map to field names on this entity (and potentially parent entities in the IS-A chain).

      Returns void

    • Discovers and initializes the IS-A child entity for a loaded record.

      After a record is loaded, this method checks whether a more-derived child entity record exists with the same primary key. If found, it creates the child entity instance, shares the current instance chain (so child._parentEntity === this), and recursively discovers further children down the hierarchy.

      This ensures that Save/Delete operations always delegate to the leaf entity, running the full validation and event chain at every level.

      Must be called AFTER a record is loaded (PK must be available). Skipped for entities that are not parent types or have already been discovered.

      Returns Promise<void>

    • Initializes the IS-A parent entity composition chain. For child type entities, this creates the parent entity instance (and recursively its parent, etc.) and caches the parent field name set for routing.

      Must be called AFTER EntityInfo is available but BEFORE any Load/NewRecord/Set/Get. This is called by Metadata.GetEntityObject() after constructing the entity.

      Returns Promise<void>

      • This method loads a single record from the database. Make sure you first get the correct BaseEntity sub-class for your entity by calling Metadata.GetEntityObject() first. From there, you can call this method to load your records.
      • NOTE: You should not be calling this method directly from outside of a sub-class in most cases. You will use the auto-generated sub-classes that have overriden versions of this method that blow out the primary keys into individual parameters. This is much easier to program against.

      Parameters

      • CompositeKey: CompositeKey

        Wrapper that holds an array of objects that contain the field name and value for the primary key of the record you want to load. For example, if you have a table called "Customers" with a primary key of "ID", you would pass in an array with a single object like this: {FieldName: "ID", Value: 1234}. *If you had a composite primary key, you would pass in an array with multiple objects, one for each field in the primary key. You may ONLY pass in the primary key fields, no other fields are allowed.

      • OptionalEntityRelationshipsToLoad: string[]

        Optional, you can specify the names of the relationships to load up. This is an expensive operation as it loads up an array of the related entity objects for the main record, so use it sparingly.

      Returns Promise<boolean>

      true if success, false otherwise

    • Loads the MJ: AI Prompts record from the database

      Parameters

      • ID: string
      • OptionalEntityRelationshipsToLoad: string[]

        (optional) the relationships to load

      Returns Promise<boolean>

      • true if successful, false otherwise

      MJAIPromptEntity

    • Loads entity data from a plain object, typically from database query results.

      This method is meant to be used only in situations where you are sure that the data you are loading is current in the database. MAKE SURE YOU ARE PASSING IN ALL FIELDS. The Dirty flags and other internal state will assume what is loading from the data parameter you pass in is equivalent to what is in the database.

      Parameters

      • data: any

        A simple object that has properties that match the field names of the entity object

      • OptionalreplaceOldValues: boolean

        If true, the old values of the fields will be set to the values provided in the data parameter; if false, they will be left alone

      Returns Promise<boolean>

      Promise - Returns true if the load was successful

      Generally speaking, you should use Load() instead of this method. The main use cases where this makes sense are:

      1. On the server if you are pulling data you know is fresh from the result of another DB operation
      2. If on any tier you run a fresh RunView result that gives you data from the database
      3. When the RunView Object RunView() method is called with ResultType='entity_object'

      Important for Subclasses: As of v2.53.0, this method is now async to support subclasses that need to perform additional asynchronous loading operations (e.g., loading related data, fetching additional metadata).

      Subclasses that need to perform additional loading should override BOTH this method AND Load() to ensure consistent behavior regardless of how the entity is populated. This is because these two methods have different execution paths:

      • Load() fetches data from the network/database and then calls provider-specific loading
      • LoadFromData() is called when data is already available (e.g., from RunView results)
      // Subclass implementation
      public override async LoadFromData(data: any, replaceOldValues: boolean = false): Promise<boolean> {
      const result = await super.LoadFromData(data, replaceOldValues);
      if (result) {
      // Perform additional async loading here
      await this.LoadRelatedData();
      await this.LoadMetadata();
      }
      return result;
      }

      // Don't forget to also override Load() for consistency, unless you INTEND to have different behavior
      // for Load() vs LoadFromData()
      public override async Load(ID: string, EntityRelationshipsToLoad: string[] = null): Promise<boolean> {
      const result = await super.Load(ID, EntityRelationshipsToLoad);
      if (result) {
      // Same additional loading as in LoadFromData
      await this.LoadRelatedData();
      await this.LoadMetadata();
      }
      return result;
      }
    • Loads the template parameters for this AI Prompt if it has a TemplateID. This method populates the _templateParams array using TemplateEngineBase's cached data.

      Returns Promise<boolean>

    • This method will create a new state for the object that is equivalent to a new record including default values.

      Parameters

      • OptionalnewValues: FieldValueCollection

        optional parameter to set the values of the fields to something other than the default values. The expected parameter is an object that has properties that map to field names in this entity. This is the same as creating a NewRecord and then using SetMany(), but it is a convenience/helper approach.

      Returns boolean

    • Propagates the ProviderTransaction handle down the IS-A parent chain so all entities in the chain execute on the same database transaction.

      Returns void

    • Used for raising events within the BaseEntity and can be used by sub-classes to raise events that are specific to the entity.

      Parameters

      • type:
            | "new_record"
            | "save"
            | "delete"
            | "load_complete"
            | "transaction_ready"
            | "save_started"
            | "delete_started"
            | "load_started"
            | "remote-invalidate"
            | "other"
      • payload: any
      • OptionalsaveSubType: "create" | "update"

      Returns void

    • Raises the transaction_ready event. This is used to indicate that the entity object is ready to be submitted for transaction processing. This is used by the TransactionGroup class to know when all async preprocessing is done and it can submit the transaction. This is an internal method and shouldn't be used by sub-classes or external callers in most cases. It is primarily used by Provider classes who are handling the tier-specific processing for the entity object.

      Returns void

    • Re-fetches the current record from the database using its existing primary key, replacing all in-memory field values with the latest data from the database. This is useful when you know (or suspect) the record has been modified externally (e.g., by a trigger, another user, or a background process) and you want to bring the entity object up to date.

      Returns Promise<boolean>

      true if the record was successfully reloaded, false if the provider returned no data.

      • The entity must have been previously loaded or saved (i.e., it must have a valid PrimaryKey). Calling Refresh() on a new, unsaved entity will throw because the primary key is not yet valid.
      • After a successful refresh, all field dirty flags are reset — the entity will report Dirty === false.
      • This is equivalent to calling InnerLoad(this.PrimaryKey).
      • If you only need to discard unsaved in-memory changes (without a database round-trip), use Revert instead.

      If the entity has no provider set, the primary key is invalid, or the user lacks Read permission.

    • This method can be used to register a callback for events that will be raised by the instance of the BaseEntity object. The callback will be called with a BaseEntityEvent object that contains the type of event and any payload that is associated with the event. Subclasses of the BaseEntity can define their own event types and payloads as needed.

      Parameters

      Returns Subscription

    • Append a result to _resultHistory, trimming the oldest entries when over MAX_RESULT_HISTORY. All Save/Delete code paths route through this — both inside BaseEntity and in callers like databaseProviderBase and entity subclasses that record their own results.

      Parameters

      Returns void

    • If the entity object has a TransactionGroup associated with it, the TransactionGroup will be notified that we are doing some transaction pre-processing so that the TransactionGroup can properly wait for those pre-processing steps to complete before submitting the transaction. This method should generally NOT be called by anyone other than a provider that is handling the tier-specific processing for the entity object.

      Returns void

    • Resets the vector embeddings for this entity to an empty state.

      Returns void

    • This method will revert the internal state of the object back to what it was when it was last saved, or if never saved, from when it was intially loaded from the database. This is useful if you want to offer a user an "undo" type of feature in a UI.

      Returns boolean

    • The reason for this override is to automatically create and update Templates and Template Contents entity records that are linked to this AI Prompt. The logic works like this:

      1. If the TemplateID is null (initial state), and the TemplateText virtual property is not empty, a new Templates entity record and a new Template Contents entity record will be created and linked to this record's TemplateID property.
      2. If the TemplateID is not null, the TemplateText changing will result in the linked Template Contents (via the TemplateID) being updated.

      Parameters

      Returns Promise<boolean>

    • Sets the value of a given field. If the field doesn't exist, nothing happens. The field's type is used to convert the value to the appropriate type.

      For IS-A child entities, parent fields are routed to _parentEntity.Set() (recursive for N-level chains). The value is also mirrored on the child's own virtual EntityField so that code iterating entity.Fields still sees it. The authoritative state for parent fields lives on _parentEntity.

      Parameters

      • FieldName: string
      • Value: any

      Returns void

    • NOTE: Do not call this method directly. Use the From method instead

      Sets any number of values on the entity object from the object passed in. The properties of the object being passed in must either match the field name (in most cases) or the CodeName (which is only different from field name if field name has spaces in it)

      For IS-A child entities, all fields are first set on self (including parent fields as mirrors), then parent fields are extracted and forwarded to _parentEntity.SetMany() for authoritative state, including proper OldValue tracking via the replaceOldValues parameter.

      Parameters

      • object: any
      • OptionalignoreNonExistentFields: boolean

        if set to true, fields that don't exist on the entity object will be ignored, if false, an error will be thrown if a field doesn't exist

      • OptionalreplaceOldValues: boolean

        if set to true, the old values of the fields will be reset to the values provided in the object parameter, if false, they will be left alone

      • OptionalignoreActiveStatusAssertions: boolean

        if set to true, the active status assertions for the fields will be ignored, if false, an error will be thrown if a field is not active. Defaults to false.

      Returns void

    • Marks the next Save() as a restore from a historical RecordChange row.

      The provider will write a new RecordChange entry with Source='Restore', RestoredFromID pointing at sourceChangeId, and RestoreReason set to reason (or NULL). This produces an auditable lineage chain that the timeline UI can render via the RestoredFromID foreign key.

      The context is consumed exactly once per Save() and persists on the entity until either (a) overwritten by a subsequent SetRestoreContext() call or (b) explicitly cleared via ClearRestoreContext(). It is NOT auto-cleared inside Save() because TransactionGroup execution is deferred — see the comment on _restoreContext for details.

      Parameters

      • sourceChangeId: string

        The ID of the historical RecordChange row whose state is being restored. Required; throws if empty.

      • Optionalreason: string

        Optional user-entered explanation captured at restore time. Persisted to RecordChange.RestoreReason for audit purposes.

      Returns void

      record.SetRestoreContext(versionId, 'Reverting incorrect Q2 entries');
      const ok = await record.Save();
      record.ClearRestoreContext();
    • Specifies if the current object supports the

      Returns boolean

      EmbedTextLocal method or not - useful to know before calling it for conditional code that has fallbacks as needed. BaseEntity does not implement this method but server-side sub-classes often do, but it is not mandatory for any sub-class.

    • Strongly-typed wrapper for the GetAll method

      Type Parameters

      • K extends AnyZodObject

      Parameters

      • Optionalschema: K

        the zod schema to validate the data against

      Returns TypeOf<K>

    • Validate() method override for MJ: AI Prompts entity. This is an auto-generated method that invokes the generated validators for this entity for the following fields:

      • CacheSimilarityThreshold: This rule ensures that the "CacheSimilarityThreshold" value, if provided, must be between 0 and 1 (including both 0 and 1). If it is not set, there is no restriction.
      • CacheTTLSeconds: This rule ensures that if a cache time-to-live (CacheTTLSeconds) value is provided, it must be greater than zero. If it is not set, that's allowed.
      • EffortLevel: This rule ensures that if an Effort Level is provided, it must be a number between 1 and 100, inclusive.
      • Table-Level: This rule ensures that if the cache match type is set to 'Vector', a cache similarity threshold must be provided. For other cache match types, the cache similarity threshold can be left blank.
      • Table-Level: This rule ensures that if the OutputType is set to "object", then an OutputExample must be provided. For all other OutputType values, OutputExample can be left empty.
      • Table-Level: This rule ensures that if the Parallelization Mode is set to 'ConfigParam', then a configuration parameter must be provided. For all other modes, the configuration parameter can be left blank.
      • Table-Level: This rule ensures that if the parallelization mode is set to 'StaticCount', then a value for parallel count must be provided. For other parallelization modes, parallel count can be left blank.
      • Table-Level: This rule makes sure that the 'ResultSelectorPromptID' field cannot have the same value as the record's own 'ID'. In other words, the record cannot select itself as its own result selector prompt.

      Returns ValidationResult

    • Asynchronous validation method that can be overridden by subclasses to add custom async validation logic. This method is automatically called by Save() AFTER the synchronous Validate() passes.

      IMPORTANT:

      1. This should NEVER be called INSTEAD of the synchronous Validate() method
      2. This is meant to be overridden by subclasses that need to perform async validations
      3. The base implementation just returns success - no actual validation is performed

      Subclasses should override this to add complex validations that require database queries or other async operations that cannot be performed in the synchronous Validate() method.

      Returns Promise<ValidationResult>

      Promise A promise that resolves to the validation result

    • This rule ensures that the "CacheSimilarityThreshold" value, if provided, must be between 0 and 1 (including both 0 and 1). If it is not set, there is no restriction.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule ensures that if the cache match type is set to 'Vector', a cache similarity threshold must be provided. For other cache match types, the cache similarity threshold can be left blank.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule ensures that if a cache time-to-live (CacheTTLSeconds) value is provided, it must be greater than zero. If it is not set, that's allowed.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule ensures that if the Parallelization Mode is set to 'ConfigParam', then a configuration parameter must be provided. For all other modes, the configuration parameter can be left blank.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule ensures that if the parallelization mode is set to 'StaticCount', then a value for parallel count must be provided. For other parallelization modes, parallel count can be left blank.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule makes sure that the 'ResultSelectorPromptID' field cannot have the same value as the record's own 'ID'. In other words, the record cannot select itself as its own result selector prompt.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • Resolves the leaf (most-derived) entity type for a given parent entity record. Walks down the IS-A child hierarchy to find which child type a record belongs to. Returns the child entity name, or the parent's own name if no children exist. Useful for polymorphic operations where you have a parent record and need to know its actual leaf type.

      Parameters

      • entityName: string

        The parent entity name

      • primaryKey: CompositeKey

        The primary key to look up

      • OptionalcontextUser: UserInfo

        Optional context user for server-side operations

      • Optionalprovider: IMetadataProvider

      Returns Promise<{ IsLeaf: boolean; LeafEntityName: string }>

      The leaf entity name and whether it was resolved to a child type