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):

<|im_start|>system You are a concise assistant.<|im_end|> <|im_start|>user Name three boroughs of New York City.<|im_end|> <|im_start|>assistant

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?

Everything the model knows about the conversation is in the input tokens. Apps that keep chats short (or summarize old turns, or retrieve only what's relevant: the next lesson) do it to save tokens and stay inside the context window.

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.

HabitInstead ofWrite
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 dataPasting the text into the middle of the requestInstructions first, then the data between clear markers (<report> … </report>)
Show examples (few-shot)Describing the format in words onlyTwo 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?

Few-shot examples work through the same next-token prediction as everything else: they make the format you want the obvious pattern to continue. This is "in-context learning": no weights change.

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:

  1. Ask for JSON in the prompt, with an example.
  2. 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.
  3. Constrain it: hosted APIs and local servers can force the output to match a JSON schema (structured outputs; Ollama's format=, OpenAI's response_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

5. Hosted APIs and open models

Hosted API (Anthropic, OpenAI, Google…)Open weights (Llama, Qwen, Mistral, SmolLM…)
QualityThe strongest modelsClose behind at the top; small ones run anywhere
CostPer token, nothing up frontYour hardware and electricity; free per call
DataLeaves your machine (under the provider's terms)Stays with you: this page runs one in your browser
ControlThe provider can update or retire a modelPinned 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?

Input: \(1{,}000 \times 400 = 400{,}000\) tokens → \$1.20. Output: \(1{,}000 \times 30 = 30{,}000\) → \$0.45. Total \$1.65 a day. Long prompts repeated on every call dominate, which is why providers offer prompt caching (a repeated prefix is billed at a fraction).

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
  1. 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).
  2. 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.
  3. 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.
  4. 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).
  5. It also explains a practical rule: asking for a shorter answer saves more time than shortening the prompt.

7. What to carry forward

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