Foundations / How LLMs and agents work
How LLMs and agents work cheat sheet
Set up and run a model
| Task | Command |
|---|---|
| Make the lab folder | mkdir -p ~/krlab/llms-and-agents |
| Check the lab (before the model) | python3 labcheck.py |
| Check the lab with the model | python3 labcheck.py --model |
| Print the Ollama version | ollama --version |
| Download a model once | ollama pull llama3.2:3b |
| List the models on the machine | ollama list |
See the loaded models and the real window (CONTEXT) | ollama ps |
| Start the server by hand | ollama serve |
| Use the smaller model | export KR_MODEL=llama3.2:1b |
Text, tokens and the window
| Task | Command |
|---|---|
| Cut text into pieces | re.findall(pattern, text) |
| Count what follows what | follows[a][b] += 1 with defaultdict(Counter) |
| Repeatable random draws | rng = random.Random(seed) then rng.choices(names, weights) |
| Temperature 0 | always the most likely token |
| Keep the newest messages that fit | fit(messages, budget) |
| Real token count of a text | tokens(text) of count.py (subtract an empty message) |
Talk to the model
| Task | Command |
|---|---|
| Send messages, get text | chat(messages) |
| Fix a run | chat(messages, temperature=0, seed=1) |
| Limit the answer | chat(messages, max_tokens=60) |
| Ask for JSON text | chat(messages, as_json=True) |
| Get counts and timing | chat(messages, full=True) |
| Prompt tokens, answer tokens | reply["prompt_eval_count"], reply["eval_count"] |
Why the answer stopped (length or stop) | reply["done_reason"] |
| Tokens per second | reply["eval_count"] / (reply["eval_duration"] / 1e9) |
| Give the model memory | send the whole history again each call |
| Show the pattern | add example user and assistant messages (few-shot) |
| Check JSON output | json.loads(raw), then keys, types, allowed values |
Measure, retrieve, use tools
| Task | Command |
|---|---|
| Score an answer | grade(answer, expected): right, unknown or wrong |
| Search your documents | retrieve(question) of retrieve.py |
| Put sources in the prompt | system message: rules, then SOURCES, then the question |
| Allow only named tools | TOOLS = {"name": function} and check(request) |
| Refuse a request | check returns the reason, not None |
| Accept whole numbers only | type(v) is int (not isinstance) |
| Match a whole value | re.fullmatch(r"KR-[0-9]{4}", value) |
Agents and MCP
| Task | Command |
|---|---|
| Stop a runaway loop | for step in range(1, max_steps + 1) |
| Refuse a repeated call | keep a set seen of raw requests |
| Record every step | log(question, step, model=raw, outcome=...) to trace.jsonl |
| Test a loop without a model | pass a stand-in model function |
| List the tools of a server | JSON-RPC method tools/list |
| Run one tool on a server | JSON-RPC method tools/call with name and arguments |
| Error for an unknown method | code -32601 |
Inside a model
| Task | Command |
|---|---|
| Score a token against a query, scaled by the square root of the length | sum(x * y for x, y in zip(query, key)) / math.sqrt(len(query)) |
| Turn scores into weights that add up to 1 | exps = [math.exp(s - max(scores)) for s in scores], then e / sum(exps) |
| Mix the values by their weights | sum(w * v[i] for w, v in zip(weights, values)) for each place i |
Attention scores for n tokens | n * n |
| Weights of a transformer (estimate) | 12 * layers * width * width + vocab * width |
| Memory of a model in bytes | weights * bits / 8 |
Step size for bits bits | max(abs(x) for x in w) / (2 ** (bits - 1) - 1) |
| Quantise a weight and restore it | round(x / step) * step |
| Prune a share of the weights | zero 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 floats | len(struct.pack("1000f", *weights)) |
Safety habits
- Keep the model server on
127.0.0.1. It has no login. - Read an installer before you run it. Never pipe a download into a shell.
- The model only writes text. Your code decides what runs: allowlist, then argument check.
- Valid JSON is not valid data. Check keys, types and allowed values.
- Set a step limit and a limit on tokens for every agent run.
- Keep secrets out of prompts. A rule in a prompt is advice. A missing capability is a control.
- Text from documents, tools and web pages is untrusted. The model may follow it.
- Log every step. Report counts with the model, the seed and the temperature.
- Check any identifier or command that a model gives against the real source.
- A quantised or pruned copy is a new model: new hash, new tests, new entry in the inventory.