Artificial Intelligence • Generative AI and Language Models • 16 min read

Large Language Models: Foundations and Capabilities

A large language model (LLM) is a language model with a large number of learned parameters, trained on extensive text or other suitable data to model patterns in language and perform language-related tasks. Modern generative LLMs commonly use Transformer neural networks and can produce text, answer questions, summarize documents, translate between languages, and generate code.

An LLM is not a database of verified facts or a program containing a rule for every possible question. It is a trained computational model whose outputs depend on its learned parameters, the input context, and the way its predictions are decoded. Fluent language generation does not by itself guarantee accuracy, reasoning correctness, or understanding of the real world.

Start with a simple example

Enter the beginning of a sentence into a language model: “The student opened the”. The model might assign high probability to tokens such as book or door. It generates text by selecting or sampling a token and repeating the process with the expanded context.

That simple operation can support surprisingly complex outputs after extensive training, including answers, code, explanations, and translations. But choosing plausible next tokens is not the same as checking whether a statement is true. A fluent answer can still be wrong.

Three concepts help separate the system’s parts:

  1. Tokens are the units processed by the model; one token is not necessarily one word.
  2. Parameters are learned numerical values that shape predictions after training.
  3. Context is the input information available during a particular request, subject to limits in length and the model’s ability to use it.

When a user asks an LLM a question, the model generally performs inference with existing parameters. It does not normally retrain those parameters from the conversation. Additional information may come from retrieved documents or tools, but that is different from updating the model’s weights.

1. Language models and large language models

A language model assigns probabilities to sequences of language units. These units are usually tokens, which may represent complete words, parts of words, punctuation, or other text fragments.

For a sequence of tokens x1,x2,…,xTx_1,x_2,\ldots,x_T, an autoregressive language model factors the sequence probability as:

P(x1,…,xT)=∏t=1TP(xt∣x1,…,xt−1).P(x_1,\ldots,x_T)=\prod_{t=1}^{T}P(x_t\mid x_1,\ldots,x_{t-1}).

Each factor describes how plausible a token is given the preceding context. This probability model supports text generation by repeatedly selecting the next token and extending the context.

The adjective large ordinarily refers to a model’s scale, particularly its number of parameters. Training data and computation also matter. There is no single universal numerical threshold that turns a language model into an LLM; size alone does not establish quality.

TermMeaningExample
Language modelModel of probabilities or representations for linguistic sequencesPredicting a missing or next token
Large language modelLanguage model trained at substantial scale, often adaptable to many tasksA general-purpose text assistant model
Generative language modelModel used to produce sequences of textDrafting a paragraph
Foundation modelBroadly pretrained model that can support many downstream tasksA pretrained model subsequently adapted for assistance
Chat applicationSoftware interface built around a model, usually with instructions and additional componentsA conversational assistant with search tools

An LLM can function as a foundation model, but the terms are not identical: foundation models can also be built for images, audio, and other modalities. Likewise, a chatbot is an application, while an LLM is a model that may power it.

2. The foundations an LLM depends on

Modern LLMs combine several ideas introduced in earlier PlainCS articles:

  • Machine learning: Learn parameters from data rather than manually specifying all language rules.
  • Neural networks: Transform numerical representations through layers of learned computations.
  • Tokenization and embeddings: Convert text into discrete token identifiers and dense numerical vectors.
  • Transformers: Use attention-based layers to build context-sensitive representations.
  • Attention mechanisms: Combine information across token positions based on learned relevance patterns.
  • Optimization: Update model parameters to reduce a training objective.

These components are related, but they are not interchangeable. Tokenization defines the input units; embeddings encode them numerically; the architecture processes those representations; and training determines parameter values.

3. How a generative LLM produces text

