How Do Large Language Models (LLMs) Work?

Most modern generative large language models produce text by predicting the next token from the context they receive, using patterns learned during training. They turn text into numbers, process those numbers through layers of a neural network, and repeatedly select a likely next piece of text. The response is constructed one token at a time—not necessarily looked up in a database. Understanding that process explains why prompts matter, why answers can vary, and why fluent responses can still be wrong.
What Is a Large Language Model (LLM)?#
A large language model, or LLM, is a machine-learning model trained to process and generate language. Its architecture—the design of its neural network—and its learned numerical values, called parameters or weights, work together to recognize patterns in text and produce useful outputs. LLMs commonly work with natural language and code; some newer systems can also process images, audio, or other kinds of input.
“Large” usually refers to the scale of a model’s parameters, training data, and computing resources. There is no single parameter count that universally defines an LLM. Nor does a larger model automatically perform every task better: training, architecture, data quality, post-training, and the task itself all matter.
The LLM meaning also depends on distinguishing the model from the product around it. A model is the component that processes input and generates output. A chatbot or AI application may use an LLM alongside an interface, system instructions, search, file handling, memory features, or other tools. The model alone is not the whole product.
GPT-family, Claude, Gemini, and Llama are examples of model families. A family name is not the same thing as a particular chat application or a specific model version. And although LLMs are a major part of generative AI, not all generative AI is language modeling: systems for creating images, music, or video may use other model architectures.
How Do Large Language Models Work? Step by Step#

To understand how large language models work, follow one short prompt through a typical autoregressive Transformer-based text generator:
Text prompt | |||||||||||||||||
↓ | |||||||||||||||||
Token IDs | |||||||||||||||||
↓ | |||||||||||||||||
Embeddings + position information | |||||||||||||||||
↓ | |||||||||||||||||
Transformer layers | |||||||||||||||||
↓ | |||||||||||||||||
Next-token scores | |||||||||||||||||
↓ | |||||||||||||||||
Decoding selects a token | |||||||||||||||||
↓ | |||||||||||||||||
Append it to the context and repeat | |||||||||||||||||
↓ | |||||||||||||||||
Returned text | |||||||||||||||||
The example throughout this section is “The capital of France is”. The model processes the supplied text, estimates possible continuations, selects one according to its decoding settings, and then uses the expanded text to predict again.
Large language models are an important part of generative AI, but not all generative AI systems are language models. To understand the broader technology, explore our beginner's guide to generative AI and how it creates text, images, audio, and other content.
Step 1: Tokenization — Turning Text Into Numbers#
A model does not normally process a sentence as a person sees it on screen. First, a tokenizer splits text into units called tokens and maps each unit to a numerical ID. A token might be a whole word, a common part of a word, punctuation, or a unit that includes whitespace. Token boundaries depend on the tokenizer’s vocabulary and rules.
For example, a tokenizer inspection of “The capital of France is” can be made with OpenAI’s Tokenizer tool. Depending on the encoding, the display may split it into pieces resembling The, capital, of, France, and is. This is a token-piece illustration, not a universal segmentation: use the named model’s tokenizer to confirm exact pieces and IDs before publishing them as a measured result.
Token count is not the same as word count. A familiar English phrase may use relatively few tokens, while an unusual name, a less common language, or a piece of code may split into more. That is why there is no fixed “words per token” conversion that works for every model and text. Tokenization can affect how much content fits in a request, how long processing takes, and—in paid API use—how usage is counted.
Step 2: Embeddings and Position Information#
After tokenization, each token ID is mapped to a learned embedding: a list of numerical values the model can process. An embedding is not a dictionary definition or a static label saying what a word means. It is a representation that helps the network work with patterns learned during training.
The model also needs information about order. “The dog chased the cat” and “The cat chased the dog” contain similar words but different relationships. Transformer architectures therefore incorporate position information in some form. Methods vary: position may be represented through added signals or through other position-aware calculations.
At this early stage, the representation of “capital” is not yet a complete interpretation of the word in the sentence. As tokens pass through the model’s layers, their representations are transformed using context from other positions. The result can reflect the role a token plays in this particular input.
Step 3: Transformer Layers and Self-Attention#

