2021: The Year Language Models Became Unreliable APIs
In 2021 the way software teams talked about large language models changed. In June 2020 the GPT-3 API had opened as a private beta, and most of what got built on it was demos. On June 29, 2021, GitHub announced Copilot as a technical preview. In July, OpenAI published the Codex paper. In August, Codex itself opened in the API as a private beta, and in November OpenAI removed the waitlist for the GPT-3 API entirely.
By the end of the year, a lot of teams, mine included, had a language model sitting in a production code path. The press wrote about whether these models would take programming jobs. Inside engineering teams the conversation was different and much more practical: how do you build a reliable system around a dependency that gives a different answer every time you call it?
I wrote last year about running GPT-3 behind a real request. This post is about the patterns that hardened around that problem in 2021, because they are still the skeleton of almost every LLM application today.
A model is an unreliable external API
The mental shift was to stop thinking of the model as an intelligence and start thinking of it as a remote service with unusually weak guarantees:
- No fixed output shape. You asked for JSON and sometimes got JSON, sometimes JSON with a friendly sentence in front, sometimes a Markdown code block, sometimes something that stopped halfway.
- No determinism. The same prompt could return different completions. Even at temperature 0, outputs could vary between calls, because batched GPU inference is not bit-for-bit reproducible.
- Variable latency. One call took 300 ms, the next three seconds, depending on length and load.
- Silent version changes. The model behind a name could be updated, and your carefully tuned prompt started behaving differently.
Every one of those properties has a known engineering answer for normal APIs: schemas, idempotency, timeouts, version pinning. The work of 2021 was adapting those answers to a service whose output is natural language.
The shape of an LLM call path
The structure that emerged is easy to see in Copilot's own design. The editor does not just send your cursor position to a model. A service collects context, builds a prompt, calls the model, filters what comes back, and only then shows a suggestion. Strip away the specifics and you get a pipeline most production LLM features still follow:
- Context assembly. Choose what goes into the prompt: the current file, nearby code, open tabs, retrieved documents. This was the start of what we would later call retrieval.
- Prompt template. A versioned template, treated like code, with the context slotted in.
- Model call. Explicit
temperature,max_tokens,stopsequences, a timeout, and oftenn > 1samples. - Parsing. Pull the useful part out of free text.
- Validation. Check the parsed result against a schema, a grammar, or the rules of the target language.
- Repair or retry. On failure, retry, sometimes feeding the validation error back into the prompt.
- Fallback. If it still fails, return something safe: no suggestion, a cached answer, or a non-LLM path.
The model is one box out of seven. Most of the engineering lived in the other six.
Determinism layers
You cannot make the model deterministic, but you can make your system behave deterministically around it:
- Pin everything that can be pinned. Model name, template version, sampling parameters. Log all of them with every request.
- Cache by input. Hash the final prompt and parameters; if you have seen it before, return the stored completion. Repeat requests become reproducible and cheap.
- Record and replay. Store prompt and completion pairs, so a bug report can be replayed against the exact output that caused it, instead of a fresh sample that may not show the problem.
- Constrain the output space. Stop sequences, short
max_tokens, and few-shot examples narrow what the model can produce. For code completion, stopping at the next top-leveldeforclasskeeps a suggestion to a single function.
Parsing: from regex to schemas
In 2021 there were no structured output modes and no function calling. You got a string. The first generation of parsers was regex: find the code block, find the first { and the last }, strip the chatter. The next step, which many of us arrived at independently, was to put a real schema behind the regex. In the Python world that usually meant Pydantic:
import json
import re
from pydantic import BaseModel, ValidationError, validator
FENCED = re.compile(r"`{3}(?:json)?\s*(\{.*?\})\s*`{3}", re.S)
class Suggestion(BaseModel):
function_name: str
code: str
confidence: float
@validator("function_name")
def is_identifier(cls, value):
if not value.isidentifier():
raise ValueError("not a valid Python identifier")
return value
def parse_completion(text: str) -> Suggestion:
match = FENCED.search(text)
raw = match.group(1) if match else text[text.find("{"): text.rfind("}") + 1]
return Suggestion.parse_obj(json.loads(raw))
def complete_with_retry(call_model, prompt: str, attempts: int = 3) -> Suggestion | None:
for _ in range(attempts):
text = call_model(prompt)
try:
return parse_completion(text)
except (json.JSONDecodeError, ValidationError) as err:
prompt += f"\n\nThe previous answer was invalid: {err}. Reply with JSON only."
return None
The pattern is regex to extract, a schema to validate, and the validation error fed back as part of the retry. The libraries that later automated this did not exist yet; this loop was written by hand in a lot of codebases.
Structural parsing for code
When the output is code, a JSON schema is not enough. The code has to be valid in the target language and has to do the thing you asked for. The cheapest useful check is to parse it:
import ast
FORBIDDEN_IMPORTS = {"os", "subprocess", "socket"}
def check_generated_function(code: str, expected_name: str) -> list[str]:
"""Return a list of problems; an empty list means the code passed."""
try:
tree = ast.parse(code)
except SyntaxError as err:
return [f"syntax error on line {err.lineno}"]
problems = []
names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef)]
if expected_name not in names:
problems.append(f"does not define {expected_name}()")
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
modules = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module]
if FORBIDDEN_IMPORTS & {m.split(".")[0] for m in modules if m}:
problems.append("imports a forbidden module")
return problems
Working at the level of the syntax tree rather than the text gives you checks that do not care about formatting: the right function exists, nothing dangerous is imported, the generated code has the structure you required. It catches a large class of bad suggestions before anything is executed.
Unit tests stop working the way you expect
A traditional unit test asserts that a function returns an exact value. Run that against a model and you get flaky tests, because two perfectly good completions rarely match character for character. Teams that kept exact-match tests learned to hate them; teams that deleted them lost all protection.
The answer came from the Codex paper. It evaluated generated code by executing it against unit tests, not by comparing text. Its HumanEval benchmark has 164 hand-written programming problems, each with tests, and it reports pass@k: the probability that at least one of k sampled solutions passes all the tests. Drawing n ≥ k samples per problem and counting the c that pass gives an unbiased estimate:
pass@k = E_problems [ 1 − C(n − c, k) / C(n, k) ]
The paper's own numerically stable version is three lines:
import numpy as np
def pass_at_k(n: int, c: int, k: int) -> float:
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
The results showed why this mattered. The 12-billion-parameter Codex model solved 28.8% of problems with a single sample. With 100 samples per problem, at least one correct solution appeared for 70.2% of them. The paper also found that text-similarity metrics like BLEU were poor predictors of whether code actually worked: two solutions can look almost identical and behave differently, or look nothing alike and both be correct.
That changed how we tested LLM features:
- Semantic checks over syntax checks. Ask "does it pass the tests, does it parse, does it satisfy the schema", not "does it match the string".
- Evaluation sets, not single assertions. Keep a fixed set of inputs with checkers, run the whole set, and track the pass rate.
- Thresholds in CI. A prompt or model change fails the build if the pass rate drops below a baseline, not if one example changes wording.
- Sampling as a feature. If you can verify cheaply, generate several candidates and keep the first one that passes. pass@k is a metric and also an architecture.
What it grew into
Looking back from today, the 2021 patterns have only been renamed. Context assembly became retrieval-augmented generation. Hand-written JSON parsers became structured output modes and function calling. Evaluation sets became eval harnesses. Generate-and-verify became agent loops with tool calls and test runners. The core idea has not changed: the model is the least reliable component in the system, and the architecture exists to contain it.
| 2021 problem | Pattern that emerged | What it became |
|---|---|---|
| Output shape not guaranteed | Regex extraction plus Pydantic validation | Structured outputs, function calling |
| Different answer every call | Pinning, caching, record and replay | Prompt versioning, tracing platforms |
| Generated code might not run | AST checks, sandboxed execution | Agent tool use with test runners |
| Exact-match tests are flaky | Execution-based checks, pass@k | Eval harnesses with CI thresholds |
| Model needs the right context | Prompt assembly from nearby code | Retrieval-augmented generation |
| Calls fail or time out | Retries with error feedback, fallbacks | Guardrail and orchestration frameworks |
The cost of generating code was falling fast in 2021. The cost of making that code trustworthy was not, and most of the architecture we still use today is the price we pay for that difference.