Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 5: Prompt Engineering and APIs

Week 05 / Lesson 3

Connecting a local model through a reliable client

Run a model-backed request through a small interface and handle partial or failed responses.

Section 3.1 1 of 7

Overview

Focus

Run a model-backed request through a small interface and handle partial or failed responses.

Your route through the lesson

  • 3.2 A first local model endpoint and deterministic test doubles
  • 3.3 Request parameters and streaming
  • 3.4 Timeouts, retries, rate limits, and request records
  • 3.5 Put it into practice
  • 3.6 Guided comparison
  • 3.7 A response stream interrupted before completion

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 7

A first local model endpoint and deterministic test doubles

Focus

Prepare a small local endpoint and distinguish actual inference from controlled substitutes.

A model endpoint is an interface that accepts a request and returns generated output. The core client uses Ollama on the same computer through loopback address 127.0.0.1, port 11434. Install Ollama from its official distribution, start the application or run ollama serve if no server is running, and download a small model with ollama pull smollm2:135m. The official model listing currently shows a roughly 271-megabyte artifact; actual memory also includes runtime and context storage.

A small processor can run this example, but speed varies. Use one short request, a 512-token configured context, and a 32-token output cap. Stop and report inference uncompleted if hardware, download, or runtime setup is unavailable; the deterministic path remains useful without pretending it ran a model. No hosted-service account is required for these local requests.

A test double is a controlled substitute. The weekly script starts a tiny local web server that returns fixed success and failure responses. This exercises the same client transport while proving nothing about model intelligence. The optional real path calls Ollama's chat endpoint; record which path actually ran and the model identity. Never put real secrets into this introductory request.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. The local fixture server returns READY without loading a model. What ran?
2. Why cap the introductory request at a short context and output?
3. The model download is unavailable but fixtures pass. What should be recorded?

Section 3.3 3 of 7

Request parameters and streaming

Focus

Explain request parameters and assemble streamed output before accepting it.

The client sends JSON with model identity, a messages list, stream=True, and generation options. Temperature influences sampling choices; zero requests a low-variation setting but does not guarantee identical results across every runtime or hardware change. num_predict limits generated tokens, while num_ctx configures context capacity for this local adapter. Preserve parameter values in the request record.

Streaming delivers pieces before the entire answer finishes. The Ollama adapter reads newline-delimited JSON events, appends each message content fragment, and waits for a terminal done event. A network connection ending is not automatically a successful completion. If the terminal reason indicates the length limit, mark the output truncated instead of presenting a partial structured answer as complete.

The standard library urllib.request sends web requests. Request holds the address, encoded JSON body, and headers. urlopen opens the response with a timeout; the with statement closes it when finished. json.dumps creates request text and encode('utf-8') converts it to bytes. These are transport operations, not model training. Ollama streaming documentation describes the event format. The provider-neutral ask function accepts a transport function returning normalized text and completion fields; request_chat is the Ollama-specific wire adapter. A different provider needs a different adapter, while the caller keeps that common result contract.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Chunks contain REA and DY followed by done=True. Assembled content?
2. A response ends without done=True. Appropriate status?
3. Temperature zero guarantees identical output across every software and hardware change. Correct?

Section 3.4 4 of 7

Timeouts, retries, rate limits, and request records

Focus

Bound retries and distinguish transport failure, refusal, and invalid requests.

A reliable client classifies failures rather than retrying every exception. A malformed request normally needs correction. Selected transient statuses such as throttling or temporary unavailability may justify bounded retry with delay. A timeout can leave outcome uncertain, especially for effects; this introductory generation call has no external mutation, but the distinction matters before tool integration.

The fixture allows at most two attempts for statuses 429 and 503 and does not retry unchanged status 400. It tests a provider-adapter refusal flag separately from truncation and interrupted streams. Real providers express refusals differently; ordinary refusal prose is not universally detectable through one magic field. The adapter must map documented provider behavior and preserve uncertain cases rather than invent a universal refusal detector.

