1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

What Is a Large Language Model? How LLMs Work, Explained Without the Hype

Understand what is really happening when an AI writes text. Learn about tokens, embeddings and attention in plain language, run a tiny next-word predictor, and see why these models can be brilliant and wrong at once.

9 min read
What is a large language model? How LLMs work, explained without the hype

Key takeaways

  • A large language model is a neural network trained on huge amounts of text to predict what comes next.
  • It works on tokens, and uses attention to weigh which earlier tokens matter most.
  • It generates a reply one token at a time, by choosing from a set of probabilities.
  • It can sound confident while being wrong, so important output needs checking.

Tools that chat, summarize and write code seem almost magical, until you see the mechanism underneath. A large language model, or LLM, is at heart a very sophisticated system for predicting the next piece of text. That one idea explains both what these tools do well and why they fail in the ways they do.

This guide explains the main concepts without any maths, then builds a tiny next-word predictor to make the idea concrete. We ran that code on Python 3.13, and the output comes from that run. It is a simple counting toy rather than a neural network, and real LLMs are vastly more capable. We also avoid quoting figures for specific models, because they change quickly.

What is a large language model?

An LLM is a type of artificial intelligence trained to understand and generate human language. Let us take the name one word at a time:

  • Large: it has a huge number of adjustable internal values, called parameters, and it learns from an enormous amount of text.
  • Language: it works with text, including natural language and code.
  • Model: it is a mathematical system that captures patterns from data and uses them to make predictions.

Models are the engine, and products such as chat assistants are the car built around them. A product often adds a user interface, safety systems, search and other tools.

The core idea: predicting what comes next

You do this yourself. If you read “the capital of France is”, your mind offers “Paris” right away. An LLM does something comparable, but on a much larger scale. Given some text, it calculates how likely each possible next token is, picks one, adds it to the text and repeats.

There is no database of stored answers being looked up. The model holds patterns learned during training, in the form of numbers. When those patterns line up with the truth, you get a correct answer. When they do not, you can still get a fluent answer, and that is an important difference from a search engine.

A tiny working demo

To see next-token prediction in its simplest form, this script counts which word follows which in a tiny text. It then generates new text from those counts. Statisticians call this a bigram model.

import random
from collections import Counter, defaultdict

TEXT = """the cat sat on the mat . the dog sat on the rug .
the cat saw the dog . the dog saw the cat ."""

tokens = TEXT.split()

follows = defaultdict(Counter)
for current, following in zip(tokens, tokens[1:]):
    follows[current][following] += 1

def probabilities(word):
    counts = follows[word]
    total = sum(counts.values())
    return {w: round(n / total, 2) for w, n in counts.most_common()}

print(probabilities("the"))
print(probabilities("sat"))

# {'cat': 0.38, 'dog': 0.38, 'mat': 0.12, 'rug': 0.12}
# {'on': 1.0}

That output is a probability distribution. After “the”, the model considers “cat” and “dog” most likely. Now we generate text by repeatedly sampling from those probabilities:

def generate(start, length, seed):
    rng = random.Random(seed)
    words = [start]
    for _ in range(length):
        counts = follows[words[-1]]
        words.append(rng.choices(list(counts), weights=counts.values())[0])
    return " ".join(words)

print(generate("the", 6, seed=1))
print(generate("the", 6, seed=2))
print(generate("the", 6, seed=3))

# the cat . the cat saw the
# the rug . the cat . the
# the cat saw the dog . the

Notice three things. The same start can produce different text, because the choice is random. The output resembles its training data, even for sequences that never appeared in it. And it has no understanding at all, which is why “the rug . the cat” reads like nonsense.

Ask it about a word that it has never seen, and it has nothing to offer: follows["elephant"] is empty. Our toy only looks at one previous word. The enormous leap in real LLMs comes from considering long stretches of context, and learning from far more data, using a neural network rather than a simple count.

Tokens: how a model reads

LLMs do not read whole words as we do. Text is first split into tokens, which may be a word, part of a word or punctuation. Each token maps to a number, and the model works entirely with numbers.

Tokens matter in practice for two reasons. Usage of hosted models is commonly priced by tokens, and each model has a limit on how many it can handle at once. Tokenization also explains some famous odd behaviour. Because models see chunks rather than letters, tasks such as counting the letters in a word have traditionally been surprisingly hard for them.

Embeddings: meaning as numbers

Each token is turned into an embedding, a long list of numbers that places it in a kind of meaning space. Related concepts end up close together, so “cat” and “kitten” have nearby positions, while “cat” and “invoice” do not.

