MODULE 01.2 · PUBLISHED · ~1-2h

Structured Outputs, Fallbacks & Basic Tracing

Schema-enforced JSON outputs with Pydantic validation retries, deterministic model fallbacks, and structured per-request latency and token trace logs tested with pytest.

Real AI workflows break when free-form text is passed directly into downstream code or when an upstream LLM call times out, rate-limits, or returns malformed JSON. In production, reliability comes from strict schemas, explicit error classification, bounded retries, clean fallbacks, and per-request tracing.

In this module, you will define a strict Pydantic output schema for triage tickets, classify retryable vs. validation errors, build a runner with targeted repair feedback and fallback support that preserves traces on failure, record per-request latency and token traces, and verify everything with pytest and GitHub Actions.

What You Will Build

  • Strict structured output schema: Define a Pydantic model with extra="forbid" and strict=True to reject unknown fields, wrong types, or invalid values.
  • Classified retry and fallback runner: In the primary loop, catch only OutputValidationError and RetryableModelError, add schema-repair instructions only on OutputValidationError while keeping the original prompt on RetryableModelError, let non-retryable errors propagate immediately, and wrap final fallback failures in WorkflowExecutionError with the trace attached.
  • Per-request trace logger and error consumption: Capture model used, fallback status, total attempt count (including fallback calls), token usage, and latency in milliseconds, and log traces on both success and failure.
  • Batch trace summary assignment + CI: Implement summarize_trace_batch using nearest-rank P95 in the practice assignment and verify all tests in pytest and GitHub Actions.

1. Structured Outputs, Fallbacks, and Basic Tracing

  • Structured generation vs. schema validation: Prompting for JSON asks the model to follow a format, while native constrained structured output can restrict token generation to a supported schema. Pydantic validates the returned data in your application so required keys, types, and extra="forbid" rules are enforced. Even schema-valid output can still contain factually incorrect information, so schema validity is not a substitute for grounding or evaluation.
  • Retries, error classification, and model fallbacks: A retry repeats a call when a transient issue or schema mismatch occurs, whereas a fallback switches to a backup model or provider when primary attempts fail. In this module, attempts tracks total calls made across the run, including the fallback call when used. In production systems, distinguish retryable issues (timeouts, rate limits, transient provider errors, mapped to RetryableModelError), potentially repairable issues (malformed JSON and schema validation failures, mapped to OutputValidationError so field and error-type feedback can guide a retry), and non-retryable errors (authentication failures, invalid configuration, or programming bugs, which should fail fast rather than trigger retries).
  • Preventing silent degradation on fallback: A fallback model may have different latency, token pricing, or instruction-following behavior. Always validate fallback responses against the same schema and tag traces with used_fallback=True and the serving model name (and for deeper production tracing later, record primary and fallback model identifiers separately if needed).
  • Basic per-request tracing: Every LLM call should emit a structured trace record containing a request ID, model identifier, fallback flag, total attempt count, status, input/output token counts, and latency in milliseconds, without leaking secrets or sensitive payloads.

2. Step-by-Step Build Walkthrough

  1. Set up the fde-01-2 repository and virtual environment: Create the package layout, configure .env.example, .gitignore, and pyproject.toml, and install editable dev dependencies.

    macOS / Linux:

    mkdir -p fde-01-2/src/fde_01_2 fde-01-2/tests
    cd fde-01-2
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env

    Windows (PowerShell):

    mkdir fde-01-2
    cd fde-01-2
    py -m venv .venv
    .\.venv\Scripts\Activate.ps1
    py -m pip install --upgrade pip
    py -m pip install -e ".[dev]"
    Copy-Item .env.example .env

    Windows (CMD):

    mkdir fde-01-2
    cd fde-01-2
    py -m venv .venv
    .venv\Scripts\activate.bat
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    copy .env.example .env
  2. Define the strict output schema and trace record: Use Pydantic v2 with ConfigDict(extra="forbid", strict=True) on TriageResult so unexpected fields and type mismatches are rejected.
    from typing import Literal
    from pydantic import BaseModel, ConfigDict, Field
    
    class TriageResult(BaseModel):
        model_config = ConfigDict(
            extra="forbid",
            strict=True,
        )
        category: Literal["billing", "auth", "infra", "general"]
        severity: Literal["low", "medium", "high"]
        summary: str = Field(min_length=1, max_length=240)
        needs_escalation: bool = False
    
    class ModelResponse(BaseModel):
        raw_content: str
        input_tokens: int = Field(ge=0)
        output_tokens: int = Field(ge=0)
    
    class RequestTrace(BaseModel):
        request_id: str = Field(min_length=1)
        model: str = Field(min_length=1)
        used_fallback: bool = False
        attempts: int = Field(ge=1)
        status: Literal["ok", "fallback_ok", "error"]
        input_tokens: int = Field(ge=0)
        output_tokens: int = Field(ge=0)
        latency_ms: float = Field(ge=0.0)
  3. Implement schema parsing, error classification, retries, fallback handling, and error trace preservation: Map JSON/schema errors to OutputValidationError with safe field and error-type details (no raw input values), catch only OutputValidationError and RetryableModelError in the primary loop (adding repair feedback only for OutputValidationError while keeping the original prompt for RetryableModelError), let non-retryable errors propagate immediately, and wrap final fallback failures in WorkflowExecutionError with trace attached.
    import json
    import time
    from typing import Callable
    from pydantic import ValidationError
    
    ModelCallable = Callable[[str, int], ModelResponse]
    
    class RetryableModelError(Exception):
        """Transient provider or network failure."""
    
    class OutputValidationError(Exception):
        """Model output could not be parsed or validated."""
    
    class WorkflowExecutionError(RuntimeError):
        """Raised when primary and fallback attempts fail, carrying the trace."""
    
        def __init__(self, message: str, trace: RequestTrace) -> None:
            super().__init__(message)
            self.trace = trace
    
    def parse_triage_result(raw_content: str) -> TriageResult:
        try:
            payload = json.loads(raw_content)
        except json.JSONDecodeError as exc:
            raise OutputValidationError("Model output was not valid JSON") from exc
    
        try:
            return TriageResult.model_validate(payload)
        except ValidationError as exc:
            issues = [
                f"{'.'.join(str(part) for part in error['loc'])}: {error['type']}"
                for error in exc.errors()
            ]
            raise OutputValidationError(
                "Schema validation failed: " + "; ".join(issues)
            ) from exc
    
    def run_with_fallback_and_trace(
        request_id: str,
        prompt: str,
        primary_model_name: str,
        primary_call: ModelCallable,
        fallback_model_name: str,
        fallback_call: ModelCallable,
        max_primary_attempts: int = 2,
    ) -> tuple[TriageResult, RequestTrace]:
        if max_primary_attempts < 1:
            raise ValueError("max_primary_attempts must be at least 1")
    
        start = time.perf_counter()
        total_input_tokens = 0
        total_output_tokens = 0
        attempts = 0
        active_prompt = prompt
    
        for attempt in range(1, max_primary_attempts + 1):
            attempts = attempt
            try:
                resp = primary_call(active_prompt, attempt)
                total_input_tokens += resp.input_tokens
                total_output_tokens += resp.output_tokens
                parsed = parse_triage_result(resp.raw_content)
                elapsed_ms = (time.perf_counter() - start) * 1000.0
                trace = RequestTrace(
                    request_id=request_id,
                    model=primary_model_name,
                    used_fallback=False,
                    attempts=attempts,
                    status="ok",
                    input_tokens=total_input_tokens,
                    output_tokens=total_output_tokens,
                    latency_ms=elapsed_ms,
                )
                return parsed, trace
            except OutputValidationError as exc:
                active_prompt = (
                    f"{prompt}\n\n"
                    "The previous response failed schema validation. "
                    f"Issues: {exc}. Return valid JSON matching TriageResult."
                )
            except RetryableModelError:
                active_prompt = prompt
    
        try:
            attempts += 1
            fb_resp = fallback_call(active_prompt, attempts)
            total_input_tokens += fb_resp.input_tokens
            total_output_tokens += fb_resp.output_tokens
            parsed = parse_triage_result(fb_resp.raw_content)
            elapsed_ms = (time.perf_counter() - start) * 1000.0
            trace = RequestTrace(
                request_id=request_id,
                model=fallback_model_name,
                used_fallback=True,
                attempts=attempts,
                status="fallback_ok",
                input_tokens=total_input_tokens,
                output_tokens=total_output_tokens,
                latency_ms=elapsed_ms,
            )
            return parsed, trace
        except Exception as fb_exc:
            elapsed_ms = (time.perf_counter() - start) * 1000.0
            error_trace = RequestTrace(
                request_id=request_id,
                model=fallback_model_name,
                used_fallback=True,
                attempts=attempts,
                status="error",
                input_tokens=total_input_tokens,
                output_tokens=total_output_tokens,
                latency_ms=elapsed_ms,
            )
            raise WorkflowExecutionError(
                "Both primary and fallback model calls failed",
                trace=error_trace,
            ) from fb_exc
  4. Format structured trace logs and log both successes and failures: Serialize trace metadata as structured JSON without raw prompts or secret tokens, and log exc.trace when a workflow raises WorkflowExecutionError.
    import json
    import logging
    
    def log_request_trace(logger: logging.Logger, trace: RequestTrace) -> str:
        payload = {
            "request_id": trace.request_id,
            "model": trace.model,
            "used_fallback": trace.used_fallback,
            "attempts": trace.attempts,
            "status": trace.status,
            "input_tokens": trace.input_tokens,
            "output_tokens": trace.output_tokens,
            "latency_ms": round(trace.latency_ms, 2),
        }
        line = json.dumps(payload, sort_keys=True)
        logger.info(line)
        return line
    
    def execute_and_log(
        logger: logging.Logger,
        primary_call: ModelCallable,
        fallback_call: ModelCallable,
    ) -> TriageResult:
        try:
            result, trace = run_with_fallback_and_trace(
                request_id="REQ-001",
                prompt="Classify this ticket",
                primary_model_name="primary",
                primary_call=primary_call,
                fallback_model_name="fallback",
                fallback_call=fallback_call,
            )
        except WorkflowExecutionError as exc:
            log_request_trace(logger, exc.trace)
            raise
        else:
            log_request_trace(logger, trace)
            return result

    In production, ship those structured trace records to a persistent logging or observability backend rather than relying only on local stdout.

  5. Run tests and commit to Git: Verify deterministic unit tests with pytest, add .github/workflows/pytest.yml, and commit to Git.
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 01.2"

