Python AI architecture & engineering

AI engineering.
Solved in Python.

Build a RAG pipeline. Troubleshoot retrieval. Set up fine-tuning and distillation. Practice the engineering work that makes AI systems useful.

settledfrontierpatha* × manhattan, live

pick a problem. write the fix.

Engineering scenarios

39 published · Python

39 scenarios

Workflow overview
Retrieval and RAG

Repair a RAG chunker that splits answers across chunks

A support assistant stopped finding multi-step runbook procedures after ingest switched to fixed-size character windows. A worked Python example packs already-parsed blocks into chunks under a budget without cutting a procedure: five inline blocks, one short function over a list of dictionaries, its exact output, a line-by-line walkthrough, and one practice variation.

  • Greedy packing under a prompt budget
  • Records as a list of dictionaries
  • A loop with a guard, a join test, and continue
Workflow overview
Retrieval and RAG

Fuse keyword and vector rankings with reciprocal rank fusion

A support assistant retrieves runbook chunks from a keyword index and a vector index, and taking the vector list first buried exact matches for error codes. A worked Python example fuses two ranked lists with reciprocal rank fusion: two inline lists, a dictionary that accumulates scores, a sort with a key function, its exact output, a trace of every contribution, and one practice variation that weights the lists.

  • Reciprocal rank fusion of two retrievers
  • A dictionary as a score accumulator with get and a default
  • Sorting with a key function and a tuple tie-break
Workflow overview
Evaluation

Compare two prompt versions ticket by ticket, not by accuracy alone

A rewritten classification prompt scored higher on the evaluation set and shipped, then misrouted the outage tickets the old prompt got right. A worked Python example pairs the two prompts item by item: nine inline tickets, zip with strict length checking, a four-way count keyed by tuples, the regressions and gains by id, its exact output, and one practice variation that normalizes answers before comparing.

  • Paired comparison of two model versions
  • zip over parallel lists with strict checking
  • Tuples as dictionary keys for a two-by-two count
Workflow overview
Serving and architecture

Retry a flaky model call with exponential backoff and a cap

An assistant retried a hosted model in a tight loop, hammering a rate-limited endpoint and retrying invalid requests forever. A worked Python example wraps one call in a retry loop with exponential backoff: a scripted fake endpoint, functions passed as values, try and except on retryable errors only, a cap that gives up loudly, its exact output, and one practice variation that adds a total time budget.

  • Exponential backoff with a retry cap
  • Passing functions as arguments (the call and the sleep)
  • try, except on chosen exception types, and raising
Workflow overview
Fine-tuning

Split a fine-tuning set by hashing ids so the split never moves

A weekly fine-tuning job reshuffled its train and validation split each run, so examples drifted between sides and validation scores jumped. A worked Python example assigns each record by hashing its id with SHA-256 into a hundred buckets: six inline transcripts, hashlib and integer conversion, a dictionary of lists, proof that new records never move old ones, a seeded shuffle for comparison, its exact output, and one practice variation that adds a test split.

  • Stable train and validation assignment by content hash
  • hashlib, encode, hexdigest, and int with base sixteen
  • Buckets with the modulo operator and a threshold
Workflow overview
Data pipelines

Validate a JSONL training file line by line and count what you reject

An overnight fine-tuning job crashed on one malformed line of a JSONL export, and after a manual fix it trained on records with empty answers. A worked Python example streams the file with a generator: nine inline lines (eight records and a blank), json.loads inside try and except, checks for missing and empty fields, kept records yielded one at a time, rejections counted by reason with their line numbers, its exact output, and one practice variation that drops duplicate prompts.

  • Streaming validation of JSONL records
  • json.loads and JSONDecodeError
  • A generator function with yield
Workflow overview
Fine-tuning

Calibrate model confidence with a hand-written training loop

An assistant escalates to a human below a confidence of 0.6, but its 0.9 answers were right only seven times in ten. A worked Python example fits a two-parameter calibration to eight scored answers with the loop PyTorch runs for you, forward, loss, gradient, update, written in plain Python: math.exp and the sigmoid, a function that returns two gradients, an epoch loop with running totals, its exact output, a trace of the weights, and one practice variation that stops early when the loss stops improving.

  • A training loop by hand: forward, loss, gradient, update
  • math.exp and the sigmoid
  • Functions that return several values as a tuple
Workflow overview
Fine-tuning

Shape a learning-rate schedule: linear warmup, then cosine decay