The same idea powers semantic search, in which you find documents by meaning rather than exact words. Our vector database guide covers that use.

Attention and the transformer

Most modern LLMs are based on the transformer architecture, introduced by Google researchers in the 2017 paper “Attention Is All You Need”. Its key mechanism is self-attention.

Consider this 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. Attention lets a model weigh every earlier token when processing each new one, so it can link “it” to the most relevant words, even when they are far apart.

Earlier approaches processed text step by step and tended to lose track of distant words. Transformers look across the context together, and they can run much of this work in parallel on specialized hardware, which made training on such large amounts of text practical.

How an LLM is trained

Stage What happens
Data collection Large amounts of text are gathered and cleaned
Pre-training The model repeatedly predicts the next token, and its parameters are nudged whenever it is wrong
Fine-tuning It learns from examples of helpful answers, with human feedback often used to rank responses
Evaluation Teams test it for quality, safety and failure cases

Pre-training gives a model broad language ability, but it may just continue your text rather than answer it. The later stages shape it into a useful assistant. Training large models takes substantial computing power and is expensive. Using a finished model, known as inference, is far cheaper per request.

How it generates text

  1. Your prompt is split into tokens and converted to embeddings.
  2. The network processes them, using attention to relate them to each other.
  3. It outputs a probability for every possible next token.
  4. One token is selected and added to the context.
  5. Steps 2 to 4 repeat until it reaches a stop condition.

This is why replies typically appear word by word when streamed. The text is literally being produced in sequence. Temperature controls how adventurous step 4 is: low values favour the most likely tokens, while higher values allow more variety.

Tip: For extraction, classification and other repeatable tasks, use a low temperature where the setting is available. For brainstorming, a higher setting can be useful. Even so, a low value does not guarantee identical answers every time.

Terms you will meet

Term Meaning
Prompt The input you give the model
Context window The maximum number of tokens it can consider at once
Parameters The internal values learned during training
Inference Running a trained model to get output
Hallucination Confident output that is false
Knowledge cutoff The point after which training data ends
RAG Fetching documents to give a model extra context
Open-weight model A model whose parameters you can download and run yourself

Limitations you should know

  • Hallucinations. A model can invent facts, citations or code functions. Because it produces likely text, false statements can look completely plausible.
  • Knowledge cutoff. Unless a product connects it to search or other tools, it may not know about recent events.
  • Limited context. If a conversation exceeds the context window, earlier details may be dropped or summarized. Models also do not automatically remember past chats, unless a product adds that feature.
  • Bias. Training data reflects human biases, and those can appear in output.
  • Inconsistency. The same question can produce different answers, which matters when you build software on top of one.
  • Security risks. Hidden instructions in text can manipulate a model, a problem known as prompt injection.

Using LLMs well

Treat an LLM as a fast, capable assistant whose work needs reviewing. A few habits make a big difference:

  • Be specific. Clear instructions, context and examples give better results. Our guide to prompt engineering shows how.
  • Supply the facts. When answers must come from your own documents, use RAG rather than relying on memory.
  • Verify what matters. Check figures, citations and legal or medical claims against reliable sources.
  • Test generated code. Run it and write tests for it, as you would for a colleague’s. Our AI code review tools guide covers some assistance.
  • Protect sensitive data. Check your organization’s rules before sharing confidential information with a hosted tool.

If you are deciding how to customize a model for your own work, our comparison of RAG vs fine-tuning vs prompt engineering will help you choose.

Final thoughts

An LLM is a next-token predictor trained at an extraordinary scale, and it is more useful and more fallible than that description suggests. Keeping the mechanism in mind helps you use it well: it is strong with language and patterns, and it needs your supervision on facts. To make it concrete, run the small script above with your own text, then try the same prompt several times in a real assistant and compare the answers.

Frequently asked questions

What is a large language model in simple terms?

It is an AI system trained on huge amounts of text to predict what comes next. By repeating that prediction, it can answer questions, write and summarize.

What is the difference between AI and an LLM?

AI is the broad field of building intelligent systems. An LLM is one specific type of AI model, focused on processing and generating language.

Do LLMs understand what they say?

This is debated. They capture rich patterns of meaning and can reason through many problems, but they do not experience the world and can fail in ways a person would not.

Why do LLMs make things up?

They generate likely text rather than retrieve verified facts. When patterns point towards a plausible but false answer, the model can state it with apparent confidence.

What is a token in an LLM?

A token is a chunk of text the model processes, such as a word, part of a word or punctuation. Limits and pricing are often measured in tokens.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →