LLM fundamentals for product engineers
Know what a model really does with your request, so you can design for cost, speed, limits and wrong answers.
AI tools change fast: we review this lesson every quarter (next by 22 Jan 2027).
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 1 March 2023, a New York lawyer filed a document in a court case against the airline Avianca. A colleague at his firm had researched and written it. It cited court decisions that did not exist, with fake quotes and fake citations. They had been made up by ChatGPT. 1
The colleague later said he had "falsely assumed" ChatGPT was "like a super search engine". 1 When doubts came up, he asked ChatGPT, "Is Varghese a real case". The chatbot said it had given "real" sources that could be found in the usual legal databases. 1 The lawyers and their firm later admitted that six of the cited decisions were generated by ChatGPT and do not exist. 1
On 22 June 2023, the judge found bad faith. The lawyers had kept standing by the fake cases after the court asked about them. 1 He ordered a $5,000 penalty, to be paid jointly by both lawyers and their firm. They also had to write to their client and to each real judge falsely named as the author of a fake decision. 1 The judge wrote that there is "nothing inherently improper" about using a reliable AI tool. But lawyers have a "gatekeeping role" to make sure their filings are accurate. 1
The lesson for product engineers: a model writes likely text, not checked facts. Asking the model if it was right is not a check. Our advice: check the output in code, against a real source of truth.
The idea in simple words
A large language model (LLM) is first trained to predict the next word, given the text before it. 2 On its own, it does not look up facts. It writes text that is likely to come next.
The model does not read words. It reads tokens: words, parts of words, characters or bytes. 2 You pay per token, limits are counted in tokens, and speed depends on tokens.
The model writes its reply one token at a time. Then your code must decide if the reply can be trusted.
The key idea. Treat the model like a fast, smart, unreliable dependency. It can be slow, rate-limited, down, or confidently wrong. Design for all four, as you would for any external service.
How it works
Step through one API call with Next and Back.
- Your app sends one request. It holds a system prompt with the rules, and the user's message. All the numbers in this example are made up.
- The API splits the text into tokens, the units the model reads and you pay for. Here the request is 412 input tokens.
- The model reads every token in its context window. It has no other memory of this user. What is not in the request, it does not know.
- The model writes its answer one token at a time. Each new token depends on the tokens before it. With streaming, your app gets each token as soon as it is made.
- The model stops when it ends its turn. It can also stop because it hit your max_tokens limit, and then the answer is cut off.
- Your code parses the JSON and checks that the category is on the allowed list. If the check fails, retry once, then use a fallback such as a human queue.
Tokens
How many characters make a token depends on the model and the language. 2 Anthropic's glossary says Claude 4.7 and later models use a newer tokenizer. It makes about 30% more tokens for the same text than earlier models. 2 So use the provider's token counter with the exact model you plan to use. 2
Language matters too. One study found that the same text, translated, can need up to 15 times more tokens in some languages than in others. 15 If your users write in Hindi or Thai, measure your own token counts before you estimate cost.
The context window
The context window is everything the model can see for one response. It includes the system prompt, all messages, tool definitions, and the output itself. 3 If the input alone is too long, the API rejects the request. 3 Each model has its own limit, and limits change, so read the provider's model table. 11
More context is not always better. Anthropic says accuracy and recall degrade as the token count grows. 3 Send what the model needs, not everything you have. For large document sets, see RAG.
Temperature: why outputs vary
At each step, some next tokens are more likely than others. The temperature setting controls how random the choice is. Higher values give more varied output. Lower values stick to the most likely words. 2 Even at temperature 0, outputs are not fully deterministic. 2 So never write a test that expects one exact string. Use evals instead.
Hallucination
Models sometimes write plausible but false statements. One paper argues that training and tests reward guessing over saying "I don't know". 16 OWASP says models fill gaps in their training data with statistical patterns. 20 It also warns about overreliance: users trust output without checking it. 20 Our advice: give the model the facts in the prompt, let it say "I don't know", and check key fields in code.
System prompts and prompt structure
The system prompt holds the rules for every request. A role there, even one sentence, focuses the model's behaviour. 4 Wrap each kind of content in its own XML tag, such as instructions, context and input. 4 Put long documents first and the question last. Anthropic says putting the question at the end improved quality by up to 30% in tests. 4 Three to five examples help with format and tone. 4
Structured output and tool use
Free text is hard to parse. With structured outputs, the API forces the reply to match your JSON schema. 6 There are exceptions. A refusal, or a reply cut off at max_tokens, may not match the schema. Even the capital letters of a fixed list value can differ. 6 And valid JSON can still hold a wrong value.
Tool use (also called function calling) lets the model ask your code to run a function. The model returns a structured call. Your app runs it and sends back the result. 5 The model never runs your code itself. So your code decides what is allowed. Tool definitions also count as input tokens. 5 More in Tool use and agents.
Latency and streaming
Time to first token (TTFT) is how long the user waits before anything appears. 2 OpenAI says generating tokens is almost always the slowest step. Halving output tokens may cut about half the time; halving the prompt may save only 1 to 5%. 13 OpenAI calls streaming the most effective way to make users wait less. 13
With streaming, tokens arrive as server-sent events. 7 An error can still arrive after the stream has started, so handle it in the stream code. 10
Cost and prompt caching
You pay for input tokens and output tokens, and tool definitions add input tokens. 5 Prompt caching lets the provider reuse a fixed start of your prompt. 8 The cached part must match exactly, so put fixed content first. 8 As of October 2026, Anthropic prices 5-minute cache writes at 1.25 times the normal input price. Cache reads cost 0.1 times on most models, and less on a few of the newest ones. 8 The default cache lives 5 minutes, and each use refreshes it. 8 Prices change, so read the current table.
Choosing a model size
Anthropic frames the choice as capability against speed and cost. One approach is to start with a small, fast model and upgrade only if your tests show a gap. 11 It calls a good evaluation set "the most important step". 11
Rate limits
Providers cap requests and tokens per minute. Go over, and you get a 429 error. When there is a retry-after header, wait that many seconds. 9 For most Claude models, cached input tokens do not count toward the input limit. 9
Prompt injection
Text the model reads can contain instructions that change what it does. OWASP lists this first in its Top 10 for LLM Applications. It says it is unclear if it can be fully prevented. 17 Its advice includes least privilege, human approval for risky actions, and marking outside content as untrusted. 17 A system prompt is not a secret and not a security control: keep keys out of it, and enforce access in code. 19 See OWASP Top 10 and secure coding.
Privacy
Everything in the prompt goes to the provider. OWASP advises cleaning sensitive data, and clear terms of use that tell users how their data is used. 18 Read each provider's data policy. OpenAI says API data is not used for training unless you opt in, and keeps abuse monitoring logs for up to 30 days by default. 14 Anthropic offers zero data retention by arrangement, for eligible features only. 12
Treat the model as an unreliable dependency
Anthropic's SDK retries connection errors, 429s and server errors twice by default, with exponential backoff. 10 Anthropic also advises streaming for long requests. 10 Our advice for the rest:
- Set a timeout that fits your feature, not the SDK default. See Idempotency, retries and timeouts.
- Validate every reply. If it fails, retry once, then fall back: a smaller model, a saved answer, or a human.
- Log input and output tokens per request, so you can see cost by feature.
- Run your eval set before any prompt or model change.
Trade-offs
This table is our own summary, except where a source is cited.
| Option | Quality on hard tasks | Cost and latency | Effort to change | Use it when |
|---|---|---|---|---|
| Smaller, faster model | Often enough. Test it on your evals first. 11 | Yes Cheaper and faster. 11 | Low. Change one setting. | High volume, simple tasks, tight latency. |
| Larger model | Higher. 11 | No Slower and costs more. | Low. | Complex reasoning, where accuracy matters more than cost. |
| Prompt only | Good if the model already knows enough. | Yes One call. | Low. Edit text and run evals. | Your first version, almost always. |
| Prompt plus RAG | Better on your own, fresh data. | Extra search step and more input tokens. | Medium. You run an index. | Answers must come from your documents. See RAG. |
| Fine-tuning | Can change style and format. | A training run for each change. | High. | Prompting and RAG have failed on a measured eval. |
Simple rule: start with a prompt and a small eval set. Change the model or add RAG only when the numbers say so.
At work: how a senior uses this
- Before building, ask: "What happens when the model is slow, down, or wrong?" Write the fallback into the design.
- Keep fixed content at the top of the prompt, so caching works.
- Never let the model decide who may do what. Check permissions in your code.
- Read the provider's data policy with your security team before sending user data.
With AI
What to ask the agent
"Here is our prompt and 20 sample inputs. Count the input and output tokens for each with the provider's token counter, and estimate monthly cost at 50,000 requests a day."
"Wrap this LLM call with a timeout, retries that respect retry-after, JSON schema validation, and a fallback to the human queue. Add a test for each failure path."
"Review this prompt. Mark every place where user or retrieved text could be read as instructions."
What to check yourself
- The token counts come from the real counter for your model, not a rough rule of characters per token.
- The retry code does not retry errors that will never succeed, such as a 400.
- Validation checks values against your own data, not only the JSON shape.
- No secret or API key is in any prompt.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 20 sources and related lessons
- U.S. District Court, S.D.N.Y., Mata v. Avianca, Inc., No. 22-cv-1461 (PKC), Opinion and Order on Sanctions, 22 June 2023 (ECF 54) (opens in a new tab)
The judge's full decision. Read pages 1 to 2 for the summary, Findings of Fact 36 to 47 for how ChatGPT was used, and page 34 for the sanctions. - Anthropic, “Glossary”, Claude documentation (opens in a new tab)
Short definitions of tokens, temperature, context window, pretraining and time to first token. - Anthropic, “Context windows”, Claude documentation (opens in a new tab)
What counts toward the context window, why more context is not always better, and what happens when a request is too long. - Anthropic, “Prompting best practices”, Claude documentation (opens in a new tab)
Roles in the system prompt, XML tags, examples, and where to put long documents. - Anthropic, “Tool use with Claude”, Claude documentation (opens in a new tab)
How a tool call works step by step, who runs the code, and how tools add to your token count. - Anthropic, “Structured outputs”, Claude documentation (opens in a new tab)
What schema-constrained output guarantees, and the cases where it can still fail. - Anthropic, “Streaming messages”, Claude documentation (opens in a new tab)
The order of streamed events, and errors that arrive in the middle of a stream. - Anthropic, “Prompt caching”, Claude documentation (opens in a new tab)
How caching works, how long a cache lives, and what cache writes and reads cost. Prices change, so read the current table. - Anthropic, “Rate limits”, Claude documentation (opens in a new tab)
Request and token limits per minute, the 429 error and the retry-after header. - Anthropic, “Claude API errors”, Claude documentation (opens in a new tab)
Each error code, which ones to retry, and advice for long requests. - Anthropic, “Choosing the right model”, Claude documentation (opens in a new tab)
How to trade capability against speed and cost, and why you need your own test set first. - Anthropic, “API and data retention”, Claude documentation (opens in a new tab)
What the API keeps, for how long, and the zero data retention option. - OpenAI, “Latency optimization”, API documentation (opens in a new tab)
A second vendor's view. Seven ways to make LLM features faster, with rough numbers for input and output tokens. - OpenAI, “Data controls in the OpenAI platform”, API documentation (opens in a new tab)
Whether API data is used for training, how long logs are kept, and which endpoints support zero data retention. - Petrov et al., “Language Model Tokenizers Introduce Unfairness Between Languages”, NeurIPS 2023 (arXiv:2305.15425) (opens in a new tab)
Measures how many more tokens the same text needs in different languages. - Kalai et al., “Why Language Models Hallucinate” (September 2025, arXiv:2509.04664) (opens in a new tab)
An argument that training and tests reward guessing over saying "I don't know". Read the abstract and section 1. - OWASP, “LLM01:2025 Prompt Injection”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
Direct and indirect prompt injection, and a list of layered defences. - OWASP, “LLM02:2025 Sensitive Information Disclosure”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
How private data leaks through LLM apps, and how to limit it. - OWASP, “LLM07:2025 System Prompt Leakage”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
Why a system prompt is not a secret and not a security control. - OWASP, “LLM09:2025 Misinformation”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
Hallucination, overreliance on model output, and ways to reduce the harm.
Related: Evals for LLM systems · RAG: retrieval-augmented generation · Tool use and agents in products (coming soon) · Guardrails, cost and latency for LLM features (coming soon) · OWASP Top 10 and secure coding