How a question becomes tokens, and how an app survives the rate limit
This week you learn what a large language model really is, how to write prompts that work, and how text is turned into tokens. Then you build the first module of DataPilot: one safe client that every later feature uses to call a model, with rate limiting, retries, timeouts and cost logging.
Two videos, and what to take from each
Watch both videos, then use the notes below to review. The first explains what a model is. The second teaches you to talk to one. You don't need an API key for any of this week's theory: you can try every prompt in the free ChatGPT, Gemini or Claude web apps.
Andrej Karpathy: Intro to Large Language Models
The talk moves through three questions: what is a language model, where is the technology heading, and how can it be attacked. The notes below follow that structure, explained as concepts you can carry into any model or provider. Each one ends with what it means for you as a builder.
Part 1 · What an LLM is
A model is learned numbers plus a small program
Strip away the chat window and a language model is two things: a very large set of numbers called parameters (or weights), and a short program that runs text through them. The program is simple and generic. All the knowledge and skill sit in the parameters, and the more parameters, the bigger the file and the more memory and compute it needs.
Think of it as a trained musician's memory (the parameters) and the act of playing (the program). The skill is in the memory, not the instrument.
For you Model size drives cost, speed and where it can run. Small open models can run on your own machine; large ones need a provider's servers.
Pretraining: learning from a huge amount of text
Parameters start as random numbers. Training shows the model enormous volumes of text and adjusts the numbers a little after each guess, over and over, on thousands of GPUs for weeks. The outcome is a compressed summary of patterns in that text. The compression is lossy: the model keeps the gist of what it read, not an exact copy.
Think of it as someone who has read a library and remembers the ideas well but can't quote page numbers reliably.
For you Never treat a model as a database of exact facts. When exact facts matter, give it the source text (that's RAG).
The core task: predict the next token
Everything a model does comes from one skill: given some text, predict what token comes next, then repeat. To predict well across billions of sentences, the model is forced to pick up grammar, facts, style and patterns of reasoning, because those all help it guess better.
Think of it as a very advanced autocomplete. To finish "The capital of France is…" correctly, it has to have learned the fact.
For you A model's answer is a sequence of likely next tokens, not a looked-up truth. That's why wording, context and examples in the prompt change the result.
Hallucination: fluent but wrong
Because the model generates what is likely, it can produce text that sounds completely right and is invented: a fake citation, a product that doesn't exist, a wrong number stated confidently. It has no built-in sense of which parts it actually remembers.
Think of it as a confident student filling gaps in an exam answer with plausible guesses.
For you Design for it: ground answers in provided documents, ask for citations, let the model say "I don't know", and test outputs (weeks 7 and 12).
Inside the model: we know the method, not the meaning
The architecture (the Transformer) is fully understood, and so is the method for adjusting parameters. What each of the billions of parameters represents is largely unknown. Knowledge can be stored in odd ways: a model may know a fact in one direction ("A is B's parent") but fail when asked the reverse ("who is A's child?").
Think of it as a very capable colleague whose reasoning you can't inspect, only check by their results.
For you You can't prove a model is correct by reading it, so you judge it by evaluation: a fixed set of test questions with expected answers.
From base model to assistant: fine-tuning
A pretrained (base) model only continues text: ask it a question and it may reply with more questions. To make an assistant, training continues on a much smaller set of carefully written example conversations, each showing a question and an ideal answer. The model keeps its broad knowledge and learns the behaviour: answer helpfully, in a clear format.
Think of it as a well-read graduate going through job training: same knowledge, new way of working.
For you Almost every app uses an instruction-tuned (assistant) model. Fine-tuning your own (week 12, LoRA) is for style or narrow tasks, not for adding facts.
The training pipeline
Building a model happens in stages. Pretraining is very expensive and done rarely; it produces the base model. Fine-tuning is far cheaper and repeated often: write guidelines, collect example conversations, train, evaluate, release, then watch for mistakes. When the assistant gets something wrong, the corrected answer becomes new training data for the next round.
Think of it as building a school once, then running a new term every few weeks.
For you This loop (find failures, add a fix, re-test) is the same loop you use in incident drills: reproduce, fix the cause, add a test.
Learning from preferences: RLHF
For many tasks it's easier for people to compare two answers than to write a perfect one. People are shown several answers and pick the best; the model is then trained to prefer what people preferred. This is reinforcement learning from human feedback. The guidelines people follow usually ask for answers that are helpful, honest and harmless, and models increasingly help draft the answers people then judge.
Think of it as a judge at a cooking contest: tasting and ranking dishes is easier than cooking the best one.
For you RLHF explains why assistants are polite, cautious and sometimes refuse. It's also a common interview concept.
Comparing models: closed and open
Models are compared with benchmarks and with blind human voting between two answers. Two families exist. Closed models are used only through a provider's API and tend to be the most capable. Open-weights models can be downloaded, run privately and fine-tuned, usually trailing slightly in quality.
Think of it as renting a top car with a driver versus owning a good car you can modify.
For you That's why DataPilot's client is provider-agnostic: you can switch between a hosted model and a local one with a config change.
Part 2 · Where it's heading
Scaling laws
Model quality improves in a smooth, predictable way as you increase two things: the number of parameters and the amount of training data. That predictability lets companies plan bigger models with confidence, which is why there's a race for chips and data. Smarter algorithms help, but scale is the dependable lever.
Think of it as a growth curve you can forecast: double the inputs, and you know roughly how much better it gets.
For you Expect models to keep getting better and cheaper. Build your app so the model is replaceable.
Tool use
Models are poor at exact arithmetic and don't know today's data, so modern assistants call tools: web search for fresh facts, a calculator or Python for exact numbers, charts, image generation. The model decides when to call a tool, reads the result, and continues. It works like a person who reaches for a calculator rather than doing sums in their head.
Think of it as a smart analyst with a laptop, not a genius working from memory alone.
For you This is how DataPilot's agents work: the model writes SQL, a tool runs it on the warehouse, and the model explains the result (week 9).
Multimodality
Models increasingly handle more than text: they read images and documents, generate images, and listen and speak. A hand-drawn sketch can become working web code; a photo of a form can become structured data.
Think of it as moving from email to a video call: more ways in and out.
For you Scanned documents (week 4) and ad images (week 14) use these abilities.
Fast and slow thinking
Psychology describes two modes: fast, instinctive answers (2 + 2) and slow, deliberate reasoning (17 × 24). A plain model spends the same small effort on every token, so it behaves like the fast mode. Letting it reason step by step, explore options and check itself trades time for better answers on hard problems.
Think of it as blitz chess versus a tournament game with time to think.
For you Ask for steps before the answer (chain-of-thought, week 2), and use reasoning models for hard tasks, accepting slower, costlier calls.
Self-improvement
Systems that learn only by copying people top out at human level. Systems that can practise against a clear score (win or lose, right or wrong) can keep improving past it, as game-playing AI showed. For open-ended language there's rarely a simple score, which limits this. In narrow tasks with checkable answers (code that runs, maths with a correct result) it works much better.
Think of it as learning a sport by watching versus by playing thousands of scored matches.
For you When you can automatically check an answer (does the SQL run, does it match the expected rows?), you can build feedback loops and evaluations around it.
Customization
Rather than one model for everything, assistants are tailored: custom instructions, a specialist persona, and documents the model retrieves from at answer time. Fine-tuning is a further option for specialised behaviour.
Think of it as the same employee given a role description and a company handbook.
For you DataPilot's domain packs (prompts, glossary, documents per industry) are exactly this, and retrieval is Ask the Docs (weeks 4–7).
The LLM as an operating system
A useful mental model: the LLM is the core of a new kind of computer. It coordinates resources the way an operating system does. Its context window works like RAM: small, fast working memory you must manage. Files, databases and the web are like disk storage it pages in when needed. Tools, other models and input/output devices plug in around it. As with operating systems, there are proprietary platforms and an open-source ecosystem.
Think of it as the model being the CPU and RAM, and your app being the operating system that decides what goes into memory.
For you Much of AI engineering is memory management: choosing which chunks, history and instructions fit in the context window, within token limits and cost.
Part 3 · Security
Jailbreaks
A jailbreak tricks a model into ignoring its safety rules. Common tricks: wrapping the request in a story or role-play, encoding it in another format or language the safety training covered less, or appending specially crafted text (even an altered image) that confuses the model's safeguards.
Think of it as social engineering aimed at a machine.
For you A public-facing assistant needs its own checks on input and output; never rely on the model's training alone (week 13).
Prompt injection
A model can't reliably tell your instructions apart from instructions hidden in the content it reads. Text inside a web page, document, email or even an image can say "ignore previous instructions and…", and the model may obey. This can leak data or trigger unwanted actions when the model has tools.
Think of it as a letter that, when read aloud by your assistant, gives your assistant new orders.
For you Treat every retrieved document and user message as untrusted data: use delimiters, limit what tools can do, keep internal data off the public endpoint, and red-team it (week 13).
Data poisoning and backdoors
If attackers can place text in a model's training data, they can plant a hidden trigger: a word or phrase that makes the model misbehave whenever it appears, while it acts normally otherwise.
Think of it as a sleeper agent with a code word.
For you Control and audit the data you fine-tune on and the documents you index, just as you'd govern any production dataset (week 15).
A security mindset
Beyond these, the list of risks includes leaking private training data, unsafe handling of model output (for example running generated SQL without limits), denial-of-service through huge requests, and model theft. Like traditional security, it's an ongoing contest: defences improve, attacks adapt.
Think of it as web security in its early years: new, fast-moving, and essential.
For you Production checks such as authentication, rate limits, timeouts, read-only database access and output validation are your defence layers. You started on rate limits and timeouts this week.
What it means for DataPilot
| Idea from the talk | Where you use it |
|---|---|
| Tokens, next-word prediction, context window as RAM | Week 1 token counting and limits; weeks 5–7 chunking and retrieval to fit the context |
| Hallucination and the reversal curse | Week 7 citations; week 12 evaluations |
| Fine-tuning, RLHF | Week 12 LoRA notebook and the RLHF concept |
| Tool use, LLM OS | Week 9 text-to-SQL agent; week 11 router and MCP server |
| System 2 thinking | Week 2 chain-of-thought prompts; ReAct agents |
| Customization and RAG | Domain packs; weeks 4–7 Ask the Docs |
| Jailbreaks, prompt injection | Week 13 guardrails and red-team tests |
DeepLearning.AI: ChatGPT Prompt Engineering for Developers
Taught by Isa Fulford (OpenAI) and Andrew Ng. Each lesson has a Jupyter notebook in the browser with an API key already set up, so you can run every example free without your own key. Below, each lesson lists the use cases the course demonstrates, a prompt in the same pattern, and a lending version to try.
The helper every lesson uses
from openai import OpenAI
client = OpenAI() # in the course notebooks the key is already set
def get_completion(prompt, model="gpt-4o-mini", temperature=0):
messages = [{"role": "user", "content": prompt}]
response = client.chat.completions.create(
model=model, messages=messages, temperature=temperature)
return response.choices[0].message.content
print(get_completion("Summarise in one sentence: ..."))
The course used gpt-3.5-turbo with an older version of the library; the version above is the current equivalent. In DataPilot, LLMClient.ask() plays the same role, with limits, retries and logging added.
Try it yourself
These two labs run the same logic as the Python scripts you build in Part 3. Change the inputs and watch what happens. Nothing is sent to any model.
Token lab: how a word becomes tokens
Step 1 learns which letters often sit together in the training text (byte-pair encoding, the method GPT models use). Step 2 splits your word with those learned pieces and counts the tokens. Common words collapse into one token; rare words stay in pieces.
Step 1 · Learned merges
Step 2 · Splitting your word
Rate-limit lab: several users, one model
Each line is one question sent one second after the previous. The provider limit is shared by everyone, like your API account. The per-user limit stops one person using everyone's share. Over a limit, the request is rejected with HTTP 429, or queued in wait mode.
| Time | User | Question | Result | Tokens in + out | Cost |
|---|
Token counts here use an approximate split. Input tokens = system prompt (32) + question + chat overhead (9). Before a call, the limiter reserves input + answer budget; afterwards it corrects to the real total. Cost uses gpt-4o-mini prices ($0.15 per million input tokens, $0.60 per million output tokens).
The LLM client: one safe door to every model
Every later DataPilot feature (Ask the Docs, Ask the Data, Triage, Customer Assistant, Marketing Studio) sends its model calls through this one client. It handles the four ways AI apps fail in production.
| Production problem | What the client does |
|---|---|
| The provider rejects you for sending too much (429) | A sliding-window limiter tracks requests and tokens per minute and waits before going over |
| A call hangs, or the provider has a short outage | A timeout on every call, and retries with exponential backoff and jitter, only for errors worth retrying |
| Nobody knows what the AI costs or how slow it is | Every call, successful or failed, is logged with tokens, latency, attempts and cost |
| The app is hard-wired to one industry | Domain packs: lending or retail is a setting, not a code change |
What happens when you ask one question
- Load settings
core/config.pyReads the provider, model, timeout, retry count, limits and active domain from the environment, and loads the domain pack's system prompt.
- Count tokens
core/tokens.pyEstimates input tokens: system prompt + question + chat overhead, plus the answer budget.
- Wait for room
core/rate_limiter.pyChecks requests and tokens used in the last 60 seconds. If this call would go over, it waits until the oldest call leaves the window.
- Call the model
core/llm_client.pySends the request with a timeout. Rate limits, timeouts and server errors are retried with growing, randomised waits. A bad request fails at once.
- Log the call
core/db.pyWrites one row to
llm_calls: provider, model, domain, tokens, latency, attempts, time waited, status and cost. - Return the answer
The caller gets the text plus its token counts, latency and number of attempts.
Files you build
| File | What it does |
|---|---|
domains/lending/domain.yaml, domains/retail/domain.yaml | Everything industry-specific: name, description, system prompt and glossary (DPD, APR, AOV, SKU…) |
core/config.py | Settings from the environment, and the domain-pack loader |
core/rate_limiter.py | Requests-per-minute and tokens-per-minute limiter with acquire, check, status and correct |
core/tokens.py | Splits text into tokens (OpenAI's tiktoken when installed, an approximate split otherwise) and counts a chat call's input |
core/db.py | The llm_calls table and the function that logs each call |
core/llm_client.py | Providers (OpenAI and a fake one for testing), retries, timeouts, logging and cost |
scripts/ask.py | Ask one question from the command line |
scripts/chat.py | Interactive chat that shows the live rate-limit status after each answer |
scripts/playground.py | Several users share one model, with limits you set; prints 429 rejections, token breakdowns and cost |
scripts/token_explainer.py | Trains a mini tokenizer and shows step by step how a word becomes tokens |
scripts/burst_test.py | Load test: 50 calls, 10 at a time |
Run it
No API key is needed. Set LLM_PROVIDER=fake and the fake model echoes your question back, while everything around it (limits, retries, logging, domains) runs for real.
python -m scripts.ask "What does DPD mean?" python -m scripts.chat --rpm 3 python -m scripts.playground --file questions.txt --users alice,bob,carol --rpm 5 --user-rpm 2 python -m scripts.token_explainer low lower lowest DPD python -m scripts.burst_test --fake pytest -q
15 tests, and the promise each one keeps
Tests check the code automatically in under a second, so a change in week 7 can't silently break what you built in week 1. They use a fake model and a fake clock, so they're free and instant.
| Test | What it proves | Result |
|---|
Load test result
| Check | Target | Result |
|---|---|---|
| 50 calls, 10 at a time | All succeed | 50/50 succeeded |
Rows in llm_calls | One per call, no errors | 50 ok, 0 error |
Switch DOMAIN=retail | No code change | Loaded retail |