Member Junction
    Preparing search index...

    Extended MJAIPromptRunEntity class with helper methods for extracting conversation messages and data from the stored JSON.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    Accessors

    __mj_CreatedAt __mj_UpdatedAt ActiveUser Agent AgentID AgentRun AgentRunID AssistantPrefill CacheHit CacheKey CancellationReason Cancelled ChildPrompt ChildPromptID Comments CommonValidationError CompletedAt CompletionTime Configuration ConfigurationID ContextCurrentUser Cost CostCurrency DefaultSkipAsyncValidation DescendantCost Dirty EffortLevel EntityInfo ErrorDetails ErrorMessage ExecutionOrder ExecutionTimeMS FailoverAttempts FailoverDurations FailoverErrors Fields FinalValidationError FinalValidationPassed FirstAttemptAt FirstPrimaryKey FirstTokenTime FrequencyPenalty ID ISAChild ISAChildren ISAParent ISAParentEntity IsBusy IsDeleting IsLoading IsSaved IsSaving Judge JudgeID JudgeScore LastAttemptAt LatestResult LeafEntity LogProbs MaxRetriesConfigured Messages MinP Model ModelID ModelPowerRank ModelSelection ModelSpecificResponseDetails OriginalModel OriginalModelID OriginalRequestStartTime Parent ParentID PresencePenalty PrimaryKey PrimaryKeys Prompt PromptID PromptTime ProviderToUse ProviderTransaction QueueTime RecordChanges RecordLoaded RerunFromPromptRun RerunFromPromptRunID ResponseFormat RestoreContext Result ResultHistory RetryStrategy RootEntity RootParentID RootRerunFromPromptRunID RunAt RunName RunQueryProviderToUse RunReportProviderToUse RunType RunViewProviderToUse Seed SelectionStrategy SkipEmbeddings Status StopSequences StreamingEnabled Success SuccessfulValidationCount Temperature TestRun TestRunID TokensCacheRead TokensCacheReadRollup TokensCacheWrite TokensCacheWriteRollup TokensCompletion TokensCompletionRollup TokensPrompt TokensPromptRollup TokensUsed TokensUsedRollup TopK TopLogProbs TopP TotalCost TotalFailoverDuration TotalRetryDurationMS TransactionGroup ValidationAttemptCount ValidationAttempts ValidationBehavior ValidationErrorCount ValidationSummary Vectors Vendor VendorID WasSelectedResult BaseEventCode Provider

    Methods

    Constructors

    Properties

    _jsonRepairInfo: JSONRepairInfo = null

    Transient property to carry JSON repair info from attemptJSONRepair to the ValidationSummary persistence step. Not saved to the database directly — it is serialized into the ValidationSummary JSON field.

    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 Agent(): string
      • Field Name: Agent
      • Display Name: Agent
      • SQL Data Type: nvarchar(255)

      Returns string

    • get AgentID(): string
      • Field Name: AgentID
      • Display Name: Agent
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Agents (vwAIAgents.ID)
      • Description: If this prompt was run as part of an agent, references the agent.

      Returns string

    • set AgentID(value: string): void

      Parameters

      • value: string

      Returns void

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

      Returns string

    • get AgentRunID(): string
      • Field Name: AgentRunID
      • Display Name: Agent Run
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Agent Runs (vwAIAgentRuns.ID)
      • Description: Optional reference to the AIAgentRun that initiated this prompt execution. Links prompt runs to their parent agent runs for comprehensive execution tracking.

      Returns string

    • set AgentRunID(value: string): void

      Parameters

      • value: string

      Returns void

    • get AssistantPrefill(): string
      • Field Name: AssistantPrefill
      • Display Name: Assistant Prefill
      • SQL Data Type: nvarchar(MAX)
      • Description: The assistant prefill text that was used during this prompt execution. Records whether native prefill or fallback was applied. NULL means no prefill was used.

      Returns string

    • set AssistantPrefill(value: string): void

      Parameters

      • value: string

      Returns void

    • get CacheHit(): boolean
      • Field Name: CacheHit
      • Display Name: Cache Hit
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Indicates whether this result was served from cache rather than executing a new model call

      Returns boolean

    • set CacheHit(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get CacheKey(): string
      • Field Name: CacheKey
      • Display Name: Cache Key
      • SQL Data Type: nvarchar(500)
      • Description: Unique key used for caching this prompt result, typically a hash of the prompt and parameters

      Returns string

    • set CacheKey(value: string): void

      Parameters

      • value: string

      Returns void

    • get CancellationReason(): string
      • Field Name: CancellationReason
      • Display Name: Cancellation Reason
      • SQL Data Type: nvarchar(MAX)
      • Description: Detailed reason for cancellation if the prompt run was cancelled. Could be user_requested, timeout, error, or resource_limit

      Returns string

    • set CancellationReason(value: string): void

      Parameters

      • value: string

      Returns void

    • get Cancelled(): boolean
      • Field Name: Cancelled
      • Display Name: Cancelled
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Indicates whether this prompt run was cancelled before completion

      Returns boolean

    • set Cancelled(value: boolean): void

      Parameters

      • value: boolean

      Returns void

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

      Returns string

    • get ChildPromptID(): string
      • Field Name: ChildPromptID
      • Display Name: Child Prompt
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompts (vwAIPrompts.ID)
      • Description: References the specific child prompt that was executed as part of hierarchical prompt composition. NULL for regular prompts or parent prompts that don't directly execute a child.

      Returns string

    • set ChildPromptID(value: string): void

      Parameters

      • value: string

      Returns void

    • get Comments(): string
      • Field Name: Comments
      • Display Name: Comments
      • SQL Data Type: nvarchar(MAX)
      • Description: Human-readable notes and comments about this prompt run

      Returns string

    • set Comments(value: string): void

      Parameters

      • value: string

      Returns void

    • get CommonValidationError(): string
      • Field Name: CommonValidationError
      • Display Name: Common Validation Error
      • SQL Data Type: nvarchar(255)
      • Description: Most frequent validation error across all attempts

      Returns string

    • set CommonValidationError(value: string): void

      Parameters

      • value: string

      Returns void

    • get CompletedAt(): Date
      • Field Name: CompletedAt
      • Display Name: Completed At
      • SQL Data Type: datetimeoffset
      • Description: When the prompt run completed, with timezone offset information.

      Returns Date

    • set CompletedAt(value: Date): void

      Parameters

      • value: Date

      Returns void

    • get CompletionTime(): number
      • Field Name: CompletionTime
      • Display Name: Completion Time (ms)
      • SQL Data Type: int
      • Description: Time in milliseconds for the model to generate the completion/response tokens. Provider-specific timing metric.

      Returns number

    • set CompletionTime(value: number): void

      Parameters

      • value: number

      Returns void

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

      Returns string

    • get ConfigurationID(): string
      • Field Name: ConfigurationID
      • Display Name: Configuration
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Configurations (vwAIConfigurations.ID)
      • Description: Optional configuration used for this execution.

      Returns string

    • set ConfigurationID(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 Cost(): number
      • Field Name: Cost
      • Display Name: Cost
      • SQL Data Type: decimal(19, 8)
      • Description: The cost of this specific prompt execution as reported by the AI provider. This does not include costs from child executions. The currency is specified in CostCurrency field.

      Returns number

    • set Cost(value: number): void

      Parameters

      • value: number

      Returns void

    • get CostCurrency(): string
      • Field Name: CostCurrency
      • Display Name: Currency
      • SQL Data Type: nvarchar(10)
      • Description: ISO 4217 currency code for the Cost field (e.g., USD, EUR, GBP). Different AI providers may use different currencies.

      Returns string

    • set CostCurrency(value: string): void

      Parameters

      • value: string

      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 DescendantCost(): number
      • Field Name: DescendantCost
      • Display Name: Descendant Cost
      • SQL Data Type: decimal(18, 6)
      • Description: The total cost of all descendant (child and grandchild) prompt runs, excluding this run's own cost. For leaf nodes (no children), this is 0. Updated when child costs change.

      Returns number

    • set DescendantCost(value: number): void

      Parameters

      • value: number

      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 that was actually used during this prompt run execution (1-100, where 1=minimal effort, 100=maximum effort). This is the resolved effort level after applying the precedence hierarchy: runtime override > agent default > prompt default > provider default.

      Returns number

    • set EffortLevel(value: number): void

      Parameters

      • value: number

      Returns void

    • get EntityInfo(): EntityInfo

      Access to the underlying metadata for the entity object.

      Returns EntityInfo

    • get ErrorDetails(): string
      • Field Name: ErrorDetails
      • Display Name: Error Details
      • SQL Data Type: nvarchar(MAX)
      • Description: Detailed error information in JSON format if the prompt execution failed, including stack traces and error codes

      Returns string

    • set ErrorDetails(value: string): void

      Parameters

      • value: string

      Returns void

    • get ErrorMessage(): string
      • Field Name: ErrorMessage
      • Display Name: Error Message
      • SQL Data Type: nvarchar(MAX)
      • Description: Error message if the execution failed.

      Returns string

    • set ErrorMessage(value: string): void

      Parameters

      • value: string

      Returns void

    • get ExecutionOrder(): number
      • Field Name: ExecutionOrder
      • Display Name: Execution Order
      • SQL Data Type: int
      • Description: Execution order for parallel child runs and result selector runs. Used to track the sequence of execution within a parallel run group. NULL for single runs and parallel parent runs.

      Returns number

    • set ExecutionOrder(value: number): void

      Parameters

      • value: number

      Returns void

    • get ExecutionTimeMS(): number
      • Field Name: ExecutionTimeMS
      • Display Name: Execution Time (ms)
      • SQL Data Type: int
      • Description: Total execution time in milliseconds.

      Returns number

    • set ExecutionTimeMS(value: number): void

      Parameters

      • value: number

      Returns void

    • get FailoverAttempts(): number
      • Field Name: FailoverAttempts
      • Display Name: Failover Attempts
      • SQL Data Type: int
      • Default Value: 0
      • Description: Number of failover attempts made during this prompt run

      Returns number

    • set FailoverAttempts(value: number): void

      Parameters

      • value: number

      Returns void

    • get FailoverDurations(): string
      • Field Name: FailoverDurations
      • Display Name: Failover Durations
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON array of duration in milliseconds for each failover attempt

      Returns string

    • set FailoverDurations(value: string): void

      Parameters

      • value: string

      Returns void

    • get FailoverErrors(): string
      • Field Name: FailoverErrors
      • Display Name: Failover Errors
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON array of error details from each failover attempt

      Returns string

    • set FailoverErrors(value: string): void

      Parameters

      • value: string

      Returns void

    • get Fields(): EntityField[]

      Returns EntityField[]

    • get FinalValidationError(): string
      • Field Name: FinalValidationError
      • Display Name: Final Validation Error
      • SQL Data Type: nvarchar(500)
      • Description: The final validation error message if validation failed

      Returns string

    • set FinalValidationError(value: string): void

      Parameters

      • value: string

      Returns void

    • get FinalValidationPassed(): boolean
      • Field Name: FinalValidationPassed
      • Display Name: Validation Passed
      • SQL Data Type: bit
      • Description: Whether validation ultimately passed (1) or failed (0)

      Returns boolean

    • set FinalValidationPassed(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get FirstAttemptAt(): Date
      • Field Name: FirstAttemptAt
      • Display Name: First Attempt At
      • SQL Data Type: datetimeoffset
      • Description: Timestamp of the first validation attempt

      Returns Date

    • set FirstAttemptAt(value: Date): void

      Parameters

      • value: Date

      Returns void

    • get FirstPrimaryKey(): EntityField

      Helper method to return just the first Primary Key

      Returns EntityField

    • get FirstTokenTime(): number
      • Field Name: FirstTokenTime
      • Display Name: First Token Time (ms)
      • SQL Data Type: int
      • Description: Time in milliseconds from request initiation to receiving the first token from the model

      Returns number

    • set FirstTokenTime(value: number): void

      Parameters

      • value: number

      Returns void

    • get FrequencyPenalty(): number
      • Field Name: FrequencyPenalty
      • Display Name: Frequency Penalty
      • SQL Data Type: decimal(3, 2)
      • Description: Frequency penalty parameter used (-2.0 to 2.0). Positive values reduce repetition of tokens based on their frequency in the output

      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 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 ISAParentEntity(): BaseEntity<unknown>

      Returns BaseEntity<unknown>

      Use ISAParent instead. Kept for backward compatibility.

    • 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 Judge(): string
      • Field Name: Judge
      • Display Name: Judge
      • SQL Data Type: nvarchar(255)

      Returns string

    • get JudgeID(): string
      • Field Name: JudgeID
      • Display Name: Judge Prompt
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompts (vwAIPrompts.ID)
      • Description: ID of the AIPrompt used as a judge to evaluate and rank multiple parallel execution results

      Returns string

    • set JudgeID(value: string): void

      Parameters

      • value: string

      Returns void

    • get JudgeScore(): number
      • Field Name: JudgeScore
      • Display Name: Judge Score
      • SQL Data Type: float(53)
      • Description: Score assigned by the judge prompt when evaluating multiple results. Higher scores indicate better results

      Returns number

    • set JudgeScore(value: number): void

      Parameters

      • value: number

      Returns void

    • get LastAttemptAt(): Date
      • Field Name: LastAttemptAt
      • Display Name: Last Attempt At
      • SQL Data Type: datetimeoffset
      • Description: Timestamp of the last validation attempt

      Returns Date

    • set LastAttemptAt(value: Date): void

      Parameters

      • value: Date

      Returns void

    • get LatestResult(): BaseEntityResult

      Returns the most recent result from the result history. If there are no results in the history, this method will return null.

      Returns BaseEntityResult

    • 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 LogProbs(): boolean
      • Field Name: LogProbs
      • Display Name: Log Probs
      • SQL Data Type: bit
      • Description: Whether log probabilities were requested for this run

      Returns boolean

    • set LogProbs(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get MaxRetriesConfigured(): number
      • Field Name: MaxRetriesConfigured
      • Display Name: Max Retries
      • SQL Data Type: int
      • Description: Maximum number of retries configured on the prompt

      Returns number

    • set MaxRetriesConfigured(value: number): void

      Parameters

      • value: number

      Returns void

    • get Messages(): string
      • Field Name: Messages
      • Display Name: Messages
      • SQL Data Type: nvarchar(MAX)
      • Description: The input messages sent to the model, typically in JSON format.

      Returns string

    • set Messages(value: string): void

      Parameters

      • value: string

      Returns void

    • get MinP(): number
      • Field Name: MinP
      • Display Name: Min P
      • SQL Data Type: decimal(3, 2)
      • Description: Minimum probability threshold used for token sampling (0-1). Tokens below this probability are filtered out

      Returns number

    • set MinP(value: number): void

      Parameters

      • value: number

      Returns void

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

      Returns string

    • get ModelID(): string
      • Field Name: ModelID
      • Display Name: Model
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Models (vwAIModels.ID)
      • Description: The AI model used for execution.

      Returns string

    • set ModelID(value: string): void

      Parameters

      • value: string

      Returns void

    • get ModelPowerRank(): number
      • Field Name: ModelPowerRank
      • Display Name: Model Power Rank
      • SQL Data Type: int
      • Description: Power rank of the model that was selected for this run. Lower numbers indicate more powerful models

      Returns number

    • set ModelPowerRank(value: number): void

      Parameters

      • value: number

      Returns void

    • get ModelSelection(): string
      • Field Name: ModelSelection
      • Display Name: Model Selection Details
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON object containing detailed model selection information including all models considered, their scores, and the selection rationale

      Returns string

    • set ModelSelection(value: string): void

      Parameters

      • value: string

      Returns void

    • get ModelSpecificResponseDetails(): string
      • Field Name: ModelSpecificResponseDetails
      • Display Name: Provider Response Details
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON field containing provider-specific response metadata and details not captured in standard fields. Structure varies by AI provider.

      Returns string

    • set ModelSpecificResponseDetails(value: string): void

      Parameters

      • value: string

      Returns void

    • get OriginalModel(): string
      • Field Name: OriginalModel
      • Display Name: Original Model
      • SQL Data Type: nvarchar(50)

      Returns string

    • get OriginalModelID(): string
      • Field Name: OriginalModelID
      • Display Name: Original Model ID
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Models (vwAIModels.ID)
      • Description: The AI Model ID that was originally attempted before any failovers

      Returns string

    • set OriginalModelID(value: string): void

      Parameters

      • value: string

      Returns void

    • get OriginalRequestStartTime(): Date
      • Field Name: OriginalRequestStartTime
      • Display Name: Original Request Start
      • SQL Data Type: datetimeoffset
      • Description: Timestamp when the original request started, before any failovers

      Returns Date

    • set OriginalRequestStartTime(value: Date): void

      Parameters

      • value: Date

      Returns void

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

      Returns string

    • get ParentID(): string
      • Field Name: ParentID
      • Display Name: Parent Run
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompt Runs (vwAIPromptRuns.ID)
      • Description: References the parent AIPromptRun.ID for hierarchical execution tracking. NULL for top-level runs, populated for parallel children and result selector runs.

      Returns string

    • set ParentID(value: string): void

      Parameters

      • value: string

      Returns void

    • get PresencePenalty(): number
      • Field Name: PresencePenalty
      • Display Name: Presence Penalty
      • SQL Data Type: decimal(3, 2)
      • Description: Presence penalty parameter used (-2.0 to 2.0). Positive values encourage the model to talk about new topics

      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 Prompt(): string
      • Field Name: Prompt
      • Display Name: Prompt
      • SQL Data Type: nvarchar(255)

      Returns string

    • get PromptID(): string
      • Field Name: PromptID
      • Display Name: Prompt
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompts (vwAIPrompts.ID)
      • Description: The prompt that was executed.

      Returns string

    • set PromptID(value: string): void

      Parameters

      • value: string

      Returns void

    • get PromptTime(): number
      • Field Name: PromptTime
      • Display Name: Prompt Time (ms)
      • SQL Data Type: int
      • Description: Time in milliseconds for the model to ingest and process the prompt. Provider-specific timing metric.

      Returns number

    • set PromptTime(value: number): void

      Parameters

      • value: number

      Returns void

    • get ProviderToUse(): IEntityDataProvider

      Returns this provider to be used for a given instance of a BaseEntity derived subclass. If the provider is not set, the BaseEntity.Provider is returned.

      Returns IEntityDataProvider

    • 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 QueueTime(): number
      • Field Name: QueueTime
      • Display Name: Queue Time (ms)
      • SQL Data Type: int
      • Description: Queue time in milliseconds before the model started processing the request. Provider-specific timing metric.

      Returns number

    • set QueueTime(value: number): void

      Parameters

      • value: number

      Returns void

    • get RecordChanges(): Promise<RecordChange[]>

      Returns a list of changes made to this record, over time. Only works if TrackRecordChanges bit set to 1 on the entity you're working with.

      Returns Promise<RecordChange[]>

    • 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 RerunFromPromptRun(): string
      • Field Name: RerunFromPromptRun
      • Display Name: Rerun From Run
      • SQL Data Type: nvarchar(255)

      Returns string

    • get RerunFromPromptRunID(): string
      • Field Name: RerunFromPromptRunID
      • Display Name: Rerun From
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Prompt Runs (vwAIPromptRuns.ID)
      • Description: If this run was initiated as a re-run of another prompt run, this field links back to the original run ID

      Returns string

    • set RerunFromPromptRunID(value: string): void

      Parameters

      • value: string

      Returns void

    • get ResponseFormat(): string
      • Field Name: ResponseFormat
      • Display Name: Response Format
      • SQL Data Type: nvarchar(50)
      • Description: The response format requested for this run (e.g., 'JSON', 'Text', 'Markdown')

      Returns string

    • set ResponseFormat(value: string): void

      Parameters

      • value: string

      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 Result(): string
      • Field Name: Result
      • Display Name: Result
      • SQL Data Type: nvarchar(MAX)
      • Description: The output result from the model.

      Returns string

    • set Result(value: string): void

      Parameters

      • value: string

      Returns void

    • 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 RetryStrategy(): string
      • Field Name: RetryStrategy
      • Display Name: Retry Strategy
      • SQL Data Type: nvarchar(50)
      • Description: Retry strategy used: Fixed, Linear, or Exponential

      Returns string

    • set RetryStrategy(value: string): void

      Parameters

      • value: string

      Returns void

    • get RootEntity(): BaseEntity

      Returns the root (least-derived) entity in the IS-A chain, walking upward through parent references. Returns this if no parent exists.

      Returns BaseEntity

    • get RootParentID(): string
      • Field Name: RootParentID
      • Display Name: Root Parent
      • SQL Data Type: uniqueidentifier

      Returns string

    • get RootRerunFromPromptRunID(): string
      • Field Name: RootRerunFromPromptRunID
      • Display Name: Root Rerun Source
      • SQL Data Type: uniqueidentifier

      Returns string

    • get RunAt(): Date
      • Field Name: RunAt
      • Display Name: Started At
      • SQL Data Type: datetimeoffset
      • Default Value: sysdatetimeoffset()
      • Description: When the prompt run started, with timezone offset information.

      Returns Date

    • set RunAt(value: Date): void

      Parameters

      • value: Date

      Returns void

    • get RunName(): string
      • Field Name: RunName
      • Display Name: Run Name
      • SQL Data Type: nvarchar(255)
      • Description: Optional name for the prompt run to help identify and tag runs for easier reference

      Returns string

    • set RunName(value: string): void

      Parameters

      • value: string

      Returns void

    • get RunQueryProviderToUse(): IRunQueryProvider

      Returns the RunQueryProvider to be used for a given instance of a BaseEntity derived subclass.

      Returns IRunQueryProvider

    • get RunReportProviderToUse(): IRunReportProvider

      Returns the RunReportProvider to be used for a given instance of a BaseEntity derived subclass.

      Returns IRunReportProvider

    • get RunType(): "ParallelChild" | "ParallelParent" | "ResultSelector" | "Single"
      • Field Name: RunType
      • Display Name: Run Type
      • SQL Data Type: nvarchar(20)
      • Default Value: Single
      • Value List Type: List
      • Possible Values
        • ParallelChild
        • ParallelParent
        • ResultSelector
        • Single
      • Description: Type of prompt run execution: Single (standard single prompt), ParallelParent (coordinator for parallel execution), ParallelChild (individual parallel execution), ResultSelector (result selection prompt that chooses best result)

      Returns "ParallelChild" | "ParallelParent" | "ResultSelector" | "Single"

    • set RunType(
          value: "ParallelChild" | "ParallelParent" | "ResultSelector" | "Single",
      ): void

      Parameters

      • value: "ParallelChild" | "ParallelParent" | "ResultSelector" | "Single"

      Returns void

    • get RunViewProviderToUse(): IRunViewProvider

      Returns the RunViewProvider to be used for a given instance of a BaseEntity derived subclass.

      Returns IRunViewProvider

    • get Seed(): number
      • Field Name: Seed
      • Display Name: Seed
      • SQL Data Type: int
      • Description: Random seed used for reproducible outputs. When set, the same seed with identical inputs should produce the same output

      Returns number

    • set Seed(value: number): void

      Parameters

      • value: number

      Returns void

    • get SelectionStrategy(): "Default" | "Specific" | "ByPower"
      • Field Name: SelectionStrategy
      • Display Name: Selection Strategy
      • SQL Data Type: nvarchar(50)
      • Value List Type: List
      • Possible Values
        • ByPower
        • Default
        • Specific
      • Description: Strategy used for model selection. Valid values: Default (system default), Specific (specific models configured), ByPower (based on power ranking)

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

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

      Parameters

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

      Returns void

    • get SkipEmbeddings(): boolean

      Returns boolean

    • set SkipEmbeddings(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get Status(): "Cancelled" | "Completed" | "Failed" | "Running" | "Pending"
      • Field Name: Status
      • Display Name: Status
      • SQL Data Type: nvarchar(50)
      • Default Value: Pending
      • Value List Type: List
      • Possible Values
        • Cancelled
        • Completed
        • Failed
        • Pending
        • Running
      • Description: Current execution status of the prompt run. Valid values: Pending, Running, Completed, Failed, Cancelled

      Returns "Cancelled" | "Completed" | "Failed" | "Running" | "Pending"

    • set Status(
          value: "Cancelled" | "Completed" | "Failed" | "Running" | "Pending",
      ): void

      Parameters

      • value: "Cancelled" | "Completed" | "Failed" | "Running" | "Pending"

      Returns void

    • get StopSequences(): string
      • Field Name: StopSequences
      • Display Name: Stop Sequences
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON array of stop sequences used. The model stops generating when any of these sequences are encountered

      Returns string

    • set StopSequences(value: string): void

      Parameters

      • value: string

      Returns void

    • get StreamingEnabled(): boolean
      • Field Name: StreamingEnabled
      • Display Name: Streaming Enabled
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Indicates whether streaming was enabled for this prompt execution

      Returns boolean

    • set StreamingEnabled(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get Success(): boolean
      • Field Name: Success
      • Display Name: Success
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Whether the execution was successful.

      Returns boolean

    • set Success(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • get SuccessfulValidationCount(): number
      • Field Name: SuccessfulValidationCount
      • Display Name: Successful Validations
      • SQL Data Type: int
      • Description: Number of validation attempts that passed validation

      Returns number

    • set SuccessfulValidationCount(value: number): void

      Parameters

      • value: number

      Returns void

    • get Temperature(): number
      • Field Name: Temperature
      • Display Name: Temperature
      • SQL Data Type: decimal(3, 2)
      • Description: The temperature parameter used for this prompt run, controlling randomness in the output (0.0 = deterministic, 2.0 = very random)

      Returns number

    • set Temperature(value: number): void

      Parameters

      • value: number

      Returns void

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

      Returns string

    • get TestRunID(): string
      • Field Name: TestRunID
      • Display Name: Test Run
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: Test Runs (vwTestRuns.ID)
      • Description: Optional Foreign Key - Links this prompt run to a test run if this prompt execution was part of a test. Enables testing individual prompts for quality and consistency before agent integration.

      Returns string

    • set TestRunID(value: string): void

      Parameters

      • value: string

      Returns void

    • get TokensCacheRead(): number
      • Field Name: TokensCacheRead
      • Display Name: Tokens Cache Read
      • SQL Data Type: int
      • Description: Number of input tokens served from the AI provider's prompt cache (a cache READ / hit) for this run, as reported by the provider. Counts only; no cost is derived here. NULL if the provider did not report cache reads or caching did not engage. Distinct from CacheHit/CacheKey, which track MemberJunction's own result cache.

      Returns number

    • set TokensCacheRead(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensCacheReadRollup(): number
      • Field Name: TokensCacheReadRollup
      • Display Name: Tokens Cache Read (Rollup)
      • SQL Data Type: int
      • Description: Rollup of TokensCacheRead across this prompt run and all of its descendant prompt runs (e.g. the individual attempts behind a parallel / multi-attempt / failover consolidation). For a leaf run this equals TokensCacheRead. Use this (not TokensCacheRead) when aggregating cache reads up a prompt-run or agent-run hierarchy so fan-out provider calls are not under-counted.

      Returns number

    • set TokensCacheReadRollup(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensCacheWrite(): number
      • Field Name: TokensCacheWrite
      • Display Name: Tokens Cache Write
      • SQL Data Type: int
      • Description: Number of input tokens written to the AI provider's prompt cache (a cache WRITE / creation) for this run, as reported by the provider. Populated for providers that report cache writes (e.g. Anthropic cache_creation_input_tokens); NULL or 0 for providers that do not bill/report writes (OpenAI, Gemini, Groq, Cerebras). Counts only; no cost is derived here.

      Returns number

    • set TokensCacheWrite(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensCacheWriteRollup(): number
      • Field Name: TokensCacheWriteRollup
      • Display Name: Tokens Cache Write (Rollup)
      • SQL Data Type: int
      • Description: Rollup of TokensCacheWrite across this prompt run and all of its descendant prompt runs. For a leaf run this equals TokensCacheWrite. Mirrors TokensUsedRollup/TokensPromptRollup; populated for providers that report cache writes (e.g. Anthropic), otherwise 0 or NULL.

      Returns number

    • set TokensCacheWriteRollup(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensCompletion(): number
      • Field Name: TokensCompletion
      • Display Name: Completion Tokens
      • SQL Data Type: int
      • Description: Number of tokens in the completion/result.

      Returns number

    • set TokensCompletion(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensCompletionRollup(): number
      • Field Name: TokensCompletionRollup
      • Display Name: Completion Tokens (Rollup)
      • SQL Data Type: int
      • Description: Total completion/output tokens including this execution and all child/grandchild executions. For leaf nodes (no children), this equals TokensCompletion. For parent nodes, this includes the sum of all descendant completion tokens.

      Returns number

    • set TokensCompletionRollup(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensPrompt(): number
      • Field Name: TokensPrompt
      • Display Name: Prompt Tokens
      • SQL Data Type: int
      • Description: Number of tokens in the prompt.

      Returns number

    • set TokensPrompt(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensPromptRollup(): number
      • Field Name: TokensPromptRollup
      • Display Name: Prompt Tokens (Rollup)
      • SQL Data Type: int
      • Description: Total prompt/input tokens including this execution and all child/grandchild executions. For leaf nodes (no children), this equals TokensPrompt. For parent nodes, this includes the sum of all descendant prompt tokens.

      Returns number

    • set TokensPromptRollup(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensUsed(): number
      • Field Name: TokensUsed
      • Display Name: Tokens Used
      • SQL Data Type: int
      • Description: Total number of tokens used (prompt + completion).

      Returns number

    • set TokensUsed(value: number): void

      Parameters

      • value: number

      Returns void

    • get TokensUsedRollup(): number
      • Field Name: TokensUsedRollup
      • Display Name: Tokens Used (Rollup)
      • SQL Data Type: int
      • Description: Total tokens used including this execution and all child/grandchild executions. This provides a complete view of token usage for hierarchical prompt trees. Calculated as TokensPromptRollup + TokensCompletionRollup.

      Returns number

    • set TokensUsedRollup(value: number): void

      Parameters

      • value: number

      Returns void

    • get TopK(): number
      • Field Name: TopK
      • Display Name: Top K
      • SQL Data Type: int
      • Description: Top-k sampling parameter used for this run. Limits sampling to the top K most likely tokens

      Returns number

    • set TopK(value: number): void

      Parameters

      • value: number

      Returns void

    • get TopLogProbs(): number
      • Field Name: TopLogProbs
      • Display Name: Top Log Probs
      • SQL Data Type: int
      • Description: Number of top log probabilities requested per token (if LogProbs is true)

      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: Top-p (nucleus) sampling parameter used for this run. Considers tokens with cumulative probability up to this value (0-1)

      Returns number

    • set TopP(value: number): void

      Parameters

      • value: number

      Returns void

    • get TotalCost(): number
      • Field Name: TotalCost
      • Display Name: Total Cost
      • SQL Data Type: decimal(18, 6)
      • Description: Total cost of this prompt run including its own cost plus all descendant costs. Calculated as Cost + DescendantCost. This value is stored (not computed) for query performance. Currency is specified in CostCurrency field.

      Returns number

    • set TotalCost(value: number): void

      Parameters

      • value: number

      Returns void

    • get TotalFailoverDuration(): number
      • Field Name: TotalFailoverDuration
      • Display Name: Total Failover Duration (ms)
      • SQL Data Type: int
      • Description: Total time spent in failover attempts in milliseconds

      Returns number

    • set TotalFailoverDuration(value: number): void

      Parameters

      • value: number

      Returns void

    • get TotalRetryDurationMS(): number
      • Field Name: TotalRetryDurationMS
      • Display Name: Total Retry Duration (ms)
      • SQL Data Type: int
      • Description: Total time spent on retries in milliseconds (excluding first attempt)

      Returns number

    • set TotalRetryDurationMS(value: number): void

      Parameters

      • value: number

      Returns void

    • get TransactionGroup(): TransactionGroupBase

      Transaction Groups are used to group multiple transactions into a single ATOMic transaction in a database. They are also useful even in situations with ATOMicity is less important but you want to submit a group of changes to the API server in a single network call.

      Returns TransactionGroupBase

    • set TransactionGroup(group: TransactionGroupBase): void

      Parameters

      Returns void

    • get ValidationAttemptCount(): number
      • Field Name: ValidationAttemptCount
      • Display Name: Validation Attempts
      • SQL Data Type: int
      • Description: Total number of validation attempts made (including the initial attempt)

      Returns number

    • set ValidationAttemptCount(value: number): void

      Parameters

      • value: number

      Returns void

    • get ValidationAttempts(): string
      • Field Name: ValidationAttempts
      • Display Name: Validation Attempt Logs
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON array containing detailed information about each validation attempt

      Returns string

    • set ValidationAttempts(value: string): void

      Parameters

      • value: string

      Returns void

    • get ValidationBehavior(): string
      • Field Name: ValidationBehavior
      • Display Name: Validation Behavior
      • SQL Data Type: nvarchar(50)
      • Description: Validation behavior used: Strict, Warn, or None

      Returns string

    • set ValidationBehavior(value: string): void

      Parameters

      • value: string

      Returns void

    • get ValidationErrorCount(): number
      • Field Name: ValidationErrorCount
      • Display Name: Validation Error Count
      • SQL Data Type: int
      • Description: Number of validation errors on the final attempt

      Returns number

    • set ValidationErrorCount(value: number): void

      Parameters

      • value: number

      Returns void

    • get ValidationSummary(): string
      • Field Name: ValidationSummary
      • Display Name: Validation Summary
      • SQL Data Type: nvarchar(MAX)
      • Description: JSON object containing summary information about the validation process

      Returns string

    • set ValidationSummary(value: string): void

      Parameters

      • value: string

      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 Vendor(): string
      • Field Name: Vendor
      • Display Name: Vendor
      • SQL Data Type: nvarchar(50)

      Returns string

    • get VendorID(): string
      • Field Name: VendorID
      • Display Name: Vendor
      • SQL Data Type: uniqueidentifier
      • Related Entity/Foreign Key: MJ: AI Vendors (vwAIVendors.ID)
      • Description: The vendor providing the model/inference.

      Returns string

    • set VendorID(value: string): void

      Parameters

      • value: string

      Returns void

    • get WasSelectedResult(): boolean
      • Field Name: WasSelectedResult
      • Display Name: Was Selected Result
      • SQL Data Type: bit
      • Default Value: 0
      • Description: Indicates whether this result was selected as the best result when multiple models were run in parallel

      Returns boolean

    • set WasSelectedResult(value: boolean): void

      Parameters

      • value: boolean

      Returns void

    • 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

    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

    • MJ: AI Prompt Runs - 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

      MJAIPromptRunEntity

    • 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

    • 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

    • Extracts the system prompt from the chat messages. This is useful for re-running prompts with the exact same system prompt.

      Returns string

      The system prompt content if found, or null

    • 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 Prompt Runs record from the database

      Parameters

      • ID: string
      • OptionalEntityRelationshipsToLoad: string[]

        (optional) the relationships to load

      Returns Promise<boolean>

      • true if successful, false otherwise

      MJAIPromptRunEntity

    • 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

      • Optional_replaceOldValues: boolean

      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;
      }
    • 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

    • Parses and extracts all message data from the Messages field. This uses the exact logic from the AI Prompt Run form component.

      Returns {
          chatMessages: ChatMessage[];
          formattedData: string;
          formattedMessages: string;
          inputData: any;
      }

      Object containing chatMessages, inputData, and formattedMessages

    • 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

    • Saves the current state of the object to the database. Uses the active provider to handle the actual saving of the record. If the record is new, it will be created, if it already exists, it will be updated.

      Debounces multiple calls so that if Save() is called again while a save is in progress, the second call will simply receive the same result as the first.

      Parameters

      Returns Promise<boolean>

      Promise

    • 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 Prompt Runs entity. This is an auto-generated method that invokes the generated validators for this entity for the following fields:

      • EffortLevel: This rule ensures that if an effort level is provided, it must be between 1 and 100, inclusive.
      • Table-Level: This rule ensures that if the 'CompletedAt' date is provided, it must be the same as or later than the 'RunAt' date. If 'CompletedAt' is not specified, there is no restriction.
      • Table-Level: This rule ensures that if either the number of prompt tokens or completion tokens is missing, or the total tokens used is missing, the check passes automatically. However, if all three are provided, then the total tokens used must exactly equal the sum of prompt tokens and completion tokens.

      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 if the 'CompletedAt' date is provided, it must be the same as or later than the 'RunAt' date. If 'CompletedAt' is not specified, there is no restriction.

      Parameters

      • result: ValidationResult

        the ValidationResult object to add any errors or warnings to

      Returns void

    • This rule ensures that if either the number of prompt tokens or completion tokens is missing, or the total tokens used is missing, the check passes automatically. However, if all three are provided, then the total tokens used must exactly equal the sum of prompt tokens and completion tokens.

      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