Skip to content

Lesson 6 of 40Learning with AI

Trust but Verify

Spot the ways AI output goes wrong, and check generated code with tests, diffs, docs and a second opinion before you rely on it.

15 min read0/5 questions

AI tools write code that looks right. It is formatted well, it has helpful names and comments, and it often works on the first example you try. That polish is exactly the problem: an answer that looks finished invites you to stop checking. This lesson shows the common ways AI output is wrong, a short set of checks that catch most of them, and how to read generated code so that you, not the model, are responsible for what ships.

Why a confident answer can be wrong

A language model produces the most likely continuation of the text so far (the lesson How LLMs Work covers this). "Likely" and "true" usually overlap, but not always. The model has no built-in step where it looks something up and confirms it. When it does not know, it still produces fluent, confident text, because fluent text is what it was trained to produce. This is called hallucination: output that sounds plausible but is not grounded in fact.

So the tone of an answer tells you nothing about its accuracy. A model says "Here is the correct function" with the same confidence whether the function is correct or not. Your job is to supply the checking step the model does not have.

Five ways AI gets code wrong

FailureWhat it looks likeWhy it happens
Hallucinated APIA method, flag or config option that does not existThe name fits the pattern of real names
Outdated versionCode for a library version from two years agoTraining data has a cutoff and mixes versions
Confident nonsenseA clear explanation of something falseFluency is not the same as knowledge
Subtle logic bugWorks on the happy path, fails on edge casesCommon examples dominate training data
Security holeString-built SQL, secrets in code, missing auth checksInsecure code is common in public examples

Hallucinated APIs are the easiest to catch, because the code fails the moment it runs. A model might write json.parse(text) in Python because JavaScript has JSON.parse. Python's function is json.loads.

Predict the outputPython

What does this print?

import json
print(hasattr(json, "parse"))
Need a nudge? Hints walk you through it.

Outdated versions are sneakier. The code may run, but use a deprecated option, an old import path, or a pattern the library now warns against. Frameworks that change quickly (front-end frameworks, cloud SDKs, AI SDKs themselves) are the worst offenders.

Subtle logic bugs are the most dangerous, because the code runs and passes a quick manual try. Off-by-one errors, wrong handling of empty input, time zones, rounding, and integer versus float division are classic examples.

Security holes often look like ordinary code. A query built with an f-string, a file path taken straight from user input, or an API key pasted into the source all work fine in a demo and fail badly in production. The lesson AI Security goes deeper on this.

Run it: a bug that looks fine

Here is a function an assistant might write when you ask for "a median function". Read it first and decide whether you trust it. Then run the tests.

Python
# An AI assistant wrote this. It looks clean, has a docstring,# and works on the first example you try.def median(values): """Return the median of a list of numbers.""" ordered = sorted(values) middle = len(ordered) // 2 return ordered[middle] # A tiny test harness: each case is (input, expected).cases = [ ([3, 1, 2], 2), # odd length ([7], 7), # one item ([4, 1, 3, 2], 2.5), # even length: average the two middle values ([10, 20], 15), # even length again] failures = 0for values, expected in cases: got = median(values) status = "ok " if got == expected else "FAIL" if got != expected: failures += 1 print(f"{status} median({values}) = {got}, expected {expected}") print(f"\n{failures} of {len(cases)} tests failed")
Output
Press Run (⌘ Enter) to see what happens.

The function is right for odd-length lists and wrong for every even-length list. If you had tried it once with [3, 1, 2], you would have shipped it. The tests only caught the bug because someone thought about the even case. That is the real skill: choosing inputs that could break the code.

Here is a fixed version, with the empty-list edge case handled and a cross-check against Python's own statistics.median, which acts as a trusted second opinion.

Python
import randomimport statistics def median(values): """Return the median of a non-empty list of numbers.""" if not values: raise ValueError("median() of an empty list") ordered = sorted(values) middle = len(ordered) // 2 if len(ordered) % 2 == 1: return ordered[middle] return (ordered[middle - 1] + ordered[middle]) / 2 cases = [([3, 1, 2], 2), ([7], 7), ([4, 1, 3, 2], 2.5), ([10, 20], 15)]for values, expected in cases: assert median(values) == expected, (values, median(values))print("all", len(cases), "cases pass") try: median([])except ValueError as err: print("empty list ->", err) # Compare with a trusted implementation on many random inputs.for _ in range(1000): data = [random.randint(-50, 50) for _ in range(random.randint(1, 9))] assert median(data) == statistics.median(data)print("matches statistics.median on 1000 random lists")
Output
Press Run (⌘ Enter) to see what happens.