A fine-tune diverged in its first twenty steps because training began at the full learning rate. A worked Python example computes the rate for every step of a warmup-then-cosine schedule and prints the table a trainer would follow: a piecewise function with early returns, math.cos and math.pi, a loop over range, a list of step and rate pairs, its exact output, a trace of the phases, and one practice variation that holds the peak for a while before the decay.

  • Learning-rate warmup and cosine decay as code
  • A piecewise function with early returns
  • math.cos, math.pi, and a formula turned into Python
Workflow overview
Distillation

Build distillation targets from a teacher with temperature softmax

A small router model trained on hard labels alone stalled, while the large assistant it replaces knows which wrong answers are nearly right. A worked Python example turns the teacher logits into soft targets with a temperature and scores a student against them: three inline examples with four classes, a softmax with the max trick, cross-entropy against a distribution, lists of lists, its exact output, a trace of every probability, and one practice variation that blends the soft loss with the hard-label loss.

  • Temperature softmax and soft targets
  • Lists of lists as small matrices
  • Numerical stability: subtract the max before exp
Workflow overview
Evaluation

Decide whether a benchmark gain is real with a bootstrap interval

A new model scored four points higher than the old one on a twenty-five item benchmark, and the team wanted to ship on that. A worked Python example resamples the paired per-item results with a seeded random generator and reports a confidence interval for the difference: two inline result lists, random.Random, a resampling loop, sorting and percentile positions, its exact output, a trace of the resamples, and one practice variation that reports the probability that the new model is better.

  • Paired bootstrap for a benchmark difference
  • random.Random with a seed and randrange
  • Resampling with replacement in a loop
Workflow overview
Data pipelines

Deduplicate a training set with normalized keys and a set

A fine-tuning set carried the same question dozens of times with different spacing and casing, and three evaluation questions verbatim. A worked Python example normalizes each prompt into a key and keeps the first record per key: eight inline records, string methods, a set of seen keys, a dictionary from key to the kept id, its exact output, a trace of every decision, and one practice variation that also drops records that overlap the evaluation set.

  • Deduplication by a normalized key
  • String normalization with lower, split, join, and isalnum
  • Sets: add, membership, intersection
Workflow overview
Retrieval and RAG

Rank chunks by cosine similarity and keep the top k

Orbit's assistant ranked runbook chunks by the raw dot product of each chunk's embedding with the question, so long chunks with large vectors won every time and a billing overview outranked the one paragraph about key rotation. A worked Python example scores five inline chunks against a query vector with cosine similarity written by hand: a dot product and a norm as loops over zip, math.sqrt, a sort with a key function and a tie-break, the top three cut with a slice, its exact output, a trace of every score, and one practice variation that drops chunks below a minimum similarity.

  • Cosine similarity from a dot product and two norms
  • Loops over zip with running totals and strict length checking
  • math.sqrt and a zero-vector guard
Workflow overview
Evaluation

Score short answers with exact match and token F1

Orbit's question answering evaluation compared answers as strings, so "The read scope." counted as wrong against the gold answer "read scope" and a mostly right answer earned nothing. A worked Python example scores five inline answer pairs the way the SQuAD benchmark does: a normalizer that lowercases, strips punctuation, and drops articles, exact match on the normalized tokens, token overlap counted with Counter intersection, precision, recall, and F1 with their zero guards, its exact output, a trace of every overlap, and one practice variation that scores against several acceptable gold answers and keeps the best.

  • Exact match after normalization
  • Token F1 from precision and recall
  • Counter intersection as a multiset overlap
Workflow overview
Serving and architecture

Smooth request bursts to a model endpoint with a token bucket

Orbit's gateway forwarded every request to the hosted model the instant it arrived, so a burst of twenty tripped the provider's rate limit, all twenty failed, and the retries made it worse. A worked Python example admits or rejects eight scripted requests with a token bucket: state variables carried across loop iterations, a refill computed from the elapsed time and capped with min, one token per admitted request, out-of-order timestamps rejected, its exact output, a trace of the bucket level at every arrival, and one practice variation that keeps a separate bucket per tenant in a dictionary.

  • A token bucket: capacity, refill rate, one token per request
  • State variables updated across loop iterations
  • min to cap a value and float arithmetic with elapsed time
Workflow overview
Retrieval and RAG

Build an inverted index and answer AND queries with set intersection

