How LLMs work: tokens, context windows and temperature

You don't need the maths. You do need to know why the model forgets everything, why long chats cost more, and which temperature to use. Here is how an LLM works, explained for the Java code you will write.

A simplified chat request on a paper sheet: model qwen3.5:4b, a messages list with a system message Be brief, a user message My name is Asha, an assistant reply Hi Asha, and a user message What's my name, then max_tokens 200 and temperature 0.2. Arrows label three parts. The messages list is the context window: everything the model can see; it remembers nothing, so you send it all. max_tokens points to tokens: the unit for limits, speed and price. temperature points to how the next token is drawn, shown as a bar split into puppy 57 percent and cat 43 percent.
Fig. 1 — Three ideas from inside the model show up as fields in every request you send.

Here is a bug report you will see sooner or later: “The chatbot forgot my name.” Or this one: “Our AI bill doubled this month and nobody changed anything.” Or: “Same question, different answer every time. Is it broken?”

None of these are bugs in your Java code. They are how large language models work. Once you understand three ideas, tokens, the context window and temperature, these reports stop being mysteries, and you know exactly which line of code to change.

This is part 2 of Java for AI Engineers. It is the developer’s version of episode 2, “How an LLM actually thinks”, where we built a tiny language model and watched it predict. No maths here. Every idea ends with what it means for your code.

The one trick: predict the next token

An LLM does one thing. You give it some text, and it gives you a score for every possible next piece of text. One piece is picked, added to the end, and the whole thing runs again. Guess, add, guess, add, until it decides to stop.

In episode 2 we trained a tiny model on one sentence, “My puppy name is River. River likes Ruby.”. After training, when you type “my”, it gives “puppy” the highest chance. A real LLM is the same idea with billions of learned numbers instead of a hundred. You can play with that tiny model in the browser, and our guide to what a large language model is explains the idea in more depth.

What this means for your code:

  • The answer is written one piece at a time. That is why APIs can stream the answer, word by word, and why streaming makes a chat app feel much faster.
  • Longer answers take longer. Response time grows with the length of the output. A one-word answer comes back much faster than a page.
  • The model can stop in the middle. If it hits the length limit you set, it simply stops, even mid-sentence. More on that below.

Tokens: the unit everything is measured in

The model doesn’t read letters or words. It reads tokens: small pieces of text, each with an ID number. A common word is often one token. A rare word gets split, so “godfather” becomes “god” + “father” in GPT-4o’s tokenizer. Spaces and punctuation count too. Our guide to tokens and embeddings shows the whole journey from text to numbers.

A rough rule for English text: one token is about 4 characters, or about three-quarters of a word. So 1,000 words is roughly 1,300 tokens. Code, numbers and many non-English languages usually need more tokens for the same amount of meaning.

What this means for your code:

  • You pay per token. Cloud providers charge for input tokens (everything you send) and output tokens (everything the model writes). Output tokens usually cost more.
  • Limits are in tokens. The context window and the maximum answer length are both counted in tokens, not characters.
  • The API tells you how many you used. Every response from an OpenAI-style API includes a usage block. Log it. It is the number your bill is made from.
"usage": { "prompt_tokens": 24, "completion_tokens": 31, "total_tokens": 55 }

The context window: what the model can see

The context window is how many tokens the model can look at in one go. Everything has to fit inside it: the system instructions, the conversation so far, any documents you paste in, and the answer the model is writing.

Sizes vary a lot. Our tiny model in episode 2 could see 1 token. GPT-2 in 2019 could see 1,024. Many models today accept 128,000 tokens or more.

Now the most important fact in this whole article:

“The model remembers nothing between requests. Every call starts with an empty context window.”

The model’s weights are frozen. Talking to it doesn’t change it. So when a chat app “remembers” your name, it is the app doing the remembering: it keeps the whole conversation in a list and sends all of it on every request. In Java, that memory is literally a List<Message>. We proved this step by step, with real output, in Call a local LLM from Java.

What this means for your code:

  • “It forgot my name” means you didn’t send the history. Keep a list of messages per conversation and send it every time.
  • Every turn costs more than the last. Turn 20 resends turns 1 to 19. A long chat gets slower and more expensive with each message. This is often the reason the bill doubled.
  • The list can’t grow forever. At some point it won’t fit in the window, and the request fails or the oldest text is cut off. You need a plan: drop old turns, or summarise them.
  • Bigger isn’t always better. A huge prompt is slower and costs more, and models can miss a detail buried in the middle of a very long prompt. Send what is relevant, not everything you have.

Here is a simple way to keep a conversation under a token budget. It keeps the system message and removes the oldest question and answer together:

record Message(String role, String content) {}

// Rough rule for English: about 4 characters per token. Good enough for a budget check.
static int roughTokens(String text) {
    return (text.length() + 3) / 4;
}

static int roughTokens(List<Message> messages) {
    return messages.stream().mapToInt(m -> roughTokens(m.content())).sum();
}

// Keep the system message (index 0). Drop the oldest question and answer together
// until the history fits the budget. Always keep the latest exchange.
static void trimToBudget(List<Message> history, int budgetTokens) {
    while (history.size() > 3 && roughTokens(history) > budgetTokens) {
        history.subList(1, 3).clear();
    }
}

With a system message and 50 question-and-answer pairs (about 1,300 tokens by this estimate), a budget of 500 keeps the system message and the last 18 pairs. The estimate is rough on purpose. For exact counts, use the usage numbers the API sends back, or a tokenizer library for your model.

Temperature: how the next token is picked

