Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / How LLMs and agents work

How LLMs and agents work cheat sheet

Set up and run a model

TaskCommand
Make the lab foldermkdir -p ~/krlab/llms-and-agents
Check the lab (before the model)python3 labcheck.py
Check the lab with the modelpython3 labcheck.py --model
Print the Ollama versionollama --version
Download a model onceollama pull llama3.2:3b
List the models on the machineollama list
See the loaded models and the real window (CONTEXT)ollama ps
Start the server by handollama serve
Use the smaller modelexport KR_MODEL=llama3.2:1b

Text, tokens and the window

TaskCommand
Cut text into piecesre.findall(pattern, text)
Count what follows whatfollows[a][b] += 1 with defaultdict(Counter)
Repeatable random drawsrng = random.Random(seed) then rng.choices(names, weights)
Temperature 0always the most likely token
Keep the newest messages that fitfit(messages, budget)
Real token count of a texttokens(text) of count.py (subtract an empty message)

Talk to the model

TaskCommand
Send messages, get textchat(messages)
Fix a runchat(messages, temperature=0, seed=1)
Limit the answerchat(messages, max_tokens=60)
Ask for JSON textchat(messages, as_json=True)
Get counts and timingchat(messages, full=True)
Prompt tokens, answer tokensreply["prompt_eval_count"], reply["eval_count"]
Why the answer stopped (length or stop)reply["done_reason"]
Tokens per secondreply["eval_count"] / (reply["eval_duration"] / 1e9)
Give the model memorysend the whole history again each call
Show the patternadd example user and assistant messages (few-shot)
Check JSON outputjson.loads(raw), then keys, types, allowed values

Measure, retrieve, use tools

TaskCommand
Score an answergrade(answer, expected): right, unknown or wrong
Search your documentsretrieve(question) of retrieve.py
Put sources in the promptsystem message: rules, then SOURCES, then the question
Allow only named toolsTOOLS = {"name": function} and check(request)
Refuse a requestcheck returns the reason, not None
Accept whole numbers onlytype(v) is int (not isinstance)
Match a whole valuere.fullmatch(r"KR-[0-9]{4}", value)

Agents and MCP

TaskCommand
Stop a runaway loopfor step in range(1, max_steps + 1)
Refuse a repeated callkeep a set seen of raw requests
Record every steplog(question, step, model=raw, outcome=...) to trace.jsonl
Test a loop without a modelpass a stand-in model function
List the tools of a serverJSON-RPC method tools/list
Run one tool on a serverJSON-RPC method tools/call with name and arguments
Error for an unknown methodcode -32601

Inside a model

TaskCommand
Score a token against a query, scaled by the square root of the lengthsum(x * y for x, y in zip(query, key)) / math.sqrt(len(query))
Turn scores into weights that add up to 1exps = [math.exp(s - max(scores)) for s in scores], then e / sum(exps)
Mix the values by their weightssum(w * v[i] for w, v in zip(weights, values)) for each place i
Attention scores for n tokensn * n
Weights of a transformer (estimate)12 * layers * width * width + vocab * width
Memory of a model in bytesweights * bits / 8
Step size for bits bitsmax(abs(x) for x in w) / (2 ** (bits - 1) - 1)
Quantise a weight and restore itround(x / step) * step
Prune a share of the weightszero every weight with abs(x) <= cut, cut = sorted(abs(x) for x in w)[int(len(w) * share) - 1]
Real bytes of weights as 32-bit floatslen(struct.pack("1000f", *weights))

Safety habits