All lessons in AI Engineering: From Foundation Models to Evaluated Applications

Build a Model-Powered Application

A small application with a validated response contract and request logs.

180 minutes · Free lesson

What you will learn

  • A small application with a validated response contract and request logs.
  • Produce reproducible implementation and assessment evidence for this practice branch.

The first week includes a guided run of the supplied support application. That gives you something concrete to inspect. The assessed build follows the model-interface lessons: you will put a checked boundary around responses and keep slow calls from occupying every execution slot.

This is a required practice branch. Complete its listed knowledge prerequisites before assessment. All example organizations, records, thresholds, and numeric results in this lesson are synthetic teaching material unless you replace them with clearly labeled measurements.

Working model

Parsing JSON and validating its meaning are separate operations. A response can parse successfully while its answer is a boolean or its citation is blank. This lab requires exactly an answer string and a list of nonempty citation strings. An empty citation list is permitted by the transport contract; later grounding checks decide whether that is appropriate for the task. Async code allows waiting calls to overlap, but unlimited overlap can exceed a provider quota or exhaust memory. A semaphore limits active requests. A deadline should cancel the awaited call and release the slot. Do not silently retry a write after timeout: the remote side may already have executed it.

Build and inspect

Work in courses/ai-engineering/support-assistant. Run uv sync --extra dev once, then implement labs/starters/p02.py. Inspect the function signatures and docstrings before changing the bodies. The instructor implementation is in labs/solutions/p02.py; compare it after making your own attempt.

  1. Start the reference application from its README, select demo-alice, and ask one policy question. Record the response contract and which fields are evidence versus interface metadata. The offline response is deterministic, not a live model benchmark.

  1. Implement validate_response and bounded_map in labs/starters/p02.py. Keep the same interfaces as the scaffold. Reject malformed shape and additional fields; preserve input order in the returned outcomes.

  1. Use the public checker to exercise success, malformed JSON, a slow request, and cancellation. Add independent cases for a nested citation, a blank answer, and an empty work list.

  1. Instrument a fake provider with an active-call counter. Run six requests with concurrency two. Demonstrate that the observed peak never exceeds two and returns to zero after timeout.

  1. Use labs/collect.py with --mode live, a bounded request count, and synthetic prompts for actual model evidence. Without a configured provider, complete the fixture work now and record the real-model run as outstanding; it is required before applied course completion. Record provider/model identifiers and repeated trials. Keep API keys in the server environment and out of submitted artifacts.

Run uv run python labs/check.py P02 --implementation starters for the public contract checks. To inspect the supplied reference behavior, use --implementation solutions. Public checks cover selected executable contracts; they do not replace the integration evidence, measurements, or instructor review described below.

Worked example

Worked example

Apply the lab decision rule to a concrete case

  1. Six fixture calls each wait 0.1 seconds. Sequential waiting is approximately 0.6 seconds before overhead.
  2. With a concurrency limit of two, there are three groups of waiting work, so the idealized waiting time is 0.3 seconds. This is a lower-bound illustration, not a measured speed guarantee.
  3. If one call never completes and its deadline is 0.2 seconds, cancellation must release its semaphore slot. A following call can then proceed.
  4. Five valid outcomes and one timeout give a completion rate of 5 / 6, about 83.3%. Reporting only the five returned answers hides the failure.

Check your decisions

Exercise

The API returns an answer string and citations equal to false. Is this valid?

Check your answer

No. JSON parsing succeeds, but the citations field violates the required list type.

Exercise

A timeout handler logs the entire request including Authorization. What should change?

Check your answer

Log metadata such as request ID, outcome, elapsed time, and model identifier. Never log the authorization header or API key; avoid raw prompts unless a separate data policy permits them.

Exercise

Does a cancelled client request prove a remote write did not happen?

Check your answer

No. The remote side may have committed before cancellation. Inspect durable state or replay the same idempotency key through an appropriate write protocol; do not create a new key automatically.

Investigate a slow response without confusing deadlines

HTTPX distinguishes connection, pool, read, and write timeouts. In particular, a read timeout bounds waiting for a chunk, not necessarily the total elapsed request. Treat the application deadline as a separate contract covering admission, attempts, validation, and cleanup.

Extend your local failure report with a transport double that emits small chunks slowly. Use synthetic data and keep it separate from real provider measurements. Compare the failure category, elapsed time, and cleanup behavior with an ordinary connection refusal and a malformed result.

Worked example

Detect a response that never finishes usefully

  1. A synthetic service sends a small chunk every 2 seconds. The client allows 3 seconds between reads.
  2. Each read arrives in time, but after 12 seconds the result is still incomplete. The read timeout alone has not enforced a 5-second product deadline.
  3. Apply a total deadline around the complete operation and verify that partial output is not accepted as a valid decision.
  4. Inspect connection and task cleanup after cancellation. A caller ceasing to wait does not prove that remote work stopped.
  5. Record one attempted task with a deadline failure, including any attempted retry cost. Do not remove it from the success denominator.

Exercise

Pool waiting consumes 4 seconds of a 6-second total budget. Should the application start a fresh 6-second model call afterward?

Check your answer

No. Only 2 seconds remain under the original deadline. Continue only if the remaining bounded work fits the policy, or return a deadline failure. Resetting the clock at every stage defeats the total budget.

Submit the injected behavior, elapsed observations, and resulting error category. Passing the normal-response fixture cannot substitute for this boundary inspection.

Assessment and evidence

Submit the validator, concurrency evidence, timeout/cancellation test, startup command, and explanation of the transport contract. Public checks cover the code boundary; live output quality requires separate evaluation. The guided week-one run is formative and does not substitute for this implementation.

Use 30 minutes for the guided run, 45 for response validation, 45 for concurrency and cancellation, 30 for failure tests, and 30 for explanation and review. These activity budgets include coding, experimentation, and evidence preparation; reading this lesson alone does not complete the estimated workload. Record actual time and unresolved issues so the schedule can be improved.

Keep an evidence folder for this lab with the brief, command/output summary, test cases, decisions, and limitations. Include package or commit identifiers and enough synthetic input to reproduce each claimed result. Exclude credentials, personal records, and local database files from shared submissions.

Sources and further reading

Summary

A small application with a validated response contract and request logs. A passing submission connects the implementation to observable evidence and explains failures and limitations.

Next action

Use the course schedule and prerequisite map to select the next main lesson or practice branch. Carry this lab’s evidence into the capstone; optional extensions do not replace required work.

Choose another lesson