SQLServerCentral Article

How to Store AI Output in SQL Server: A Practical Data Model

,

An application can begin with a deceptively simple requirement: call an AI model and save the answer. A table with an ID, a timestamp, and an nvarchar(max) column is enough for a prototype. It stops being enough when the answer becomes part of a business workflow.

This article uses one concrete example: a support-ticket copilot. It classifies an incoming ticket, drafts a reply, cites relevant knowledge-base articles, and places the draft in a queue for a support agent to approve, edit, or reject. The customer does not see unapproved text.

The database is the operational record for that workflow. It is not a model-training store. The same history may later support evaluations, but the immediate requirements are to display an approved answer, explain how it was produced, prevent duplicate ingestion, measure cost and quality, and preserve the original output when a reviewer changes it.

Table Overview

Ticket 42 reports that a query now takes 45 seconds. Before calling the provider, the application selects one row from AIModel and one row from PromptTemplate. After the provider responds, the application saves one AIInteraction row that points back to both. Citations and review decisions arrive as child rows. The table below shows where the application writes each part of the workflow.

TableOne Row RecordsHow It Relates to the Interaction
AIModelA registered model releaseThe interaction stores its ModelID
PromptTemplateA published revision of the prompt instructionsThe interaction stores its PromptTemplateID
AIInteractionOne provider invocation and its current workflow stateThe parent record for the draft
AICitationOne source associated with a draftZero or more per interaction, in display order
AIResponseRevisionOne human editZero or more per interaction
AIReviewEventOne review decisionReferences the interaction and, when applicable, a specific revision
AIResponseEmbedding1536One optional draft embedding for a model versionAdded only if the product supports similarity search over drafts

Model and Prompt Versions

The application registers each provider release it can select in AIModel. ModelVersion is the release identifier from the provider or deployment registry. In this example the fictional provider names its release 2026-06-15. SQL Server independently sets CreatedAt to the UTC time the registration row is inserted. If a provider supplies only a moving alias, record the alias and any available release metadata without claiming that the exact backend is known.

The support team owns the prompt contract. It publishes a new PromptTemplate row whenever instructions or the expected response change, and keeps prior rows for lineage. The IsActive default makes a newly registered row eligible for selection. Set it explicitly to zero when importing a retired version or staging a release. The application configuration still chooses the specific model and prompt versions to use.

CREATE TABLE dbo.AIModel
(
    ModelID       int IDENTITY(1,1) NOT NULL,
    ProviderName  varchar(50) NOT NULL,
    ModelName     varchar(100) NOT NULL,
    ModelVersion  varchar(100) NOT NULL,
    IsActive      bit NOT NULL
        CONSTRAINT DF_AIModel_IsActive DEFAULT (1),
    CreatedAt     datetime2(3) NOT NULL
        CONSTRAINT DF_AIModel_CreatedAt DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_AIModel PRIMARY KEY (ModelID),
    CONSTRAINT UQ_AIModel
        UNIQUE (ProviderName, ModelName, ModelVersion)
);
GO

CREATE TABLE dbo.PromptTemplate
(
    PromptTemplateID int IDENTITY(1,1) NOT NULL,
    PromptName       varchar(100) NOT NULL,
    TemplateVersion  int NOT NULL,
    SystemText       nvarchar(max) NULL,
    TemplateText     nvarchar(max) NOT NULL,
    IsActive         bit NOT NULL
        CONSTRAINT DF_PromptTemplate_IsActive DEFAULT (1),
    CreatedAt        datetime2(3) NOT NULL
        CONSTRAINT DF_PromptTemplate_CreatedAt DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_PromptTemplate PRIMARY KEY (PromptTemplateID),
    CONSTRAINT UQ_PromptTemplate
        UNIQUE (PromptName, TemplateVersion)
);
GO

The example seeds one model release and two revisions of DraftSupportReply. Version 3 requested a category and draft. The support team added a confidence score in version 4 to prioritize drafts below 0.80 for closer review. The threshold is an example product rule. Every customer-facing draft still needs approval. Version 3 is inactive, but earlier interactions can still join to it.

INSERT dbo.AIModel
    (ProviderName, ModelName, ModelVersion)
VALUES
    ('ExampleProvider', 'support-model', '2026-06-15');

INSERT dbo.PromptTemplate
    (PromptName, TemplateVersion, SystemText, TemplateText, IsActive)