Orbit's keyword retriever scanned every runbook for every query, so each question cost a pass over the whole collection. A worked Python example builds an inverted index from five inline documents and answers queries with set intersection: a tokenizer that lowercases and strips punctuation, a dictionary from each term to the documents that contain it, set() to collapse repeated terms within a document, AND queries as intersections, its exact output, a trace of the postings, and one practice variation that answers OR queries ranked by how many terms matched.

  • A dictionary of lists as an inverted index
  • Tokenizing with lower, a character filter, and split
  • set() to deduplicate terms within a document
Workflow overview
Data pipelines

Re-ingest only what changed by hashing each document's content

Orbit re-embedded its whole knowledge base every night, hours of compute and provider spend, although most documents never change. A worked Python example compares a previous run's manifest of content hashes with the current documents and plans the work: hashlib SHA-256 of the text, a dictionary built in a loop, membership tests against the previous manifest, set difference for deletions, sorted ids for a stable report, its exact output, a trace of every classification, and one practice variation that recognizes a moved document by its unchanged hash.

  • SHA-256 content hashes with hashlib, encode, and hexdigest
  • A manifest as a dictionary from id to hash
  • Classifying records by dictionary membership and value comparison
Workflow overview
Fine-tuning

Batch training examples with a seeded shuffle and a generator

Orbit's fine-tuning script fed examples in file order, so every early batch held a single label, and the ragged last batch crashed a shape check. A worked Python example yields batches from a seeded shuffle with a generator: a copy of the list so the input is never reordered, random.Random with a seed and shuffle, range with a step and list slicing, yield instead of return, a different seed per epoch that is still reproducible, its exact output, a trace of every batch, and one practice variation that drops the ragged last batch.

  • A generator function with yield
  • random.Random(seed).shuffle on a copy
  • range with a step and list slicing into batches
Workflow overview
Evaluation

Measure a retriever with precision at k, recall at k, and MRR

Orbit swapped its embedding model because the new results felt better, with no number to show for it. A worked Python example scores four inline queries, each with the old ranking, the new ranking, and the set of relevant chunk ids: precision and recall at three from a slice and set membership, reciprocal rank from enumerate with an early return, means across queries, its exact output, a trace of every hit, and one practice variation that adds nDCG at three with math.log2.

  • Precision and recall at k from a slice and set membership
  • Reciprocal rank with enumerate(start=1) and an early return
  • Averaging per-query metrics
Workflow overview
Serving and architecture

Cache model responses by prompt with a small least-recently-used cache

Orbit's assistant answered the same ten questions all day and paid for a model call every time. A worked Python example caches responses by normalized prompt in a plain dictionary with least-recently-used eviction: dictionaries remember insertion order, deleting and reinserting a key moves it to the end, the first key is the oldest, a capacity of three, a scripted fake model that counts its calls, its exact output, a trace of every hit, miss, and eviction, and one practice variation that expires entries after a time to live.

  • Insertion-ordered dictionaries as an LRU cache
  • del and reinsert to mark a key as recently used
  • next(iter(cache)) for the oldest key
Workflow overview
Distillation

Find where a student disagrees with its teacher using KL divergence

Orbit distilled a small router from its assistant, and the student agreed with the teacher's top choice on every checked example, yet some routes behaved badly in production. A worked Python example computes the KL divergence from the teacher to the student for four inline examples over three routes: a loop over zip accumulating p times the log of p over q, a guard that clips a zero student probability, a check that each distribution sums to one, the examples ranked worst first, its exact output, a trace of every term, and one practice variation that computes the symmetric Jensen-Shannon divergence instead.

  • KL divergence as a sum over classes with math.log
  • Validating a probability distribution with abs and a tolerance
  • Clipping a zero probability with max
Workflow overview
Data pipelines

Convert a CSV support export into JSONL training examples with the csv module

Orbit's support export is a CSV whose agent replies contain commas and line breaks, and a hand-written split on commas shredded two of every five rows. A worked Python example turns five inline CSV rows into JSONL examples: csv.DictReader over io.StringIO, quoted fields with commas and newlines handled by the module, a status filter and an empty-reply filter counted by reason, json.dumps per line, a missing column rejected by name, its exact output, a trace of every row, and one practice variation that drops examples over a character budget.

  • csv.DictReader over io.StringIO
  • Quoted fields with embedded commas and newlines
  • Filtering rows and counting skips by reason
Workflow overview
Fine-tuning

Clip gradients by their global norm before the update