Many modern text-generation LLMs use Transformer architecture. Within its layers, self-attention lets the model calculate how token positions relate to one another, while feed-forward networks transform the resulting representations. The learned parameters determine how those operations behave.
Consider: “The trophy did not fit in the suitcase because it was too large.” To produce a useful continuation, a model has to process relationships among the words, including what “it” might refer to. Attention provides a way to combine information from different positions in the input. It is not a hand-written grammar rule, and we should not claim that the model “looked at” a particular word in exactly the way a person would without measuring its internal behavior.
In our running example, “The capital of France is,” the preceding tokens provide context for the next-token prediction. A token’s representation after several Transformer layers can differ from its initial embedding because the network has processed the surrounding sequence.
Step 4: Predicting the Next Token#
At the end of processing the current context, the model produces a score—often called a logit—for each token in its vocabulary. A decoding process converts or uses those scores to select a continuation. Depending on the settings, it may choose a high-scoring token directly or sample from a distribution of candidates.
Here is a teaching-only illustration for the prompt “The capital of France is”:
Illustrative next-token candidate Toy probability#
Paris 0.80
Lyon 0.07
the 0.05
Other candidates combined 0.08
These are invented values, not results from a real model. They also do not mean the model is “80% confident that Paris is factually correct.” The values illustrate how a generation system can rank possible continuations in context. Token likelihood and the truth of a complete statement are different things.
Worked example: from prompt to response#
Here is the full process, using the same phrase:
- Input: The application sends “The capital of France is” as the current text context.
- Tokenization: A model-specific tokenizer converts the phrase into token pieces and IDs. Exact boundaries depend on the tokenizer.
- Context processing: Embeddings and position information are processed through Transformer layers.
- Next-token scores: The model assigns scores across candidate tokens. In our invented example, Paris is the leading candidate.
- Decoding: A decoding strategy selects Paris as the next token.
- Repeat: The expanded context becomes “The capital of France is Paris.” The model can predict another token, such as punctuation, or stop.
This trace explains how do LLMs work at a high level: process context, score possible next tokens, choose one, and repeat. A real generation may include more complex instructions, conversation history, output constraints, or tool results. Those additions change the context the model receives; they do not normally retrain its weights.
Step 5: Generating a Response One Token at a Time#
For ordinary autoregressive generation, the model predicts a token, appends it to the current context, and predicts again. This loop continues until a stop condition is reached— for example, a special end-of-turn token, an application instruction to stop, or a configured output limit.
Many services can stream the response, showing pieces as they are generated instead of waiting for the full answer. Under the hood, implementations use optimizations to reduce repeated work, but standard autoregressive generation still depends on previously generated tokens: the next token is conditioned on the context that came before it. By contrast, processing the prompt itself can often be parallelized across positions.
What Is the Transformer Architecture in LLMs?#
The Transformer is a neural-network architecture introduced in the 2017 research paper “Attention Is All You Need” by Ashish Vaswani and co-authors. It was first presented for sequence-to-sequence machine translation. Transformer-based designs were later adapted for many language tasks, including text generation. Google’s machine-learning course offers an accessible overview of LLMs and Transformers.
A Transformer layer commonly combines attention with a feed-forward network. Attention exchanges contextual information across token positions; feed-forward layers apply learned transformations to the representations. Residual connections provide paths that help information flow through a deep network, while normalization helps keep intermediate values manageable during training and processing.
Together, these components allow the model to transform an initial sequence of token representations into context-sensitive representations that are useful for its training objective. The architecture is a design, not a complete explanation of an individual model’s behavior: learned weights, training data, objectives, and post-training shape the results too.
Self-attention and contextual meaning#
The word “bank” can refer to the edge of a river or a financial institution. In “We sat by the river bank,” the surrounding words differ from those in “She opened a bank account.” The model’s representations can incorporate surrounding context, helping it generate a continuation that fits the sentence.
In a standard causal next-token setup, a causal attention mask prevents a position from using future tokens that have not yet been generated. This fits the task of predicting what comes next. Encoder models trained with masked-token objectives behave differently: they may use surrounding words on both sides of a masked position.
Encoder, decoder, and encoder–decoder models#
LLMs do not all use the same Transformer layout. The table below gives common patterns, not a complete taxonomy:
Architecture Illustrative objective or Common task patterns example Encoder-only Masked-token prediction; BERT Representations, classification, extraction Decoder-only Causal next-token prediction; Text generation, code, GPT-style models conversational applications Encoder– Conditioned sequence Translation, summarization, decoder generation; T5 sequence transformation
The architecture and training objective are related, but they do not dictate every possible deployment. For an accessible treatment of Transformer task types, see the Hugging Face course.
How Are Large Language Models Trained?#
An LLM is not typically built by writing a dictionary of answers. Its weights are learned through training: the model processes examples, makes predictions, measures how those predictions compare with training targets, and adjusts numerical parameters to reduce a loss over time.
Pretraining: learning patterns from large datasets#
Before training, data may be selected, filtered, deduplicated, tokenized, and divided into training and evaluation sets. The exact data and preparation choices vary by provider. It is not safe to assume that all models use the same sources, quantities, or filtering methods.
For a causal language-model objective, a sequence can supply its own prediction targets. Consider “The cat sat on the” followed by the target token “ mat”. The model predicts a continuation; a loss function measures how its prediction compares with the training target. An optimization process then adjusts its weights. Repeated across many examples and training steps, this process teaches the model patterns that help it predict sequences.
The resulting parameters can encode statistical regularities, associations, and other learned patterns. Training is not simply a searchable index of the documents used to create the model. But the opposite claim—that a model can never memorize training material— would also be too strong. Models may reproduce portions of training data in some circumstances, which is one reason data handling and privacy deserve care.
Not every language model uses the same training objective. A causal model learns to predict future tokens from prior context; a masked-language model may learn to predict tokens hidden within a sequence. The objective shapes what the model learns to do.
Fine-tuning and post-training#
A pretrained model can be adapted after pretraining. Supervised instruction tuning uses examples of instructions and desired responses to encourage the model to follow requests in a more useful format. Other post-training methods may use preference data or feedback to shift which answers the model favors.
Reinforcement learning from human feedback (RLHF) is one approach, not a universal recipe. The 2022 paper “Training language models to follow instructions with human feedback” describes InstructGPT as a historical example of instruction tuning and preference-based training. Providers use different combinations of data, techniques, and evaluation processes.
This helps explain why a base model and an assistant-style product can behave differently. A base model may continue text in a broad range of ways; post-training can make a model more likely to interpret a prompt as an instruction and return a conversational answer. That does not mean every assistant has the same training pipeline or behavior.
What makes an LLM large?#
Parameter count is one measure, but size alone does not explain capability. Results depend on parameters, data, compute, architecture, training methods, and the match between the model and a particular task. A more capable model for one use case may not be the most suitable choice for another.
Some designs, including mixture-of-experts models, route a token through selected parts of a larger model rather than activating every parameter for every token. Details vary.
Unless a provider has disclosed a figure and its meaning, avoid treating rumored parameter counts as verified or directly comparable.
LLM Training vs. Inference: What Is the Difference?#
Training changes the model’s weights. Inference uses the trained weights to process a request and produce an output. For most user-facing interactions, inference does not update those weights.
Dimension Training Inference#
Goal Learn or adapt model weights Produce output using learned weights Inputs Training examples and targets Request context and generated tokens Weights Normally updated Normally unchanged
Computation Optimization across many Forward computation and decoding examples User impact Shapes capabilities and Affects response time, usage, and limitations output
If you correct an answer or add context in the same conversation, the model can respond differently because it is given a different context. That is not the same as changing its underlying weights. Separately, an application or provider may have data-retention or training policies; these are product-specific and should be checked in the relevant privacy documentation.
What Are Context Windows and LLM Memory?#
An LLM’s context window is the amount of tokenized information the model can process for a request or conversation, subject to the model and product’s limits. It can include system instructions, user messages, prior turns, retrieved passages, and the response being generated. The precise limit and how input and output share it vary by model.
A long context window can make more material available, but it does not guarantee that every detail will be recalled accurately. The model still has to process and use the supplied information. Output limits may be separate from—or constrained alongside—the input context budget, depending on the system.
Understanding how LLMs work is only the first step. In practice, different models offer different trade-offs in speed, accuracy, cost, and context handling. Our guide on how to choose the right AI model explains how to evaluate these differences for real-world tasks.
Context window vs. long-term memory#
Context is what the model receives for a particular inference. Long-term memory is an application-level feature: a product may save information, retrieve it later, or provide none of the earlier conversation when a new chat begins. The model does not inherently have access to every past conversation. It can only use information included in the current context or made available through tools and product features.
For example, if someone starts a new chat, an application might send no history. Another application might retrieve a saved preference and include it in the request. In both cases, the model responds to the context supplied at that time. Do not infer memory or retention behavior across all products.
How tokens affect cost, speed, and output limits#
A request may count input tokens and output tokens separately. Some APIs also distinguish cached or reasoning-related token categories. The definitions and billing rules vary, so check the current documentation for the provider and model you use.
Here is a hypothetical calculation, not a live UltraGPT price quote:
- 2,000 input tokens at $2 per million: $0.004
- 500 output tokens at $8 per million: $0.004
- Total: $0.008, before any additional fees
Longer inputs and outputs can affect processing time and usage charges. To estimate a real request, use the provider’s current rate card and the model’s applicable token categories and limits.
Why Do LLMs Give Different Answers to the Same Prompt?#
The same visible prompt can produce different answers because generation settings may vary, and even small context differences can matter. Responses can also differ across models because their weights, training, post-training, system instructions, and available tools are not identical. A product may add instructions or retrieved information that are not visible in the user’s prompt.
Temperature and sampling explained#
A temperature setting can change how sharply the model favors higher-scoring candidates during sampling. Lower temperature generally makes selection more concentrated; higher temperature can allow a wider range of continuations. Top-p sampling limits selection to a set of candidates whose cumulative probability reaches a chosen threshold. Not every product exposes these controls, and their exact effects depend on the implementation.
Imagine asking, “Write a tagline for a reusable bottle.” A setting that favors more predictable continuations may produce a straightforward line; a more varied sampling setup may return more unusual options. Neither setting guarantees factual accuracy.
Lower randomness is not the same as better evidence, and temperature zero does not guarantee identical outputs across every system or run.
For a fair comparison, use the same prompt and context, keep settings equivalent where possible, and note when a product does not offer a particular control.
What Can Large Language Models Do?#
LLMs can help draft, explain, classify, summarize, transform, or extract information from language and code. Their usefulness depends on the task, the context provided, and how the result is checked.
Reader or role Useful behavior How to verify#
Student Explain a concept at different Check a textbook or instructor’s levels sources Developer Draft a function or explain a bug Review the code and run tests
Business owner Group themes in customer Compare themes with original feedback records Writer or Draft copy to match a style or Check facts, tone, and brand rules marketer constraint Analyst Summarize supplied documents Inspect source passages and calculations
For work that depends on evidence, provide source material and ask the model to distinguish what the text states from what it does not. For code or calculations, use appropriate tests or tools rather than relying only on a fluent explanation.
Why Do Large Language Models Hallucinate?#
A model can produce a polished answer without having verified that its claims are true. Its generation objective is about producing a plausible sequence in context; that objective does not itself guarantee factual correctness. The term hallucination is commonly used for unsupported or false generated content, including invented citations, incorrect calculations, and details that were not in the supplied source.
Risk can increase when a request is ambiguous, relevant information is missing, a topic is unfamiliar, or an external search or retrieval step fails. A model may fill gaps with a plausible continuation rather than clearly identifying what it does not know. NIST’s Generative AI Profile discusses risks associated with generative AI, including confabulation.
How to improve the reliability of LLM responses#
- Provide authoritative source material. Ask the model to quote or point to evidence, and to say “Not stated” when the answer is absent. Check the original source, not just a generated citation.
- Use the right tool for the task. A calculator, database query, or code test is often more reliable for deterministic work than asking a language model to do it unaided.
- Treat retrieval and tools as helpful, not infallible. Retrieval-augmented generation (RAG) can add relevant external passages to the context; tool use can let an application search, calculate, or execute an operation. These methods can fail, and neither automatically retrains the model.
- Review consequential outputs. For decisions with significant effects, use appropriate human review and independent evidence. Agreement among multiple models is not, by itself, proof.
A practical prompt for source-grounded work is: “Answer using only the reference paragraph below. Quote the phrase supporting each answer. If the answer is absent, say ‘Not stated.’” This makes the evidence requirement explicit, though the response still needs checking.
LLM vs. Chatbot vs. Generative AI: What Is the Difference?#
These terms refer to different parts of the AI landscape:
Term Meaning Example role#
Generative A broad category of systems that create Text, image, or audio generation AI content LLM A model designed for language-related Generating text or code tasks AI chatbot An application or interface for A chat assistant using an LLM conversation LLM API A programmatic way to send requests An application sends messages to a deployed model and receives output AI A service that provides access to Compare models through one aggregator multiple AI models or providers access layer
An LLM can power a chatbot, but it is not the chatbot interface itself. The surrounding application may supply conversation logic, tools, and other features. An AI aggregator may offer a common way to try different models, while the models themselves remain distinct.
How Do LLM APIs Work?#
An LLM API lets software send a request to a model service and receive a response. In a typical workflow, an application assembles a request, sends it to an API endpoint, and receives generated output from the selected hosted model. An API is an access mechanism—not a different learning algorithm.
A request commonly involves authentication, a model identifier, messages or other input, and generation settings that the service supports. A robust application also handles usage information, timeouts, errors, and response parsing. Exact fields and model IDs are provider-specific and can change; check the provider’s current documentation before building against them.
What happens when an app sends a prompt?#

