Worked example lessons
Follow a problem from its starting evidence to a completed response. Notice why each step is justified, then try the same reasoning on a different case.
Lesson previews
The nightly updater finishes with a wrong output, and the current logs do not show source identity, row counts, external write results, or failure reasons. OWASP-style event logging: capture when, where, who, what, result, and reason while excluding sensitive data. The common shortcut is printing progress messages that feel useful during development but cannot support an incident later. Before print('started'), print('done'), and an unstructured stack trace in the scheduler output. After Structured run events include run ID, input hash, validation counts, write counts, status, and reason codes. Step 1 Create a run_id and log script version, run mode, and input…
5 minValidate the CSV before transforming itThe campaign upload expects one row per customer with valid country names. The source CSV has inconsistent country values and possible duplicate customer IDs. Data quality gate: completeness, validity, consistency, uniqueness, and freshness are checked before transformation. The shortcut is to fix values silently during transformation. That makes the output uploadable but hides source quality issues. Before Transform first, discover bad country values when the campaign platform rejects the upload. After Validate first, send invalid rows to an exceptions file, and transform only approved records. Step 1 Check required columns: customer_id, email, country, opt_in. Completeness starts with the file shape.…
5 minClean a CSV row in four readable stepsstepper before-after panel marigold trap callout A raw CSV row is a list of strings, but the rest of the script needs a named customer dictionary. Raw row -> named fields -> validated dictionary -> sample check Indexing raw columns everywhere makes the script brittle when the file changes. Name input Start with the raw row and assign named fields like email_text and tier_text. This prevents the code from pretending every value is already clean. Choose shape Use a dict for the cleaned customer because later code needs lookup by field name. The right Python structure makes the next operation…
5 minTurn a traceback into a fixstepper before-after panel marigold trap callout A ValueError occurs when converting quantity text to an integer. Read last line -> inspect value -> trace caller -> fix boundary Changing the crash line without inspecting the value can hide bad input. Name input Read the exception type and message at the bottom. This prevents the code from pretending every value is already clean. Choose shape Print or inspect the exact raw quantity value. The right Python structure makes the next operation obvious. Transform visibly Move validation to the parser where the raw string first appears. Small named steps beat one dense…
5 minWrite a small function you can teststepper before-after panel marigold trap callout The fee rule must be reused in a report and verified with examples. Inputs in -> calculation -> return value -> test case Mixing input prompts with calculation makes the rule hard to test. Name input Name the parameters weight_kg and zone. This prevents the code from pretending every value is already clean. Choose shape Use if/elif branches for the small set of zones. The right Python structure makes the next operation obvious. Transform visibly Return the numeric fee instead of printing it. Small named steps beat one dense expression when the code is…
5 minBlueprint a clinic check-in queuePatients wait 16 minutes, then appointments start late because insurance and symptom forms are incomplete. Map customer action, frontstage action, backstage dependency, and fail point. The novice fix is to add a form earlier without checking whether it is accepted. That can occupy the wait but still leave rework for the clinician. Step 1 Customer action: arrive, confirm identity, update insurance, complete symptom form. This identifies what the patient can do while waiting. Step 2 Frontstage action: greeter checks arrival and explains the next step within 60 seconds. This starts the wait psychologically and reduces fear of being forgotten. Step…
5 minCapacity fix or psychology fix?Chat wait complaints doubled. Average queue wait is 4 minutes, agent utilization is 72 percent, and 35 percent of chats transfer after first response. Diagnose capacity, flow, and perceived wait before choosing the fix. The reflex is to hire another agent. That may help if utilization is the constraint, but here the data points to transfer rework and uncertainty after arrival. Step 1 Actual wait: average 4 minutes, peaks at 9 minutes during lunch. The clock wait is not trivial, but it is not enough by itself to explain doubled complaints. Step 2 Flow constraint: 35 percent transfer after first…
5 minTurn a Policy PDF into a Grounded AnswerAn employee asks, Can I expense meals during a same-day client trip? You have the current travel policy PDF indexed for RAG. Answer only from the retrieved policy section, and keep the exception attached to the rule. A generic model might answer from common business travel norms instead of your actual policy. 1. Retrieve the source Search the current travel policy for same-day trip meal expenses. The retrieval target is specific enough to find the relevant section, not the whole policy. 2. Extract the rule The retrieved section says meals are reimbursable for client travel lasting more than six hours.…
5 minDiagnose a Bad Retrieval ResultA product assistant says audit-log export is available on all paid plans, citing a product FAQ. Diagnose the stage of failure before rewriting prompts. Adding be more accurate does not fix stale sources or poor retrieval. 1. Check the source Open the cited FAQ. It discusses data export generally, not audit-log export by plan. The citation is real but only partially relevant. 2. Check whether a better source exists The current feature matrix contains plan-level audit-log availability. If it is indexed but not retrieved, retrieval needs tuning. 3. Check answer discipline The model generalized from data export to audit-log export.…
5 minDesign a Citation-First PromptYou need a prompt for an assistant that answers customer security questions from approved docs. A citation-first prompt should define source scope, claim support, unsupported behavior, and conflict handling. Asking for sources at the end allows the model to write first and justify later. 1. Define scope Use only the current security whitepaper, subprocessors page, and DPA template. Named sources prevent the assistant from blending in generic knowledge. 2. Define citation granularity For every security control, cite the document title and section or URL. Each important claim gets a checkable handle. 3. Define unsupported behavior If the sources do not…
5 minCalculate Precision and Recall at KA refund-policy RAG query has four relevant source chunks in the label set. The retriever returns five chunks: three relevant chunks and two irrelevant chunks. One relevant exception chunk is missing. Precision@k = relevant retrieved in top k divided by k. Recall@k = relevant retrieved in top k divided by all relevant items. Teams often celebrate that three relevant chunks appeared, while ignoring the two noisy chunks and the missing exception that can change the final answer. List the gold evidence Gold relevant chunks = refund_overview, annual_plan_exception, cancellation_window, regional_rule. Total relevant = 4. Recall needs the denominator from the label…
5 minTurn a Ticket Into an Eval CaseSupport ticket: AI told Acme they could upgrade mid-cycle without proration. The customer is on an annual plan with 7 months left. Eval case = capability claim + required evidence + answer requirements + scoring rule. Copying the messy ticket text into the eval set preserves ambiguity but not a reliable measurement. The case must be self-contained and scoreable. Name the failed capability Capability: answer upgrade eligibility with billing-cycle proration rules. This prevents the case from becoming a one-off Acme story. Identify required evidence Required sources: upgrade_policy_annual, proration_faq, billing_terms_current. A retrieval check can now verify whether the system found the…
5 minScore an Answer for FaithfulnessAnswer: Vendor review takes 5 business days, requires security approval for data processors, and is available to all suppliers. Retrieved context supports the first two claims and says only active contracted suppliers can request review. Faithfulness score = supported answer claims divided by total answer claims. A citation near the topic can make the whole answer feel grounded, but the unsupported eligibility claim still makes the response unfaithful. Split the answer Claim 1: review takes 5 business days. Claim 2: data processors require security approval. Claim 3: all suppliers can request review. Atomic claims make the review concrete. Check support…
5 minTurn a local variable into real stateA Gallery component declares let index = 0. handleNext runs index = index + 1, but the displayed item never changes. State gives React memory and a render trigger Changing a local variable inside an event handler does not persist across renders and does not ask React to render again. Locate the changing value The selected gallery item is controlled by index. A value that changes after a user click and affects rendering needs component memory. Replace the local variable Use const [index, setIndex] = useState(0) at the top level of the component. useState returns the current value and a…
5 minExtract a reducer when handlers multiplyA TaskApp component keeps tasks in state and has separate handlers for add, edit, delete, toggle, and reorder. Dispatch what happened; reduce to the next state in one function When every handler edits the same state shape directly, transition rules scatter and bugs hide in branches. Name user actions added, changed, deleted, reordered Reducer actions should describe what happened, not how to mutate the array. Move update logic Create tasksReducer(tasks, action) with a case for each action type. The reducer receives current state and action, then returns next state. Dispatch from handlers dispatch({ type: 'deleted', id }) Handlers become small…
5 minUpdate nested state without mutationA form stores profile = { name, address: { city, country } }. Updating city mutates profile.address.city and then calls setProfile(profile). Copy the changed path: root object plus changed nested object Mutating a nested object keeps old references alive and can make React consumers miss the change. Identify the path The changed field is profile.address.city. The changed path runs through profile and address. Copy the nested object address: { ...profile.address, city: nextCity } This preserves country and replaces only the changed city. Copy the root object setProfile({ ...profile, address: nextAddress }) The root state value is also new, so React…
5 minDecode a tense update step by stepA PM says the date is still possible while speaking faster than usual, avoiding eye contact, and cutting off questions after the sponsor asks about delay cost. Signal → Context → Granular hypothesis → Accuracy check The common shortcut is to treat confident words as the full truth or to diagnose “panic” from speed alone. Both skip the method. Signal List only observable changes: faster speech, less eye contact, interrupted questions, repeated date assurance. Observation prevents projection. You are collecting data, not naming the emotion yet. Context Anchor the cue to the trigger: sponsor asked about delay cost; launch date…
5 minTurn a vague read into a testable hypothesisThe team leaves a stakeholder meeting saying, “The vibe was off,” but no one can identify what should happen next. Vague impression → Observable cue → Granular hypothesis → Test question The common trap is treating “vibe” as either nonsense or truth. It is usually unprocessed data that needs translation. Capture the impression Write the vague read exactly: “The vibe was off.” Do not shame the impression. It may be your brain noticing a pattern before language has caught up. Find the cue Identify what changed: silence after rollout timing, COO looked at ops lead, fewer questions after pricing. Observable…
5 minConvert a Signal into a QuestionA director says yes to the timeline while leaning back and lowering her voice. Cue -> Trigger -> Risk -> What/How question. The shortcut is asking "Are you really okay with it?" which invites a polite yes and no detail. Cue Leaned back; voice got softer; answer shortened to "yes." Use specific observations, not adjectives like negative or resistant. Trigger The shift happened when the timeline moved from draft to commitment. The trigger tells you where the question should attach. Risk If the cue reflects concern, the risk is timeline feasibility under support load. Decision risk turns body language into…
5 minRead a Room in Three PassesThe room is quiet before a launch decision. The operations lead stopped typing exactly when Friday deployment was named. Three passes: observe the cue, triangulate the channels, ask a calibrated question. The common shortcut is to decide the operations lead is against the launch and either pressure them or avoid them. Pass 1 Observe: stopped typing, shoulders tightened, gaze stayed on the deployment date. This keeps the data behavioral and tied to a moment. Pass 2 Triangulate: words have not changed, but posture and participation shifted at the date. The signal cluster suggests confidence may be lower than the slide…
5 minCalculate NOI before cap rateA duplex is listed at $420,000 with advertised NOI of $31,200 and a 7.4 cap. Naomi wants to verify the operating income before deciding whether the price is reasonable. Income approach: gross income -> effective income -> operating expenses -> NOI -> cap rate The seller used pro forma rent, ignored vacancy, excluded management because they self-manage, and left out ordinary repairs. That makes the cap rate look precise while the income base is overstated. Gross scheduled rent $1,650 per unit x 2 units x 12 months = $39,600 gross scheduled rent. Start with rent that is supported by leases…
5 minFind the repair line that deserves attentionKarim has a 27-item inspection report and only $18,000 of repair capacity. He needs a negotiation request that targets investment risk, not every defect. Pareto first, Five Whys second: prioritize the vital few, then find the root cause. Treating every inspection item equally creates a scattered ask. The seller resists, the investor misses root causes, and the real risk remains unpriced. Group the list Sort 27 findings into water intrusion, electrical, safety, mechanical, cosmetic, and routine maintenance. Inspection order is not investment priority. Grouping creates categories you can price and explain. Find the vital few Water intrusion: $8,500 likely cost.…
5 minScore deals with confidence, not just upsideMei needs to choose one deal to underwrite deeply this month: a verified duplex, a heavy fourplex, or an out-of-state turnkey. RICE for deal priority: Reach x Impact x Confidence / Effort Ranking by projected IRR alone rewards optimistic assumptions and ignores effort, evidence quality, and operator fit. Define Reach Duplex 4, fourplex 5, turnkey 2 based on fit with Mei's goal of local small multifamily cash flow. Reach is not unit count alone. It is how much the opportunity advances the chosen strategy. Score Impact Duplex 3, fourplex 5, turnkey 2 based on return potential and strategic value. The…
5 minPhase I Due Diligence TriageA buyer is under contract for a former dry cleaner site. The Phase I draft notes a historic solvent release next door, no soil vapor data, and a 10-day closing deadline. All Appropriate Inquiries triage: identify the environmental condition, test migration relevance, tie the finding to deal consequences, and choose a risk treatment. The common trap is to dismiss contamination because it began offsite or to demand broad testing without linking the request to liability, lender, use, or contract rights. Name the condition Extract the consultant-s actual finding: historic chlorinated-solvent release next door, possible migration pathway, and no vapor data.…
5 min