Skip to main content
LearnMLAcademy
Intermediate10 min read

Build a Generative AI Application End-to-End

Develop an interactive Generative AI application with streaming responses, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

A prompt builder with a narrow task contract
A free deterministic mock provider plus a replaceable real-provider adapter
JSON parsing, schema and business-rule validation
Bounded retry, fallback, safety and evaluation records

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

Understand every project input
Input / outputTypeTrust treatment
user_changestringLength-limit and treat as user data, not instructions
system_contractdeveloper textDefines fields, allowed risk values and refusal behavior
raw_provider_textstringUntrusted until parsed and validated
Drafttyped objectAccepted only after schema and policy checks
evaluation_recordexpected vs actualStores validity, safety, latency and cost

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?

User input
bounded request
Prompt builder
instructions + data
Provider adapter
mock or real model
Validator
JSON + schema + policy
Application result
typed and logged
Application code builds the prompt, calls an interchangeable provider adapter, validates the returned schema, applies safety policy and records outcome, latency and cost.

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?

Raw text
probabilistic
Parse JSON
syntax
Check schema
fields + types
Business rules
allowed values
Accept
trusted object
Any failed gate → repair request, fallback, or review
Parsing checks syntax; schema validation checks fields and types; business rules check allowed values. Only validated data crosses into the application.

Worked Example: Trace one response through validation

Given: The provider returns {"title":"Release note","summary":"Adds CSV export","risk":"low"}.

  1. 1json.loads parses the text into three key-value pairs.
  2. 2The schema requires title, summary and risk, and all three values are strings, so the shape passes.
  3. 3The business rule allows risk only in {low, medium, high}; 'low' passes.
  4. 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.

Run the provider-free vertical sliceRUNNABLE CODE
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)
Representative expected output: Expected object: Draft(title='Release note', summary='...', risk='low').

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.

Add bounded repair and fallbackRUNNABLE CODE
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.

Swap in a real provider only at the boundaryPROVIDER-DEPENDENT CODE
# 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.text

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
Test caseExpected statusWhat is measured
Valid requestokSchema valid, safe, latency recorded
Malformed JSON onceok after repairRetry count = 1
Missing field twicereviewNo invalid object released
Unsafe requestrefusedPolicy decision logged without model text

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?

Call provider
attempt 1 of 2
Valid + safe
return structured result
Malformed / transient
classify failure
One bounded retry
repair hint + backoff
Still invalid
safe fallback / human review
Retry only transient or repairable failures, cap attempts, and use a safe fallback or human review when validation or policy still fails.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
JSON parse errorProvider added prose or truncated outputRepair once, then safe fallback
Valid schema, wrong factsNo evidence checkAdd source data and semantic evaluation
Repeated timeoutProvider/network issueBackoff, circuit breaker and alternate adapter
Secret exposureKey in source/logEnvironment secret store and redaction

13. Improve the Project

Add a fixed evaluation set with expected fields and reviewer rubrics.
Use provider-native constrained decoding where available, while retaining validation.
Cache safe repeated requests when privacy and freshness allow.
Compare providers behind the same adapter on quality, latency and cost.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
SecretsManaged secret store; never browser bundle, source or logs
ReliabilityTimeout, bounded retry, idempotency and circuit breaker
ReleaseVersion prompt/schema/model together; canary with rollback
ObservabilityRequest ID, model version, validation result, latency, tokens and cost

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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Build a Generative AI Application End-to-End"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is valid JSON not automatically a safe application result?
Question 2 of 5application/scenario
A response omits the required risk field twice. What should a bounded application do?
Question 3 of 5interpretation
What is the main benefit of a provider adapter?
Question 4 of 5practical selection
Where should a real provider API key be stored?
Question 5 of 5debugging/diagnostic
Schema-valid rate is 99%, but summaries often contain incorrect facts. Which evaluation is missing?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is valid JSON not automatically a safe application result?▼

Correct Answer: Syntax can be valid while values are wrong, disallowed or unsafe

Parsing proves syntax only. Schema, business-rule, semantic and safety checks still have different responsibilities.

2A response omits the required risk field twice. What should a bounded application do?▼

Correct Answer: Return a safe fallback or human-review state

After the allowed repair attempts, the system must stop and return a controlled outcome instead of trusting malformed data.

3What is the main benefit of a provider adapter?▼

Correct Answer: It isolates vendor-specific calls behind a stable application interface

A narrow adapter lets mock and real providers share the same contract while the rest of the application remains provider-neutral.

4Where should a real provider API key be stored?▼

Correct Answer: In an environment or managed secret store

Secrets are injected at runtime and redacted from logs; they must not be exposed in source or browser bundles.

5Schema-valid rate is 99%, but summaries often contain incorrect facts. Which evaluation is missing?▼

Correct Answer: Semantic correctness against reviewed examples or evidence

Structural validity cannot measure whether the content is true or useful. Add semantic and evidence-grounding evaluation.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next