Record request identifier, model, parameters, attempts, elapsed duration where measured, completion status, and error category. Do not log secrets or full private payloads by default. The script limits response bytes and uses a socket timeout; that timeout is not a complete end-to-end deadline for an endlessly slow stream. A production client needs a total deadline and cancellation behavior in addition to these starter bounds.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A fixture returns 429 once then succeeds. Under a two-attempt policy?
2. A request receives 400 for invalid input. What should the client do?
3. Does a socket timeout alone bound the total duration of every slowly streaming response?

Section 3.5 5 of 7

Put it into practice

Focus

Run the failure suite and optionally make one actual local-model request.

Download week05.py, save it in an exercise folder, and run python week05.py --lesson 3. This single practice first exercises a temporary loopback web server. It uses standard-library urllib, json, threading, and http.server; no packages or model are needed for those fixtures. It normally finishes within seconds.

The script checks complete assembly, a represented refusal, length truncation, one throttling retry, an invalid request with no retry, and interruption without completion. It then stops the fixture server. To run actual inference after the setup taught above, use python week05.py --lesson 3 --local-model smollm2:135m. The client contacts only the local Ollama endpoint and requests the one-word answer READY.

Expected real output includes actual_local_model, generated text, completion state, attempts, and available token counts. A completed nonempty answer establishes an actual inference request; inspect whether the one-word task was obeyed separately. The model can produce the wrong content despite successful transport. A traceback or truncation is an uncompleted run to diagnose, not a result to relabel as success. The fixture and real paths are deliberately printed separately so their evidence remains reviewable.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Which command requests the optional installed local model?
2. A real model completes but answers several unrelated sentences. What passed?
3. Why stop the temporary fixture server before the optional model request?

Section 3.6 6 of 7

Guided comparison

Focus

Trace the controlled failures and interpret the actual-inference boundary.

The worked success stream returns REA then DY and a terminal stop, producing READY. The throttling endpoint returns 429 on its first attempt and the success stream on the second, so attempts equals two. The invalid endpoint returns 400 once; the client raises instead of repeatedly sending the unchanged request.

Refusal, truncation, and interruption fail for different reasons. The fixture refusal uses an explicit adapter flag. Truncation has a terminal event but length as its reason. Interruption supplies a fragment without the terminal event. Treating all three as successful text would obscure whether the user received an authorized, complete answer.

The optional actual path uses the same assembly function against Ollama and reports actual output. It does not rely on the fixture answer to claim a model run happened. If the local model is absent or returns an error, real inference remains uncompleted even though client failure handling works. The weekly artifact therefore establishes a reliable interface foundation with explicit limits: no universal refusal interpretation, no general model-quality claim, and no complete production deadline implementation. Those limits are engineering facts that guide later extensions.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A terminal event says done_reason=length. Why reject it as complete task output?
2. A test endpoint returns status 400 and the client contacts it only once. What does that verify?
3. Ollama is unavailable but the local failure suite passes. Which statement is accurate?

Section 3.7 7 of 7

A response stream interrupted before completion

Focus

Reject an interrupted response even when its prefix looks plausible.

An invoice response stream begins with a syntactically plausible fragment containing invoice_id N4. The connection ends before total_cents and before the terminal completion event. A user interface might already have displayed the prefix, but the application cannot accept it as the completed extraction.

The worked client retains the fragment only as partial diagnostic content and returns incomplete status. It does not fill the missing total from memory or execute a tool based on the prefix. A bounded retry may restart a side-effect-free generation under policy, but the new attempt is recorded separately and must complete and validate on its own. Partial fragments from different attempts must not be concatenated into a fabricated answer.

If a future tool stream has already caused an effect, restarting requires operation reconciliation rather than assuming the interrupted stream means nothing happened. This transfer connects client reliability to action safety. Complete transport, valid structure, grounded values, and authorized effects remain separate required checks. A smooth streaming interface should make partial state visible while preserving the application's refusal to treat unfinished data as accepted evidence.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A stream ends after invoice_id N4 with no total or done event. Accept?
2. A retry produces a different partial fragment. Should fragments from both attempts be joined?
3. An interrupted tool stream may already have caused an effect. What is required before repeating it?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Budgeting a model request →