How do LLMs work? How large language models predict the next word

How do LLMs work? Explore the process from pre-training and the Transformer architecture to how a model predicts the next token.
How do LLMs work? How large language models predict the next word

A large language model (Large Language Model, or LLM) is an AI system trained on large amounts of language data to process and generate text. LLMs help with drafting emails, summarizing documents, answering questions, translating text, and generating code.

When you use an AI chatbot, a fluent answer can appear almost instantly. However, the system usually doesn’t look up a finished answer and copy it out. The model converts your input into tokens, draws on the language patterns and context it has learned, and then generates a response piece by piece.

Key Takeaways

  • What an LLM is: An LLM is a deep learning model that learns statistical patterns in language in order to process and generate text. It is a type of generative AI.
  • How an LLM works: During training, the model adjusts its internal parameters through repeated prediction tasks. During inference, it converts the prompt into tokens and predicts the response one token at a time.
  • Verify the output: LLMs can produce polished text that still contains unsupported, outdated, or inaccurate claims. For important work, provide appropriate sources and check the results.

What is a large language model?

A large language model is a deep learning model trained on large amounts of language data to process and generate text. Rather than storing a ready-made answer to every question, the model learns relationships between words, phrases, structures, and other language patterns. IBM describes LLMs as deep learning models built to understand and generate natural language for a wide range of tasks.

You can think of an LLM as a system that has been exposed to many examples of how language is written and how ideas tend to appear together. When it receives a prompt, it uses those patterns to build a response. This description doesn’t mean the model memorizes every document like a searchable library, or that it understands the world the way humans do.

LLMs are a type of generative AI, a broader category of systems that create new content such as text, images, audio, video, or code. LLMs focus mainly on language and text output.

A simplified process: From prompt to answer

An LLM typically converts the prompt into tokens, processes the relationships between those tokens with a Transformer, and then generates the response one token at a time. Specific implementations vary from model to model, but the high-level process usually looks like this:

1. Receive the prompt. The system takes in the instructions, questions, or documents you provide. Other instructions and the conversation history may also be used as context.
2. Split the text into tokens. The text is broken into smaller units called tokens. A token can be a whole word, part of a word, a punctuation mark, or another unit of text.
3. Convert tokens into numerical representations. Each token is mapped to numbers so the model can process it. These representations are called embeddings.
4. Process relationships and context. Transformer layers analyze how tokens relate to one another, which helps the model use the surrounding text when interpreting a phrase.
5. Predict the next token. Based on the prompt and the text generated so far, the model calculates which tokens could come next and then applies a generation process to choose one.
6. Repeat the process. The new token becomes part of the response. The model keeps predicting the next token until it reaches a stopping point or completes the output.

This response-generation stage is called inference. The output is built step by step rather than retrieved from a database as a finished answer. For example, a model can write an email summarizing a meeting because it has learned the patterns of emails, summaries, and workplace language. The model does not automatically know whether every detail in that email is supported by real data.

Diagram of how an LLM works - How do LLMs work? How large language models predict the next word
Process diagram How do LLMs work How large language models predict the next word

If you ask a model to write an email based on meeting notes, it processes the notes and instructions, recognizes the patterns common in professional emails, and generates a response step by step. The model does not independently check whether the notes are accurate unless you provide a reliable source and ask it to work from that source.

How does text become tokens and embeddings?

Text is split into tokens and then converted into embeddings, which are numerical representations that the computational layers can process.

Tokens are the units the model processes

Tokenization breaks text into smaller, machine-readable units. A token can be a complete word, part of a word, a punctuation mark, or another piece of text. An uncommon word may be split into several pieces; how text is split depends on each model’s tokenizer.

A token is not always equal to one word. The same document can contain a different number of tokens depending on the technical terms, proper names, code, numbers, or language it uses.

When summarizing a report, the model doesn’t process the page the way a person sees it. It processes the text and other supported inputs as units that can be represented and analyzed.

Embeddings turn tokens into useful numerical representations

An embedding is a numerical representation of a token. These numbers help the model represent relationships between tokens and refine those representations as it processes text; they are not definitions a person can read.

Terms that often appear in related contexts can receive representations that help the model distinguish how they relate. A word’s representation is also refined based on the surrounding sentence. The word “draft” can refer to writing a contract, a current of air moving through an office, or a preliminary version of a document. The neighboring tokens help determine the appropriate meaning.

IBM explains that tokens are mapped to numerical vectors called embeddings, and Transformer layers then refine these representations into more context-rich forms. The model turns language into numerical patterns so the processing layers can compare and connect parts of the input.

How does a Transformer use context to relate words?

A Transformer helps an LLM analyze the relationships between tokens in a sequence, while self-attention helps determine which tokens are relevant at a given point in the text.

A Transformer is a neural network architecture that LLMs commonly use to process sequences of tokens. Its central mechanism is self-attention, which lets the model connect tokens that are close together and, within the available context, tokens that are farther apart. IBM’s explanation of LLMs describes self-attention as a way of calculating the relationships and dependencies between tokens.

  • “Please draft the contract before Friday.”
  • “The draft from the window made the room cold.”