Orbit's fine-tune hit NaN at step three hundred after one bad batch produced enormous gradients. A worked Python example clips gradients by their global norm, the operation a framework's clip-grad-norm performs: three parameter groups as nested lists, a sum of squares over every element with nested loops and math.sqrt, one scale factor from min, new lists built without mutating the input, the update applied with the clipped gradients, its exact output, a trace of the norms, and one practice variation that clips each group separately.

  • Global norm over nested lists with nested loops and math.sqrt
  • One scale factor with min
  • Building new lists instead of mutating inputs
Workflow overview
Evaluation

Estimate pass at k for a code model from n samples per problem

Orbit sampled five solutions per problem, reported the share of problems where any sample passed as the model's score, and had no honest pass at one. A worked Python example computes the unbiased pass at k estimator for six inline problems: math.comb, the identity one minus C(n minus c, k) over C(n, k), an early return when every subset must contain a passing sample, a table for k of one, three, and five, means, its exact output, a trace of the ten subsets for one problem, and one practice variation that estimates the chance that all k samples pass.

  • math.comb and the unbiased pass at k estimator
  • A guard clause with an early return
  • Building a table over several k values
Workflow overview
Retrieval and RAG

Diversify retrieved chunks with maximal marginal relevance

Orbit's top three for "rotate key" came back as three near-copies of one paragraph from different runbook versions, so the answer never saw the revocation step. A worked Python example reranks six inline candidates with maximal marginal relevance: a relevance list and a similarity matrix as lists of lists, a greedy while loop that scores every remaining candidate as lambda times relevance minus one minus lambda times its highest similarity to anything already picked, a best-so-far variable, list.remove, its exact output, a trace of every pick, and one practice variation that caps picks per source.

  • Greedy selection with a while loop and a best-so-far variable
  • A similarity matrix as a list of lists
  • The MMR score and the lambda tradeoff
Workflow overview
Serving and architecture

Extract and validate the JSON object inside a model's reply

Orbit asked the model for JSON and got prose, code fences, trailing commentary, and sometimes a truncated object; one unparseable reply crashed the whole service. A worked Python example finds the first balanced object in six inline replies and validates it: a character walk with a depth counter that ignores braces inside strings, a slice for the span, json.loads inside try and except JSONDecodeError, required keys and types checked with in and isinstance, a reason returned for every rejection, its exact output, a trace of every reply, and one practice variation that repairs a trailing comma before parsing.

  • A character walk with a depth counter and a string flag
  • Slicing the balanced span
  • json.loads with try and except JSONDecodeError
Workflow overview
Distillation

Store only a teacher's top-k probabilities and renormalize

Orbit's teacher model has a vocabulary of thirty two thousand tokens, and storing its full distribution for every training position would take terabytes. A worked Python example keeps the top three probabilities per position and renormalizes: enumerate to pair each index with its probability, a sort key of negative probability then index, a slice, a renormalizing division, the dropped mass measured, its exact output, a trace of three positions, and one practice variation that keeps the smallest set reaching ninety percent of the mass instead.

  • enumerate to carry indices through a sort
  • A tuple sort key for descending value with an index tie-break
  • Slicing the top k
Workflow overview
Retrieval and RAG

Flag answer sentences that no retrieved chunk supports

Orbit's assistant cited runbook chunks and still invented a step, restart the gateway, that appeared in none of them, and the citation check passed because every sentence carried a bracket. A worked Python example splits a four-sentence inline answer and finds, for each sentence, the retrieved chunk with the largest share of its content words: a sentence splitter written as a character loop, word sets with a small stopword list, set intersection divided by the sentence's own size, a best-so-far search over three chunks, a threshold that flags the unsupported sentence, its exact output, a trace of every score, and one practice variation that also requires the best chunk to be the one the sentence cites.

  • Splitting sentences with a character loop and a buffer
  • Word sets with a stopword filter
  • Overlap as intersection over the sentence's size
Workflow overview
Data pipelines

Balance a skewed label set by capping each class with a seeded sample

Orbit's intent training set was seven tenths billing, and the fine-tuned classifier answered billing to everything. A worked Python example caps every label at three records with a seeded sample: Counter for the label counts, a dictionary of lists grouped by label, random.Random with a seed and sample for the classes over the cap, smaller classes kept whole, the kept records restored to input order with a position dictionary, its exact output, a trace of every decision, and one practice variation that lifts small classes to a floor by repeating records.

  • Counter for class counts
  • Grouping records into a dictionary of lists
  • random.Random(seed).sample for a class over the cap
Workflow overview
Fine-tuning

Turn chat transcripts into supervised fine-tuning examples

Orbit exports support chats as flat rows of conversation id, turn index, role, and text, while fine-tuning wants one example per assistant turn with the preceding turns as context. A worked Python example groups nine inline rows into two conversations, walks each in turn order, and emits an example at every non-empty assistant turn with at most the last four turns as context: a dictionary of lists, sorting by a key, slicing with max for the window, nested dictionaries for messages, a skipped counter, a duplicate turn index rejected, its exact output, a trace of every window, and one practice variation that prepends a system message and skips targets shorter than three words.

  • Grouping rows into a dictionary of lists
  • Sorting turns with a key function
  • A sliding window with max and slicing
Workflow overview
Serving and architecture

Stop hammering a failing model provider with a circuit breaker

When Orbit's hosted model provider degraded, every request to the gateway waited out the full timeout and failed, and the retries kept the provider saturated. A worked Python example protects the calls with a three-state circuit breaker: ten scripted calls inline, a state kept in a string variable, a failure counter that opens the breaker at a threshold, a cooldown measured from the moment it opened, a half-open trial call that closes it or opens it again, calls skipped with continue while it is open, its exact output, a trace of the state at every call, and one practice variation that requires two trial successes before closing.

  • A three-state circuit breaker over scripted calls
  • A state machine as a string variable and an if, elif chain
  • A failure counter that resets and a timestamp for the cooldown
Workflow overview
Serving and architecture

Batch single requests to a model by size or deadline, whichever comes first

Orbit's embedding service called the model once per request, so every call paid the fixed overhead and the busy hours fell behind. A worked Python example collects nine scripted arrivals into batches with a dynamic batcher: a pending list that fills, a flush when the list reaches the size cap, a flush at the deadline of the oldest pending request checked lazily at each arrival, a final flush after the loop, one small helper function called from three places, its exact output with every wait, a trace of the pending list, and one practice variation that adds a token budget per batch and rejects an oversized request loudly.

  • Dynamic batching with a size cap and a wait deadline
  • A pending list that fills and is flushed
  • A small helper function called from several places
Workflow overview
Evaluation

Report p50, p95, and p99 latency with the nearest-rank method, not the mean

Orbit's new gateway deployment reported a lower mean time to first token, and the complaints about slow answers grew: the mean hid a longer tail. A worked Python example computes p50, p95, and p99 for two deployments of twenty inline latency samples each with the nearest-rank method: a sorted copy, a rank from math.ceil, zero-based index arithmetic, a function that returns a dictionary, a loop over a dictionary of deployments, an empty list and an out-of-range percentile rejected, its exact output, a trace of every rank, and one practice variation that interpolates linearly between ranks.

  • Percentiles by nearest rank from a sorted list
  • sorted, math.ceil, and zero-based index arithmetic
  • A function that returns a dictionary of results
Workflow overview
Evaluation

Measure judge agreement beyond chance with Cohen's kappa

Orbit replaced human review of assistant answers with a model judge that grades each one pass or fail, and the report said the judge agrees with the reviewer on 80 percent of answers. Seven answers in ten pass anyway, so two graders who pass most answers agree often by luck. A worked Python example computes Cohen's kappa, the agreement beyond chance, for ten inline graded answers: pair counts in a dictionary keyed by tuples, marginal totals summed from the pairs, observed and chance agreement, the kappa formula with its undefined case rejected, an if, elif chain that names the band, a judge that passes everything scoring 70 percent agreement and a kappa of zero, its exact output, a trace of every pair, and one practice variation that collapses a third label with a mapping before comparing.

  • Cohen's kappa: observed minus chance agreement, rescaled
  • Pair counts in a dictionary keyed by tuples
  • Marginal totals summed from pair counts
Workflow overview
Retrieval and RAG

Chunk a flat document into sliding word windows with overlap

Orbit's older runbooks are flat paragraphs with no headings, so ingest fell back to fixed windows of twelve words with no overlap, and the recovery instruction was cut in two at a window boundary. A worked Python example slides a twelve-word window forward eight words at a time over one inline paragraph of thirty-nine words, so every chunk shares its first four words with the one before: range with a step, a window end capped with min, slicing and join, a break after the window that reaches the end, the guarantee that an overlap of four keeps every span of up to five words whole, the storage cost measured, its exact output, a trace of every window, and one practice variation that expands a retrieval hit to its neighbouring chunks.

  • Sliding windows with range and a step
  • Capping a slice end with min and reading end-exclusive positions
  • Breaking out of a loop once the end is reached
Workflow overview
Data pipelines

Find near-duplicate training records with word shingles and Jaccard similarity

Orbit's fine-tuning set had been deduplicated by exact normalized text, and the model still memorized an answer that appeared three times with one word changed or added. A worked Python example compares five inline records by their word shingles, every run of three consecutive words as a tuple in a set, scores each pair with Jaccard similarity, shared shingles over the union, and walks the records keeping the first of each near-duplicate group: nested loops that build normalized words, range with an arithmetic bound, set intersection and union, a best-so-far search over the kept records, its exact output, a trace of every pair and decision, and one practice variation that slides character windows instead of word windows.

  • Word shingles as tuples in a set
  • Jaccard similarity with & and |
  • A best-so-far search over the records kept so far
Workflow overview
Fine-tuning

Build fine-tuning labels that ignore the prompt tokens

Orbit fine-tuned its assistant on support chats, the loss fell, and the model learned to repeat the customer's question before answering, because the trainer computed the loss on every token. A worked Python example builds the labels a causal language model trainer expects for three inline examples: a stand-in tokenizer as a growing dictionary, list concatenation and repetition that put minus one hundred over every prompt position and the completion ids and end-of-sequence token over the rest, a batch padded to its longest row with an attention mask, the trained count of twenty of thirty-three tokens, its exact output, a trace of every row, and one practice variation that fits rows into a maximum length by dropping prompt tokens from the left.

  • Labels aligned with ids: -100 where the loss must skip
  • A vocabulary as a growing dictionary
  • List concatenation and repetition
Workflow overview
Distillation

Spend the teacher's label budget where the student is least sure

Orbit distills a small router from its large assistant, and every teacher label costs a call; the script that shipped sent the first three prompts in arrival order, one of them a prompt the student already routes with ninety-two percent confidence. A worked Python example ranks eight inline prompts by the student's margin, the gap between its top two route probabilities: sorted over zipped pairs with reverse, a function that returns three values, a key function with a tuple that breaks ties by id, a slice for the budget, guards with a floating-point tolerance, its exact output, a trace of the ranking, and one practice variation that ranks by entropy instead.

  • Uncertainty sampling by the top-two margin
  • sorted over zipped pairs with reverse
  • A key function returning a tuple for a deterministic tie-break
Workflow overview
Distillation

Keep a teacher label only when the teacher's samples agree

Orbit samples its large assistant five times per prompt to build the distillation set for a small router, and the script that shipped took the first sample as the label, so prompts the teacher never settled, and minority answers, went in as labels. A worked Python example normalizes the sampled answers, counts them with a Counter, reads the most common answer and its share, drops ties and weak majorities, and keeps the rest with the majority answer as the label: five inline prompts, most_common and tuple unpacking, an agreement compared with a threshold, its exact output, a trace of every tally, what the first-sample labels got wrong, and one practice variation that grades kept prompts gold or silver.

  • Self-consistency filtering by majority vote
  • collections.Counter and most_common
  • Normalizing answers before counting
Workflow overview
Serving and architecture

Assemble a streamed model reply from network chunks with a line buffer

Orbit's gateway streamed the model's reply to the browser and parsed each network chunk as one complete event; a chunk can carry two events or half of one, so the parser crashed and the reply died at a random word. A worked Python example reads six inline chunks through a line buffer: the chunk appended to a string, a while loop that splits off every complete line at the first line break and keeps the rest, comment and blank lines skipped with continue, json.loads inside try and except, an end marker that stops reading, a stream that is independent of where the network cut it, its exact output, a trace of the buffer at every chunk, and one practice variation that captures the usage event.

  • A line buffer: append, split at the first line break, keep the rest
  • while with a substring membership test and split with a maximum of one
  • startswith, removeprefix, and continue for lines to skip
Practicing for an interview? Read, build, test, explain.

Work with the supplied Python files, validate the result, and explain your decisions before revealing the reference solution.

  1. 01

    Understand the system

    Read the brief, trace the data, and identify the constraints.

  2. 02

    Work in Python

    Build or repair the implementation using the supplied files.

  3. 03

    Prove the result

    Run tests, inspect failures, and check the quality of the output.

  4. 04

    Explain the choices

    Compare alternatives and defend the engineering tradeoffs.