VALUES
(
    'DraftSupportReply',
    3,
    N'Return valid JSON. Do not invent facts.',
    N'Classify this ticket and draft a reply: {{ticket_text}}',
    0
),
(
    'DraftSupportReply',
    4,
    N'Return valid JSON. Use the ticket and any supplied knowledge-base articles.',
    N'Return category, confidence from 0 to 1, and draft as JSON fields. '
      + N'Ticket: {{ticket_text}}',
    1
);
GO

The Interaction Record

AIInteraction stores both foreign keys, the rendered request, the provider result and the current review state. The application preserves three different outputs. RawProviderResponse is the original provider JSON. ResponseText is the proposed reply an agent sees. StructuredOutput is the application’s normalized JSON, such as category and confidence. Typed token and timing columns support reports across providers.

ValidationStatus starts at NotChecked so an omitted value cannot imply validation succeeded. The sample worker explicitly writes Valid after checking the response contract. ReviewStatus defaults to Pending so even a valid response stays out of the customer view until an agent approves it. CreatedAt records when SQL Server inserts the row. The worker supplies the actual call timestamps and elapsed time.

CREATE TABLE dbo.AIInteraction
(
    InteractionID       bigint IDENTITY(1,1) NOT NULL,
    ConversationID      uniqueidentifier NOT NULL,
    IngestionKey        uniqueidentifier NOT NULL,
    ProviderRequestID   varchar(200) NULL,

    ModelID             int NOT NULL,
    PromptTemplateID    int NOT NULL,

    StartedAt           datetime2(3) NOT NULL,
    CompletedAt         datetime2(3) NULL,
    LatencyMilliseconds int NULL,

    RenderedPrompt      nvarchar(max) NULL,
    InputHash           varbinary(32) NULL,
    RequestParameters   nvarchar(max) NULL,

    RawProviderResponse nvarchar(max) NULL,
    ResponseText        nvarchar(max) NOT NULL,
    StructuredOutput    nvarchar(max) NULL,
    FinishReason        varchar(50) NULL,

    InputTokens         int NULL,
    OutputTokens        int NULL,
    ValidationStatus    varchar(20) NOT NULL
        CONSTRAINT DF_AIInteraction_ValidationStatus DEFAULT ('NotChecked'),
    ReviewStatus        varchar(20) NOT NULL
        CONSTRAINT DF_AIInteraction_ReviewStatus DEFAULT ('Pending'),
    ReviewedBy          nvarchar(256) NULL,
    ReviewedAt          datetime2(3) NULL,

    CreatedAt           datetime2(3) NOT NULL
        CONSTRAINT DF_AIInteraction_CreatedAt DEFAULT SYSUTCDATETIME(),
    RowVersion          rowversion NOT NULL,

    CONSTRAINT PK_AIInteraction PRIMARY KEY (InteractionID),
    CONSTRAINT FK_AIInteraction_Model
        FOREIGN KEY (ModelID) REFERENCES dbo.AIModel(ModelID),
    CONSTRAINT FK_AIInteraction_Prompt
        FOREIGN KEY (PromptTemplateID)
        REFERENCES dbo.PromptTemplate(PromptTemplateID),
    CONSTRAINT CK_AIInteraction_CompletedAt
        CHECK (CompletedAt IS NULL OR CompletedAt >= StartedAt),
    CONSTRAINT CK_AIInteraction_RequestParameters
        CHECK (RequestParameters IS NULL OR ISJSON(RequestParameters) = 1),
    CONSTRAINT CK_AIInteraction_RawProviderResponse
        CHECK (RawProviderResponse IS NULL OR ISJSON(RawProviderResponse) = 1),
    CONSTRAINT CK_AIInteraction_StructuredOutput
        CHECK (StructuredOutput IS NULL OR ISJSON(StructuredOutput) = 1),
    CONSTRAINT CK_AIInteraction_ValidationStatus
        CHECK (ValidationStatus IN ('NotChecked', 'Valid', 'Invalid', 'Warning')),
    CONSTRAINT CK_AIInteraction_ReviewStatus
        CHECK (ReviewStatus IN ('Pending', 'Approved', 'Rejected'))
);
GO

CREATE UNIQUE INDEX UX_AIInteraction_IngestionKey
ON dbo.AIInteraction(IngestionKey);
GO

CREATE INDEX IX_AIInteraction_Operations
ON dbo.AIInteraction(CreatedAt, ModelID)
INCLUDE
(
    PromptTemplateID, LatencyMilliseconds, InputTokens, OutputTokens,
    ValidationStatus, ReviewStatus
);
GO

