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"andstrict=Trueto reject unknown fields, wrong types, or invalid values. - Classified retry and fallback runner: In the primary loop, catch only
OutputValidationErrorandRetryableModelError, add schema-repair instructions only onOutputValidationErrorwhile keeping the original prompt onRetryableModelError, let non-retryable errors propagate immediately, and wrap final fallback failures inWorkflowExecutionErrorwith 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_batchusing nearest-rank P95 in the practice assignment and verify all tests inpytestand 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,
attemptstracks 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 toRetryableModelError), potentially repairable issues (malformed JSON and schema validation failures, mapped toOutputValidationErrorso 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=Trueand the servingmodelname (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
- Set up the
fde-01-2repository and virtual environment: Create the package layout, configure.env.example,.gitignore, andpyproject.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 .envWindows (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 .envWindows (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 - Define the strict output schema and trace record: Use Pydantic v2 with
ConfigDict(extra="forbid", strict=True)onTriageResultso 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) - Implement schema parsing, error classification, retries, fallback handling, and error trace preservation: Map JSON/schema errors to
OutputValidationErrorwith safe field and error-type details (no raw input values), catch onlyOutputValidationErrorandRetryableModelErrorin the primary loop (adding repair feedback only forOutputValidationErrorwhile keeping the original prompt forRetryableModelError), let non-retryable errors propagate immediately, and wrap final fallback failures inWorkflowExecutionErrorwithtraceattached.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 - 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.tracewhen a workflow raisesWorkflowExecutionError.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 resultIn production, ship those structured trace records to a persistent logging or observability backend rather than relying only on local stdout.
- 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
RequestTracetoWorkflowExecutionError(even on unexpected fallback failures) and passexc.traceinto 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
OutputValidationErrorrather thanRetryableModelError. - 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: letxbe the sorted latency list andnbe the number of observations (1-based rankceil(0.95 * n), so 0-based indexceil(0.95 * n) - 1). An empty trace list returns0or0.0for 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
- How do JSON prompting, constrained structured generation, and Pydantic schema validation differ, and why can schema-valid output still be factually wrong?
- How do you prevent a fallback model from silently degrading output structure or cost budgets during an upstream spike?
- What fields should a basic per-request trace record, and how should failed requests preserve and log their trace?
- How should you distinguish retryable, potentially repairable, and non-retryable failures in production, and how does
attemptscount fallback calls here? - 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
WorkflowExecutionErrorcarryingtraceon failure (including unexpected fallback exceptions) and logexc.traceso 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 (OutputValidationErrorwith safe field/type feedback), and auth/config/programming errors as non-retryable; hereattemptscounts 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
TriageResultusesConfigDict(extra="forbid", strict=True)and rejects invalid JSON, missing/extra fields, or bad types/enums.run_with_fallback_and_traceretries onlyRetryableModelErrorandOutputValidationErrorin the primary loop (with schema-repair feedback only onOutputValidationError), falls back cleanly, and raisesWorkflowExecutionErrorwithtracepreserved on any fallback failure.summarize_trace_batchimplemented with nearest-rank P95 and tested across empty and multi-request batches.- All
pytesttests pass locally and in GitHub Actions, and the repository is committed to GitHub.
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.
Test your understanding
- How do JSON prompting, constrained structured generation, and Pydantic schema validation differ, and why can schema-valid output still be factually wrong?
- How do you prevent a fallback model from silently degrading output structure or cost budgets during an upstream spike?
- What fields should a basic per-request trace record, and how should failed requests preserve and log their trace?
- How should you distinguish retryable, potentially repairable, and non-retryable failures in production, and how does
attemptscount fallback calls here? - Why should trace logging avoid dumping raw sensitive payloads or secrets into unredacted logs?
Reveal self-review answers (attempt the questions first)
- 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.
- Protecting structure and cost on fallback: Enforce the same schema on fallback, bound attempts, and log fallback usage, model name, tokens, and latency.
- Core trace fields and failed runs: Record request ID, model, fallback flag, attempt count, status, token counts, and latency; raise
WorkflowExecutionErrorcarryingtraceon failure (including unexpected fallback exceptions) and logexc.traceso failed runs are recorded. - Error classes and attempt counting: Treat transient network/rate-limit errors as retryable (
RetryableModelError, preserving the base prompt), schema/JSON errors as repairable (OutputValidationErrorwith safe field/type feedback), and auth/config/programming errors as non-retryable; hereattemptscounts total calls including the fallback call. - Log hygiene: Redact secrets, tokens, and sensitive customer payloads, logging structured metadata and counts instead.
Questions or notes on this module?