3. Common Pitfalls and Operational Hygiene

  • Discarding or failing to log error traces: Always attach the error RequestTrace to WorkflowExecutionError (even on unexpected fallback failures) and pass exc.trace into your trace logger before re-raising.
  • Retrying non-retryable errors or adding schema feedback on transient timeouts: Do not retry auth failures, invalid config, or programming errors in the primary loop, and only append schema-repair instructions on OutputValidationError rather than RetryableModelError.
  • Allowing unexpected extra fields or type coercion surprises: Using ConfigDict(extra="forbid", strict=True) catches schema drift and unexpected keys early.
  • Logging sensitive payloads or secrets: Never log API keys, auth headers, or raw sensitive customer payloads in plain trace logs or validation feedback messages.

4. Practice Assignment

In fde-01-2, implement summarize_trace_batch(traces: list[RequestTrace]) -> dict[str, float | int] in src/fde_01_2/tracing.py returning:

  • total_requests (int)
  • fallback_count (int)
  • total_input_tokens (int)
  • total_output_tokens (int)
  • avg_latency_ms (float)
  • p95_latency_ms (float) using the nearest-rank method: let x be the sorted latency list and n be the number of observations (1-based rank ceil(0.95 * n), so 0-based index ceil(0.95 * n) - 1). An empty trace list returns 0 or 0.0 for every metric.

Add unit tests in tests/test_tracing.py for empty batches, mixed primary/fallback batches, and nearest-rank P95 latency calculation, then run python -m pytest -v and push fde-01-2 (including .github/workflows/pytest.yml) to GitHub.

