Code examples:

Building a Reliable Structured-Output LLM Service

October 27, 2026 14 min read By Jaffar Kazi
Real-World AI Engineering Structured Outputs LLM Reliability
C# Python Azure

This is the first article in Real-World AI Engineering, a 25-part series on production AI patterns in order of engineering maturity. It starts with the problem that shows up before any of the others matter: getting a predictable, typed response out of a model that was never designed to guarantee one.

What You'll Learn

  • Why asking an LLM nicely for JSON is not a validation strategy
  • How to define a typed response contract with a JSON schema, in both C# and Python
  • A bounded-retry pattern that feeds parsing errors back to the model instead of failing immediately
  • Why schema validation and business-rule validation are two different layers, not one
  • What this actually costs in tokens, and when the validation overhead is worth building at all

1. The Problem: "Ask Nicely for JSON" Isn't a Strategy

I built this because I kept hitting the same failure in different clothes: a ticket-triage feature, an invoice parser, a résumé screener. Different domains, same crash — code downstream expected a clean object, and the LLM's response was almost right.

Almost right is the trap. Individually, failures are rare: a missing field, an enum with the wrong casing, a date written as "next Friday" instead of ISO, a priority score outside your 1–5 scale. At real volume, they're inevitable. If a human reads the output, none of this matters. The moment the consumer is other code — a database write, a routing rule, a billing calculation — the LLM's output has to satisfy a contract it was never actually forced to honor.

The usual first build is: ask for JSON in the prompt, Deserialize/json.loads the result, move on. It survives the demo and the first fifty manual tests, then meets real input. In rough order of how often I've hit each one:

  • Malformed JSON — a trailing comma, an unescaped quote, a markdown code fence wrapped around the output.
  • Missing required fields — the model omits a field instead of returning null.
  • Type mismatches — a priority field comes back as "high" instead of an integer.
  • Values outside the allowed set — an enum field returns something you never defined.
  • Business-rule violations that are still valid JSON — an SLA deadline in the past. No JSON parser will ever catch this.

None of this is "the model being bad." Azure OpenAI's structured-output mode makes malformed JSON and off-schema enums genuinely rare. But rare isn't impossible, and "pretty good" isn't an engineering control. Every LLM response needs the same scrutiny as any other untrusted input off the network.

The running example throughout: a support-ticket triage service — raw customer email in, category/priority/sentiment/SLA-deadline extraction out. Simple enough to hold in your head, representative enough to carry over to invoices, résumés, or anything else that's "read some text, return a typed object."

2. The Shape of a Real Solution

The fix isn't a smarter prompt — it's a hard boundary between what the model produces and what your code is allowed to trust, with three things sitting at that boundary:

  1. A typed response model — the single source of truth for the shape, not prose in a prompt.
  2. A bounded retry loop that treats a bad response as recoverable: feed the specific error back to the model, cap the attempts, then fail loudly and predictably.
  3. A business-rule layer that runs after schema validation, because shape being right says nothing about whether the values make sense.

Stack for the examples: Azure OpenAI structured outputs as the model layer, ASP.NET Core with typed records on the C# side, FastAPI with Pydantic on the Python side. Same pattern, different syntax.

3. Architecture Overview

The request flow has exactly one loop, and it's deliberate and bounded — not an accident of retry-everywhere code:

Architecture diagram: client request flows through the API to prompt building, LLM call, JSON parsing, schema validation, and business rule validation, with a bounded retry loop feeding parse failures back into prompt building

Four things worth noticing. There are two separate failure exits — a parse failure that exhausts the retry budget, and a validation failure (schema or business-rule) that doesn't retry at all, since asking the same question again rarely fixes a business-rule violation. Schema and business-rule validation are separate boxes, not one (Section 6 explains why). The retry loop only re-enters at prompt-building, so each attempt can include the previous error. And there's no "mostly valid" branch — it's binary: fully valid, or a structured error.

4. Core Implementation: The Typed Contract

Everything starts from the response model — the contract the LLM is constrained against, not a DTO bolted on afterward. Get the shape right before writing a line of prompt.

TicketExtraction.cs

public enum TicketCategory { Billing, Technical, Account, Other }
public enum Sentiment { Positive, Neutral, Negative, Angry }

public record TicketExtraction
{
    public required string Summary { get; init; }
    public required TicketCategory Category { get; init; }

    // 1 = low, 5 = urgent — enforced in the business-rule layer, not the schema
    public required int Priority { get; init; }

    public required Sentiment Sentiment { get; init; }

