1. Project Goal
Build a provider-neutral application that turns a bounded user request into a validated structured result. The model may be probabilistic; parsing, schema checks, policy, retries and release decisions remain deterministic application responsibilities.
2. What You Will Build
3. Skills / Prerequisites
Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.
4. Dataset or Inputs
The example accepts a short product-change description and returns a Draft object with title, summary and risk. The provider boundary accepts a prompt string and returns raw text. This narrow interface lets the learner run the mock for free and later replace only one function.
Understand every project input
5. Architecture / Workflow
Validate and normalize the user's bounded input.
Build a prompt that states the task, output schema and constraints.
Call a provider adapter with timeout and request metadata.
Parse, validate and apply safety/business policy before returning a typed result.
Project figure
A provider-neutral GenAI application keeps control outside the model
Which layers remain deterministic around probabilistic generation?
6. Environment / Dependencies
- Python 3.10+ for the free mock
- Standard-library json and dataclasses
- Optional provider SDK only for the labelled extension
- GENAI_API_KEY environment variable for a real provider—never source code
7. Data or Input Understanding
A language model returns a sequence of tokens. Even when asked for JSON, it can omit a field, use the wrong type or wrap JSON in prose. Treat the response exactly like untrusted external input.
Structured output reduces ambiguity but does not guarantee factuality or safety. Schema validation answers 'is the shape acceptable?'; domain validation asks 'are the values permitted and meaningful?'
8. Baseline / Simplest Working Approach
Begin with the mock provider and one happy-path example. It tests the application contract without cost, network failure or vendor differences.
Then deliberately return malformed JSON, a missing field and a disallowed risk value. A baseline is complete only when each failure produces a controlled outcome.
Project figure
Structured output is accepted only after deterministic checks
What happens between raw model text and trusted application data?
Worked Example: Trace one response through validation
Given: The provider returns {"title":"Release note","summary":"Adds CSV export","risk":"low"}.
- 1json.loads parses the text into three key-value pairs.
- 2The schema requires title, summary and risk, and all three values are strings, so the shape passes.
- 3The business rule allows risk only in {low, medium, high}; 'low' passes.
- 4The safety check finds no prohibited content, so the object is released and logged as valid.
Interpretation: The result is trusted because deterministic checks passed, not because the model formatted it confidently.
9. Step-by-Step Implementation
Step 1: Run the provider-free vertical slice
mock_provider is deterministic and free. validate turns raw text into a typed Draft or raises a controlled error.
import json
from dataclasses import dataclass
@dataclass
class Draft:
title: str
summary: str
risk: str
def build_prompt(user_change: str) -> str:
if not isinstance(user_change, str) or not 1 <= len(user_change) <= 500:
raise ValueError("change description must contain 1–500 characters")
return ("Create a release-note JSON object with string fields title, summary, "
"and risk. risk must be low, medium, or high. Change: " + user_change)
def mock_provider(prompt: str) -> str:
"""Free deterministic stand-in for a paid model provider."""
return json.dumps({"title": "Release note", "summary": prompt[:60], "risk": "low"})
def validate(raw: str) -> Draft:
value = json.loads(raw)
required = {"title": str, "summary": str, "risk": str}
for field, expected_type in required.items():
if field not in value or not isinstance(value[field], expected_type):
raise ValueError(f"invalid field: {field}")
if value["risk"] not in {"low", "medium", "high"}:
raise ValueError("risk must be low, medium, or high")
return Draft(**value)
draft = validate(mock_provider(build_prompt("Add CSV export")))
print(draft)Step 2: Add bounded repair and fallback
Retry only once for a repairable parse/schema failure. The second failure returns a safe application-owned fallback rather than looping.
def generate_draft(user_change):
prompt = build_prompt(user_change)
for attempt in range(2):
try:
return {"status": "ok", "draft": validate(mock_provider(prompt))}
except (json.JSONDecodeError, ValueError) as error:
prompt += f"\nRepair the output. Validation error: {error}"
return {"status": "review", "message": "A valid draft could not be produced."}Step 3: Swap in a real provider only at the boundary
A provider SDK and paid account are optional. Keep credentials in the environment and preserve the same raw-text return contract.
# PROVIDER-DEPENDENT CODE: the adapter is the only layer that changes.
import os
def call_provider(prompt: str) -> str:
api_key = os.environ["GENAI_API_KEY"] # never commit this value
response = provider_client.generate(prompt=prompt, api_key=api_key, timeout=15)
return response.text10. Expected Results / Outputs
Read the output as evidence, not decoration
11. Evaluation
Measure schema-valid rate, task correctness against reviewed examples, safety-policy outcomes, retry rate, fallback rate, p50/p95 latency and cost per accepted result.
Separate model quality from system reliability. A beautiful response that fails the schema is an application failure; a valid JSON object with an incorrect summary is a semantic-quality failure.
Project figure
Failures follow a bounded retry, fallback and review path
How does the app recover without retrying forever?
12. Failure Analysis
Failure mode → diagnosis → response
13. Improve the Project
14. Production Considerations
What changes beyond the notebook
15. Summary / Key Takeaways
- A GenAI application surrounds probabilistic generation with deterministic input, validation and policy controls.
- A narrow provider adapter lets a free mock and real APIs share the same application contract.
- Raw model text remains untrusted until JSON parsing, schema checks and business rules pass.
- Retries should target repairable failures, remain bounded and end in a safe fallback or review state.
- Environment variables demonstrate secret injection; API keys must never appear in learner or client-side code.
- Evaluation separates structural validity, semantic quality, safety, latency and cost.
- Production readiness requires versioned prompts and schemas, observability, circuit breaking, canary release and rollback.