AI from scratch · Using LLMs · Stage 6: LLM engineering
Using LLMs
Chapter 10 built a tiny GPT that writes station names. The models behind chatbots are the same machine, trained on trillions of tokens and then taught to follow instructions. Most ML engineers never train one: they use one, as a component inside a product, through an API or as open weights on their own hardware. This lesson is that job: how a conversation becomes tokens, how to ask so the answer is useful, how to get output a program can rely on, and what each call costs. You'll practice on a real (small) open model that runs entirely in your browser.
1. A chat is one long text
An instruction-tuned model is still a next-token predictor (chapter 10). A conversation is turned into one token sequence by a chat template: each turn wrapped in special tokens that mark who's speaking, ending with the opening of the assistant's turn, so the most likely continuation is the assistant's reply. This is SmolLM2's template (the same one Qwen models use):
The system message sets the rules, user and assistant turns alternate, and the model writes until it produces <|im_end|>. It has no memory between calls: every request resends the whole conversation, which is why long chats get slower and pricier.
A chat has 20 turns. For the 21st reply, what does the model receive?
- Only the new message: it remembers the rest
- All 20 turns plus the new message, as one token sequence
- A summary of the earlier turns
A chat is serialized into one token sequence with special tokens marking each speaker, and the model continues it; nothing is remembered between calls.
2. A model in your browser
SmolLM2-135M-Instruct (Hugging Face, Apache 2.0): 135 million weights, small enough to download once (137 MB, 8-bit) and run on your device with transformers.js. It's about 1/5,000 the size of the largest models, so expect it to be confidently wrong often; that makes it a good teacher. Nothing you type leaves your browser.
Things to try: run the same prompt twice at temperature 0 (the same answer) and at 0.7 (different ones, chapter 10's sampling). At temperature 0 this small model often gets stuck repeating a sentence: greedy decoding keeps taking the single likeliest path, and a loop is a very likely path once it starts; a little temperature, or a repetition penalty, breaks it. Ask for a fact it can't know, like the station after Court Sq on the G: in our test it confidently named "the 1st Street and 2nd Street subway station". Change the system message to "Answer only in French."
An open model is a file of weights you can run yourself: here, a small one in the browser, streaming tokens you can time.
3. Prompts that work
Prompting isn't magic words; it's writing a clear task for a reader who knows a lot and nothing about your situation.
| Habit | Instead of | Write |
|---|---|---|
| Say exactly what you want | "Summarize this." | "Summarize this outage report in one sentence for riders: which station, which elevator, when it's back." |
| Separate instructions from data | Pasting the text into the middle of the request | Instructions first, then the data between clear markers (<report> … </report>) |
| Show examples (few-shot) | Describing the format in words only | Two or three input → output pairs before the real input |
| Name the format | "Give me the data." | "Answer only with JSON: {"station": …, "line": …}" |
| Allow "I don't know" | Questions that force an answer | "If the text doesn't say, answer null." |
Examples matter most for small models. In the practice notebook, SmolLM2-360M extracts the station and line from sentences like "The 7 train is delayed at Court Sq.": asked plainly, it gets both right 3 times in 10. With two worked examples placed before the question as earlier chat turns, 9 times in 10. Retrying up to three times changed neither number: retries rescue answers that don't parse, not answers that are wrong.
Why do worked examples help a model more than a description of the format?
- They make the prompt longer
- The model trains on them
- The model is a continuation machine: after two question → JSON pairs, a third JSON answer is simply the most likely continuation
Good prompts are clear task descriptions: specific, with instructions apart from data, a named format, examples, and permission to say "I don't know".
4. Output a program can trust
When code consumes the answer, "usually JSON" isn't enough. Three layers, from weakest to strongest:
- Ask for JSON in the prompt, with an example.
- Check it: parse it, check the fields and types, and if anything fails, ask again (with the error, or with a fresh sample). This needs one more piece of Python, below.
- Constrain it: hosted APIs and local servers can force the output to match a JSON schema (structured outputs; Ollama's
format=, OpenAI'sresponse_format), by masking out every next token that would break the schema. The result always parses; whether the values are right is still your job.
try and except. When a line might fail, like json.loads on text that isn't JSON, put it in a try: block; if it raises an error, Python jumps to the except block instead of stopping the program:
Never trust a model's format: parse it, check it, retry on failure, and use schema-constrained decoding where the API offers it.
Where it breaks: fluent isn't true
- Hallucination. The model produces the most likely-sounding continuation, not a looked-up fact. Ask the small model which station comes after Court Sq on the G and it answers confidently and wrongly; large models are wrong less often but just as fluently. Facts a product depends on should come from data you give the model (retrieval, next lesson) or from tools (chapter 8), and the answer should be checked against them.
- Sensitive to phrasing. Reordering the examples, changing a word, or adding a trailing space (the tokens lesson) can change answers. Measure prompts on a test set (the evaluating LLMs lesson), not on one try.
- Temperature 0 isn't fully deterministic. Hosted models batch your request with others, and the order of floating-point additions on the GPU varies (the experiments lesson), so even greedy decoding can differ between calls. Design for small variations.
- Instructions and data share one stream. Roles are just special tokens in the same sequence, so text inside the data can still read as an instruction: prompt injection (chapter 8). Markers help; they don't make it impossible.
5. Hosted APIs and open models
| Hosted API (Anthropic, OpenAI, Google…) | Open weights (Llama, Qwen, Mistral, SmolLM…) | |
|---|---|---|
| Quality | The strongest models | Close behind at the top; small ones run anywhere |
| Cost | Per token, nothing up front | Your hardware and electricity; free per call |
| Data | Leaves your machine (under the provider's terms) | Stays with you: this page runs one in your browser |
| Control | The provider can update or retire a model | Pinned forever; you can fine-tune it (the LoRA lesson) |
The code is short either way. A hosted call with Anthropic's Python SDK, and the same request to a local open model through Ollama's OpenAI-compatible endpoint:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=200,
system="You are a concise assistant.",
messages=[{"role": "user", "content": "Name three boroughs of New York City."}])
print(msg.content[0].text, msg.usage.input_tokens, msg.usage.output_tokens)
from openai import OpenAI
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # Ollama on your machine
r = local.chat.completions.create(model="qwen2.5:0.5b", messages=[{"role": "user", "content": "Name three boroughs of New York City."}])
print(r.choices[0].message.content)
Keep API keys on a server, never in a web page (this site's keys live in a server-side .env, chapter 8).
Hosted APIs give the strongest models per token; open weights give control, privacy and a fixed version; the calling code is a few lines either way.
6. Cost and latency
Both are counted in tokens. A request costs
\[ \text{cost} = n_{\text{in}} \cdot p_{\text{in}} + n_{\text{out}} \cdot p_{\text{out}} \]
with prices per million tokens, output usually several times dearer than input. Latency has two parts: time to first token (reading the whole prompt) and then a steady rate of output tokens per second, the playground's readout. A 2,000-token prompt with a 300-token answer at 50 tokens a second takes about 6 seconds of writing however fast the first token arrives.
Prices (illustrative): \$3 per million input tokens, \$15 per million output tokens. A support bot answers 1,000 questions a day, each with a 400-token prompt and a 30-token reply. What does a day cost, in dollars?
Cost is tokens in and out times their prices; latency is the time to read the prompt, then a steady pace per output token.
Why output tokens are slower and dearer than input tokens
- Reading the prompt (the prefill) processes all its tokens in one pass: big matrix products over many positions at once, the compute-bound work GPUs are fast at (the GPUs lesson).
- Writing the answer (the decode) is one token at a time: each new token needs the previous one, so each step is a product with a single vector.
- Every decode step still reads all the model's weights from memory: 14 GB for a 7B model in float16, for one token's worth of arithmetic. That's memory-bound work, the GPU's cores mostly waiting.
- So a GPU produces far fewer output tokens per second than it reads input tokens, and providers price output higher. Batching many users' decode steps together reuses each weight fetch for many tokens, which is how serving gets affordable (stage 7).
- It also explains a practical rule: asking for a shorter answer saves more time than shortening the prompt.
7. What to carry forward
- A chat is a templated token sequence; the model is stateless and rereads everything each call.
- Prompt like a task spec: specific, instructions apart from data, a named format, examples, room for "I don't know".
- Parse, validate and retry structured output; constrain it with schemas where possible.
- Fluent isn't true: ground facts in data or tools, and check.
- Hosted for strength, open weights for control and privacy; keys on the server.
- Cost = tokens × price; output tokens are slow (memory-bound decode) and expensive.
All lessons: AI from scratch. Model: SmolLM2-135M-Instruct (Hugging Face, Apache 2.0), run with transformers.js. Anthropic's and OpenAI's prompting guides are good next reads.
Last updated