When the model scores the next token, the scores are turned into chances that add up to 100%. Then one token is picked. It is not always the top one. In episode 2 we used a jar of marbles: if “puppy” has 57 marbles and “cat” has 43, you reach in and draw one. Usually you get “puppy”. Sometimes you get “cat”.

Temperature changes the jar:

  • Low temperature (near 0) gives almost all the marbles to the top token. The output becomes focused and repeatable.
  • High temperature spreads the marbles more evenly. The output becomes more varied and surprising, and more likely to go wrong.

That is why the same question can give different answers. It isn’t broken. It is drawing marbles. (A second setting, top_p, limits the draw to only the most likely tokens. Most of the time you change temperature or top_p, not both.)

What this means for your code. Pick the temperature for the job:

Job Temperature Why
Pull data out of text, classify, answer from documents 0 to 0.2 You want the same, safest answer every time.
A normal chat assistant around 0.5 to 0.8 Natural wording, still sensible.
Brainstorming names or ideas 0.9 and up You want variety.

A few practical details:

  • Ranges differ by provider. OpenAI accepts 0 to 2. Anthropic’s Claude accepts 0 to 1. Check the docs of the API you use.
  • Temperature 0 is not a promise. It makes answers much more consistent, but not always identical. Never write a test that expects the exact same sentence twice.
  • Some models don’t let you change it. Some reasoning models only accept their default temperature and return an error if you send another value. If that happens, leave the field out.

Max tokens: the length limit you set

You can cap the length of the answer, usually with a field called max_tokens. (Newer OpenAI models call it max_completion_tokens. Anthropic’s API requires it on every request.) It protects you from runaway answers and runaway costs.

When the model hits the cap, it stops right there. The response tells you why it stopped in a field like finish_reason: "stop" means it finished naturally, "length" means it ran out of room.

What this means for your code: always check why the model stopped. If you asked for JSON and got "length", the JSON is cut off and won’t parse. Either raise the limit or ask for a shorter answer. Part 4 shows a clean way to handle every kind of reply with Java’s sealed types.

Training vs inference: chatting doesn’t teach it

Training is when the weights change. It happens before release, takes weeks and costs a fortune. Inference is what happens when you send a prompt: the frozen weights are only read, and an answer comes out in seconds.

Your API calls are always inference. Nothing you send changes the model, and it doesn’t learn from your users. Its knowledge stops at its knowledge cutoff.

What this means for your code: if the model needs your facts (your products, your policies, today’s prices), you put them in the prompt. Searching your own documents and adding the relevant parts to the prompt is called RAG, and we build it later in this series.

Hallucination: likely is not the same as true

The model picks what is likely to come next, not what is true, and it always picks something. In episode 2 we trained the tiny model on “My puppy name is River. My cat name is Ruby.” Then “my puppy name is” had a 50% chance of “river” and a 50% chance of “ruby”. So it could confidently write “my puppy name is ruby”. Every single step looked reasonable. The result was wrong.

That is a hallucination: a confident answer that isn’t true.

What this means for your code: treat model output like user input. Validate it. Parse it into types and reject what doesn’t fit. Give the model the facts it needs instead of hoping it knows them. And never let it take a real action, like a refund or a payment, without your own checks.

Cheat sheet: from LLM facts to Java code

How the model works What you do in Java
Predicts one token at a time Stream long answers; expect time to grow with output length
Reads tokens, not words Log usage; set budgets and alerts in tokens
Sees only the context window Keep a List<Message> per conversation and send it every time
Window has a limit Trim or summarise old turns; send only relevant documents
Picks tokens by chance Low temperature for data jobs; never test for an exact sentence
Stops at max tokens Check finish_reason; handle "length"
Weights are frozen Put fresh facts in the prompt (RAG)
Predicts likely, not true Validate output; check before any real action

Key takeaways

  • An LLM predicts the next token, adds it and repeats. That is why answers stream and why long answers are slow.
  • Tokens are the unit for price, speed and limits. About 4 characters of English per token.
  • The model remembers nothing. Your app keeps the history and sends it on every request, so long chats cost more each turn.
  • The context window must hold the instructions, history, documents and the answer. Trim it on purpose.
  • Temperature controls randomness. Use near 0 for data jobs and higher for creative ones.
  • Check finish_reason and validate output. Likely is not the same as true.

Frequently asked questions

Why does the LLM forget what I said earlier?

Because each API request starts with an empty context window. The model only sees what is inside the current request. To keep a conversation going, your app must send the earlier messages again every time.

How many tokens is 1,000 words?

For English, roughly 1,300 tokens, using the rule of about three-quarters of a word per token. The exact number depends on the model’s tokenizer, the language and the kind of text.

What temperature should I use?

For pulling data out of text, classifying or answering from documents, use 0 to 0.2. For a general chat assistant, try around 0.5 to 0.8. For brainstorming, go higher. Check your provider’s allowed range.

Why do I get different answers to the same question?

The model picks each token by chance from its scores, so at normal temperatures two runs can choose different words. Lowering the temperature makes answers much more consistent, but not guaranteed identical.

Does the model learn from my API calls?

No. Your requests only run the model (inference); they don’t change its weights. To give it new knowledge, include the facts in the prompt.

What happens when the conversation is bigger than the context window?

Depending on the API, the request fails with an error, or the oldest text is cut off. Either way, the model can’t see it. Trim or summarise old messages before you hit the limit.

Next in the series

Previous: Why Java for AI? Where Java fits next to Python. Next: Call an LLM API from plain Java, where we send these exact fields with HttpClient, read the answer into Java records, and handle errors and streaming.

See it in action

Prefer watching? This video walks through the same ideas with live, hands-on demos.

Video thumbnail: How LLMs work: tokens, context windows and temperatureWatch on YouTube ↗

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.