Metadata-Version: 2.4
Name: ai-concepts-lab
Version: 0.1.0
Summary: Learn how LLMs, agents, skills and MCP work by running them against your own Ollama, with every call shown.
Author-email: Ram Pangeni <rampangeni@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/rampangeni/ai-concepts-lab
Project-URL: Issues, https://github.com/rampangeni/ai-concepts-lab/issues
Keywords: llm,ollama,education,rag,mcp,agents,tokens
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Education
Classifier: Intended Audience :: Education
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# AI Concepts Lab

A hands-on, local-first way to *see* how LLMs work. Run one Python command, a page opens in your browser, and thirty-two interactive chapters, in a deliberate learning order, walk you through tokens, tokenizers, embeddings, attention, the transformer, sampling, context, vision, training, scaling laws, model size, choosing a model, cost and caching, prompting, reasoning, structured output, retrieval (chunking, hybrid search, reranking), memory, fine-tuning versus RAG, tools, skills, MCP, ReAct agents, multi-agent systems, hallucination, evaluation, prompt injection and guardrails, using a small free model running on your machine through [Ollama](https://ollama.com).

Every request, response, tool call and MCP message your input causes is recorded on the **Call Tape**, and at the end you can export everything as a **report** (Markdown, HTML, or PDF).

- Python 3.9+ standard library only. No pip install, no build step, no CDN. Works offline.
- Beginner / Engineer toggle: plain-language explanations or the exact payloads and math.

![Multi-agent chapter with sequence diagram and Call Tape](docs/multi.png)

![Demo: a few chapters, the Call Tape, and the report (recorded in Practice mode)](docs/demo.gif)

## Quick start

```bash
# 1. Install Ollama (https://ollama.com), then pull the models
ollama pull qwen3:4b
ollama pull nomic-embed-text

# 2. Run the lab (from a clone; or install the package, see below)
python3 -m ai_concepts_lab
```

### Install as a package

No clone needed. It needs only Python 3.9 or newer (the standard library, nothing else) and [Ollama](https://ollama.com):

```bash
pipx install ai-concepts-lab                     # once published; or install a downloaded wheel:
pipx install ./ai_concepts_lab-0.1.0-py3-none-any.whl
ai-concepts-lab                                   # opens the lab
```

`pip install` works the same way. From a source checkout, `python3 -m ai_concepts_lab` does the same.

Your notes, skills, reports and feedback are kept in `~/.ai-concepts-lab/` (set `AI_CONCEPTS_LAB_HOME` to change it), so upgrading the package never touches them. Starter notes and the built-in skills are copied there the first time you run it.

To build the package yourself: `python -m build` creates a wheel and a source archive in `dist/`.

### Pick a learning level

```bash
ai-concepts-lab              # same as basic: 9 essential chapters, simplest screen (the default)
ai-concepts-lab basic      # 9 essential chapters, simplest screen
ai-concepts-lab medium     # basic plus 10 more, 19 chapters
ai-concepts-lab advance    # all 32 chapters
```

- **Basic:** tokens, meaning as numbers, context window, how a model is made, model size, prompting, retrieval (RAG), tool calling, and making things up. The Engineer view, the "Under the hood" boxes and Sessions are hidden.
- **Medium:** adds tokenizers, attention, sampling, reasoning models, structured output, choosing a model, chunking, memory, evaluation and prompt injection.
- **Advance:** everything, including the transformer, scaling laws, vision, cost and caching, hybrid search, fine-tuning vs RAG, ReAct, guardrails, skills, MCP and multi-agent.

The level shows at the top of the screen. Roadmaps, Previous/Next buttons, progress and the Run-all tour follow the level you chose. You can add `--mock` to any of them.

The browser opens at http://localhost:8765. No model yet? Open the status pill at the top and turn on **Practice mode** (or start with `ai-concepts-lab --mock`) to explore the whole UI with scripted (simulated) responses.

If port 8765 is busy, the server tries the next free port and prints the address it chose.

Options: `--port`, `--host`, `--ollama-url` (default http://localhost:11434), `--model`, `--embed-model`, `--no-browser`, `--mock`, `--verbose`. Any installed chat model that supports tools works, and the status pill (top right) lets you pick one.

The **Help** page in the lab explains how to read the screen, the Call Tape and the charts.

## Chapters

| # | Chapter | What you do |
|---|---------|-------------|
| | **How models work** | |
| 1 | Tokens and the next word | Watch a model choose each token, see the alternatives it rejected, and change the odds yourself. |
| 2 | How text is cut up | Byte-pair encoding step by step, and why other languages, code and numbers cost more tokens. |
| 3 | Meaning as numbers | Turn words into vectors, see similar meanings cluster, and do arithmetic on ideas. |
| 4 | Attention | See how every token decides which other tokens to look at, with masks and multiple heads. |
| 5 | The transformer, layer by layer | Embedding, repeated attention and feed-forward blocks, the residual stream, the output head, and the KV cache. |
| 6 | Sampling in depth | Temperature, top-k, top-p, min-p, repetition penalty, and greedy versus beam search, on one distribution. |
| 7 | Context window | Discover that the model remembers nothing between requests, and see what each one really carries. |
| 8 | Vision: pictures as tokens | Cut a picture into patches, count the tokens it costs, and ask a vision model about it. |
| | **Making and choosing models** | |
| 9 | How a model is made | Step through the three stages that turn raw text into a helpful chat model. |
| 10 | Why bigger models help | Scaling laws: how parameters, training text and compute trade off, with a curve you can move along. |
| 11 | Model size and memory | See why a 7B model needs about 14 GB at full quality and about 4 GB when rounded, and check if one fits on your computer. |
| 12 | Choosing a model | Read your installed models: size, quantization, context length, abilities, license. Then filter with a checklist. |
| 13 | Cost, speed and caching | Measure where the time goes (reading the prompt vs writing the answer) and see how a reused prefix gets cheaper. |
| 14 | Compare models | Send one prompt to two models and compare the answers, the wait for the first word, and the speed. |
| | **Talking to models** | |
| 15 | Prompting | Ask the same question three ways (just ask, show examples, ask for steps) and compare what comes back. |
| 16 | Reasoning models | Turn thinking on and off for the same question and read what the model wrote to itself first. |
| 17 | Structured output | Get answers your code can read: ask for JSON in a fixed shape, then check it. |
| | **Giving models knowledge** | |
| 18 | Retrieval (RAG) | Give the model your own notes by finding the right lines first, then compare with and without them. |
| 19 | Chunking and retrieval quality | How you cut documents into pieces decides whether the right piece is found. Sweep chunk size and overlap. |
| 20 | Hybrid search and reranking | Keyword search finds exact words, meaning search finds paraphrases. Fuse them, then let a model reorder the best few. |
| 21 | Memory for agents | Models remember nothing between calls. Compare three ways to give an assistant a memory: window, summary, notes. |
| 22 | Prompting, RAG or fine-tuning? | Three ways to make a model fit your job. Answer a few questions and see which one to try first. |
| | **Tools and agents** | |
| 23 | Tool calling | Watch a model ask for a calculator, your code run it, and the answer flow back. |
| 24 | Skills | Teach the model new procedures without bloating every prompt. Write your own skill and watch it load. |
| 25 | MCP | Plug tools in through a standard protocol and read the real JSON-RPC messages as they cross the wire. |
| 26 | Tools, schemas or MCP? | Three ways to connect a model to code: ask for structured output, give it tools, or plug in an MCP server. |
| 27 | Planning with ReAct | An agent that thinks out loud, acts, reads what happened, and repeats until it can answer. |
| 28 | Multi-agent | Split a job between a researcher, a writer and a reviewer, and see what each one can and cannot see. |
| | **Quality and safety** | |
| 29 | Making things up | Ask the same question several times. Stable answers are a good sign. Scattered ones are a warning. |
| 30 | Evaluating answers | Stop guessing which prompt is better. Run a small test set against two prompts and keep score. |
| 31 | Prompt injection | Hide an instruction inside a document and watch the model obey it. Then try three defenses. |
| 32 | Guardrails | Put checks before and after the model so one bad input or one bad answer does not reach the user. |

The last stop is a **Feedback** page (rating, what worked, what confused you, what to add). It saves a small JSON file in `feedback/` on your computer and can export Markdown. Nothing is sent anywhere. The chapters are grouped into six parts, A to F. Each chapter opens with a **roadmap box**: what you have covered so far, what this chapter covers, why it comes now, and what is next. Every chapter ends with a short **Check yourself** quiz and Previous / Next buttons, and the start page tracks your progress. Chat streams its reply and shows time to first token.

Every chapter has a **More details** page with diagrams, written separately for Beginner and Engineer, and **(i)** buttons next to its controls that explain what each one does.

![Deep-dive page with a diagram](docs/learn.png)

![An (i) popover explaining top-p](docs/info.png)

## Run everything in one click

The start page has a **Run all chapters** button. It runs one example from each lab that calls the model, in turn, fills the Call Tape, and then you can open the report. Handy for a first look, or to compare how different models behave on the same inputs.

## The Call Tape and reports

![Tool-calling lab: sequence diagram and call tape](docs/tools.png)


The tape on the right lists every call: Ollama API requests and responses (with a copy-as-curl tab and timing bars), your tool code, MCP messages and agent hand-offs. Click a sequence-diagram arrow to jump to its call.

**Report** turns your session into a short lesson: a plain-language summary, what to notice in each run, diagrams of the main ideas, every call in order, and a glossary. Download Markdown or HTML, print to PDF, or tick "Also save a copy" to write it to `reports/`.

![Token probabilities with sampling controls](docs/tokens.png)

## Sessions

Your runs are saved in the browser automatically, so a reload does not lose them. **Sessions** in the top bar lets you save a named copy, load it later, compare two sessions side by side, and export or import a file. Nothing leaves your computer.

## Check it against a real model

The tests use a simulated model. To check the labs against your own Ollama, run:

```bash
python3 scripts/check_ollama.py                 # or --model llama3.2:3b --embed-model nomic-embed-text
```

It runs every lab once and prints PASS or FAIL with a hint for each failure. (It has only been run against the simulated model by the author so far, so please report anything odd.)

## Your own content

- Notes for RAG and MCP live in `notes/` (edit them in the UI or on disk).
- Skills live in `skills/<name>/SKILL.md` (frontmatter + instructions). Built-ins are read-only; make your own in the Skills chapter.

## Tests

```bash
python3 -m unittest discover -s tests
```

Tests run against `ai_concepts_lab/labs/mock_ollama.py`, so no model is needed. The browser tests need Playwright and skip themselves without it: `pip install playwright && playwright install chromium`. CI runs both on every push.

## Layout

```
ai_concepts_lab/server.py   HTTP server + CLI (the `ai-concepts-lab` command)
ai_concepts_lab/labs/         Ollama client, agent loop, MCP client, lab runners, mock Ollama
ai_concepts_lab/mcp_servers/  the notes MCP server (stdio)
ai_concepts_lab/skills, notes/  built-in skills and starter notes
ai_concepts_lab/web/          the UI (plain HTML/CSS/JS)
pyproject.toml                package metadata (command: ai-concepts-lab)
scripts/         check_ollama.py: run the labs against a real Ollama
tests/           API tests and browser tests against the mock
```

## Honest notes

- The attention chapter is a teaching illustration. Ollama does not expose real attention weights, so it uses seeded random projections of real embeddings.
- Small models make mistakes with tools. That is part of the lesson; try a larger model if one misbehaves.
- In Practice mode (`--mock`) outputs are scripted, not produced by a model.
- The demo GIF was recorded in Practice mode, not with a real model.
- Troubleshooting: the start page shows a notice when Ollama is not running or a model is missing. A red status pill means Ollama is not reachable; run `ollama serve` or pass `--ollama-url`. If the model reports a missing model, `ollama pull` it.

## License

MIT


> The chapters were tested against the built-in Practice-mode model and the automated tests. In Practice mode the retrieval chapters (chunking, hybrid search) use a simple word-counting stand-in for embeddings, so use a real embedding model to see true semantic matches.
