What Language Models Can and Cannot Do
Objectives
- Explain tokens and the context window as the model's working memory
- Describe what hallucination is and why models produce it
- Explain why a bigger context window does not guarantee better answers
- Identify the gaps that retrieval can fill
Introduction: Why Start With Limitations
This book is about Retrieval Augmented Generation, usually shortened to RAG: a way of building applications in which a large language model answers questions using information you fetch for it at the moment of the question, rather than relying only on what it absorbed during training. Before we can appreciate why that design exists, we need an honest picture of what a language model actually is, what it is very good at, and where it reliably falls short. Every component you will meet later in this book, from document chunking to vector search to grounded prompts, is a response to one of the limitations described in this opening chapter.
If you have used a chat assistant, you have already seen both sides of the story. The same model that drafts a clear email, explains a recursive function or translates a paragraph in seconds will also, from time to time, state a wrong date with complete confidence, invent a library function that does not exist, or know nothing about your company's internal policies because it has never seen them. These behaviours are not random bugs. They follow from how the model reads text, how much text it can hold at once, and how it was trained.
We will work through these ideas in plain terms. First we look at tokens, the units in which a model reads and writes. Then we examine the context window, which acts as the model's working memory, and see how a prompt fills it. From there we explain why models seem to forget, why they hallucinate, and why simply buying a bigger context window does not make the problems disappear. We close by naming the specific gaps that retrieval is designed to fill, which sets up the next chapter's overview of a complete RAG system. You only need basic programming familiarity to follow along; no machine learning background is assumed.
Tokens: How a Model Reads Text
A language model does not see letters or words the way you do. Before any text reaches the model, a component called a tokenizer splits it into pieces called tokens and maps each piece to a number. A token might be a whole common word such as the, a fragment of a longer word, a punctuation mark, a space followed by a word, or a chunk of code syntax. A rare word or an unusual identifier is typically broken into several tokens, while a frequent word often fits into one. The model works entirely with these numeric token sequences: it receives a list of token ids, and it produces new token ids one at a time, which are then turned back into text.
Why does this matter to an application builder? Because nearly everything about cost, speed and capacity is measured in tokens rather than in words or characters. Providers price requests by the number of tokens going in and coming out. Limits on how much you can send are expressed in tokens. The time a model takes to respond grows with the number of tokens it must generate. When you later decide how large each document chunk should be, or how many chunks to place in a prompt, you will be reasoning in tokens.
A handy rule of thumb for ordinary English prose is that a token is somewhat shorter than an average word, so a page of text costs noticeably more tokens than it has words. That ratio is only an approximation. Code, tables, URLs, non-English languages and text full of numbers can tokenize very differently, often using many more tokens than you would guess. Different model families also use different tokenizers, so the same paragraph can produce different counts on different models. For anything that matters, measure rather than estimate: providers expose ways to count tokens before you send a request, and Anthropic's documentation describes a token counting API for exactly this purpose.
The other consequence of tokenization is subtler. Because the model generates one token at a time, each new token is chosen based on everything that came before it in the sequence. The model is, at its core, a very sophisticated predictor of what token is likely to come next. That simple fact explains a surprising amount of the behaviour we discuss in the rest of this chapter, including hallucination.
The Context Window: The Model's Working Memory
When you send a request to a model, the text it can look at while producing its answer is limited to a fixed number of tokens called the context window. Anthropic's documentation describes the context window as the model's working memory: all the text it can refer to while generating, including the response it is writing, and something separate from the large body of data the model was trained on. This distinction between working memory and training is the most important idea in this chapter, so it is worth slowing down on it.
Think of a capable consultant who has read an enormous library over many years but has a fairly ordinary memory for detail. What they learned from that library is their general knowledge: patterns of language, broad facts about the world, common ways of solving problems. That corresponds to the model's training. Now imagine you hand the consultant a folder of papers and ask a question. While they are working on your question, the only specific material in front of them is what is in the folder. That folder is the context window. If something is not in the folder and was not well represented in their years of reading, they simply do not have it.
The folder has a strict size limit, and everything counts against it. Anthropic lists the pieces that consume the window: the system prompt, every message in the conversation, results returned by tools, attached documents and images, the definitions of any tools the model may call, and the output the model generates. Beginners are often surprised by the last item. The model's own answer occupies the same space as your input, so a request that fills the window almost completely leaves very little room for a reply.
Window sizes have grown dramatically. At the time of writing, Anthropic's documentation states that its current flagship models offer a context window of one million tokens, while older models such as Sonnet 4.5 provide 200,000 tokens. Other providers offer windows of varying sizes, and these numbers change often, so always check your model's documentation. What does not change is the behaviour at the boundary: if the input alone is larger than the window, the API refuses the request outright rather than quietly trimming it. Many chat applications hide this by dropping or summarising older messages for you, but when you build your own application you are responsible for keeping requests within budget.
The diagram accompanying this chapter shows the context window as a single container that holds every part of a request. Keep this picture in mind. In a RAG system, retrieved documents are just one more thing poured into that container, competing for space with instructions, conversation history and the answer itself.
Prompting: Everything the Model Knows in the Moment
A prompt is simply the content you place in the context window to steer the model. In modern chat-style APIs the prompt is usually split into a system prompt, which sets the model's role and rules, and a sequence of user and assistant messages. From the model's point of view, though, all of it becomes one long sequence of tokens that it reads before generating its reply.
This gives prompting a peculiar power. Whatever you put in the context window, the model can use directly. If you paste the text of a contract and ask which clause covers termination, the model can read the clause and point to it. If you provide three examples of the output format you want, the model will usually follow the pattern. If you tell it to answer only from the supplied material and to say so when the material is insufficient, it will often comply. Instructions, examples and reference material all work through the same mechanism: they are tokens in the window that shape the prediction of the next token.
It also explains a limitation. A model has no hidden channel to your files, your database or yesterday's conversation. The only route from your data to the model's answer at request time is the context window. If a fact is not in the prompt and was not learned during training, the model cannot use it, no matter how clever the phrasing of the question.
The code example in this chapter illustrates this from a builder's perspective. It assembles a prompt from a system instruction, a few labelled context passages and a question, and it checks a rough token budget before sending anything. The exact numbers are deliberately crude; the point is the habit. Every RAG application you build will contain some version of this assembly step, deciding what goes into the window and in what order, and making sure there is space left for the answer. Microsoft's guidance on RAG prompting describes a very similar structure: a system message, a block of retrieved context, the user's question and optionally a few examples, with each context section labelled by its source so the model can attribute facts correctly.
Why Models Forget
People who use chat assistants regularly often describe the model as forgetful. It loses track of a detail mentioned early in a long conversation, it does not remember last week's session, or it asks again for information you already gave. These experiences have three distinct causes, and separating them will help you design better systems.
The first cause is that the model itself is stateless between requests. When you call a model through an API, it does not keep any memory of previous calls. A chat application creates the illusion of memory by resending the earlier conversation as part of every new request. The model rereads the whole transcript each time. Anything the application chooses not to resend is, from the model's point of view, gone. Features marketed as long-term memory are built by the application storing information somewhere and placing relevant parts back into the context window later, which is itself a small form of retrieval.
The second cause is the size limit. Because every message counts against the context window, a long enough conversation eventually will not fit. Applications cope by dropping the oldest turns, summarising them, or truncating attached documents. Each of these strategies loses information. A summary may omit the precise figure you mentioned at the start; a truncated document may cut off the appendix where the answer lives.
The third cause is the most interesting: even when information is still inside the window, the model may not use it well. As the amount of text grows, a model's ability to find and correctly use any particular detail tends to decline. We will look at the evidence for this shortly, because it changes how you should think about long contexts. For now, notice that forgetting is not only about information leaving the window. Information can be present and still be effectively overlooked.
There is also a kind of forgetting that is really never knowing. A model's training data stops at some point in time, often called the training cutoff. Events, product releases, price changes and documentation updates after that point are not part of its general knowledge. Unless you supply them in the prompt, the model will answer from an older picture of the world, frequently without signalling that its information may be stale.
Hallucination: Confident Guesses
Hallucination is the name given to a model producing an answer that sounds plausible and confident but is false. OpenAI's researchers define it in essentially those terms: a model confidently generating an answer that is not true. A hallucination can be small, such as a wrong year or a misattributed quote, or large, such as an invented legal case, a fictitious API parameter or a detailed description of a product feature that does not exist. What makes hallucination dangerous is not that the model is sometimes wrong, since every source of information is sometimes wrong, but that its errors are delivered in exactly the same fluent, assured tone as its correct answers.
Why does it happen? The explanation begins with how models are trained. During pretraining, a model learns to predict the next token across vast amounts of text. That text contains fluent language but no labels saying which statements are true and which are false. OpenAI's analysis points out that consistent patterns, such as spelling and grammar, can be learned reliably from this kind of data, whereas arbitrary, rarely mentioned facts cannot be inferred from patterns at all, and those are the facts that tend to be hallucinated. A person's birthday that appears once in the training data, the exact version in which a configuration flag was introduced, or the name of your company's on-call rotation are all examples. The model has learned that answers to such questions look like a date, a version number or a name, so it produces something with the right shape.
The second part of the explanation concerns incentives. Models are refined and compared using evaluations, and many evaluations score only accuracy. Under such a scoring scheme, a model that guesses will sometimes be right and gain points, while a model that says it does not know always scores zero for that question. OpenAI argues that this rewards guessing over admitting uncertainty and helps keep hallucination alive even in advanced models. You do not need to follow the research debate in detail to take away the practical lesson: a model's default tendency is to produce an answer, and a confident tone is not evidence of correctness.
Put those two ideas together and a clear pattern emerges. Hallucination is most likely where the model's training gives it the least to go on. The research singles out facts that are rare and arbitrary. Following the same reasoning, two further kinds of fact are just as exposed: facts that are private and never appeared in public text, and facts newer than the training data, because in both cases the model had nothing to learn them from. This is exactly the territory most business applications care about. Questions about your products, your customers, your internal procedures and this quarter's numbers are, almost by definition, questions a general model cannot answer from training alone.
There are practical ways to reduce hallucination, and they will become central techniques later in this book. Anthropic's guidance recommends explicitly allowing the model to say it does not know or lacks enough information, which can substantially reduce false answers. For long documents, it suggests asking the model first to extract word-for-word quotes relevant to the question and then to answer using only those quotes, which ties the answer to the text. Requiring a citation or supporting quote for every claim makes the answer auditable, and a follow-up check can ask the model to find support for each claim and withdraw any it cannot back up. Instructing the model to rely only on the provided documents rather than its general knowledge is another common restriction. Notice what all of these techniques share: they work best when the right information is actually in the context window. Telling a model to answer only from the supplied documents is useless if the documents do not contain the answer. That is the job retrieval will take on.
Why a Bigger Context Window Is Not Enough
If the root problem is that the model lacks the right information, an obvious idea is to give it everything. With context windows now reaching hundreds of thousands or even a million tokens, why not paste your entire documentation set, your whole policy manual or every support ticket from the last month into each request and let the model sort it out? For small collections this can genuinely work, and it is worth trying before you build anything elaborate. But as a general strategy it runs into several walls.
The first wall is quality. Anthropic's documentation states plainly that more context is not automatically better: as the number of tokens grows, accuracy and recall decline, a phenomenon it calls context rot, which is why curating what goes into the window matters. The model's attention is spread across everything it is given. Irrelevant passages are not harmless padding; they are distractions that can pull the answer in the wrong direction, particularly when they contain similar but subtly different information, such as an outdated version of the same policy.
The second wall concerns position. A widely cited study from researchers at Stanford, UC Berkeley and Samaya AI, titled Lost in the Middle, tested models on multi-document question answering and on retrieving a value from a list of key-value pairs, while moving the relevant information to different positions in the input. Accuracy turned out to depend heavily on where the relevant material sat. Performance followed a U-shaped curve: highest when the needed passage appeared near the beginning or the end of the context, and lowest when it was buried in the middle. The researchers also found that models advertised as having long contexts showed much the same sensitivity to position as their shorter-context counterparts, so a larger window did not by itself mean the model used that window robustly.
The same study examined a setup very close to RAG, in which a retriever supplies documents to a reader model. As more retrieved documents were added, the chance that the correct one was somewhere in the input kept rising, but answer accuracy levelled off well before that, so piling on more documents mostly added length without a matching gain in correct answers. In other words, getting the right document into the window is necessary but not sufficient; the model also has to notice and use it.
It is important to read this research carefully. The study was published in 2023; models released since then may handle long inputs better, and model providers have invested heavily in long-context performance. Even so, the general lesson has held up well in practice and is echoed in current vendor documentation: the amount of context and its arrangement both affect answer quality. The paper's practical implication for RAG systems is to choose retrieved passages carefully, place the most relevant ones where the model is most likely to use them, and avoid padding prompts with many marginal passages.
The remaining walls are practical. Every token you send costs money and adds latency, so stuffing a huge context into every request can make an application slow and expensive at scale. Your data may simply be larger than any window: a company's document store, ticket history and wiki together can easily exceed millions of tokens. Data changes, and resending a changing corpus on every request is wasteful. Finally, not every user should see every document. If all of your data goes into every prompt, you lose the ability to respect permissions, because the model may quote a confidential document to someone who should never have seen it. Selecting what to include, per question and per user, solves all of these problems at once.
Curating Context: Less, but Better
The conclusion of the previous section can be stated simply: the context window is a scarce, valuable resource, and the quality of a model's answer depends heavily on what you put in it. Treating the window as a carefully edited briefing, rather than a dumping ground, is the mindset that underlies good RAG design.
Curating context involves a handful of decisions you will return to throughout this book. You decide what to include: only passages that are likely to bear on the question, rather than everything vaguely related. You decide how much: enough to cover the answer, while leaving room for instructions and the response, and without the dilution that comes from marginal material. You decide the order: given the position effects described earlier, putting the strongest passages where the model attends most reliably is a sensible default. And you decide how to label what you include, so that each passage carries its source and the model can cite it, a practice recommended in Microsoft's RAG prompting guidance.
Curation also covers what you tell the model to do with the material. A good grounded prompt states the model's role, restricts it to the supplied context, specifies the answer format and citation style, and defines what the model should do when the context does not contain enough information, for example replying with a fixed message or handing the question to a person. That last instruction connects directly back to hallucination. When you give the model explicit permission and a clear procedure for saying that it does not know, you remove much of the pressure to guess.
There is one more reason to be thoughtful about what enters the window. Anything you place there is read by the model as text that can influence its behaviour, including instructions hidden inside documents. The OWASP Top 10 for LLM Applications places prompt injection at the head of its list of risks. A particularly relevant variant is indirect injection, in which the instructions arrive inside external content, such as a web page or a file, that the application hands to the model; an attacker who can edit a document in your knowledge base can try to change the answers your assistant gives. A later chapter deals with this properly. For now, simply remember that curation is about safety as well as quality: retrieved text is data, and your application should treat it that way.
Case Study: The Helpdesk Assistant That Guessed
Consider a composite scenario based on a pattern many teams encounter. A mid-sized software company wants an internal assistant that answers employees' questions about IT and HR policy. A developer connects a capable general-purpose model to the company chat tool with a short system prompt saying that it is a helpful assistant for the company's employees. Early demonstrations go well. The assistant explains how to write a good password, describes what a VPN does and drafts a polite leave request.
Trouble starts within the first week of real use. An employee asks how many days of parental leave the company offers. The assistant replies with a specific number and a confident explanation of eligibility. The number is plausible, roughly in line with common practice, and entirely wrong for this company. Another employee asks which VPN client to install; the assistant names a product the company stopped using two years ago, because public discussion of that product was common in its training data. A third asks about the expense limit for a new travel policy announced last month and receives an answer based on nothing at all, since the policy postdates the model's training.
Each failure maps onto an idea from this chapter. The parental leave answer is a classic hallucination: a specific, arbitrary figure of the kind models tend to guess. Here it is worse still, because the figure is private and the model never saw it at all, so it simply produced something in the shape of a correct answer. The VPN answer reflects general knowledge being used where specific, current knowledge was needed. The travel policy answer combines both: the information is private and newer than the training cutoff.
The team's first fix is to paste the entire employee handbook, the IT wiki and the policy archive into the system prompt. It fits in the model's large window, and some answers improve. But responses become slow and expensive, and new errors appear. The assistant sometimes quotes the superseded version of the travel policy, which is still in the archive, and it occasionally misses a clause buried deep in the middle of the long handbook, which is the kind of behaviour the Lost in the Middle research would predict. Worse, a manager's confidential compensation guide in the archive is now visible to anyone who asks the right question.
The lasting fix is the approach this book teaches. Instead of sending everything, the team indexes the current documents, retrieves only the few passages relevant to each question, filters them by the employee's permissions, labels each with its source, and instructs the model to answer only from those passages, to cite them, and to say plainly when they do not contain the answer. Answers become shorter, faster, traceable to a specific policy page and, when the information is missing, honest about it. The model did not get smarter; its context got better.
The Gaps Retrieval Can Fill
We can now name precisely what a language model, used on its own, cannot provide, and which of those gaps retrieval addresses. Researchers have framed RAG in just these terms. The paper that introduced the name, by Lewis and colleagues at Facebook AI Research in 2020, distinguished knowledge stored in the model's weights, which it called parametric memory, from an external index of passages that a retriever can search, called non-parametric memory. Its motivations were that pure language models find it hard to update their knowledge, cannot easily show where an answer came from, and may hallucinate. A later survey similarly presents RAG as a response to hallucination, outdated knowledge and reasoning that cannot be traced, achieved by drawing knowledge from external databases.
Translating those ideas into the practical gaps you will meet when building applications gives a short list.
- Private knowledge. The model has never seen your internal documents, tickets or databases. Retrieval brings the relevant parts into the window at question time.
- Fresh knowledge. The model's knowledge ends at its training cutoff. Because retrieved knowledge lives in an index, it can be updated or extended without retraining the model.
- Rare and specific facts. Exact figures, names and versions are where models guess. Supplying the source text replaces a guess with a lookup.
- Provenance. A model answering from memory cannot reliably point to where a fact came from. Retrieved passages carry their sources, so answers can cite them and readers can check.
- Focus. Instead of an ever-larger context that degrades quality, retrieval selects a small, relevant set of passages, which is exactly the curation the previous sections argued for.
- Access control. Selecting documents per request makes it possible to include only what the current user is entitled to see.
It is equally important to be clear about what retrieval does not fix. It does not make the model better at reasoning, arithmetic or writing style. It cannot help if the answer is not in your data, or if your search fails to find it. Retrieved text can itself be wrong, outdated or deliberately malicious, and security guidance such as OWASP's is clear that adding retrieval does not by itself remove the risk of prompt injection. And a model can still misread or overstate what a retrieved passage says, which is why the field measures faithfulness: evaluation tools such as Ragas break an answer into individual claims and check how many of them the retrieved context actually supports, with low scores signalling hallucination. Retrieval narrows the gap between what the model knows and what it needs to know; it does not close every gap, and later chapters on evaluation and security return to the ones that remain.
The second diagram in this chapter summarises this mapping from limitation to remedy. Keep it in mind as a checklist: when you are deciding whether an application needs RAG at all, ask whether its questions depend on private, fresh, rare or citable information. If they do, retrieval is probably part of the answer.
Summary and What Comes Next
This chapter set out what a language model can and cannot do, because every design decision in a RAG system responds to those limits. We began with tokens, the units in which a model reads and writes. Tokens are the currency for cost, speed and capacity, their count varies with the kind of text and the tokenizer, and they are best measured rather than guessed. Because a model generates one token at a time by predicting what is likely to come next, fluency is its native strength, and fluency is not the same as truth.
We then looked at the context window as the model's working memory: the limited set of tokens it can refer to while answering, including its own output, and something distinct from what it learned in training. Every part of a request draws on this budget, and requests that exceed it are rejected. A prompt is simply what you put in that window, and it is the only route by which your data reaches the model at the moment of the question.
We saw that models seem to forget for several reasons. They are stateless between calls, long conversations overflow the window, information can be present but overlooked, and knowledge stops at the training cutoff. We defined hallucination as a confident answer that is false, and traced it to training that rewards fluent prediction without labels for truth, and to evaluations that reward guessing over admitting uncertainty. Hallucination concentrates where knowledge is rare, private or recent, which is where most business questions live. Prompting techniques such as permission to say "I don't know", quote-first answering and mandatory citations help, but only when the right material is actually in front of the model.
We explained why bigger windows are not a complete solution. Accuracy declines as context grows, relevant information in the middle of a long input is used less reliably than information at the edges, and adding more retrieved documents yields diminishing returns. Cost, latency, data size, change and permissions add practical reasons to send less. The answer is curation: include fewer, better passages, label them, order them sensibly and give the model clear rules for grounded answers. The helpdesk case study showed these ideas playing out in a realistic setting.
Finally, we named the gaps retrieval fills: private, fresh and rare knowledge, provenance, focus and access control, along with the limits it leaves in place. The next chapter, Retrieval Augmented Generation: The Big Picture, builds on this foundation. It walks through the stages of a complete RAG system, from preparing and indexing your documents to retrieving, assembling context and generating an answer, and shows how each stage addresses one of the limitations you have just learned about.
CONTEXT_WINDOW = 200_000 # tokens; check your model's documentation
RESERVED_FOR_ANSWER = 2_000 # the reply shares the same window
def rough_tokens(text: str) -> int:
"""Very rough estimate for English prose: about 4 characters per token."""
return max(1, len(text) // 4)
def build_prompt(question: str, passages: list[dict]) -> str:
system = (
"You answer employee questions using ONLY the passages below. "
"Cite the source id for every claim, like [handbook-3]. "
"If the passages do not contain the answer, reply: "
"'I could not find this in the provided documents.'"
)
# Label each passage with its source so the model can cite it.
context = "\n\n".join(
f"[{p['source']}]\n{p['text']}" for p in passages
)
return f"{system}\n\n<passages>\n{context}\n</passages>\n\nQuestion: {question}"
passages = [
{"source": "handbook-3", "text": "Employees may claim up to the travel limit set in the 2026 policy."},
{"source": "it-wiki-12", "text": "Install the VPN client from the internal software portal."},
]
prompt = build_prompt("Which VPN client should I install?", passages)
used = rough_tokens(prompt)
if used + RESERVED_FOR_ANSWER > CONTEXT_WINDOW:
raise ValueError("Prompt too large: retrieve fewer or shorter passages.")
print(f"Estimated prompt tokens: {used}")
print(prompt)
{
"system": "Answer only from the provided passages and cite them.",
"tools": [
{
"name": "search_policies",
"description": "Search current HR and IT policies.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}
],
"messages": [
{"role": "user", "content": "What is our parental leave policy?"},
{"role": "assistant", "content": "Let me check the handbook."},
{"role": "user", "content": "[handbook-7] Parental leave details... Question: how many weeks?"}
],
"max_tokens": 1024
}
Key takeaways
- Models read and write tokens; cost, speed and limits are all measured in tokens, so count them rather than guess.
- The context window is the model's working memory for one request, and everything, including the generated answer, shares it.
- A model knows only what it learned in training plus what is in the current prompt; it has no access to your private or recent data otherwise.
- Hallucination is a confident false answer, most likely for facts that are rare, private or newer than the training data.
- Bigger context windows do not guarantee better answers: accuracy declines as context grows and information in the middle is used less reliably.
- Curating context, meaning fewer, relevant, well-ordered and labelled passages with clear grounding rules, matters more than raw window size.
- Retrieval fills gaps in private, fresh and specific knowledge, provenance, focus and access control, but does not fix reasoning or guarantee correctness.
Common mistakes
- Treating the model's confident tone as a sign that an answer is correct.: Require citations to supplied sources and give the model explicit permission to say it does not know.
- Forgetting that the model's output shares the context window with the input.: Reserve a token budget for the answer and check the prompt size before sending.
- Pasting every available document into the prompt because the window is large enough.: Retrieve only the most relevant passages per question, filter them by permissions, and order the strongest where the model uses them best.
- Estimating tokens from word counts for code, tables or non-English text.: Use the provider's token counting tools, since these kinds of text often tokenize very differently from English prose.
- Assuming a model remembers earlier sessions or conversations.: Remember that models are stateless between calls; store and resend or retrieve whatever the model needs.
See the full ebook: Retrieval Augmented Generation from the Ground Up