How do you enforce enum constraints in JSON Schema so an LLM only outputs valid database status codes? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you enforce enum constraints in JSON Schema so an LLM only outputs valid database status codes?

message-square
0

How JSON Schema Enum Constraints Enforce Valid Status Codes

Enforcing an enum constraint in JSON Schema restricts a model field to an explicit allowlist of string or integer values—such as exact database status codes ("PENDING", "PAID", "FAILED", "REFUNDED"). When paired with Structured Outputs (strict: true), constrained decoding forces token selection to valid enum members rather than relying on prompt instructions alone.

  • Deterministic allowlist enforcement: Any value outside the enum array is rejected by strict schema compilation or downstream validation (zod / ajv), preventing invented synonyms like "COMPLETED" or "CANCELLED" when "SETTLED" is required.
  • Exact case and type matching: JSON Schema enum checks exact string casing and types; "pending" does not match "PENDING", and string enums should not mix numbers unless intended.
  • Single source of truth with database enums: Deriving the JSON Schema enum directly from your TypeScript/database status constants guarantees the LLM schema never drifts out of sync with database constraints or CHECK constraints.

Steps to Enforce Status Code Enums in JSON Schema

  1. Define canonical status constants in code: Declare your allowed database status codes once as a const tuple or enum so both application types and JSON Schema share the exact same values.
  2. Declare "type": "string" and "enum": [...] on the status property: Set "enum" to the exact allowed status literals and include the property name in "required" when using strict JSON Schema.
  3. Enable strict Structured Outputs on the API call: Pass the JSON Schema with strict: true so the provider enforces schema adherence during generation.
  4. Validate again at runtime before database writes: Re-validate the parsed payload with Zod or your schema validator and guard against unexpected states or transitions before executing SQL/ORM writes.

TypeScript Example: Enforcing Database Status Codes with JSON Schema and Zod

import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const openai = new OpenAI();

// Canonical database status codes (single source of truth)
export const ORDER_STATUS_CODES = [
  "PENDING_PAYMENT",
  "PAID",
  "FULFILLED",
  "REFUNDED",
  "FAILED",
] as const;

export type OrderStatus = (typeof ORDER_STATUS_CODES)[number];

const OrderStatusUpdateSchema = z.object({
  orderId: z.string().min(1),
  status: z.enum(ORDER_STATUS_CODES),
  reason: z.string().nullable(),
});

// Equivalent explicit JSON Schema with strict enum constraint
export const orderStatusJsonSchema = {
  type: "object",
  additionalProperties: false,
  required: ["orderId", "status", "reason"],
  properties: {
    orderId: {
      type: "string",
      description: "Target order identifier",
    },
    status: {
      type: "string",
      enum: [...ORDER_STATUS_CODES],
      description: "Valid database status code for the order",
    },
    reason: {
      type: ["string", "null"],
      description: "Optional audit reason or null when not applicable",
    },
  },
} as const;

export async function classifyOrderStatus(
  eventSummary: string
): Promise<z.infer<typeof OrderStatusUpdateSchema>> {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    temperature: 0,
    messages: [
      {
        role: "system",
        content:
          "Map the payment/fulfillment event to an exact allowed database order status code.",
      },
      {
        role: "user",
        content: eventSummary,
      },
    ],
    response_format: zodResponseFormat(
      OrderStatusUpdateSchema,
      "order_status_update"
    ),
  });

  const message = completion.choices[0]?.message;
  if (message?.refusal) {
    throw new Error(`Model refused status classification: \${message.refusal}`);
  }

  const parsed = JSON.parse(message?.content ?? "{}");
  return OrderStatusUpdateSchema.parse(parsed);
}

Helpful Tips for Database Status Schemas

  • Include an explicit fallback status when ambiguity is possible: If an input lacks enough evidence to pick a final state, include "NEEDS_REVIEW" or "UNKNOWN" in the enum rather than forcing the model to guess "PAID" or "FAILED".
  • Enforce state-machine transitions in application/DB logic: An enum proves the string is a valid status code, not that transitioning from "REFUNDED" back to "PAID" is legal—check current DB row state before updating.
  • Keep enum values concise and descriptive: Clear uppercase snake_case codes like "PENDING_PAYMENT" or "CHARGEBACK_OPEN" map cleanly to SQL enums/check constraints and reduce classification ambiguity.