Before a call, the worker allocates and durably records an application-generated IngestionKey for that invocation. If the worker resends the same result to SQL Server after losing a database acknowledgment, it reuses that key. The unique index enforces one row per key. The ingestion routine must still return the existing InteractionID on a replay. A fresh provider invocation receives a fresh key. If a timeout leaves the provider outcome unknown, use provider-supported idempotency or reconcile the outcome before retrying the external call.

RowVersion protects concurrent review updates. The reviewer submits the token read with the draft. If the conditional update affects zero rows, the application rolls back the review transaction and reloads. Give the review procedure permission to change review fields and write review events while preserving the original model output.

From Ticket to Stored Draft

Run the table definitions and seed inserts first in a scratch database. The sample uses OPENJSON, which requires database compatibility level 130 or higher. Run both blocks in this section as one batch so the second block can use the variables from the first.

The example below uses a synthetic provider response for ticket 42. In production, the worker selects the configured AIModel and PromptTemplate rows before sending the request. It sends SystemText as the system message and replaces the ticket_text placeholder in TemplateText with the actual ticket. The two selected IDs, rendered user prompt and generation settings go into the interaction. The model version in the registry and the version number on the template are different identifiers.

After the response arrives, the worker extracts the draft from output.draft and maps the category and confidence to its own JSON contract. It takes 62 input tokens and 86 output tokens from the provider’s usage object. The 842 ms latency is measured by the application. For this valid response the worker supplies Valid and lets the database default the review status to Pending.

DECLARE @Key uniqueidentifier = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
DECLARE @Ticket nvarchar(max) = N'The reporting query now takes 45 seconds.';
DECLARE @ModelID int, @PromptID int, @RenderedPrompt nvarchar(max);

SELECT @ModelID = ModelID
FROM dbo.AIModel
WHERE ProviderName = 'ExampleProvider' AND ModelName = 'support-model'
  AND ModelVersion = '2026-06-15';

SELECT @PromptID = PromptTemplateID,
       @RenderedPrompt = REPLACE(TemplateText, N'{{ticket_text}}', @Ticket)
FROM dbo.PromptTemplate
WHERE PromptName = 'DraftSupportReply' AND TemplateVersion = 4;

DECLARE @Raw nvarchar(max) =
    N'{"id":"req_8f12d9","finish_reason":"stop",
        "output":{"draft":"Please attach the Query Store plan.",
                  "category":"performance","confidence":0.92},
        "usage":{"input_tokens":62,"output_tokens":86}}';

DECLARE @Draft nvarchar(max), @Normalized nvarchar(max);
SELECT @Draft = draft
FROM OPENJSON(@Raw, '$.output')
WITH (draft nvarchar(max) '$.draft');

SET @Normalized = (
    SELECT JSON_VALUE(@Raw, '$.output.category') AS category,
           TRY_CONVERT(decimal(4,3), JSON_VALUE(@Raw, '$.output.confidence'))
               AS confidence
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
);

The following transaction is the persistence portion of the same batch. The lookup holds a lock through commit so two workers using the same ingestion key cannot both observe a missing row and insert it. The first write creates the interaction. Replaying the same batch returns the same ID, with no second row. The catch block rolls back and rethrows failures. The caller can retry a transient failure with the original key. In a production routine, reject attempts to reuse the key for a different invocation.

SET XACT_ABORT ON;
DECLARE @InteractionID bigint;

BEGIN TRY
    BEGIN TRANSACTION;

    SELECT @InteractionID = InteractionID
    FROM dbo.AIInteraction WITH (UPDLOCK, HOLDLOCK)
    WHERE IngestionKey = @Key;

    IF @InteractionID IS NULL
    BEGIN
        INSERT dbo.AIInteraction
        (
            IngestionKey, ConversationID, ModelID, PromptTemplateID,
            StartedAt, CompletedAt, LatencyMilliseconds, RenderedPrompt,
            RequestParameters, ProviderRequestID, RawProviderResponse,
            ResponseText, StructuredOutput, FinishReason,
            InputTokens, OutputTokens, ValidationStatus
        )
        VALUES
        (
            @Key, '11111111-2222-3333-4444-555555555555', @ModelID, @PromptID,
            '2026-07-17T13:30:00.000', '2026-07-17T13:30:00.842', 842,
            @RenderedPrompt, N'{"temperature":0.1,"max_output_tokens":300}',
            JSON_VALUE(@Raw, '$.id'), @Raw, @Draft, @Normalized,
            JSON_VALUE(@Raw, '$.finish_reason'),
            TRY_CONVERT(int, JSON_VALUE(@Raw, '$.usage.input_tokens')),
            TRY_CONVERT(int, JSON_VALUE(@Raw, '$.usage.output_tokens')),
            'Valid'
        );

        SET @InteractionID = CONVERT(bigint, SCOPE_IDENTITY());
    END;

    COMMIT TRANSACTION;
    SELECT @InteractionID AS InteractionID;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    THROW;
END CATCH;

On a fresh demo database, the first call and its replay both return interaction ID 1. That single row links model release 2026-06-15 to prompt version 4 and holds category performance, confidence 0.920, 148 total tokens, 842 ms latency and Pending review status.

Indexing the Output Category

The provider envelope is JSON because providers add and rearrange optional metadata. The normalized output is JSON because different tasks may have different properties. SQL Server's ISJSON constraint proves that a value is syntactically valid JSON; it does not prove that confidence is a number from zero through one or that a cited article exists. The application or a validation service must enforce that contract and store the result in ValidationStatus.

Suppose agents frequently filter the queue to performance tickets. The following code exposes the category from StructuredOutput as a computed column named OutputCategory and adds an index beginning with that column. Validate the category against the application’s allowed values before writing it so the conversion to 50 characters cannot truncate an accepted category. The final SELECT queries OutputCategory directly and returns the pending sample draft.

ALTER TABLE dbo.AIInteraction
ADD OutputCategory AS
    CONVERT(varchar(50), JSON_VALUE(StructuredOutput, '$.category'));
GO

CREATE INDEX IX_AIInteraction_OutputCategory
ON dbo.AIInteraction(OutputCategory, CreatedAt)
INCLUDE (ModelID, ValidationStatus, ReviewStatus);
GO

SELECT InteractionID, CreatedAt
FROM dbo.AIInteraction
WHERE OutputCategory = 'performance' AND ReviewStatus = 'Pending'
ORDER BY CreatedAt;

This keeps optional task-specific attributes flexible while making a stable reporting dimension easy to query. Microsoft documents the same approach in its guidance for indexing JSON properties.

Citations, Revisions, and Review Decisions

A support draft may cite zero, one, or several knowledge-base articles. That is a one-to-many relationship, so citations belong in a child table. For ticket 42, the application could save knowledge-base article 311 as citation 1. The primary key combines InteractionID and CitationNumber so each draft has its own display order. SourceURI locates the source, while RetrievedAt and ContentHash help identify the material used if the page changes.

CREATE TABLE dbo.AICitation
(
    InteractionID  bigint NOT NULL,
    CitationNumber int NOT NULL,
    KnowledgeBaseID int NULL,
    SourceURI       nvarchar(2048) NOT NULL,
    SourceTitle     nvarchar(500) NULL,
    RetrievedAt     datetime2(3) NULL,
    ContentHash     varbinary(32) NULL,
    CONSTRAINT PK_AICitation
        PRIMARY KEY (InteractionID, CitationNumber),
    CONSTRAINT FK_AICitation_Interaction
        FOREIGN KEY (InteractionID)
        REFERENCES dbo.AIInteraction(InteractionID)
);
GO

If an agent improves the draft, AIResponseRevision stores the revised text without changing the model’s original. The example adds revision 1 to interaction 1 from the fresh demo. AIReviewEvent stores the decision separately so an agent can approve the original without creating a revision. Its composite foreign key ensures a decision can reference only a revision belonging to that interaction.

CREATE TABLE dbo.AIResponseRevision
(
    RevisionID     bigint IDENTITY(1,1) NOT NULL,
    InteractionID  bigint NOT NULL,
    RevisionNumber int NOT NULL,
    RevisedText    nvarchar(max) NOT NULL,
    ChangeReason   nvarchar(1000) NULL,
    EditedBy       nvarchar(256) NOT NULL,
    CreatedAt      datetime2(3) NOT NULL
        CONSTRAINT DF_AIResponseRevision_CreatedAt
        DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_AIResponseRevision PRIMARY KEY (RevisionID),
    CONSTRAINT UQ_AIResponseRevision
        UNIQUE (InteractionID, RevisionNumber),
    CONSTRAINT UQ_AIResponseRevision_InteractionRevisionID
        UNIQUE (InteractionID, RevisionID),
    CONSTRAINT FK_AIResponseRevision_Interaction
        FOREIGN KEY (InteractionID)
        REFERENCES dbo.AIInteraction(InteractionID)
);
GO

INSERT dbo.AIResponseRevision
    (InteractionID, RevisionNumber, RevisedText, ChangeReason, EditedBy)
VALUES
(
    1,
    1,
    N'This appears to be a query-performance regression. '
      + N'Please attach the Query Store plan. We will compare it with the last known good plan.',
    N'Removed an unnecessary request and clarified the next action.',
    N'agent@example.com'
);
GO

CREATE TABLE dbo.AIReviewEvent
(
    ReviewEventID bigint IDENTITY(1,1) NOT NULL,
    InteractionID bigint NOT NULL,
    RevisionID    bigint NULL,
    Decision      varchar(20) NOT NULL,
    Reviewer      nvarchar(256) NOT NULL,
    Notes         nvarchar(1000) NULL,
    ReviewedAt    datetime2(3) NOT NULL
        CONSTRAINT DF_AIReviewEvent_ReviewedAt
        DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_AIReviewEvent PRIMARY KEY (ReviewEventID),
    CONSTRAINT FK_AIReviewEvent_Interaction
        FOREIGN KEY (InteractionID)
        REFERENCES dbo.AIInteraction(InteractionID),
    CONSTRAINT FK_AIReviewEvent_Revision
        FOREIGN KEY (InteractionID, RevisionID)
        REFERENCES dbo.AIResponseRevision(InteractionID, RevisionID),
    CONSTRAINT CK_AIReviewEvent_Decision
        CHECK (Decision IN ('Approved', 'Rejected', 'NeedsChanges'))
);
GO

AIReviewEvent preserves every decision, including an approval that did not require an edit. When a reviewer changes the text, RevisionID identifies the version considered in that decision; when the original model text is approved or rejected unchanged, it remains NULL.

The review procedure should insert the revision when needed, insert the review event, and update the interaction's current ReviewStatus, ReviewedBy, and ReviewedAt in one transaction. Its update includes the previously read RowVersion. The application displays text only when the current review status is Approved. It uses the revision referenced by that approval, or the original ResponseText when the approval has no revision. This preserves what the model produced, what the agent changed, every decision, and what the customer ultimately saw.

Optional Embeddings

An embedding is a numerical representation produced by a particular embedding model. It does not replace the source text. In SQL Server 2025, vector(1536) is one typed column containing 1,536 numbers; it does not require 1,536 relational columns. The declared dimension rejects vectors of the wrong length.

Embedding models with different dimensions or incompatible vector spaces should not share a column. A child table keeps the optional data away from routine operational reads and makes the compatible model family explicit:

CREATE TABLE dbo.AIResponseEmbedding1536
(
    InteractionID         bigint NOT NULL,
    EmbeddingModelName    varchar(100) NOT NULL,
    EmbeddingModelVersion varchar(100) NOT NULL,
    ResponseEmbedding     vector(1536) NOT NULL,
    CreatedAt             datetime2(3) NOT NULL
        CONSTRAINT DF_AIResponseEmbedding1536_CreatedAt
        DEFAULT SYSUTCDATETIME(),
    CONSTRAINT PK_AIResponseEmbedding1536
        PRIMARY KEY
        (InteractionID, EmbeddingModelName, EmbeddingModelVersion),
    CONSTRAINT FK_AIResponseEmbedding1536_Interaction
        FOREIGN KEY (InteractionID)
        REFERENCES dbo.AIInteraction(InteractionID)
);
GO

If a future embedding model returns 1,024 dimensions, create a separate vector(1024) table or column and migrate deliberately. Even models with the same dimensions may be semantically incompatible, so always store the embedding model and version. SQL Server 2025 supports at most 1,998 dimensions in a native vector. A 3,072-dimension result therefore cannot be stored directly as vector(3072); use a lower-dimensional output from the embedding service when supported, or choose another representation or store. The SQL Server 2025 vector type and exact VECTOR_DISTANCE function are available for this design. Approximate VECTOR_SEARCH and CREATE VECTOR INDEX remain preview features in boxed SQL Server 2025 as of August 2026, so check the current vector-index documentation before adopting them.

Operational Reporting

The schema exposes operational measurements as typed columns, so daily reporting does not have to parse provider JSON. AIInteraction supplies timestamps, latency, token counts, and current statuses. The query groups by provider, model release, prompt name and prompt version. On the demo data, the row for version 4 shows one interaction, 148 tokens, 842 ms average latency, zero invalid responses and zero rejected drafts. ActivityDate uses the UTC insert date.