At a high level, a decoder-style autoregressive LLM processes text through the following steps:

  1. Receive a prompt. The input may include user text, system instructions, prior conversation, and retrieved material.
  2. Tokenize the input. A tokenizer maps text to token IDs.
  3. Compute token representations. Embeddings and positional information become the inputs to Transformer layers.
  4. Process the context. Attention and feed-forward computations build contextual representations.
  5. Predict scores for the next token. A final output projection produces a score, often called a logit, for each possible next token.
  6. Select a token. A decoding strategy chooses a next token from the model’s output distribution.
  7. Repeat. The selected token joins the context, and the model generates subsequent tokens until it stops.
Autoregressive LLM generation pipeline from prompt to tokens and repeated next-token prediction
A simplified decoder-style generation loop. Implementations can cache previous computations to reduce repeated work.

A model typically works with a context window: a limited span of tokens available during a request. The exact window size varies by model and configuration. A long conversation or document can exceed this limit, and fitting within it does not guarantee that every earlier detail is used reliably.

Next-token prediction is more than autocomplete

A toy autocomplete system might count which word commonly follows another word. A modern LLM instead evaluates a sequence through multiple nonlinear layers and learned contextual representations. Its next-token predictions can incorporate long-range context, syntax, domain-specific patterns, and representations useful for tasks such as code generation or answering questions.

Even so, the model’s prediction objective is not the same as a guarantee of truth. A plausible continuation can still be incorrect.

4. A small numerical example of token selection

Imagine a model has processed the prompt:

A square has four

For illustration, suppose it assigns these probabilities to three candidate next tokens:

Candidate tokenProbability
sides0.80
corners0.15
colors0.05

The probabilities sum to 1 in this deliberately simplified vocabulary. Greedy decoding chooses sides, the highest-probability option. Sampling may choose a different option, depending on the configured distribution.

Real LLMs use much larger vocabularies and can produce unexpected continuations. The table is an illustration, not an output measured from a particular model.

A brief Python example shows the selection principle:

import numpy as np

tokens = [" sides", " corners", " colors"]
probabilities = np.array([0.80, 0.15, 0.05])

# Deterministic choice: choose the most probable token.
greedy_token = tokens[int(np.argmax(probabilities))]
print("Greedy:", greedy_token)

# Sample one token according to the probability distribution.
rng = np.random.default_rng(42)
sampled_token = rng.choice(tokens, p=probabilities)
print("Sampled:", sampled_token)

This example demonstrates decoding only. It does not train or implement a language model. Actual model inference involves token representations, neural-network computations, and a distribution over the full vocabulary.

5. How LLMs acquire their capabilities

An LLM’s lifecycle usually involves several distinct phases.

5.1 Pretraining

Pretraining adjusts model parameters using large datasets. For an autoregressive language model, a common objective is to predict the next token from the preceding tokens.

Given a target sequence, the training process compares the probability assigned to each correct next token with the target and minimizes a loss such as negative log-likelihood:

L(θ)=−∑t=1Tlog⁡Pθ(xt∣x<t),\mathcal{L}(\theta)=-\sum_{t=1}^{T}\log P_{\theta}(x_t\mid x_{<t}),

where θ\theta represents the model’s learnable parameters and x<tx_{<t} denotes preceding tokens.

Pretraining can teach patterns of language, factual associations, code syntax, document structures, and other useful regularities. It does not directly verify the truth of every learned association.

5.2 Post-training and instruction following

After pretraining, developers may apply supervised fine-tuning and preference-based optimization to improve a model’s ability to follow instructions, respond helpfully, and avoid certain harmful behaviors. The chosen techniques and training data differ across model families.

Pretraining is not the same as instruction tuning: the first develops broad modeling abilities, while the second adapts behavior to desired tasks and response patterns. For more detail, see LLM Pretraining, Fine-Tuning, and Alignment.

5.3 Inference

Inference is the use of trained model parameters to process new inputs and produce outputs. A request does not ordinarily change those parameters. Giving a model additional text during a conversation changes its context, not its learned weights.