The application may combine system instructions, the current message, conversation history, retrieved context, and a requested output format into one request. The model processes the resulting context and returns text or, where supported, structured data. If the application uses a tool, it may send the tool’s result back to the model for a follow-up response.
Conceptual pseudocode:
POST [provider's documented chat endpoint] | ||||||||||
Authorization: Bearer [API key stored securely on the server] | ||||||||||
Content-Type: application/json | ||||||||||
{ | ||||||||||
"model": "[verified model ID]", | ||||||||||
"messages": [ | ||||||||||
{ | ||||||||||
"role": "user", | ||||||||||
"content": "Explain tokens in two sentences." | ||||||||||
} | ||||||||||
] | ||||||||||
} | ||||||||||
Keep API keys on the server or in an appropriate secrets manager; do not expose them in public code or a browser-based client. Before using UltraGPT or another provider in production, confirm its current endpoint, supported request fields, model identifiers, limits, and pricing in the UltraGPT developer documentation.
How to Compare and Use Multiple LLMs With UltraGPT#
Different models can respond differently because their weights, instruction-following behavior, context limits, and available tools vary. A shared access layer can make it easier to try alternatives, but a useful comparison still depends on testing models against the same task and checking the outputs. Verify which models and features are currently available in the product before relying on them.
A simple comparison process:
- Choose two or three models available in your account or API.
- Give each model the same task and source material.
- Keep generation settings equivalent where supported, and record settings that are unavailable.
- Check factual accuracy, missing evidence, format compliance, and—if measured— latency and usage.
- For disagreements, consult independent evidence instead of choosing the answer that sounds most confident.
For example, provide this fictional reference: “The Atlas store closes at 18:00 on weekdays and 15:00 on Saturdays. Sunday hours are not listed.” Ask each model, “What time does the store close on Sunday?” A useful evaluation checks whether the model says the hours are not stated, rather than inventing a time. This is a reader exercise, not a benchmark or a claim about any model’s performance.
Explore how different language models respond to the same prompt with UltraGPT, or review the developer API documentation to see how API access may fit your workflow. Confirm current model availability, limits, and terms before integrating a service.
Reference
Frequently asked questions
What does LLM stand for?
LLM stands for large language model. It is a machine-learning model trained to process and generate language, using learned numerical parameters to produce outputs from the context it receives. “Large” describes scale broadly; there is no single parameter threshold that defines every LLM.
How does an LLM generate text?
An LLM converts input into tokens, processes the context, and calculates scores for possible next tokens. A decoding method selects a token, which is added to the context. The model repeats this process until it reaches a stopping condition or output limit.
How are LLMs trained?
Training typically involves preparing data, making predictions against a learning objective, measuring errors with a loss function, and adjusting model weights. Some models are then fine-tuned or otherwise post-trained to improve instruction following or other behaviors. The exact data and training recipe vary.
What is a token in an LLM?
A token is a unit of text as defined by a particular tokenizer. It may be a whole word, part of a word, punctuation, or a piece that includes whitespace. Token boundaries are model-specific, so a token is not always the same thing as a word.
What is a Transformer in an LLM?
A Transformer is a neural-network architecture that processes sequences using components such as attention and feed-forward layers. Many modern LLMs use Transformer-based designs, but their architecture details and training objectives can differ.
Are LLMs just predicting the next word?
Causal text-generation models typically predict the next token, not necessarily a whole word. Other language models may use different training objectives, such as predicting masked tokens. Next-token prediction can support complex behavior, but it does not mean every LLM works in exactly the same way.
Do LLMs understand language like humans?
LLMs can perform many language tasks, but fluent output does not establish human-like understanding or consciousness. Their observable abilities should be assessed through appropriate tasks and evidence rather than assumed from conversational style alone.
Why do LLMs hallucinate?
A language model can generate a plausible continuation without verifying that it is true. Missing context, ambiguity, unfamiliar topics, and retrieval failures can contribute. Check important claims against reliable sources and tools.
Do LLMs learn from every conversation?
Inference normally uses learned weights without updating them for each reply. Whether a product stores conversations or uses data for improvement depends on that provider’s policies and settings; check the relevant privacy documentation rather than assuming a universal rule.
Do LLMs have access to the internet?
Not inherently. An application needs to provide an appropriate search or retrieval tool and make its results available to the model. Even when search is enabled, verify important claims and citations against the original sources.
Why do LLM responses vary?
Responses can vary because of sampling settings, model weights, system instructions, context, and product tools. Different models may also have different limits and post-training. Use the same inputs and comparable settings when conducting a practical comparison.
How can I access different LLMs through an API?
You can use hosted APIs from individual providers or a service that offers access to multiple models. Before choosing one, verify its current model list, endpoint, authentication requirements, limits, pricing, and data policies. Start with the provider’s official developer documentation.