    // Null when the email doesn't imply a deadline
    public DateOnly? SlaDeadline { get; init; }
}

public record ExtractionResult
{
    public TicketExtraction? Data { get; init; }
    public IReadOnlyList<string> Errors { get; init; } = [];
    public bool Success => Data is not null && Errors.Count == 0;
}

from enum import Enum
from datetime import date
from pydantic import BaseModel, Field

class TicketCategory(str, Enum):
    BILLING = "billing"
    TECHNICAL = "technical"
    ACCOUNT = "account"
    OTHER = "other"

class Sentiment(str, Enum):
    POSITIVE = "positive"
    NEUTRAL = "neutral"
    NEGATIVE = "negative"
    ANGRY = "angry"

class TicketExtraction(BaseModel):
    summary: str
    category: TicketCategory
    # 1 = low, 5 = urgent — enforced in the business-rule layer, not the schema
    priority: int = Field(ge=1, le=5)
    sentiment: Sentiment
    sla_deadline: date | None = None  # None when no deadline is implied

class ExtractionResult(BaseModel):
    data: TicketExtraction | None = None
    errors: list[str] = []

    @property
    def success(self) -> bool:
        return self.data is not None and not self.errors

Two choices trip people up here. First, Priority is a plain integer — the schema declares the 1–5 range at generation time, but a model can still drift outside it, so real enforcement lives in Section 6's business-rule layer, where a violation becomes a specific, loggable error instead of a crash. Second, SlaDeadline is nullable — "the model correctly found no deadline" has to stay distinct from "the model failed to extract one," or you'll debug a bug that was actually correct behavior.

5. Challenge One: Malformed Output and the Retry Loop

With structured-output mode, outright malformed JSON is genuinely rare — under 1% in my testing across a few thousand synthetic tickets. But rare isn't zero, and at volume, a sub-1% failure rate means daily incidents. The fix: a bounded retry loop that feeds the specific failure back to the model instead of repeating the same question.

ExtractionService.cs

public class ExtractionService(AzureOpenAIClient client, ILogger<ExtractionService> logger)
{
    private const int MaxRetries = 2; // 3 attempts total

    public async Task<ExtractionResult> ExtractAsync(string ticketText, CancellationToken ct)
    {
        string? lastError = null;

        for (var attempt = 0; attempt <= MaxRetries; attempt++)
        {
            var prompt = BuildPrompt(ticketText, previousError: lastError);
            var raw = await CallModelAsync(prompt, ct);

            try
            {
                var data = JsonSerializer.Deserialize<TicketExtraction>(raw, JsonOptions)
                    ?? throw new JsonException("Model returned null");

                logger.LogInformation(
                    "Extraction succeeded on attempt {Attempt}", attempt + 1);

                return new ExtractionResult { Data = data };
            }
            catch (JsonException ex)
            {
                lastError = ex.Message;
                logger.LogWarning(
                    "Attempt {Attempt} failed to parse: {Error}", attempt + 1, lastError);
            }
        }

        return new ExtractionResult
        {
            Errors = [$"Extraction failed after {MaxRetries + 1} attempts: {lastError}"]
        };
    }
}

import json
import logging

logger = logging.getLogger("extraction_service")
MAX_RETRIES = 2  # 3 attempts total

class ExtractionService:
    def __init__(self, client):
        self.client = client

    async def extract(self, ticket_text: str) -> ExtractionResult:
        last_error: str | None = None

        for attempt in range(MAX_RETRIES + 1):
            prompt = build_prompt(ticket_text, previous_error=last_error)
            raw = await self.call_model(prompt)

            try:
                data = TicketExtraction.model_validate_json(raw)
                logger.info("Extraction succeeded on attempt %d", attempt + 1)
                return ExtractionResult(data=data)
            except (json.JSONDecodeError, ValidationError) as exc:
                last_error = str(exc)
                logger.warning(
                    "Attempt %d failed to parse: %s", attempt + 1, last_error
                )

        return ExtractionResult(
            errors=[f"Extraction failed after {MAX_RETRIES + 1} attempts: {last_error}"]
        )

The detail worth the extra code: BuildPrompt feeds the previous error into the retry prompt. That one addition measurably improves retry success over a blind retry — the model gets something specific to fix, not another roll of the dice.

What each outcome looks like in practice:

ScenarioWhat happensAttempts used
Clean extractionValid JSON, all fields present, schema satisfied1
Markdown-wrapped JSONResponse wrapped in ```json fences — stripped by the parser before deserializing, doesn't even need a retry1
Trailing commaParse fails, error fed back, model self-corrects2
Missing required fieldDeserialization fails on the missing property, retried with the specific field named2–3
Persistent malformed outputAll 3 attempts fail — returns a structured error, not an exception3 (exhausted)

6. Challenge Two: Schema Validation Isn't Business-Rule Validation

This distinction is easy to skip and expensive to skip. A response can perfectly satisfy the JSON schema and still be wrong — Priority: 5 with Sentiment: Positive is schema-valid and almost certainly a misread; an SlaDeadline of yesterday is schema-valid and useless. Schema validation only checks shape — type, required-ness, enum membership, numeric bounds — it has no concept of whether the combination makes sense. Keep the two as separate passes: schema failures are rare (the model is constrained to it at generation time) and usually mean "retry." Business-rule failures are domain-specific and usually mean "surface this — retrying won't help."

BusinessRules.cs

public class TicketExtractionValidator : AbstractValidator<TicketExtraction>
{
    public TicketExtractionValidator()
    {
        RuleFor(t => t.Priority).InclusiveBetween(1, 5);

        RuleFor(t => t.SlaDeadline)
            .Must(d => d is null || d >= DateOnly.FromDateTime(DateTime.UtcNow))
            .WithMessage("SLA deadline cannot be in the past");

        // Cross-field rule: schema validation can't see this, only business logic can
        RuleFor(t => t)
            .Must(t => !(t.Priority >= 4 && t.Sentiment == Sentiment.Positive))
            .WithMessage("High priority with positive sentiment is inconsistent — flag for review")
            .WithSeverity(Severity.Warning);
    }
}

from datetime import date
from pydantic import model_validator

class TicketExtraction(BaseModel):
    summary: str
    category: TicketCategory
    priority: int = Field(ge=1, le=5)
    sentiment: Sentiment
    sla_deadline: date | None = None

    @model_validator(mode="after")
    def check_business_rules(self) -> "TicketExtraction":
        if self.sla_deadline and self.sla_deadline < date.today():
            raise ValueError("SLA deadline cannot be in the past")

        # Cross-field rule: schema validation can't see this, only business logic can
        if self.priority >= 4 and self.sentiment == Sentiment.POSITIVE:
            # Soft warning, not a hard failure — route for human review instead
            self._needs_review = True

        return self

Notice the third rule is a warning, not a hard failure — some violations should route to human review rather than bounce back to the model, since the "violation" might just be an unusual ticket. Treating every failure as equally severe floods the review queue or silently drops cases that needed a human.

7. What This Actually Costs

Token costs are small per request and easy to ignore until volume makes them not small. Using GPT-6 Luna pricing at the time of writing — Azure's current cheapest-tier model, Global Standard pay-as-you-go list price (check current Azure OpenAI pricing before building a budget around this; it moves) — roughly $0.10 per million input tokens, $0.50 per million output:

ComponentTokensNotes
System prompt + schema description~350Fixed cost per request — schema-heavy prompts aren't free
Ticket text (avg email)~200Varies with input length
Model output (JSON)~90Structured output is compact by nature
Single clean request~640 total≈ $0.00010

The number that matters is the retry multiplier, not the base cost. At ~3% of requests needing one retry and ~0.4% needing two, the effective average cost is roughly 1.04× the clean-request cost — a rounding error. It stays a rounding error only because retries are bounded at 2. An unbounded retry-until-success loop against a persistently malformed response is the difference between a $0.00010 request and one that burns budget until a timeout or circuit breaker stops it — at 10,000 tickets/day, roughly $1.04/day versus an unmetered liability.

The Retry Budget Is a Cost Control, Not Just a Reliability Control

A bounded retry loop reads like a reliability pattern, but it's doing cost-control work too. Every unbounded retry loop I've seen in production started as "just keep trying until it works" and became an incident the day a model deployment started failing on an edge case.

8. Observability

Track three things per request: which attempt succeeded (or that all were exhausted), which validation layer failed, and latency per attempt. Be careful: raw ticket text and raw model output can both contain PII, so logs should capture failure metadata by default, not the content that triggered it.

ExtractionTelemetry.cs

using var activity = ActivitySource.StartActivity("ticket.extract");
activity?.SetTag("extraction.attempt_count", attemptCount);
activity?.SetTag("extraction.outcome", result.Success ? "success" : "exhausted_retries");
activity?.SetTag("extraction.validation_layer_failed",
    result.Success ? "none" : failedLayer); // "schema" | "business_rules" | "parse"
// Deliberately NOT logging ticketText or the raw model response here —
// log them only behind a separate, access-controlled debug flag.

from opentelemetry import trace

tracer = trace.get_tracer("ticket_extraction")

with tracer.start_as_current_span("ticket.extract") as span:
    span.set_attribute("extraction.attempt_count", attempt_count)
    span.set_attribute("extraction.outcome", "success" if result.success else "exhausted_retries")
    span.set_attribute(
        "extraction.validation_layer_failed",
        "none" if result.success else failed_layer,  # "schema" | "business_rules" | "parse"
    )
    # Deliberately NOT logging ticket_text or the raw model response here —
    # log them only behind a separate, access-controlled debug flag.

In practice, extraction.validation_layer_failed is the single most useful triage field — a spike in parse failures usually means a model/prompt regression; a spike in business_rules failures usually means the input distribution shifted.

9. Testing the Extraction Pipeline

This pipeline is testable because everything except the LLM call is deterministic. Mock that one piece, and everything downstream — parsing, validation, business rules, the retry loop's control flow — tests like ordinary code, against fixed inputs and expected outputs.

Five scenarios map directly to the earlier failure modes: a clean response, a missing required field, a rule-violating value, a malformed response that self-corrects on retry, and one that exhausts the retry budget (Section 1's failure list, Section 5's demonstration table).

ExtractionServiceTests.cs

public class ExtractionServiceTests
{
    [Fact]
    public async Task ValidResponse_SucceedsOnFirstAttempt()
    {
        var client = FakeModelClient.AlwaysReturns(ValidTicketJson);
        var service = new ExtractionService(client, NullLogger<ExtractionService>.Instance);

        var result = await service.ExtractAsync("Sample ticket text", default);

        Assert.True(result.Success);
        Assert.Equal(TicketCategory.Billing, result.Data!.Category);
    }

    [Fact]
    public async Task MalformedJson_RetriesThenSucceeds()
    {
        var client = FakeModelClient.Sequence(MalformedJson, ValidTicketJson);
        var service = new ExtractionService(client, NullLogger<ExtractionService>.Instance);

        var result = await service.ExtractAsync("Sample ticket text", default);

        Assert.True(result.Success);
        Assert.Equal(2, client.CallCount); // confirms the retry actually happened
    }

    [Fact]
    public async Task PersistentlyMalformed_ExhaustsRetryBudget()
    {
        var client = FakeModelClient.AlwaysReturns(MalformedJson);
        var service = new ExtractionService(client, NullLogger<ExtractionService>.Instance);

        var result = await service.ExtractAsync("Sample ticket text", default);

        Assert.False(result.Success);
        Assert.Equal(3, client.CallCount); // 1 initial + 2 retries, then stop
    }

    [Fact]
    public void PastSlaDeadline_FailsBusinessRuleValidation()
    {
        var extraction = SampleExtraction with { SlaDeadline = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-1)) };
        var result = new TicketExtractionValidator().Validate(extraction);

        Assert.False(result.IsValid);
        Assert.Contains(result.Errors, e => e.ErrorMessage.Contains("cannot be in the past"));
    }
}

import pytest
from datetime import date, timedelta

@pytest.mark.asyncio
async def test_valid_response_succeeds_on_first_attempt(valid_ticket_json):
    client = FakeModelClient.always_returns(valid_ticket_json)
    service = ExtractionService(client)

    result = await service.extract("Sample ticket text")

    assert result.success
    assert result.data.category == TicketCategory.BILLING

@pytest.mark.asyncio
async def test_malformed_json_retries_then_succeeds(malformed_json, valid_ticket_json):
    client = FakeModelClient.sequence(malformed_json, valid_ticket_json)
    service = ExtractionService(client)

    result = await service.extract("Sample ticket text")

    assert result.success
    assert client.call_count == 2  # confirms the retry actually happened

@pytest.mark.asyncio
async def test_persistently_malformed_exhausts_retry_budget(malformed_json):
    client = FakeModelClient.always_returns(malformed_json)
    service = ExtractionService(client)

    result = await service.extract("Sample ticket text")

    assert not result.success
    assert client.call_count == 3  # 1 initial + 2 retries, then stop

def test_past_sla_deadline_fails_business_rule_validation(sample_extraction_dict):
    sample_extraction_dict["sla_deadline"] = date.today() - timedelta(days=1)

    with pytest.raises(ValidationError, match="cannot be in the past"):
        TicketExtraction(**sample_extraction_dict)

Worth noting: FakeModelClient.Sequence(...) returns a different canned response each call, which lets the retry test assert on client.CallCount — proving the loop actually re-called the model, not just that it eventually returned something valid.

10. Technology Choices

C#/.NET Implementation

Why choose C#: first-party Azure SDK support, a static type system that catches schema drift at compile time, and mature validation tooling (FluentValidation).

  • Native Azure integration — first-party SDKs, Microsoft-maintained
  • Compile-time shape enforcement — records and required properties catch model-mismatch bugs early
  • Production-ready validation — FluentValidation composes cleanly with ASP.NET Core's pipeline

Python Implementation

Why choose Python: Pydantic gives you schema generation, validation, and JSON parsing in one declarative model — less boilerplate for the same guarantees.

  • Pydantic's dual role — the same model defines the JSON schema and validates the response
  • Rapid iteration — changing the contract is a one-file edit
  • Ecosystem — most structured-output examples document Python first

The Bottom Line

Python team? Pydantic in one model. C#/.NET team? Records plus FluentValidation. Same guarantees either way — don't fight your stack.

Azure AI Foundry Agent Service

Azure AI Foundry Agent Service is generally available and changes where some of this logic can live, even for a service this simple.

  • Structured-output enforcement at the platform level
  • Managed state persistence, relevant once this grows multi-step
  • Observability through Azure Monitor

Check Azure AI Foundry Agent Service for current capabilities and pricing.

11. Engineering Trade-offs: When This Pays Off, and When to Skip It

Honest accounting: this adds a typed model, a retry loop, and a second validation layer over a "just call the LLM" version — real code to write and maintain. The payoff is specific: once more than one caller depends on this response's shape staying stable, an unvalidated LLM response becomes someone else's bug report, not yours.

Rough rule of thumb: if the extraction feeds a human reading a summary, skip most of this. If it feeds a database write, a billing calculation, or a routing decision made by other code, build all of it — the cost of a bad response grows the further downstream it travels before anyone notices.

Skip the Full Pattern When...

  • You're prototyping and a person, not code, reads the output directly
  • The task is low-stakes and self-correcting — a one-off script someone re-runs if it looks wrong
  • The provider's native structured-output guarantees already match your risk tolerance, and nothing downstream depends on catching a rare bad response

Building the full pattern for a script three people run twice is over-engineering. It earns its complexity once the output has more than one consumer, or a wrong answer is expensive to discover late.

12. Key Takeaways

  • A schema constrains what the model is likely to produce — it doesn't guarantee what your code can trust. Validate anyway.
  • Bound every retry loop, and feed the specific failure back into the next attempt.
  • Schema validation and business-rule validation are different layers with different failure semantics.
  • Not every validation failure deserves equal severity — some should be hard failures, some should route to human review.
  • Log outcomes and failure layers, not raw request/response content, by default.
  • This is the foundation the rest of the series builds on — document pipelines, RAG extraction, and agent tool results all need the same typed-contract discipline.

Interview Questions

This series is built to leave you with concrete answers to questions an interviewer would actually ask about production AI systems. Here are the ones this article earns you:

  1. Why isn't "ask the model for JSON" sufficient for production? Structured-output modes reduce malformed and off-schema output but don't eliminate it, and schema-valid output can still violate business rules a JSON schema can't express.
  2. What's the difference between schema and business-rule validation? Schema checks shape — types, required fields, enums, numeric bounds — and is partly enforced at generation time. Business-rule validation checks domain correctness and can only run after the data exists.
  3. Why bound the retry loop instead of retrying until success? An unbounded loop against a persistently malformed response has no natural stopping point. Bounding it turns an open-ended failure into a predictable, loggable one.
  4. Why feed the parse error back into the retry prompt? A blind retry gives the model nothing new and often reproduces the same mistake. Including the specific error measurably improves the odds of self-correction.
  5. How do you distinguish "confidently wrong" from "correctly found nothing"? Explicit nullability for fields that can legitimately be absent, kept separate from a validation failure for fields that are required but missing.
  6. What would you log, and deliberately not log? Attempt counts, outcome, and which validation layer failed. Not raw request or response text by default, since both can hold PII.
  7. When would you skip this pattern entirely? When a human can sanity-check the output directly, or the task is low-stakes enough that an occasional bad extraction costs less than preventing it.

Want More Practical AI Tutorials?

I write about building production AI systems with Azure, Python, and C#. Subscribe for practical tutorials delivered twice a month.

Subscribe to Newsletter →

Written by Jaffar Kazi, a software engineer in Sydney building AI-powered applications. Connect on LinkedIn.