This distinction matters when comparing prompting, retrieval, and fine-tuning: they influence behavior in different ways.

6. Why Transformers are important

Transformers became central to modern LLMs because their attention-based layers can construct context-sensitive token representations and support efficient large-scale training.

Three commonly encountered architectural arrangements are:

ArchitectureTypical characteristicCommon use
Encoder-onlyBuilds contextual representations from input tokensClassification, retrieval, representation learning
Decoder-onlyOften generates tokens autoregressively using causal attentionGeneral-purpose text generation
Encoder-decoderEncodes an input and generates a conditioned outputTranslation, summarization, sequence transformation

Not every model uses the same architecture, and not all language models are generative chat models. A classification model may process language without producing an extended text response.

To study the mechanism at the layer level, read The Transformer Architecture and Attention, Self-Attention, and Multi-Head Attention.

7. What LLMs can do

LLMs can be useful across several categories of language-oriented work:

CapabilityExample taskImportant qualification
Text generationDraft a product descriptionOutput needs review for correctness and appropriateness
SummarizationCondense a long reportThe model can omit or distort important details
Question answeringExplain a conceptUnverified answers can contain factual errors
TranslationTranslate a passageNuance, terminology, and low-resource languages may be challenging
Code generationProduce a Python functionGenerated code requires testing and security review
Information extractionExtract fields from textStructured output still needs schema validation
ClassificationCategorize customer requestsQuality depends on instructions, examples, and distribution of inputs
Conversational assistanceHelp users complete a workflowTools and external state require application-level safeguards

In-context learning

An LLM can sometimes adapt its responses from instructions and examples placed directly in the prompt. This is called in-context learning. For example, a prompt might show three support tickets and their categories, then ask the model to categorize a fourth.

In-context adaptation does not require parameter updates. It differs from fine-tuning, where model weights are changed through a training process.

Tool use and retrieval

An application may let an LLM request a search, run an approved function, or consult a document index. Such capabilities are provided by the surrounding software system, not automatically by the model’s stored parameters.

For example, retrieval-augmented generation can supply relevant external documents to a model. Retrieval can improve grounding, but retrieved information can also be irrelevant, incomplete, outdated, or malicious.

8. Capabilities are not guarantees

A model that generates fluent explanations may still fail on elementary arithmetic, multi-step reasoning, specific factual claims, or tasks requiring information unavailable in its input.

8.1 Hallucinations and factual errors

Hallucination refers to generated content that is false or unsupported yet presented as though it were valid. An LLM might invent a citation, misstate a historical date, or produce a function that uses a nonexistent API.

A model’s confidence-sounding wording is not a calibrated probability of correctness. Reliable applications therefore need source checks, tests, or other verification appropriate to the task.

8.2 Context and knowledge limitations

Important constraints include:

  • Context limits: The model cannot necessarily process an unlimited amount of input.
  • Incomplete or outdated information: Training data may not cover recent events, specialized documents, or private information.
  • Ambiguity: Vague inputs can yield responses that do not match the user’s intent.
  • Distribution shift: Unfamiliar tasks and styles may reduce accuracy.
  • Non-determinism: Sampling settings or infrastructure details can change outputs between runs.
  • Bias: Training and evaluation data can reflect social, linguistic, or geographic imbalances.

8.3 Reasoning and reliability

Models may solve difficult problems and fail on simpler variants. A correct-looking explanation is not proof that intermediate steps are valid. When correctness matters, use independently testable procedures such as unit tests for code, symbolic tools for calculations, or source validation for factual claims.

8.4 Security and privacy

LLM applications can face prompt injection, accidental disclosure of sensitive data, insecure tool execution, and other risks. Instructions embedded in retrieved documents must not automatically acquire the same authority as trusted application instructions.

Users and developers should also consider what data they send to a service, how it is retained, and which tools the application may execute. See Responsible AI, Ethics, and Governance and AI Security Threats and Defenses for broader context.