SELECT
    CONVERT(date, ai.CreatedAt) AS ActivityDate,
    m.ProviderName,
    m.ModelName,
    m.ModelVersion,
    p.PromptName,
    p.TemplateVersion,
    COUNT_BIG(*) AS InteractionCount,
    AVG(CONVERT(decimal(18,2), ai.LatencyMilliseconds))
        AS AverageLatencyMilliseconds,
    SUM(CONVERT(bigint, COALESCE(ai.InputTokens, 0))
      + CONVERT(bigint, COALESCE(ai.OutputTokens, 0))) AS TotalTokens,
    SUM(CASE WHEN ai.ValidationStatus = 'Invalid' THEN 1 ELSE 0 END)
        AS InvalidResponses,
    SUM(CASE WHEN ai.ReviewStatus = 'Rejected' THEN 1 ELSE 0 END)
        AS RejectedResponses
FROM dbo.AIInteraction AS ai
JOIN dbo.AIModel AS m ON m.ModelID = ai.ModelID
JOIN dbo.PromptTemplate AS p
    ON p.PromptTemplateID = ai.PromptTemplateID
GROUP BY
    CONVERT(date, ai.CreatedAt),
    m.ProviderName, m.ModelName, m.ModelVersion,
    p.PromptName, p.TemplateVersion
ORDER BY ActivityDate, m.ProviderName, m.ModelName, m.ModelVersion;

Grouping by both model and prompt version separates two causes of changed behavior. A rise in rejections limited to prompt version 4 gives the support team a place to investigate. Compare similar tickets and review policies before attributing the change to the prompt. Counts provide the denominator: 20 rejected drafts out of 100 interactions is very different from 20 out of one million.

Security, Privacy, and Retention

AI output is untrusted input. A model can return unsafe HTML, invented links, confidential text copied from context, or executable instructions. Storing the output does not make it safe.

  • Use parameterized commands for prompts, responses, and review text.
  • Encode text for its destination when rendering it.
  • Never execute generated SQL, shell commands, or tool arguments merely because they came from an approved model.
  • Give the ingestion account permission to insert raw interactions, not to rewrite them.
  • Restrict access to rendered prompts and raw provider responses; they may contain customer data.
  • Define retention periods separately for prompts, raw responses, approved revisions, citations, and embeddings.
  • Make deletion cascade through revisions, citations, caches, and vector-search structures according to policy.

Do not store hidden chain-of-thought. If the product needs an explanation, request a concise user-facing rationale and store that explicit output. It is easier to govern and more useful to reviewers.

Common Design Problems

Each shortcut below removes context that the support workflow later needs. The correction follows directly from the lifecycle.

FailureOperational impactCorrection
Only an ID, timestamp, and one nvarchar(max) responseNo reliable model lineage, token reporting, validation status, or review stateKeep long text in nvarchar(max), but add typed interaction metadata and foreign keys
One JSON document containing the request, provider response, review state, and revisionsFrequent filters require repeated parsing, constraints are weak, and multiple writers contend for one valueUse JSON only for variable payloads; promote stable facts and repeating entities to columns and child tables
Overwriting the model response after reviewDestroys evidence of model quality and what the reviewer changedMake the original output immutable and append revisions
Storing only a friendly model aliasEarlier output cannot be tied to the deployment that produced itStore provider, model identifier, and deployment version
Mixing embeddings from different modelsSimilarity scores become invalid even when dimensions happen to matchStore embedding model and version; separate incompatible dimensions or vector spaces
Retaining every prompt and response foreverRaises storage cost, privacy exposure, and deletion complexitySet explicit, enforceable retention rules for each data class

Design Summary

Nvarchar(max) remains the right SQL Server type for many AI prompts and answers. The mistake is treating that text as the complete record.

For the support-ticket copilot, a durable design records the exact model and prompt version, the rendered request, the provider's raw envelope, the text and structured data extracted by the application, validation and review state, citations, human revisions, and optional embeddings. Relational columns hold stable facts, JSON holds variable details, and child tables hold repeating or independently governed data.

The practical test is simple: can the application show the approved answer, explain how it was produced, measure its quality and cost, prevent duplicate ingestion, preserve reviewer changes without rewriting history, and remove all related data when policy requires? If the schema can do those things, it is treating AI output as production data rather than as a string to save.

Rate

★ ★ ★ ★ ★ ★ ★ ★ ★ ★

You rated this post out of 5. Change rating

Share

Share

Rate

★ ★ ★ ★ ★ ★ ★ ★ ★ ★

You rated this post out of 5. Change rating