5. Knowledge Check

  1. How do JSON prompting, constrained structured generation, and Pydantic schema validation differ, and why can schema-valid output still be factually wrong?
  2. How do you prevent a fallback model from silently degrading output structure or cost budgets during an upstream spike?
  3. What fields should a basic per-request trace record, and how should failed requests preserve and log their trace?
  4. How should you distinguish retryable, potentially repairable, and non-retryable failures in production, and how does attempts count fallback calls here?
  5. Why should trace logging avoid dumping raw sensitive payloads or secrets into unredacted logs?
Self-Review Answers
  • 1. Structured generation vs. validation: Prompting requests a format, constrained generation restricts token choices, and Pydantic validates runtime structure and types (including rejecting extra fields); none of them guarantees factual accuracy.
  • 2. Protecting structure and cost on fallback: Enforce the same schema on fallback, bound attempts, and log fallback usage, model name, tokens, and latency.
  • 3. Core trace fields and failed runs: Record request ID, model, fallback flag, attempt count, status, token counts, and latency; raise WorkflowExecutionError carrying trace on failure (including unexpected fallback exceptions) and log exc.trace so failed runs are recorded.
  • 4. Error classes and attempt counting: Treat transient network/rate-limit errors as retryable (RetryableModelError, preserving the base prompt), schema/JSON errors as repairable (OutputValidationError with safe field/type feedback), and auth/config/programming errors as non-retryable; here attempts counts total calls including the fallback call.
  • 5. Log hygiene: Redact secrets, tokens, and sensitive customer payloads, logging structured metadata and counts instead.

6. Completion Criteria

  • TriageResult uses ConfigDict(extra="forbid", strict=True) and rejects invalid JSON, missing/extra fields, or bad types/enums.
  • run_with_fallback_and_trace retries only RetryableModelError and OutputValidationError in the primary loop (with schema-repair feedback only on OutputValidationError), falls back cleanly, and raises WorkflowExecutionError with trace preserved on any fallback failure.
  • summarize_trace_batch implemented with nearest-rank P95 and tested across empty and multi-request batches.
  • All pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

Build this

In fde-01-2, implement summarize_trace_batch(traces: list[RequestTrace]) -> dict[str, float | int] in src/fde_01_2/tracing.py returning total_requests, fallback_count, total_input_tokens, total_output_tokens, avg_latency_ms, and p95_latency_ms using the nearest-rank method (for sorted latencies x of length n, 1-based rank ceil(0.95 * n), i.e., index ceil(0.95 * n) - 1). An empty trace list returns zeros for every metric.

Add unit tests in tests/test_tracing.py covering:

  • An empty trace list returning zeroed summary metrics without errors.
  • A mixed batch of primary and fallback runs with known latencies and token counts.
  • Nearest-rank P95 latency calculation on multi-item batches.

Run python -m pytest -v and push your completed fde-01-2 repository (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. How do JSON prompting, constrained structured generation, and Pydantic schema validation differ, and why can schema-valid output still be factually wrong?
  2. How do you prevent a fallback model from silently degrading output structure or cost budgets during an upstream spike?
  3. What fields should a basic per-request trace record, and how should failed requests preserve and log their trace?
  4. How should you distinguish retryable, potentially repairable, and non-retryable failures in production, and how does attempts count fallback calls here?
  5. Why should trace logging avoid dumping raw sensitive payloads or secrets into unredacted logs?
Reveal self-review answers (attempt the questions first)
  1. Structured generation vs. validation: Prompting requests a format, constrained generation restricts token choices, and Pydantic validates runtime structure and types (including rejecting extra fields); none of them guarantees factual accuracy.
  2. Protecting structure and cost on fallback: Enforce the same schema on fallback, bound attempts, and log fallback usage, model name, tokens, and latency.
  3. Core trace fields and failed runs: Record request ID, model, fallback flag, attempt count, status, token counts, and latency; raise WorkflowExecutionError carrying trace on failure (including unexpected fallback exceptions) and log exc.trace so failed runs are recorded.
  4. Error classes and attempt counting: Treat transient network/rate-limit errors as retryable (RetryableModelError, preserving the base prompt), schema/JSON errors as repairable (OutputValidationError with safe field/type feedback), and auth/config/programming errors as non-retryable; here attempts counts total calls including the fallback call.
  5. Log hygiene: Redact secrets, tokens, and sensitive customer payloads, logging structured metadata and counts instead.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.