9. LLMs compared with search engines and databases

An LLM, a search system, and a database answer different engineering needs:

SystemPrimary functionTypical strengthMain limitation
LLMGenerate or transform language from contextFlexible natural-language responsesCan produce unsupported claims
Search engineRetrieve relevant indexed materialProvides discoverable sourcesSearch results require interpretation
DatabaseStore and query structured recordsReliable access to defined stored valuesDoes not independently explain arbitrary questions
LLM with retrievalRetrieve evidence and generate an answerCombines source access with readable responsesStill needs retrieval and response evaluation

An effective application often combines all three rather than treating an LLM as a replacement for a database.

10. Key engineering considerations

When choosing an LLM for a software product, evaluate the complete system rather than a model’s advertised size alone.

ConsiderationQuestion to ask
Task qualityDoes the model perform well on representative examples of our actual task?
Language coverageDoes it handle the target languages, terminology, and writing systems?
Context handlingCan it process the required documents without losing essential details?
LatencyHow quickly are outputs delivered under expected load?
CostWhat is the cost of input, output, and supporting infrastructure?
DeploymentIs hosted access acceptable, or is local deployment needed?
SecurityWhat data can the model see, and which actions can it trigger?
EvaluationHow will failures, regressions, and unsupported claims be detected?

Model size is not a substitute for evaluation. Smaller models can be effective for well-defined tasks, while larger models may be justified for more demanding work. The right choice depends on measured performance, reliability, deployment constraints, and cost.

11. Worked application example: document question answering

Suppose a university wants a system that answers questions about its academic regulations.

A plain LLM may have general knowledge about universities but lack the institution’s actual current rules. A more reliable application can:

  1. Store approved policy documents in a searchable collection.
  2. Retrieve sections relevant to a student’s question.
  3. Provide those sections and the question to an LLM.
  4. Ask the model to answer using only supported information and cite relevant sections.
  5. Check that citations point to retrieved text, and escalate ambiguous or high-impact questions to a human reviewer.

This design separates knowledge retrieval from language generation. It is not infallible: incorrect retrieval, missing policy updates, or misinterpretation can still produce an inaccurate answer.

12. Common misunderstandings

“LLMs store every sentence from their training data.” Training generally compresses patterns into parameters rather than maintaining a conventional searchable record of each source. However, memorization of some training content can occur, so privacy and data-use questions remain important.

“An LLM searches the internet for every answer.” Not inherently. Internet search requires connected tools or services supplied by the application.

“A bigger model is always better.” No. Quality varies by task, training, architecture, inference settings, and evaluation criteria.

“Giving the model an example retrains it.” Prompt examples affect the current context. They do not ordinarily update the model’s weights.

“If the explanation sounds logical, it must be correct.” Fluency and correctness are different properties. Important claims and outputs require external checks.

13. Check your understanding

  1. How does a language model differ from a chatbot application?
  2. What does the probability P(xt∣x<t)P(x_t\mid x_{<t}) represent?
  3. Why do LLMs use tokenization and embeddings?
  4. What is the difference between pretraining, post-training, and inference?
  5. Why might a model answer a question fluently but incorrectly?
  6. How does retrieval change an LLM application without retraining the LLM?
  7. Why should deployment teams measure task quality, latency, and security rather than parameter count alone?
Show short answers
  1. A language model is a trained computational model; a chatbot adds interaction logic and may add tools, memory, and policies.
  2. The probability of token xtx_t given previous tokens in the sequence.
  3. Tokenization creates manageable units; embeddings convert token identities into numerical representations.
  4. Pretraining learns broad patterns; post-training adapts behavior; inference uses fixed trained parameters for new inputs.
  5. Its objective can reward plausible language patterns without verifying facts.
  6. Retrieval supplies external context that the application places in the prompt.
  7. Model size alone does not establish usefulness, reliability, affordability, or safe operation.

15. References and further reading

Related articles in

Image preview

Fit