Lesson 274 of 296
What an LLM is: tokens, context and calling a model
What you will learn
- What a large language model (LLM) is
- Tokens and why they matter for cost and limits
- The context window
- Messages and roles: system, user, assistant
- Temperature
- How your code calls a model, and streaming
- Keeping a chat inside the token budget
On this page
What is an LLM?
A large language model (LLM) is a program trained on a very large amount of text. Given some text, it predicts what text should come next, one small piece at a time. Chat assistants, coding assistants and many "AI features" in apps are built on LLMs.
Important facts for developers:
- The model does not look things up unless you give it the information or a tool. It answers from patterns it learned in training.
- Its knowledge stops at a training cut-off date.
- It is not deterministic by default: the same question can give different answers.
- It can be confidently wrong (Lesson 275).
As a developer you usually do not train models. You call a model through an API from a provider, or run an open-weight model on your own server.
Tokens
Models do not read letters or whole words. Text is split into tokens: small pieces such as a word, part of a word, or a punctuation mark. Providers count, limit and bill everything in tokens.
OpenAI gives these rules of thumb for English: 1 token is about 4 characters, about three quarters of a word, and 100 tokens is about 75 words. Other languages and code often use more tokens for the same meaning.
Why tokens matter:
| Thing | Why it matters |
|---|---|
| Cost | You pay per input token and per output token. Output tokens usually cost more. |
| Limits | Each model has a maximum number of tokens it can handle at once |
| Speed | More output tokens means a longer wait |
The context window
The context window is the maximum number of tokens the model can work with in one request: your instructions, the chat history, any documents you include, plus the answer it writes. If you go over it, the request fails or old text must be removed.
Common mistake: thinking the model "remembers" earlier chats. It does not. Each API call is stateless. To continue a conversation, your code sends the earlier messages again in the next request.
Messages and roles
Chat APIs take a list of messages. Each has a role:
| Role | Who writes it | Used for |
|---|---|---|
| system | You, the developer | Rules and behaviour: "You are a support assistant for an online shop. Answer in UK English." |
| user | The person using your app | Their question |
| assistant | The model | Its earlier answers, sent back so it has the history |
type Role = "system" | "user" | "assistant";
type Message = { role: Role; content: string };
const messages: Message[] = [
{ role: "system", content: "You answer questions about our shop. Be short and polite." },
{ role: "user", content: "Do you deliver to Ireland?" },
];
console.log(messages.length); // 2Temperature
Temperature controls how random the output is.
| Temperature | Result | Good for |
|---|---|---|
| Low (0 to 0.3) | More predictable, repeats the most likely answer | Extracting data, classification, code |
| Higher (0.7 and above) | More varied | Brainstorming, creative writing |
Even at 0 the output is not guaranteed to be identical every time, so never rely on that.
Calling a model from your code
Every provider's API works in a similar way:
- Your server sends an HTTPS request with the model name, the messages, and settings such as maximum output tokens and temperature.
- The provider returns the answer text plus usage: input and output token counts.
- You show the answer and record the usage for cost tracking.
Rules:
- Call the model from your server, never from the browser. The API key is a secret (Part 20).
- Set a maximum output tokens value so one request cannot run up a huge bill.
- Set a timeout and retry with backoff on rate-limit or server errors (Lesson 204).
- Log token usage per user or feature.
Streaming
Waiting 10 seconds for a full answer feels slow. With streaming, the provider sends the answer in small chunks as it is written, and your app shows the words as they arrive. Streaming does not make the model faster; it makes the wait feel shorter. It is usually sent with server-sent events (SSE): one long HTTP response that the server keeps writing to, a simpler, one-way alternative to WebSockets (Lesson 205).
Keeping a chat inside the token budget
A long chat will eventually not fit. A simple strategy: always keep the system message, then keep the newest messages that fit in the budget.
type Role = "system" | "user" | "assistant";
type Message = { role: Role; content: string };
// Rough estimate only. Use the provider's tokenizer for exact counts.
function estimateTokens(text: string): number {
return Math.ceil(text.length / 4);
}
function fitToBudget(messages: Message[], budget: number): Message[] {
const system = messages.filter((m) => m.role === "system");
const rest = messages.filter((m) => m.role !== "system");
let used = system.reduce((sum, m) => sum + estimateTokens(m.content), 0);
const kept: Message[] = [];
for (let i = rest.length - 1; i >= 0; i--) {
const cost = estimateTokens(rest[i].content);
if (used + cost > budget) break;
kept.unshift(rest[i]);
used += cost;
}
return [...system, ...kept];
}
const chat: Message[] = [
{ role: "system", content: "Be brief." },
{ role: "user", content: "a".repeat(400) },
{ role: "assistant", content: "b".repeat(400) },
{ role: "user", content: "Latest question?" },
];
console.log(fitToBudget(chat, 110).map((m) => m.role)); // [ 'system', 'assistant', 'user' ]Other strategies: summarise old messages into one short message, or store facts in a database and send only what is needed (Lesson 276).
How to say it in an interview
"An LLM predicts the next token from the text it is given. Everything is measured in tokens: cost, limits and speed. Each API call is stateless, so my server sends the system message and the relevant history every time, trimmed or summarised to fit the context window. I call models only from the server, set max output tokens, timeouts and retries, stream long answers, use low temperature for extraction, and log token usage per feature to control cost."
Key words
| Word | Meaning |
|---|---|
| LLM | A model trained on large amounts of text that predicts the next token |
| Token | A small piece of text that models count and bill |
| Context window | The maximum tokens in one request, input plus output |
| System message | The developer's instructions to the model |
| Temperature | How random the output is |
| Stateless | Each request is separate; history must be sent again |
| Streaming | Receiving the answer in chunks as it is written |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.