What Is a Large Language Model?
A plain-English guide to the technology behind modern AI chat assistants: what it is, how it learns, how it produces an answer, where it fails, and how to build with it safely.
Type a question into an AI assistant and a few seconds later a well-formed answer appears, often written in a friendly, confident voice. It can explain a tax rule, draft an email, fix a bug in your code, or translate a paragraph into another language. It is natural to wonder what kind of machine could do all of that, and whether it actually understands what it is saying.
The engine behind these assistants is called a large language model, or LLM. In this guide you will learn what an LLM really is, how text is broken into pieces a computer can handle, how those pieces become numbers, and how a design called the Transformer lets the model focus on the right words. You will also see how models are trained, what happens during the seconds after you press Enter, why they sometimes invent facts, how attackers try to trick them, and how teams run them in production. Every idea is explained step by step, with a real-life comparison and, where it helps, an example from a well-known company.
1What Is a Large Language Model?
Before looking at gears and numbers, let us agree on what we are talking about.
The definition in one sentence
A large language model is a computer program that has learned the patterns of human language by studying an enormous amount of text, and that uses those patterns to read, write, summarize, translate, and answer questions. It does not follow a hand-written list of grammar rules. Instead, it absorbed statistical habits of language from billions of pages and now applies those habits to whatever you give it.
The name, one word at a time
Large
Large describes two things at once. One is the amount of text the model studied, often trillions of small text pieces. The other is the number of adjustable settings inside it, called parameters, which run from billions to hundreds of billions.
Language
The model works with human language, and most modern ones also handle programming languages, because code is a kind of structured text. Many newer models can also accept images or audio, but language remains the core.
Model
In computing, a model is a mathematical stand-in for something in the real world. Here, the “something” is the way language behaves. The model is a giant pile of numbers that captures that behavior.
Imagine a friend who has read an entire city’s worth of libraries but is not allowed to carry any books with them. When you ask a question, they answer from memory, using everything they remember about how people write and explain things. They are fast and fluent, and usually right, but they are working from impressions, not from pages they can check. An LLM is that friend.
What an LLM is not
An LLM is not a search engine. A search engine looks up existing web pages and shows them to you, while an LLM writes new text one piece at a time. It is also not a database, because it does not keep a neat table of facts that it can query. And it is not a person, even though it speaks in the first person and can sound warm.
Think of an LLM as a skilled writer working from memory, not a librarian fetching documents. This one picture explains both its brilliance and its mistakes.
Where you already meet LLMs
You probably use LLMs without noticing. They draft and polish emails, write summaries of long meetings, power customer-support chat windows on shopping and banking sites, suggest code as developers type, and produce the short summaries that now sit above some search results. Behind each of those features is the same basic machine, wrapped in different software.
2A Short History: From Autocomplete to Assistants
LLMs look like a sudden arrival, but they sit at the end of a long road of small ideas.
Understanding the history helps you see why LLMs work the way they do. Each step below solved a specific problem left behind by the step before it.
Predicting text with statistics
Claude Shannon, the founder of information theory, showed that English text can be modeled by counting how often letters and words follow each other. This is the seed of the whole idea.
ELIZA
Joseph Weizenbaum at MIT built a chatbot that rephrased what users typed. It used simple pattern rules, yet many people felt it understood them, an early sign of how easily humans read understanding into language.
N-gram models and LSTMs
Search and speech systems counted short word sequences to guess the next word. In 1997, the LSTM network gave computers a better short-term memory for sequences, though it still struggled with long passages.
Word vectors
Google’s word2vec showed that words could be turned into lists of numbers in which similar meanings sit close together. Language finally became something a neural network could handle gracefully.
Attention arrives
Researchers added a mechanism that lets a model look back at the most relevant earlier words while producing each new one. It greatly improved machine translation.
The Transformer
Google researchers published the paper “Attention Is All You Need”. It dropped the slow step-by-step reading of older designs and let the model look at all the words together, which made training on huge datasets practical.
BERT and GPT-1
Google released BERT, which is good at understanding text. OpenAI released the first GPT, which is good at generating it. Both showed the power of learning from raw text first and specializing later.
GPT-3
With 175 billion parameters, GPT-3 could perform many tasks from just a few examples in the prompt. Scale, it turned out, unlocked surprising abilities.
ChatGPT
Models were taught to follow instructions and hold conversations, and ChatGPT launched in November. It became one of the fastest-growing consumer apps ever and brought LLMs to the general public.
An open and crowded field
Meta’s Llama family, Anthropic’s Claude, Google’s Gemini, Mistral, and many others appeared. Models grew able to read images, call outside tools, and work through multi-step problems.
3The Core Idea: Predicting the Next Piece of Text
Strip away the mystery and an LLM does one job, over and over.
One job: guess what comes next
Given some text, an LLM calculates which piece of text is most likely to come next. That is the entire task. If the text so far is “The capital of France is”, the model assigns a very high chance to ” Paris”, a tiny chance to ” Lyon”, and almost no chance to ” banana”.
Your phone keyboard suggests the next word as you type a message. An LLM is like that feature after years of intense schooling. The phone looks at the last word or two; the LLM considers thousands of words of context, and has absorbed patterns from a vast library.
How one answer is built
The model does not write a whole paragraph in one go. It produces a single piece of text, adds it to the conversation, and then predicts the next piece, again and again. Each new piece is chosen from a list of probabilities. This loop is why you see answers appear word by word on screen. It is not just a visual effect; the model truly generates them one at a time.
Read the text so far
The model receives your question plus the conversation history.
Score every possible next piece
It produces a probability for each entry in its vocabulary, which can be tens of thousands of options.
Choose one
It picks a piece, usually a likely one, with a little controlled randomness so answers do not sound robotic.
Add it and repeat
The chosen piece joins the text, and the whole process runs again until the model decides the answer is finished.
Why such a simple task produces such rich behavior
To guess the next word well across billions of different texts, the model has to pick up many things along the way. It must learn grammar, because ungrammatical guesses are usually wrong. It must learn facts, because “the tallest mountain on Earth is” demands knowledge. It must learn tone and style, because a legal letter continues differently from a joke. It must even learn patterns of reasoning, because many texts contain worked-out arguments and solutions. These abilities are side effects of getting very good at one narrow game.
Grammar and style
Which sentences sound natural, and how a formal email differs from a casual message.
World knowledge
Common facts about places, science, history, and everyday life, stored as patterns in the numbers.
Task formats
What a summary, a translation, a recipe, or a block of code usually looks like.
Reasoning habits
The way people walk through a problem step by step, which the model can imitate on new problems.
The model is aiming for text that is likely, not text that is guaranteed true. When the likeliest-sounding continuation happens to be wrong, the model still produces it fluently. Chapter 11 returns to this problem.
4Tokens: How Computers Read Text
A computer cannot work with letters directly, so text is first chopped into small, numbered pieces.
What a token is
A token is a small chunk of text that the model treats as a single unit. A token can be a whole common word like “table”, a piece of a longer word like “believ” plus “able”, a bit of punctuation, or even a single space-and-letter combination. The piece of software that does the chopping is called a tokenizer.
Think of LEGO bricks. You do not build a castle out of raw plastic; you use a set of standard bricks in different sizes. A tokenizer breaks any sentence into a fixed set of standard text bricks, so the model always works with parts it already knows.
Why not use whole words or single letters?
Designers tried both extremes. Whole words create a vocabulary so large that rare words, names, and typos break the system. Single letters make every sentence very long, which slows the model and makes it harder to see meaning. Subword tokens strike the balance: common words stay whole, and rare words are assembled from familiar pieces.
| Approach | Advantage | Drawback |
|---|---|---|
| Single characters | Tiny vocabulary; nothing is ever unknown | Very long sequences; meaning is spread thin |
| Whole words | Short sequences; each unit carries meaning | Huge vocabulary; new or misspelled words fail |
| Subword tokens | Balanced length; can build any word from parts | Splits can look odd; some languages need more tokens |
From text to numbers
Each token in the vocabulary has a number, called a token ID. A common method, byte pair encoding, builds the vocabulary by repeatedly merging the pairs of characters that appear together most often in the training text. The final vocabulary usually holds tens of thousands to a couple of hundred thousand entries. When you type a sentence, the tokenizer turns it into a list of these IDs, and that list is what the model actually receives.
Why tokens matter to you
As a rough guide, one token in English is about four characters, or three quarters of a word, so 1,000 tokens is around 750 words. This matters because nearly everything about an LLM is measured in tokens: how much text it can read at once, how long its answer can be, how fast it responds, and how much a provider charges. Many non-English languages need more tokens for the same sentence, so they can cost more and fit less into the model’s working space.
When you hit a length limit or a surprising bill, think in tokens, not words. Long documents, long chat histories, and pasted data all count toward the same budget.
5Embeddings: Turning Meaning into Numbers
A token ID is just a label. To work with meaning, the model needs something richer.
What an embedding is
An embedding is a long list of numbers that represents the meaning of a token. Where a token ID such as 4821 says only “this is entry number 4821”, an embedding says “this token is a bit like other animal words, a bit like a friendly pet, and nothing like a tax form”. The model learns these lists during training, so that tokens used in similar ways end up with similar numbers.
A map uses two numbers, latitude and longitude, to place a city, and cities close together have similar coordinates. An embedding does the same for meaning, but with thousands of coordinates instead of two. “Cat” and “kitten” live in the same neighborhood; “cat” and “mortgage” are on opposite sides of the world.
Why this helps
Once words are positions in a space, the model can do arithmetic with meaning. A famous early example from word2vec showed that the numbers for “king” minus “man” plus “woman” land very near the numbers for “queen”. Modern embeddings are far richer, and they change depending on the sentence, so the word “bank” ends up in different places in “river bank” and “bank account”.
Order matters too
The Transformer reads all tokens together, so it needs a way to know which came first. The model adds position information to each embedding. Without it, “the dog bit the man” and “the man bit the dog” would look like the same bag of words.
Embeddings outside the model
Embeddings are useful on their own. Companies use them for semantic search, where a query like “how do I get my money back” finds a page titled “Refund policy” even though they share no words. Recommendation systems, duplicate detection, and document clustering use them too. In Chapter 14 you will see how they power a popular technique called retrieval-augmented generation.
Semantic search
Find content by meaning, not by exact keywords.
Recommendations
Suggest items whose numbers sit close to what a person already likes.
Deduplication
Spot support tickets or articles that say the same thing in different words.
Grouping
Cluster thousands of reviews into themes without reading each one.
6Parameters: What “Large” Really Means
The word “large” is not marketing. It refers to something you can count.
Neural networks in plain words
An LLM is built from a neural network, a structure loosely inspired by the brain. It is arranged in layers of simple units. Each unit takes in numbers, multiplies them by adjustable weights, adds them up, and passes the result onward. No single unit is clever. The skill comes from millions of them working together in layers.
Parameters are the knobs
The adjustable weights are called parameters. Training is the process of tuning all of them until the network predicts text well. When people say a model has 70 billion parameters, they mean 70 billion numbers that were tuned, and that together hold everything the model has learned.
Picture a gigantic mixing desk in a recording studio with billions of tiny knobs. Nobody sets them by hand. Instead, an automatic process listens to the sound, nudges the knobs a little, listens again, and repeats this trillions of times until the music sounds right. The final knob positions are the model.
Why size matters, and its cost
Each parameter is stored as a number that takes up memory, commonly two bytes. A model with 70 billion parameters therefore needs about 140 gigabytes just to hold its numbers, before any extra working memory. That is far beyond a normal laptop, which is why large models run on data-center computers with many specialized chips called GPUs. Smaller models, with a few billion parameters, can run on a laptop or even a phone, at the price of being less capable.
| Model size class | Typical parameters | Where it can run | Typical strengths |
|---|---|---|---|
| Small | 1 to 8 billion | Laptop, phone, single GPU | Fast, cheap, good for focused tasks |
| Medium | 30 to 70 billion | Server with several GPUs | Strong general ability at moderate cost |
| Large | Hundreds of billions | Data-center GPU clusters | Best at hard reasoning and wide knowledge |
Scaling laws
Around 2020, researchers noticed that model quality improves in a smooth, predictable way as you increase three things together: parameters, training data, and computing power. Later, DeepMind’s Chinchilla study in 2022 showed that many earlier models were too big for the data they saw. A 70-billion-parameter model trained on about 1.4 trillion tokens beat much larger models trained on less. The lesson is that bigger is not automatically better; balance between model size and data matters.
Benefits of bigger models
- Broader knowledge and better handling of rare topics
- Stronger multi-step reasoning
- More reliable at following detailed instructions
Costs of bigger models
- Slower answers and higher price per request
- Need expensive hardware and more energy
- Harder to run privately inside a company
7The Transformer and the Idea of Attention
This is the architecture inside almost every modern LLM, and its secret ingredient is learning where to look.
The big picture
The Transformer takes a list of token embeddings and passes them through a tall stack of identical blocks. Each block lets the tokens exchange information and then refines each token’s representation. After the last block, a final layer converts the result into probabilities for the next token. GPT-3, for example, stacked 96 such blocks.
flowchart TD
A["Your text"] --> B["Tokenizer"]
B --> C["Token IDs"]
C --> D["Embedding layer"]
D --> E["Add position information"]
E --> F["Transformer block 1"]
F --> G["Transformer block 2"]
G --> H["Many more blocks"]
H --> I["Output layer"]
I --> J["Probability for every possible next token"]
J --> K["Choose one token"]
K --> L["Add it to the text and repeat"]
Read the diagram from top to bottom. Your text is split into tokens, the tokens become IDs, the IDs become embeddings with position information, and the stack of blocks does the heavy thinking. At the bottom, the model scores every possible next token, one is chosen, and the loop starts again with the longer text.
Attention: deciding what to focus on
Consider the sentence “The trophy did not fit in the suitcase because it was too big.” What does “it” refer to? You know it means the trophy, because a big suitcase would not be the problem. A model needs a way to make the same link. Attention is the mechanism that lets each token look at all the other tokens and decide how much weight to give to each one when updating its own meaning.
Imagine a meeting where every person listens to everyone else, but pays closer attention to the people whose comments matter most for what they are about to say. When the word “it” speaks, it listens hard to “trophy” and much less to “the” or “because”. Attention is that listening pattern, calculated automatically for every word at every layer.
Queries, keys, and values
Inside attention, each token creates three versions of itself. The query says what this token is looking for. The key says what this token offers. The value holds the information it will hand over. The model compares each query with every key, and the better the match, the more of that token’s value flows in. Think of a library: your query is the topic you want, the keys are the labels on the shelves, and the values are the books you pull down.
Many heads, many highlighters
One round of attention can only capture one kind of relationship at a time. So each block runs many attention “heads” side by side, a bit like using highlighters in different colors: one for grammar links, one for who-did-what, one for nearby words, and so on. Their results are combined, giving a much richer view of the sentence.
Inside a single block
flowchart TD
A["Input from previous layer"] --> B["Self-attention with many heads"]
B --> C["Add the input back and normalize"]
C --> D["Feed-forward network"]
D --> E["Add the input back and normalize"]
E --> F["Output to next layer"]
A -.-> C
C -.-> E
Self-attention
Lets every token gather useful information from the tokens before it.
Feed-forward network
Processes each token separately afterward, and is where much of the stored knowledge seems to live.
Shortcut connections
Add each step’s input back to its output, so information and learning signals flow smoothly through very deep stacks.
Normalization
Keeps numbers in a healthy range so training stays stable.
Why it beat older designs
Older networks such as LSTMs read text strictly one token after another, like a person reading with a finger under each word. That made them slow to train and forgetful over long passages. A Transformer processes all tokens at once during training, which suits GPUs, and attention lets any word connect directly to any other word, however far apart they are. Together these two traits made training on internet-scale data practical.
Decoder-only models and the “no peeking” rule
Chat-style LLMs such as the GPT, Claude, and Llama families use a version called decoder-only. During training, each token is allowed to look only at tokens before it, never at the ones that follow. This “no peeking” rule, called causal masking, keeps the game honest: the model must truly predict the next token, not copy it. BERT, in contrast, was built to look both ways and is better at understanding than at writing.
Attention is why an LLM can follow a long conversation, connect a pronoun to the right noun, or notice that a question refers to something said ten paragraphs earlier.
8How an LLM Is Trained
Training turns a blank network of random numbers into something that can hold a conversation.
Training an LLM resembles raising a skilled professional. First comes years of broad reading at school. Then comes an apprenticeship where a mentor shows how real work is done. Finally comes feedback from reviewers who say which responses were good and which were not. LLM training has exactly these three stages.
flowchart TD
A["Raw text from the web, books, and code"] --> B["Cleaning and removing duplicates"]
B --> C["Tokenization"]
C --> D["Stage 1: Pretraining by predicting the next token"]
D --> E["Base model"]
E --> F["Stage 2: Supervised fine-tuning on example conversations"]
F --> G["Stage 3: Preference tuning using human feedback"]
G --> H["Safety testing and red teaming"]
H --> I["Released assistant model"]
Stage 0: Preparing the data
Before any learning, teams gather huge collections of text: web pages, books, articles, encyclopedias, and computer code. Then comes the unglamorous but vital cleaning. Duplicate pages are removed, low-quality and spam text is filtered out, and personal data is scrubbed where possible. Data quality has an outsized effect on the final model, and many labs treat their exact data recipe as a closely guarded secret.
Stage 1: Pretraining
In pretraining, the model plays the next-token game on trillions of tokens. It sees a stretch of text with the next token hidden, makes a guess, and measures how wrong it was using a score called the loss. An algorithm called backpropagation works out which parameters contributed to the error, and another method, gradient descent, nudges each of them a tiny amount in a better direction. This happens an astronomical number of times, spread across thousands of GPUs, for weeks or months, and can cost millions of dollars in computing.
The result is a base model. It is very good at continuing text, but it is not yet a helpful assistant. Ask a base model “What is the capital of France?” and it might continue with a list of more quiz questions, because that is what such a line often looks like in its training text.
Stage 2: Supervised fine-tuning
To make the model behave like an assistant, teams train it further on a much smaller set of carefully written examples: a question or instruction, paired with an ideal answer. The model learns the format of being helpful, how to follow instructions, how to answer politely, and when to say it is unsure. OpenAI’s InstructGPT research in 2022 showed that this kind of tuning can make a far smaller model preferred by users over a much larger untuned one.
Stage 3: Learning from preferences
Next, the model is shown several different answers to the same prompt, and human reviewers rank which they prefer. A separate scoring model learns those preferences, and the LLM is then trained to produce answers that score well. This approach is known as reinforcement learning from human feedback, or RLHF, and newer simpler variants exist too. Some labs also write down a set of principles and have models critique their own answers against them. This stage shapes tone, helpfulness, and refusal of harmful requests.
Stage 4: Testing before release
Finally, the model is tested hard. Evaluation suites measure skills like math, coding, and factual accuracy. Red teams, groups of people paid to attack the model, try to make it produce dangerous or biased output so the problems can be fixed before the public sees them.
Training data sources and the legal questions around copyrighted material are the subject of ongoing court cases and policy debates in several countries. If you build a product on a model, check the provider’s terms about data use and ownership of outputs.
Training versus using
Training is a one-time, enormously expensive event done by the model’s creator. Using the model, called inference, is what happens every time you send a message, and it does not change the parameters. This is why an LLM does not learn from your conversation in the way a person would; the next chapter shows what actually happens during use.
9What Happens When You Press Enter
Follow a single question from your keyboard to the answer on your screen.
The prompt
The text you send is called a prompt. Real products usually add more text to it behind the scenes: a system prompt that sets the assistant’s role and rules, the earlier messages in the conversation, and sometimes documents or tool results. All of it is joined into one long sequence of tokens.
Your app sends a request
The message travels over the internet to the provider’s servers, passing through an API gateway that checks your key and limits.
Tokenize
The text is turned into token IDs, and the token count is checked against the allowed limit.
Prefill
The model reads the whole prompt in one fast parallel pass and stores its intermediate work. This is the pause you feel before the first word appears.
Generate token by token
The model picks one token, appends it, and repeats. Each new token reuses the stored work from earlier tokens instead of starting over.
Stream back
Tokens are sent to you as soon as they are ready, which is why the answer seems to type itself.
Stop
Generation ends when the model produces a special end marker or reaches the maximum length you allowed.
The KV cache: not repeating work
Generating each new token requires attention over all earlier tokens. Redoing the calculations for the earlier ones every time would be wasteful, so servers store the keys and values already computed in a memory area called the KV cache. It makes generation much faster, but it takes up valuable GPU memory, and it grows with every token in the conversation. This is one big reason long conversations cost more to serve.
The context window
Every model has a limit on how many tokens it can consider at once, called the context window. It covers your prompt, the history, any attached documents, and the answer being written, all together. Modern models range from a few thousand tokens to hundreds of thousands or more. When a conversation exceeds the limit, older material must be dropped or summarized.
The context window is the size of the desk the model works at. Everything on the desk can be seen and used at once. Papers that do not fit on the desk simply are not visible, no matter how important they were.
Settings that change the answer
| Setting | What it does | When to change it |
|---|---|---|
| Temperature | Controls randomness when picking the next token. Low values favor the most likely choice; high values allow more surprising ones. | Low for facts, extraction, and code; higher for brainstorming and creative writing |
| Top-p | Limits choices to the smallest group of tokens whose combined probability reaches a chosen value. | To trim unlikely, odd word choices without fully removing variety |
| Max output tokens | Sets the longest answer allowed. | To control cost, speed, and verbosity |
| Stop sequences | Text patterns that end generation immediately. | To keep output in a strict format |
| System prompt | Standing instructions placed ahead of the conversation. | To set role, tone, rules, and output format |
Temperature is like a creativity dial on a jukebox. At zero, it always plays the number-one hit. Turn it up and it starts picking songs from further down the chart, which is more varied and also more likely to include a clunker.
Serving at scale
A popular assistant answers millions of requests a day, so the serving system around the model matters as much as the model. A typical setup puts a load balancer and API gateway at the front, a layer of checks for safety and limits, and a fleet of GPU servers that run the model. Requests are grouped into batches so that GPUs stay busy, and logs and metrics flow out to monitoring tools.
flowchart TD
A["Client app or website"] --> B["API gateway"]
B --> C["Authentication and rate limiting"]
C --> D["Load balancer"]
D --> E["Input safety checks"]
E --> F["Request queue and batching"]
F --> G["GPU inference server 1"]
F --> H["GPU inference server 2"]
F --> I["GPU inference server N"]
G --> J["Output safety checks"]
H --> J
I --> J
J --> K["Streamed response to client"]
G --> L["Logs and metrics"]
H --> L
I --> L
L --> M["Monitoring dashboards and alerts"]
Two speed measures matter most to users. Time to first token tells you how long you wait before anything appears, and tokens per second tells you how quickly the rest streams in. Providers tune both with techniques such as batching, caching, and using smaller helper models to speed up generation.
10What LLMs Do Well, and Who Uses Them
The skills below all come from the same trick of predicting text, applied to different kinds of text.
Writing and editing
Drafting emails, reports, and posts, then adjusting tone or length on request.
Summarizing
Shrinking long documents, meetings, or threads into the key points.
Translation
Moving text between many languages while keeping the meaning and tone.
Coding help
Suggesting, explaining, and fixing code, and converting between programming languages.
Question answering
Explaining concepts, especially when given the relevant documents to read first.
Data extraction
Pulling names, dates, and amounts out of messy text into a tidy structure.
Real-world examples
GitHub Copilot: a pair programmer in the editor
GitHub, owned by Microsoft, built Copilot to suggest code as developers type. It reads the surrounding file and comments, predicts what code is likely to come next, and offers it as a suggestion the developer can accept, change, or ignore. The developer stays in control.
Duolingo: practice conversations and explanations
Duolingo added LLM-powered features to its premium tier in 2023, including an explanation of why an answer was right or wrong and role-play chats for practicing a language. These are tasks where fluent, patient text generation fits naturally.
Morgan Stanley: an assistant over internal knowledge
The bank announced in 2023 that it was giving its wealth-management advisers an assistant built on GPT-4 that answers questions using the firm’s own research and documents. This is the retrieval pattern covered in Chapter 14, which keeps answers grounded in trusted sources.
Khan Academy: a tutor that guides rather than tells
Khan Academy created Khanmigo, a tutoring assistant that is designed to ask guiding questions and nudge students toward the answer, instead of simply handing it over.
Google Search: summaries above the results
Google added AI-generated overviews, powered by its Gemini models, to many search results. They summarize several sources for a question, with links to the pages behind the summary.
In each example the LLM assists a human or works with trusted material. The most successful products pair the model’s fluency with checks, sources, or a person who makes the final call.
11Limits, Weaknesses, and Trade-offs
Knowing where an LLM fails is as valuable as knowing where it shines.
Hallucination: fluent and wrong
A hallucination is an answer that sounds confident but is false or made up, such as an invented book title, a fake web address, or a non-existent legal case. It happens because the model is built to produce plausible text, and a plausible-sounding falsehood can score just as well as a truth when the model lacks the facts. The model has no built-in feeling of “I am not sure”, though training can reduce the problem.
Picture a gifted storyteller at a dinner party who hates saying “I don’t know”. Asked about something half-remembered, they fill the gaps with details that sound right. They are not lying on purpose; they are completing the story as well as they can.
In 2023, in a case known as Mata v. Avianca, lawyers in New York filed a court document citing cases that a chatbot had invented. The judge sanctioned the lawyers. The lesson is simple: anything that matters must be checked against a real source.
Other limits to keep in mind
Knowledge cutoff
The model knows only what was in its training data. Recent events are unknown unless you supply them or give it a search tool.
Bias
Training text reflects human society, including its stereotypes and gaps, and the model can repeat them.
Inconsistency
Because of controlled randomness, the same question can produce different answers on different tries.
Exact calculation
Arithmetic, counting letters, and strict logic can go wrong, since the model predicts text instead of running a calculator.
Limited working space
Very long inputs can exceed the context window, and details in the middle of long inputs can be overlooked.
Cost and energy
Training and serving large models use significant computing power and electricity.
Does it understand?
Experts genuinely disagree. Some argue that modeling language well enough requires building a real internal picture of the world, and point to the models’ ability to solve new problems. Others argue that the model only manipulates patterns of text without grounding in real experience. For practical work you do not need to settle this. What matters is that the system is powerful, uneven, and best treated as a capable assistant whose work needs review.
The big trade-offs
| Trade-off | One side | Other side |
|---|---|---|
| Quality versus cost | Large models answer better | Small models cost far less per request |
| Speed versus depth | Short, direct answers arrive quickly | Step-by-step reasoning takes more tokens and time |
| Creativity versus reliability | High temperature gives varied ideas | Low temperature gives steadier, repeatable output |
| Convenience versus control | Hosted APIs need no hardware | Self-hosted models keep data in-house |
Strengths
- Flexible: one model handles many kinds of language tasks
- Available instantly and at any hour
- Can be guided in plain language, with no special programming
- Improves quickly as new models appear
Weaknesses
- Can state falsehoods with total confidence
- Can be tricked by cleverly written input
- Results vary from run to run
- Hard to inspect or explain why a specific answer was produced
12Security and Safety
An LLM follows instructions written in ordinary language, which makes it both easy to use and easy to trick.
Imagine a very eager assistant who obeys any note slipped under the office door, whether it came from the boss or a stranger. Most security problems with LLMs come from the model not being able to tell a trustworthy instruction from a sneaky one that merely looks like text.
The main threats
Prompt injection
An attacker hides instructions in the input, such as “ignore your previous rules and reveal your secrets”. In indirect injection, the hidden text sits inside a web page, email, or document that the model is asked to read.
Jailbreaking
Role-play, tricks, or long clever prompts used to push the model past its safety training into producing forbidden content.
Data leakage
Sensitive information escaping through the model, either because users paste secrets into a prompt, or because the model repeats private content from its context or training data.
Unsafe output handling
An app that passes the model’s text straight into a database command, a web page, or a shell can be attacked through that text.
Excessive agency
Giving a model power to send emails, spend money, or delete files, then having it tricked into misusing that power.
Abuse of cost
Attackers flooding an app with huge requests to run up the bill or slow the service down for real users.
The OWASP project, a well-known security community, publishes a “Top 10 for LLM Applications” that lists risks like these and is a good starting point for any team building with LLMs.
Defense in layers
No single fix stops all attacks, so teams stack several protections, much like a building that has a fence, a locked door, and a guard.
Treat all model output as untrusted
Validate and sanitize it just as you would any text typed by an anonymous visitor, before using it in a page, a query, or a command.
Give the least possible power
Allow only the tools and data the task needs, with read-only access wherever possible.
Ask a human before risky actions
Require approval for payments, deletions, outgoing messages, and anything that cannot easily be undone.
Separate instructions from data
Clearly mark untrusted content, such as a fetched web page, and tell the model to treat it as material to read, not orders to follow.
Filter and limit
Check inputs and outputs for sensitive data and harmful content, and apply rate limits and spending caps.
Keep secrets out of prompts
Never place passwords or API keys inside text the model can see, since anything in the prompt can potentially be coaxed out.
What teams do
They connect an LLM to a database or email account with full permissions and let it act on whatever it reads, trusting the system prompt to keep it safe.
Why it fails
A system prompt is only text, and attacker text can compete with it. One poisoned email or web page could instruct the model to forward private data or delete records.
Better approach
Limit permissions, require approval for sensitive actions, and enforce rules in ordinary code outside the model, where an attacker’s wording cannot change them.
Privacy and compliance
Before sending customer or employee data to any provider, check where it is stored, whether it is used for training, and how long it is kept. Regulated fields such as health and finance may need contracts, regional hosting, or self-hosted models. Redact personal data when it is not needed for the task.
13Monitoring, Logging, and Metrics
An LLM feature that nobody watches will quietly get slower, costlier, or worse.
A car dashboard shows speed, fuel, temperature, and warning lights so you notice trouble before the engine fails. Monitoring an LLM application is the same: a set of gauges that tell you whether it is fast, affordable, correct, and safe.
What to measure
| Area | Metric | Why it matters |
|---|---|---|
| Speed | Time to first token, total response time, tokens per second | Slow answers frustrate users and cause abandoned sessions |
| Reliability | Error rate, timeouts, rate-limit rejections | Reveals provider outages and capacity problems |
| Cost | Input and output tokens per request, spend per user or feature | Prevents surprise bills and shows which features cost most |
| Quality | Thumbs-up rate, escalation to humans, scores on a fixed test set | Shows whether answers are actually helping |
| Grounding | How often answers are supported by retrieved sources | Catches hallucination in document-based assistants |
| Safety | Blocked requests, flagged outputs, suspected injection attempts | Spots abuse and attacks early |
Logging with care
Useful logs record the prompt version, model name and settings, token counts, timing, and a trace ID that links all the steps of one request. Storing full prompts and replies helps debugging, but those can contain personal or confidential data, so redact sensitive fields, restrict who can read logs, and set a retention period.
Testing quality over time
Models change when providers update them, and prompts change when teams edit them. To catch regressions, keep a fixed set of representative questions with known good answers, and rerun it before every change. Scoring can combine automatic checks, human review, and sometimes another LLM acting as a judge, which is fast but should itself be spot-checked by people.
Set alerts on cost and latency from day one, and review a random sample of real conversations every week. Many problems show up in reading real examples long before they show up in averages.
14Design Patterns for Building with LLMs
Most real products wrap the raw model in a handful of well-proven patterns.
Retrieval-augmented generation
Retrieval-augmented generation, or RAG, solves two LLM weaknesses at once: missing knowledge and hallucination. Instead of trusting the model’s memory, the app first searches a collection of trusted documents for passages relevant to the question, then places those passages in the prompt and tells the model to answer from them.
RAG turns a closed-book exam into an open-book exam. The student, here the LLM, is still the one writing the answer, but now has the right pages open on the desk and can cite them.
flowchart TD
subgraph P1["Preparation done in advance"]
D1["Company documents"] --> D2["Split into chunks"]
D2 --> D3["Create an embedding for each chunk"]
D3 --> D4["Vector database"]
end
subgraph P2["At question time"]
Q1["User question"] --> Q2["Create an embedding of the question"]
Q2 --> Q3["Search the vector database for closest chunks"]
Q3 --> Q4["Build prompt with question and top chunks"]
Q4 --> Q5["LLM writes the answer"]
Q5 --> Q6["Answer with source references"]
end
D4 --> Q3
The diagram has two halves. In the preparation half, documents are split into manageable chunks, each chunk is turned into an embedding, and the embeddings are stored in a vector database that can quickly find the closest matches. At question time, the question is embedded the same way, the closest chunks are retrieved, and the model writes an answer based on them. Because the sources are known, the answer can include references that a reader can verify.
More patterns worth knowing
System prompt and templates
A carefully written, version-controlled set of instructions with slots for user input, so behavior stays consistent.
Tool use
The model asks the app to call a calculator, database, or web search, then uses the result. This fixes weak math and stale knowledge.
Agent loop
The model plans, uses a tool, looks at the result, and repeats until the task is done, with limits on steps and permissions.
Guardrails
Checks before and after the model that block unsafe input, mask private data, and verify that output fits the expected format.
Model routing
Send easy questions to a small, cheap model and hard ones to a larger model, saving money without hurting quality.
Caching
Reuse stored answers or stored prompt processing for repeated questions, cutting both cost and delay.
Prompting, RAG, or fine-tuning?
Teams often ask which technique to start with. A useful rule is to begin with the simplest one and move on only when it falls short.
| Approach | Best for | Limitations |
|---|---|---|
| Better prompting | Setting tone, format, and rules; quick experiments | Cannot add large amounts of new knowledge |
| RAG | Answers that depend on private or frequently changing documents | Quality depends on search quality and document cleanliness |
| Fine-tuning | Teaching a consistent style, format, or specialized skill | Needs good example data, effort, and retraining when things change |
Prompting is giving a new employee written instructions. RAG is handing them the company handbook to look things up. Fine-tuning is sending them on a training course so the skill becomes second nature. Each costs more effort, and each solves a different problem.
15Best Practices, Common Mistakes, and Anti-Patterns
The same few errors catch nearly every new team. Here is how to sidestep them.
Best practices
Be specific in prompts
State the role, the goal, the audience, the format, and any limits. Vague requests get vague answers.
Show examples
One or two sample inputs with ideal outputs teach the format faster than a long description.
Ground answers in sources
Supply the relevant documents and ask the model to answer only from them and to say when they do not contain the answer.
Verify what matters
Check facts, numbers, and citations before they reach customers, courts, or patients.
Evaluate before shipping
Build a test set of real questions and track scores each time the prompt or model changes.
Start small and add control
Launch to a small group, collect feedback, keep a human in the loop for risky tasks, and widen carefully.
Common mistakes
- Treating the first impressive demo as proof that the system is ready for real users.
- Forgetting that every token costs money and time, and then pasting giant documents into every request.
- Assuming the model has current information when its training ended long ago.
- Changing a prompt without rerunning tests, which quietly breaks older cases.
- Logging full conversations without thinking about privacy.
What teams do
They ship an assistant that answers every question confidently, with no sources, no way for users to flag mistakes, and no one reviewing real conversations.
Why it fails
Errors go unnoticed until a customer or regulator finds them, and users lose trust in everything the assistant says, including the correct answers.
Better approach
Show sources, let the assistant say “I am not sure” and hand off to a person, add a feedback button, and review a sample of conversations on a schedule.
What teams do
They fine-tune a model to teach it facts that change every week, such as prices or policies.
Why it fails
The knowledge is frozen at the time of training, so the model keeps giving outdated answers and each update needs another expensive training run.
Better approach
Keep changing facts in a searchable store and retrieve them at question time, and reserve fine-tuning for style, format, and stable skills.
Before trusting any important answer, ask yourself three questions: where did this come from, could it be out of date, and what happens if it is wrong? If the third answer is “something serious”, have a person check it.
16Frequently Asked Questions
Short answers to questions that come up again and again.
17Summary and Key Takeaways
You now have the full picture, from a single token to a production system.
A large language model is a very large neural network that learned the patterns of language by predicting the next token across a vast collection of text. Text is split into tokens, tokens become embeddings, and a stack of Transformer blocks uses attention to decide what to focus on before scoring the next token. Training happens in stages, from broad pretraining to instruction tuning to feedback-based shaping, and then the finished model is used over and over without further learning. Its strengths are fluency and flexibility; its weaknesses are invented facts, inconsistency, and exposure to tricky input. Good products surround the model with sources, tools, checks, monitoring, and human review.
Key Takeaways
- An LLM predicts the next token. Every skill it shows, from writing to coding, grows out of getting very good at this one task.
- Tokens and embeddings are the language of the model. Text becomes numbered pieces, and those pieces become lists of numbers that capture meaning.
- Attention is the Transformer’s key idea. It lets each word weigh all the other words, which makes long, connected text understandable and training scalable.
- Training has stages. Pretraining builds knowledge, fine-tuning builds helpfulness, and preference tuning shapes tone and safety.
- Fluent does not mean true. Hallucinations are a built-in risk, so verify important facts and ground answers in trusted sources with RAG.
- Treat the model as untrusted and powerful. Limit its permissions, validate its output, and put sensitive actions behind human approval.
- Measure everything. Track speed, cost, quality, and safety, and keep a test set so you notice problems before your users do.