The word “draft” appears in both sentences, but the surrounding words point to different meanings. A Transformer helps the model use those relationships instead of treating the word as an isolated label.

A similar mechanism helps connect pronouns to what they refer to earlier in the text. If a paragraph says Maria approved the budget and then says “she requested changes,” the surrounding context provides signals for interpreting “she.” This is pattern-based processing, not conscious attention or human-like understanding.

A prompt that is clear about the audience, format, source material, and constraints provides more useful signals than a vague one.

How does an LLM learn during pretraining?

During pretraining, an LLM learns broad language patterns by predicting tokens or other training targets, measuring its errors, and adjusting its internal parameters. This stage uses training data, typically collections of text that have been prepared, filtered, and preprocessed. Specific datasets and policies differ between models, so this general description does not represent every commercial system.

The learning process includes:

1. Preparing training examples. Text is collected and processed for learning. This step may include cleaning, formatting, and removing or handling problematic content.
2. Asking for a prediction. The model receives part of a sequence and tries to predict the next token or another training target.
3. Measuring the error. The system compares the prediction with the target and calculates how far off it was.
4. Adjusting internal parameters. The model updates the numerical values inside the network to improve future predictions.
5. Repeating across many examples. This cycle helps the model learn recurring patterns in grammar, phrasing, structure, and associations.

This process is often called self-supervised learning because the text itself supplies many of the prediction targets. For example, after seeing “Please attach the quarterly…”, the model can learn which tokens or sequences typically come next. Many examples help the model recognize patterns in emails, reports, explanations, conversations, and other forms of language.

The model is not taught a human-written explanation for every fact. It is shaped through many prediction tasks. That’s why a model can produce grammatically correct, well-structured language that still makes unsupported claims.

The process above does not identify exactly which books, websites, code repositories, or other sources a particular commercial model used. Claims like that need to be based on the relevant provider’s documentation.

Pretraining, fine-tuning, and inference are different stages

Pretraining builds broad language capabilities, fine-tuning adjusts behavior for narrower purposes, and inference generates output from new prompts.

Stage Main purpose Typical input Practical result
Pretraining Learn broad language patterns Large collections of text A general-purpose model
Fine-tuning Adapt the model to a narrower task or style Smaller, task-specific datasets More targeted behavior
Inference Generate output from new input Your prompt and available context A generated response, prediction, or text

Pretraining exposes the model to many examples and continually adjusts its internal parameters.

Fine-tuning adapts a broadly trained model to a more specific purpose, such as summarization, classification, or customer support responses, using a smaller dataset. Fine-tuning changes how the model tends to respond to related inputs, but that doesn’t mean every product uses the same process. IBM distinguishes fine-tuning from pretraining, describing fine-tuning as a narrower form of adaptation that requires fewer resources than training from scratch.

Inference happens when a trained model is put to use. If a support agent pastes in a customer’s message and asks for a polite reply, the model is performing inference. The prompt shapes the current response; it typically does not permanently rewrite the underlying model. A conversation can influence the output because it is included in the context, but that is different from changing the trained parameters.

How does an LLM generate a response one token at a time?

During inference, an LLM estimates the next token based on the prompt and the part of the response generated so far, selects or samples a token, and repeats the process until it reaches an end point or a system limit.

Say you ask the model to rewrite an email that begins “Thank you for reviewing the proposal.” Those first words set the tone and sentence structure. They then become part of the context used to generate what comes next.

The simplified sequence is:

1. Read the prompt and available context.
2. Estimate which tokens could come next.
3. Select or sample a token according to the generation settings.
4. Add the token to the response.
5. Use the expanded context to predict the next token.
6. Stop when the response reaches a suitable end point or hits a system limit.

This process can produce paragraphs, summaries, translations, and code, even when that exact wording doesn’t appear as a complete passage in the prompt. It also reveals the model’s limits: a continuation is likely to fit based on patterns and context, which is not evidence that every sentence is supported.

The model doesn’t necessarily always choose the token with the highest mathematical probability. Generation settings and system design can affect how predictable or varied the output is.

What does context window mean?

A context window is the maximum number of tokens an LLM can use at once when processing an interaction and generating text. It can include the prompt, documents, conversation history, instructions, and the response being generated. IBM defines the context window as the maximum number of tokens a model can see and use at one time.

With a long policy document or an extended project discussion, if the content exceeds the available context, the system may not be able to use the entire document in the current request. A summary therefore depends on the content that was actually provided and available to the model.

A context window is not permanent memory. It only describes what the model can use within a specific processing context and does not show that the system will retain information for later conversations. Memory or saved-conversation features in certain products need to be reviewed in their documentation and assessed separately for privacy.

A larger context window also doesn’t guarantee the model will use every detail perfectly. Important names, numbers, obligations, and exceptions still need to be checked against the source.

What can LLMs do in everyday work?

LLMs are well suited to tasks that involve transforming, organizing, explaining, or generating language. Common uses include:

1. Drafting and rewriting: Turning bullet points into an email, adjusting tone, or producing a draft report.
2. Summarizing: Condensing meeting notes, policies, research passages, or customer feedback you provide.
3. Answering questions: Explaining technical content or answering questions about documents within the available context.
4. Translating: Producing draft translations for a qualified person to check for meaning, tone, and terminology.
5. Classifying and extracting themes: Grouping survey comments, identifying recurring themes, or labeling support requests.
6. Conversational support: Helping service teams draft replies or guide users.
7. Generating code: Suggesting code, explaining errors, or drafting formulas or scripts.

These uses are a form of assistance, not automatic authority. An LLM can turn meeting notes into a to-do list, but the project manager still needs to confirm owners and deadlines. Likewise, spreadsheet formulas, customer replies, and report content need to be tested or reviewed before use.

Elastic lists text generation, summarization-related language tasks, conversational systems, and code generation among the applications of LLMs. Results depend on the quality of the input, how well suited the task is, and the process for reviewing the output.

Why can an LLM sound right but still be wrong?

LLMs can produce polished language without guaranteeing that their claims are true. The model generates text from learned patterns and the context provided; those patterns sometimes lead to responses that sound appropriate even when the claims are unsupported, outdated, or inaccurate.

This error is often called AI hallucination: output that seems plausible but isn’t supported by relevant evidence. When asked to provide a source for an obscure claim, a model may produce something that looks like a citation but still needs to be checked. When asked to summarize without the source text, a model may fill in the gaps with plausible-sounding content.

Problems can include:

  • Facts with no supporting source, or fabricated references
  • Incorrect figures, dates, names, or quotations
  • Outdated information
  • Weak performance on complex reasoning tasks
  • Biased or skewed patterns inherited from training data
  • Misinterpretation of vague instructions or long contexts

Stanford University’s overview of LLMs notes that these systems can produce plausible but inaccurate or nonsensical output because they rely on learned patterns rather than human-like understanding. Fluent writing is a property of the generated response, not evidence that the answer has been independently verified.

How to use LLM output responsibly

Using LLMs for important work should start with appropriate sources and clear requests, followed by verifying the output and keeping accountability with people.

1. Start with approved sources. Provide the relevant policies, notes, data, or requirements when you want the model to work from specific information.
2. State the task and constraints clearly. Specify the audience, format, length, tone, assumptions, and what to do when information is missing.
3. Ask for a draft or an analysis. Treat the response as generated assistance, not a final decision.
4. Check important claims. Verify names, figures, quotations, dates, calculations, and conclusions against reliable sources.
5. Protect sensitive information. Don’t paste passwords, API keys, security codes, confidential source code, private customer information, personal identifiers, financial records, or restricted contracts into a tool unless you understand its approved use and data policy.
6. Keep accountability with people. Someone with the right expertise should approve decisions that affect customers, employees, money, safety, legal obligations, privacy, or compliance.

It’s important to distinguish between a provider using the content users submit to train models and a provider storing prompts, logging interactions, or keeping files for a period of time. The inference process on its own does not show that user data isn’t stored. Before using sensitive information, check the service’s current policies on privacy, retention periods, and training data.

For a customer email or internal report, a sound workflow is to provide approved sources, ask for a draft, check each claim, verify key details against the source, remove unnecessary sensitive information, and leave the final decision to a person.

Training teaches an LLM broad language patterns; tokenization turns text into processable units; embeddings and Transformers represent and relate those units; and inference generates the answer one token at a time. This process explains both the usefulness and the limits of LLMs: they help with drafting, summarizing, explaining, and exploring, but they still need context, verification, and human judgment.

For a fuller picture of this topic, you can also read our articles on what generative AI is and what an AI context window is.

Frequently asked questions about how LLMs work (FAQ)

What is a large language model?

A large language model is a deep learning model trained on large amounts of language data to process and generate text. Rather than storing a ready-made answer to every question, the model learns relationships between words, phrases, structures, and other language patterns. IBM describes LLMs as deep learning models built to understand and generate natural language for a wide range of tasks.

What does the simplified process from prompt to answer look like?

An LLM typically converts the prompt into tokens, processes the relationships between those tokens with a Transformer, and then generates the response one token at a time. Specific implementations vary from model to model, but the high-level process usually looks like this:

How does text become tokens and embeddings?

Text is split into tokens and then converted into embeddings, which are numerical representations that the computational layers can process.

How does a Transformer use context to relate words?

A Transformer helps an LLM analyze the relationships between tokens in a sequence, while self-attention helps determine which tokens are relevant at a given point in the text.

Was this article helpful?

Learn AI Mindset researches and fact-checks every article so you can understand and use AI well. If this one was useful, you can support us voluntarily so we can keep writing more like it.

Completely optional. Every article stays free to read whether or not you support us.

Support Learn AI Mindset on Ko-fi
Previous Article

What is an LLM? Large language models explained simply, with examples

Next Article

What Are AI Tokens? How ChatGPT and Gemini Count Tokens and Charge for Them