Part I: How LLMs Work · Lesson 01
LLMs & Agents, Explained | One question at a time
For software engineers who can write code but haven’t studied machine learning.
Concrete examples, pseudocode, and data flows you can follow—so you can see how LLMs and agents actually work.
Imagine opening an AI assistant and typing:
Translate “我喜欢猫” into English.
A moment later, the answer appears:
I like cats.
The translation makes sense. But how did it get there?
- Did the model prepare the whole sentence before displaying it?
- Or, when it produced
I, had it yet to choose what came next?
In this article, we’ll use a few snippets of pseudocode to trace what happens between hitting Send and seeing a response. First, we’ll follow the overall flow. Later, we’ll look inside the model.
We’ll focus on typical autoregressive text generation: the model predicts the next token from the current context, the surrounding program selects one and appends it, and the process repeats. The name sounds more intimidating than the basic idea: keep writing from what’s already there. We’ll explain what a token is shortly.
Here’s the route we’ll follow:
In this article
- 1. The model receives a formatted conversation
- 2. Text becomes IDs: What exactly is a token?
- 3. What does one call to model() return?
- 4. Why does the output go back into the input?
- 5. When does generation stop—and how does the text appear?
- 6. Putting the whole process into code
- 7. Where do we go from here?
1. The model receives a formatted conversation
You send a sentence. The application also needs to tell the model who said it and whose turn it is to reply.
messages = [ { "role": "user", "content": "Translate “我喜欢猫” into English." } ] prompt = format_chat(messages) Here, role identifies the speaker, and content holds the message itself. format_chat() combines them using the chat format expected by the model.
Think of this as adding speaker labels and message boundaries, followed by a cue for the assistant to begin its reply. Schematically, the formatted input might look like this:
<user_message_start> Translate “我喜欢猫” into English. <user_message_end> <assistant_reply_start> Notice the last line. It doesn’t contain an answer. It marks where the assistant’s answer should begin.
format_chat()is a placeholder function for this article, and these markers are illustrative. Actual chat templates and special markers vary by model.
We’ll explore how models learn to respond to roles and instructions in Article 05. For now, remember this: the input includes conversation structure, not just the text of your message.
With the conversation formatted, the next step is to turn the text into IDs.
2. Text becomes IDs: What exactly is a token?
The conversation is ready, but the model’s core is a network that performs numerical calculations. Before text can enter that network, it needs to become a sequence of numerical IDs.
The component responsible for this is the tokenizer.
A model typically comes with a tokenizer that defines two key things:
- A vocabulary: the tokens it uses and the numerical ID assigned to each one.
- Tokenization rules: how to split a piece of text into those tokens.
So what is a token?
Think of tokens as the tokenizer’s building blocks for text. A token might be a character, part of a word, or a longer sequence of characters. Spaces and punctuation can be part of a token, too. A token is not necessarily a “word” in the everyday sense.
Suppose our tokenizer has the following vocabulary entries. We’ll keep the Chinese text in these examples so you can follow the same pieces through the diagrams: 我 means “I,” 喜欢 means “like,” 猫 means “cat,” and 狗 means “dog.”
| Token (text fragment) | Token ID |
|---|---|
| 我 | 12 |
| 喜欢 | 357 |
| 猫 | 89 |
| 狗 | 90 |
| 。 | 9 |
This is an excerpt from an invented vocabulary, used only to illustrate the idea.
Rearrange and reuse those same building blocks, and you get different sentences:
我喜欢猫。 → [12, 357, 89, 9] # I like cats. 猫喜欢我。 → [89, 357, 12, 9] # Cats like me. 我喜欢狗。 → [12, 357, 90, 9] # I like dogs. A finite vocabulary does not limit the model to a fixed list of sentences. A finite alphabet can form an enormous variety of words and sentences; tokens work in a similar way.
The tokenizer doesn’t need to register every sentence you might ever write. What happens when it encounters a word that isn’t in its vocabulary? It can usually split it into smaller units. Many tokenizers can fall back to basic units such as bytes, allowing unfamiliar names and made-up words to be represented without assigning them new IDs on the fly.
To make the conversion concrete, here is our translation request written entirely in Chinese:
请把“我喜欢猫”翻译成英文。 This means “Translate ‘我喜欢猫’ into English.” In practice, the tokenizer encodes the full formatted conversation from Section 1, including any role and message-boundary markers. We’re showing only the message body here to make the steps easier to see.
Using an invented split and invented IDs:
Text fragments: ["请", "把", "“", "我", "喜欢", "猫", "”", "翻译", "成", "英文", "。"] Token IDs: [7, 18, 23, 12, 357, 89, 24, 502, 31, 608, 9] That is encoding:
# Split the text into tokens and return their IDs. prompt_ids = tokenizer.encode(prompt) The tokenizer can also convert a sequence of IDs back into text:
text = tokenizer.decode(token_ids) Encoding turns text into IDs the model can accept; decoding turns generated IDs back into text we can read. Whether decoding reproduces the original input byte for byte depends on details such as whether the tokenizer normalizes the text.
Two details are worth keeping in mind:
- An ID is just an identifier. In this vocabulary,
89identifies 猫. It isn’t a score for “cat,” and neighboring IDs don’t imply similar meanings. - The split and the IDs depend on the tokenizer. Another tokenizer might give 猫 a different ID or split the entire sentence differently. Different models can also share the same tokenizer.
We now have a list of integers. It’s time to pass them to model().
3. What does one call to model() return?
We’ve converted the input into token IDs. Now the model finally enters the picture.
To keep the focus on generation, we’ll treat model() as a simple interface: pass in the current context as token IDs, and get back a score for every token in the vocabulary as a possible next token.
For this article, model() is a teaching wrapper that returns only the scores used to predict the next token, from the final input position.
On the first step, no answer has been generated yet, so the current context is just our prepared input:
context_ids = prompt_ids scores = model(context_ids) For the request “Translate ‘我喜欢猫’ into English,” the scores might look like this:
| Candidate token | Score |
|---|---|
I | 5.2 |
The | 3.1 |
Hello | 0.4 |
| … | … |
These fragments and scores are illustrative. The actual output contains a score for every token in the vocabulary; only a few are shown here. The diagram above uses a separate, three-candidate toy example with scores of 3, 2, and 1 to make the probability conversion visible.
Notice what model() has returned: a scorecard for the next token, not a finished essay. A higher score means the model favors that token more strongly in the current context.
Scoring the candidates doesn’t select one, though. The program still has two jobs to do:
# Convert candidate scores into probabilities. probabilities = softmax(scores) # Choose the next token ID using a selection strategy. next_token_id = select_token(probabilities) softmax() is a fixed mathematical transformation that turns the scores into probabilities that sum to 1. We can leave the formula for another day. Here, its job is simply “scores in, probabilities out.”
select_token() makes the actual choice. It might pick the most probable token, or it might sample according to the probabilities. Sampling isn’t a blind guess: a more probable candidate is more likely to be picked, but it isn’t guaranteed to win every time.
Put those steps together:
# First step: no answer prefix yet, so use the original input. context_ids = prompt_ids # Score the candidates for the next token. scores = model(context_ids) # Convert the scores into probabilities. probabilities = softmax(scores) # Select one token ID. next_token_id = select_token(probabilities) The division of labor is straightforward:
model()scores the candidates.softmax()converts the scores into probabilities.select_token()picks one.
Why does the model assign these particular scores? That’s the black box we’ll open in the next article. For now, the important point is that we’re using a model that has already been trained.
Training adjusts the model’s parameters so it gets better at predicting what comes next. Using those parameters to compute an output is called inference. In machine learning, “inference” doesn’t necessarily mean complex logical reasoning—translating a short sentence counts, too. Ordinary inference generally does not update the model’s parameters.
Suppose we select the token ID for I. We’ve got the first building block of the answer.
But what comes after I? To keep going, we need to feed that new token back into the process.
4. Why does the output go back into the input?
We’ve selected our first token: I. It’s a start, but hardly a complete translation.
The program records that token ID as part of the answer, then calls the model again with the text generated so far included in the context:
# Add the selected ID to the answer. answer_ids.append(next_token_id) # Next step's context = original input + answer generated so far. context_ids = prompt_ids + answer_ids Here, + means list concatenation, not arithmetic on the IDs. The original input stays the same; the growing answer is appended to it.
Why feed the model its own output?
Because the next step needs to know: “You’ve already written I. Continue from there.”
In this simplified program, which has no other state, passing in the same original input every time would be like repeatedly asking, “How should this answer begin?” If we also always picked the highest-scoring candidate, we’d get the same opening over and over. Excellent practice at starting a sentence. Not much progress toward finishing one.
Here’s how the answer grows:
| Step | Answer before this step | Text fragment selected |
|---|---|---|
| 1 | Empty | "I" |
| 2 | "I" | " like" |
| 3 | "I like" | " cats" |
| 4 | "I like cats" | "." |
The table shows text for readability; the program stores token IDs. These token boundaries are assumed for teaching purposes. The leading spaces in " like" and " cats" are part of the example tokens.
The original input is still present at every step. What changes is the answer prefix—the part already written. Together, they form the current context used to predict the next token.
For example, after generating I like:
Original request: Translate “我喜欢猫” into English. Answer so far: I like ↓ Score candidates and select ↓ Selected fragment: " cats" One more ID is added to answer_ids, and the answer grows from I like to I like cats. Then the loop runs again, until a stopping condition is met.
You might be wondering: if the model generates such a small piece at a time, doesn’t it lose track of the whole sentence?
The distinction is this: a small output step does not mean a small context. We select only one token at a time, but the original instructions and everything written so far are both available in the current context.
Having access to context doesn’t guarantee the model will use it correctly, of course. Nor does it guarantee a correct answer. We’ll explore those limitations in Part II.
Our generation loop is now connected: select a token, append it, and predict the next one using the updated context. But it can’t go on forever. How does it stop, and how do those IDs become text on the screen?
5. When does generation stop—and how does the text appear?
The answer is growing one token at a time. How does the program know when to call it a day?
Chat models typically use special markers to signal the end of a response. In our simplified code, selecting the end token causes the program to leave the loop:
if next_token_id == end_token_id: break The end marker is meant for the program. It usually isn’t shown to the user as part of the answer.
The program can also enforce a maximum generation length or other stopping conditions. So generation may stop because the model signals that it is done, or because the program’s limit has been reached. Stopping doesn’t prove the answer is complete, and it certainly isn’t a correctness check.
Next, the generated IDs need to become text. That’s where decode(), which we met earlier, comes in:
answer = tokenizer.decode(answer_ids) To keep our example simple, we’ll wait for generation to finish, then decode and display the answer all at once.
But AI assistants often show their answers a little at a time. How does that fit?
The model generates; the application displays. Those are separate jobs.
The application can wait for the complete answer, or it can receive, decode, and display the output incrementally. The latter is usually called streaming: users can begin reading before the whole response is finished.
The model generates tokens ↓ The application receives and decodes them ↓ The interface displays text in chunks Network delivery, buffering, and rendering all affect when the screen updates. One visible update doesn’t necessarily correspond to one token—or even one character. Some tokens represent byte fragments that need to be combined before they form a complete character.
So don’t use the screen’s refresh rhythm as a token counter. Token-by-token generation describes the generation mechanism. Incremental display describes what the user sees.
We now have the main pieces, from receiving a message to showing an answer. Let’s put them together.
6. Putting the whole process into code
We’ve taken apart the steps between hitting Send and seeing a response. Time to put them back together.
First, follow the complete flow:
Now the pseudocode. Every line should connect to something we’ve already covered:
# 1. Format the conversation with roles and message boundaries. messages = [ { "role": "user", "content": "Translate “我喜欢猫” into English." } ] prompt = format_chat(messages) # 2. Convert the formatted input into token IDs. prompt_ids = tokenizer.encode(prompt) # Track only the answer generated in this response. answer_ids = [] for _ in range(max_new_tokens): # 3. Current context = original input + answer so far. context_ids = prompt_ids + answer_ids # 4. Score the candidates and select the next token. scores = model(context_ids) probabilities = softmax(scores) next_token_id = select_token(probabilities) # 5. Stop if the selected token is the end marker. if next_token_id == end_token_id: break # Otherwise, record the token and continue. answer_ids.append(next_token_id) # 6. Decode the answer's IDs into text and display it. answer = tokenizer.decode(answer_ids) display(answer) This pseudocode illustrates the logical flow.
model()wraps an already-trained model and returns only the scores used to predict the next token.max_new_tokenslimits the number of generation steps;end_token_idis the end marker used in this example. We’ve omitted inference optimizations such as caching and chosen to display the answer only after generation finishes.
A complete answer doesn’t simply fall out of a single call to model(). The model scores possible next tokens using the current context. The surrounding program selects a token, appends it, checks whether to stop, and ultimately displays the result.
That leaves one very important function still waiting to be opened up:
scores = model(context_ids) A list of integers goes in. Candidate scores come out. What happens in between?
In the next article, we’ll step inside model(): how token IDs become vectors, how those vectors incorporate context, and how the result becomes scores for the next token. We’ve traced the outer loop. Next, we’ll look at the machinery inside it.
7. Where do we go from here?
In this article, we followed a message all the way through to a generated answer. Some of the most interesting work is still hidden inside model(). That’s where we’re headed next.
Why am I writing this series?
Because I’ve been that engineer: plenty of experience shipping software, using AI every day, yet struggling to explain what actually happens under the hood. Try to learn the basics and you immediately meet a wall of terminology—tokens, embeddings, attention, Transformers. I came looking for an explanation and got handed a glossary.
So I’m approaching these questions as a working software engineer without a machine learning background. We’ll start with the input, follow the data, and see how the output is produced. When a detail is essential to understanding the mechanism, we’ll dig deeper. Along the way, we’ll distinguish what needs a high-level mental model from what deserves a closer look.
The series is currently planned in three parts:
| Part | Focus | Where we’re headed |
|---|---|---|
| Part I · How LLMs Work | The mechanics behind a response | From using AI to understanding how it works |
| Part II · Why LLMs Behave This Way | Why they work well sometimes—and fail at others | From understanding the principles to getting better results |
| Part III · Connecting LLMs to Real-World Applications | Putting models to work in actual products and workflows | From a working demo to a dependable system |
You’re at Lesson 01 of Part I. The rest of Part I will cover the model’s internals, memory, where its knowledge comes from, and how it learns to answer, translate, or continue text according to instructions. The specific lessons in Parts II and III will take shape as the learning and practical work progress.
I’ll learn, check, and write as I go. I’m not waiting until I know everything to start—otherwise, this series might never get past an empty project folder.
But learning in public doesn’t mean presenting guesses as facts. I’ll check the key claims and make the limits of teaching simplifications explicit. This series is both my learning notebook and something I hope others can learn from. If you spot an error, a skipped step, or a passage where every word makes sense but the explanation still doesn’t, please say so. Let’s work out how to explain it better.
Next up: inside model(), following what happens to that list of token IDs.
Explore the bilingual series on GitHub, or read the Simplified Chinese edition.