Comparing against a known-good implementation on random inputs is a cheap, powerful trick. It finds cases you would never think to write by hand.

Quick check
An AI writes a function that splits a list into pages of 10 items. Which single test input is most likely to expose a bug?
Need a nudge? A hint rules out a wrong answer.

A checking routine

You do not need to check everything with the same intensity. A throwaway script deserves less scrutiny than code that touches payments or user data. But the same tools apply at every level.

From AI output to code you trust
AI output: code or answerAI outputcode or answerRun it: does it even work?Run itdoes it even work?Read the diff: line by lineRead the diffline by lineOfficial docs: APIs and versionsOfficial docsAPIs and versionsTests: edge casesTestsedge casesCommit: you own it nowCommityou own it now1234passfail: fix

Run it. The fastest check there is. Hallucinated imports and methods fail immediately.

1/5

Two more checks help with answers that are not code:

  • Ask for sources, then open them. A model can invent a link or a quote as easily as an API. A source only counts once you have read it yourself.
  • Ask a second model, or a fresh session, to critique the answer. Paste the code and ask "find bugs, security issues and edge cases this misses". A reviewer that did not write the code is less attached to it. The Build, Review, Test Loop lesson turns this into a habit.
Put it in order5 steps

Put the checking routine in a sensible order, cheapest check first.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Checking explanations, not just code

Code has a built-in referee: you can run it. Explanations do not. When an AI tells you "React re-renders a component whenever its parent re-renders" or "this library is thread-safe", there is nothing to execute. You need other ways to check.

  • Ask where it came from. "Which page of the official docs says this?" Then open that page. If the model cannot point to one, or the link does not say what it claimed, treat the answer as a guess.
  • Turn the claim into a test. Many explanations can become a tiny experiment. "Is sorted stable in Python?" is a five-line script away from a definite answer.
  • Get a second opinion from a fresh context. A model that just wrote an answer tends to defend it. A new session, or a different model, has no stake in it.
A second opinion from a fresh session
YouSession ASession Bwrite a rate limitercode + explanationfind bugs in this code2 issues: race, no resetfix these, add tests

The first session writes the code. It has the full conversation and its own assumptions.

1/5

How much checking is enough?

Match the effort to the cost of being wrong.

SituationReasonable check
A one-off script on your own machineRun it and look at the output
A feature in a side projectRead the diff, run the tests, try the edge cases
Code your team depends onAll of the above, plus a review by someone (or something) that did not write it
Auth, payments, user data, anything irreversibleAll of the above, plus the official docs for every API, and a human expert sign-off

The mistake is not skipping checks on a throwaway script. It is applying throwaway-script checking to code that handles money.

Reading AI-written code line by line

Reading generated code is a different skill from skimming it. Go line by line and, for each line, ask: what does this do, and would I have written it? If you cannot explain a line, you are not ready to commit it. Ask the AI to explain that line, then verify the explanation.

Things to look at closely:

  • Imports and dependencies. Does the package exist? Is it the one you meant? A misspelled package name could install something malicious.
  • Boundaries. Loops, slices and ranges are where off-by-one errors hide.
  • Error handling. Does it catch every exception and silently continue? That hides bugs instead of fixing them.
  • Inputs from outside. User input, file contents and API responses must be validated before use.
  • What changed that you did not ask for. A renamed variable, a deleted check, a loosened test.
Match the pairs0/4 matched

Match each problem to the check most likely to catch it.

Choose an item, then its match on the other side.
Quick check
An AI writes cursor.execute(f"SELECT * FROM users WHERE name = '{name}'") and it works in your demo. What is the problem?
Need a nudge? A hint rules out a wrong answer.
Key terms
hallucination
Fluent, confident model output that is not grounded in fact, like an invented API or source.
edge case
An input at the boundary of what code handles: empty, one item, maximum size, invalid.
diff
The exact lines added, removed and changed between two versions of the code.
deprecated
Still present but discouraged and likely to be removed; a sign the AI may know an older version.
SQL injection
An attack where input changes the meaning of a database query built from strings.
cross-check
Comparing results against a trusted reference implementation, often on random inputs.