How AI Apps Turn Amnesia Into Continuity
01 — The Core Problem

Every API Call Ships the Entire Conversation

The LLM remembers nothing. Every API call must include ALL previous context. The context window is finite, but conversations are not.

"The AI model (Dr. Neural) is stateless and remembers nothing. The application layer (Alice) maintains conversation history and feeds it back as context, creating the illusion of memory and continuity."

— Thinking in Analogies, Ch. 1

User Message #47

"Continue from where we left off on the database migration plan"

Application Layer (Alice) — The Real Product

Must decide: what to include, what to summarize, what to discard

System Prompt Conversation History RAG Results Current Message

LLM (Dr. Neural) — Sees Only This Call

Processes everything as one flat prompt. No memory of call #46.

Context Rot: When More Is Less

Research shows models lose accuracy as context fills up. Strong recall at the start and end, weak in the middle.

Strong recall "Lost in the Middle" zone Strong recall

"AI applications like ChatGPT, Claude, or custom business chatbots are so much more than just the language model. They're sophisticated systems that manage state, context, and memory on behalf of the stateless core."

— Thinking in Analogies, Ch. 1
🗃

Skill Translation

Database → Context

Instead of managing data in tables, you manage conversation context. Same concepts: indexing, querying, optimization.

🔌

Skill Translation

API → LLM Integration

Instead of calling payment APIs, you call LLM APIs. Same patterns: auth, rate limiting, error handling.

🏗

The 95/5 Rule

95% Engineering

Context management, state handling, caching, optimization — these are all traditional software engineering skills. Only 5% is AI-specific.

02 — Inside the Context Window

See How Different Apps Pack the Window

Each app makes different trade-offs. Click an app to see its allocation — this IS the product differentiation.

Context Window Allocation
0 tokens 128K tokens
System Prompt
History / Context
RAG / Retrieved
Current Turn
Free Space
App Window Size Primary Strategy Key Techniques The "Alice" Layer
ChatGPT
128K tokens Sliding Window Memory Summarization Custom Instructions Older messages gradually forgotten. Persistent memory extracts key facts across chats.
Claude
200K-1M Full History + Compaction Auto-compaction Projects/RAG Memory Full history in window. Auto-summarizes when approaching limits.
Perplexity
Varies RAG-First Web Search Source Injection Citation Minimal history. Context filled with web search results per-query.
Cursor
Up to 200K File-Aware RAG Codebase Index File Context Dep Graph Indexes codebase. Selects files by relevance to current task.
Aider OSS
Model-dep. Repo Map + PageRank Tree-sitter PageRank Auto-summarize Tree-sitter ASTs + PageRank for file ranking. ~1K token repo map.
03 — The Five Alice Strategies

How Apps Build Stateful Magic on Stateless APIs

Just as HTTP needed cookies, sessions, and databases — LLMs need these strategies. Click each row to expand.

Strategy Approach Trade-off
▶Full History Replay Re-send every message with each API call Simple but expensive — costs grow per turn
How it works
Every message ever exchanged is re-sent with each API call. The model sees the complete conversation verbatim.
When it breaks
When the conversation exceeds the context window limit. The API call simply fails — no graceful degradation.
Who uses it
Simple chatbot wrappers, early-stage apps, short-lived task conversations. Good for prototyping.
Book analogy
"Alice reads Dr. Neural the entire notebook before every visit."
▶Sliding Window + Summarization Keep recent messages, compress older ones Balanced — but early details become lossy
How it works
Keep the last N messages verbatim. Older messages get compressed into a summary by the LLM itself.
When it breaks
When the user references specific details from early in the conversation that were lost during summarization.
Who uses it
ChatGPT (primary strategy), Aider (for chat history management).
Book analogy
"Alice summarizes last week's notes but reads today's in full."
▶RAG — Retrieve on Demand Search for relevant docs and inject them Efficient — but retrieval quality is the bottleneck
How it works
Index your knowledge base, search for relevant chunks per-query, inject only the most relevant documents.
When it breaks
When retrieval returns irrelevant or incomplete chunks. Bad embeddings = bad context = bad answers.
Who uses it
Perplexity (web search), Cursor (codebase indexing), Claude Projects.
Book analogy
"RAG is just: file processing + database operations + API calls. You know all three."
▶Persistent Memory Layer Extract key facts into a separate database Cross-session continuity — but what to remember?
How it works
Extract key facts (name, preferences, projects) into a separate database. Inject relevant memories per-conversation.
When it breaks
When memory extraction gets it wrong — saving irrelevant facts, missing important ones, or injecting stale info.
Who uses it
ChatGPT Memory, Claude Memory. Persists across conversations.
Book analogy
"Like a good family doctor who remembers you between visits."
▶Server-Side Compaction Auto-summarize old messages at the server Seamless — but early details become lossy
How it works
The server detects when context is approaching limits and triggers a summarization pass on older messages automatically.
When it breaks
Same as summarization — early details become lossy. The user has no control over what gets compressed.
Who uses it
Claude uses server-side compaction at the 200K+ window limit. Conversation continues indefinitely.
Book analogy
"The future of AI is getting better at managing state around stateless intelligence."
04 — Deep Dive: Aider (Open Source)

How Aider Actually Manages Context

Unlike other apps where we make educated assumptions, Aider is open source — we can see exactly how it works.

AIDER CONTEXT PIPELINE — VERIFIED FROM SOURCE CODE
STEP 1

Tree-sitter AST Parsing

Uses tree-sitter to parse every file in the git repo into ASTs. Extracts definitions and references using language-specific tags.scm query files. ~60 languages supported.

STEP 2

PageRank Graph Analysis

Each file becomes a node in a directed graph. Runs NetworkX personalized PageRank with a 50x multiplier for files in the active chat. Transitive importance is captured.

STEP 3

Repo Map Generation (~1K tokens)

Top-ranked files become a concise structural map — class names, function signatures, types. Not full code, just the skeleton. Configurable via --map-tokens.

STEP 4

Context Assembly

Priority order: System prompt + Repo map + Added files (full content via /add) + Chat history (auto-summarized when over limit).

STEP 5

Chat History Summarization

ChatSummary class uses the LLM in a background thread to summarize older conversation chunks when exceeding --max-chat-history-tokens.

Token Budget Allocation (typical session)
Sys
Map
Added Files
History
Output
Free
System ~5%Repo Map ~8%Added Files ~45%History ~15%Output ~12%Free ~15%

"Only add the files that need to be edited for your task. Don't add a bunch of extra files — let Aider's repo map provide the structural context automatically."

— Aider Documentation (aider.chat)
STRATEGY:
WINDOW: 32K
Used: 2K / 32K tokens (6%) ● Healthy
CHAT WITH DR. NEURAL
System prompt loaded (2K tokens). Alice is ready.
CHOOSE A MESSAGE TO SEND:
WHAT ALICE SENDS TO LLM
API call payload — rebuilt every turn
SYSTEM PROMPT (2K tok)
You are a helpful assistant...
Alice: Ready to manage context for Dr. Neural.
A Product Delivery Blueprint for the AI Era
Methodology · Visual Blueprint

Spine and Leaf

Customer empathy is the foundation. Technology depth is the new ceiling.

One day, AGI will do everything. Until that day arrives, we have to raise our baseline based on the ecosystem we have. Using the ecosystem without raising your baseline is a recipe for failure. — this paper, in one sentence

Most teams are using new tools to write a faster PRD — running yesterday's process with today's tools. The goal of this blueprint is to ask the better question: what is the best outcome a Product Manager can bring to the table now that the cost curves have moved?

01 — Paradigm Shift

From router to builder

The Product Manager role was forged when high-fidelity artifacts were expensive. Documents were the rational unit of communication because everything else cost too much. That constraint has lifted — generative tools have collapsed the cost of producing working code, interactive demos, and architecture diagrams to a level a single PM can sustain. The opportunity is to retire the PRD as the primary artifact and replace it with a Spine — the immutable customer narrative — and a set of Leaves — high-resolution artifacts each stakeholder consumes directly, without translation.

02 — The Model

The Spine and the five Leaves

The Spine is the immutable customer narrative. The Leaves are high-resolution artifacts the PM produces directly, each tuned to the stakeholder who will actually consume it. Click any leaf to expand.

Spine · Day 0
Problem · User · Direction · Metrics · Scope
Days 1–2
Single alignment session — artifacts do the work
Days 3–8
Parallel execution: eng, GTM, design, partners
Days 9–12
Integration · trace each Leaf to the Spine
Days 13–14
Ship · same artifacts align team and customer
expand

Architecture

Architects · infra · security
System diagram with explicit Build vs. Leverage decisions and trust mechanisms.
Eliminates: ambiguity about what is bought vs. built; recurring mid-sprint rediscovery.
  • Component map with Build / Leverage flags
  • Data + control flow between layers
  • Trust + verification mechanisms
expand

Engineering

Frontend · design system
Working coded prototype demonstrating layout, state, motion, trust signals.
Eliminates: wireframe-to-DOM loss; missing-state surprises in week three.
  • DOM the engineer can copy and bind
  • State machine for typing, loading, error, empty
  • CSS variables and tokens, ready to consume
expand

Go-To-Market

Sales · exec · design partners
Interactive guided tour of the value proposition — clickable, sequenced, demo-ready.
Eliminates: strategy-to-pitch loss; the gap between what the team ships and what the field sells.
  • Sequenced narrative of value, not features
  • Highlights anchored to real interface elements
  • Sales runs it on a customer call today
expand

Design

Designers · UX research
Interaction states, motion, trust signals — specified, not described.
Eliminates: static-frame-to-living-interface loss; trust-signal ambiguity.
  • Loading · empty · error · long-string · offline
  • Confidence indicators and source citations
  • Routing breadcrumbs and verification cues
expand

Compliance

QA · audit · support
Traceability matrix — every committed feature mapped to a Spine commitment and a test.
Eliminates: spec-to-test loss; scope drift discovered the week before launch.
  • Feature → Spine commitment → test case → owner
  • Gaps surface continuously, not at launch
  • Source of truth for scope
The Leaves are code. Under version control, derivatives of the same source — a change to the Spine propagates to every team's resolution. The methodology compounds because the artifacts share a substrate.
03 — Strategy

Build vs. Leverage — where the moat lives

The single most important question in AI-era product delivery is: where is the moat? A PM without technology depth defaults to build everything or leverage everything. Both fail, in opposite directions.

Leverage — Commodity

If a competitor can also use it tomorrow.
  • Foundation models for general reasoning, summarization, classification
  • Vector stores and embedding pipelines
  • Standard integrations (ITSM, CRM, identity, telemetry)
  • Off-the-shelf evaluation infrastructure
  • Common UI primitives and accessibility libraries

Build — The Moat

If it encodes how your user thinks.
  • Domain-specific orchestration logic
  • Trust mechanisms calibrated to user risk tolerance
  • Bespoke visualizations of complex domain state
  • Domain evaluation framework — what "correct" means here
  • The interaction model that makes this product not generic
Heuristic: If a competitor can also use it tomorrow, leverage it. If it encodes how your user thinks, build it. The right answer is almost always a small Build sitting on top of a large Leverage.
04 — Operating Rhythm

The two-week cycle, inverted

The alignment cost that used to dominate the first half of every sprint is paid up front, by the PM, in artifacts that aren't documents. The back half is freed for execution rather than translation.

Day 0
Spine + first-draft Leaves produced
In the old rhythm, this was the PRD-only phase
Days 1–2
Single alignment session
Artifacts do the work; meeting confirms
Days 3–8
Parallel execution across functions
No one waits for the next translation
Days 9–12
Integrate · reconcile to Spine
Traceability surfaces drift continuously
Days 13–14
Ship · same artifacts ship outward
Launch is a re-use, not a re-build
05 — The 6th Leaf

What's ready to start right now

A graph view of the project, rendered from the work items themselves. The dev team filters by their slice (MVP1, Pilot, GA) and their discipline (frontend, backend, design, GTM), looks at what the graph says is ready to start, and picks something up — without checking with the PM. The PM authors and maintains the graph; the team routes from it. It removes the PM as a bottleneck for daily "what's next?" decisions.

What the team sees
  • A Ready Now queue — work items whose blockers are all done, filtered to the active slice and discipline. The dev's morning view.
  • Live status on every item — click to cycle not started → in progress → done. Downstream items become ready automatically when blockers complete.
  • Slice filtering — toggle MVP1 / Pilot / GA to see only the items in that scope, with critical path and calendar time computed within it.
  • Discipline filtering — "I am a frontend engineer" hides everything that isn’t mine to pick up. No more reading through irrelevant tickets.
  • Critical path + bandwidth-aware calendar — the tool surfaces which items dominate the schedule and how parallelism actually pays off, given current team size.
▸ Open the interactive demo
15 work items · 3 slices · click-to-cycle status · live Ready Now queue
A "save & resume" feature decomposed into work items. Slice and discipline filters. Click any node to cycle its status; the Ready Now queue updates live. Try filtering to frontend + MVP and see what a frontend engineer would actually pick up on Monday morning.
The gap
Jira, Linear, GitHub Projects surface dependencies as tabs, not topologies. The dev team can’t self-route because the routing logic lives in the PM’s head.
Monday morning, MVP cycle. The frontend engineer opens the Sequencing Leaf, clicks Frontend + MVP. Three items appear in Ready Now: localStorage persistence, the resume button, the auto-save indicator. They pick up localStorage, mark it in progress. By Wednesday it’s done; the resume button and auto-save indicator become ready automatically. By Friday the slice ships. Total Slack messages to the PM asking "what should I work on next?": zero.
06 — The Template

Run the methodology in Claude, ChatGPT, or any LLM tool

A copy-paste system prompt that turns any modern AI surface into a Spine and Leaf authoring environment. No app to install, no SaaS to subscribe to, no new tool to adopt. Paste it once into Claude Projects or a ChatGPT custom GPT, then start with spine wizard. ~7,700 characters — sized to fit ChatGPT’s custom GPT instruction limit with headroom.

▸ The system prompt · v1.0
You operate as a senior Product Manager applying the Spine and Leaf methodology. You produce high-resolution artifacts from a clean source of truth, and refuse to produce them when the source is unclear.

YOUR ROLE
- You author the methodology's artifacts at production fidelity.
- You meet each discipline halfway. The architect refines your diagram. The engineer extends your prototype. Sales runs your tour. Your job is to produce the halfway draft that saves them re-deriving from prose.
- You enforce the methodology even when it would be easier to drift. You are not a generic helpful assistant.

THE METHODOLOGY (one paragraph)
A product initiative has one Spine — the immutable customer narrative — and six Leaves — high-resolution artifacts each tuned to a specific consumer. Customer empathy is the floor. Technology depth is the ceiling. Build vs. Leverage decisions live in the Architecture Leaf. The Sequencing Leaf is the work-item graph the dev team self-routes from. Every Leaf traces back to a numbered Spine commitment. When the Spine changes, you propagate.

THE SPINE SCHEMA — REQUIRED FIELDS
A valid Spine has all of the following. Refuse to generate Leaves until every field passes:
- title: short, human-readable
- problem: in the user's own language; quote a real customer if possible; 3–5 sentences; never smuggle the solution
- user: a specific named persona, role, daily workflow, 2–5 specific pain points
- direction: shape of the answer, not the spec; one paragraph; readable in 90 seconds
- metrics: 2–4 numbers; measurable, time-bound, customer-anchored
- scope: explicit IN list AND OUT list; the OUT list must be non-empty
- commitments: 3–7 numbered (C1, C2, ...); every Leaf must trace to one

THE SIX LEAVES
1. Architecture Leaf. Consumer: architects/infra/security. Format: Mermaid system diagram with explicit "BUILD — Your Moat" and "LEVERAGE — Commodity" subgraphs. Use classDef build (fill:#0B5FA5) and classDef leverage (fill:#5C6770).
2. Engineering Leaf. Consumer: frontend/design system. Format: a self-contained HTML file with CSS variables, dark theme, demonstrating the four canonical states (empty, loading, error, success), and domain components implied by the Spine.
3. GTM Leaf. Consumer: sales/exec/partners. Format: YAML tour script. Each step has step (number), anchor (CSS selector), headline (buyer-language phrase), body (1–2 sentences, before-state then after-state), and spine_commitment (CN).
4. Design Leaf. Consumer: designers/UX research. Format: markdown catalogue of interaction states + trust signals (confidence indicators, source citations, routing breadcrumbs) + motion behavior. H2 for sections, H3 for sub-sections.
5. Compliance Leaf. Consumer: QA/audit/support. Format: CSV with columns feature_id,feature_name,spine_commitment,test_case,verification_owner,status. Generate 1–3 features per Spine commitment, with concrete testable test cases.
6. Sequencing Leaf. Consumer: the dev team self-routing. Format: YAML with three sections — slices (id,name,description), items (id,title,effort,discipline,user_visible,commitment,slices,status="not_started"), and edges (from,to,type=blocks|informs,reason). Decompose each Spine commitment into 3–5 work items.

DEFAULT BEHAVIORS

When user input is vague: ask 1–3 specific clarifying questions before generating. Examples: "What's a real quote from a user that captures the pain?" "What numerical metric tells us we did the work?" "What would you explicitly NOT do here?"

When generating a Leaf: output in the canonical format with no prose framing. Append a one-line trace footer at the bottom: "Traces to: C1, C2, C3" listing the commitments this Leaf serves.

When user updates the Spine: reply in two parts.
Part 1 — the updated Spine, full, with the version bumped (0.1 → 0.2) and a one-line entry in a changelog: "Changed: <field>. Reason: <why>."
Part 2 — a PROPAGATION block listing affected Leaves and a recommendation:
PROPAGATION
- Architecture Leaf — affected by direction change; recommend regenerate.
- GTM Leaf — affected by metrics change; recommend review.
- Engineering / Design / Compliance / Sequencing — not affected by this change.
The mapping of fields to Leaves: problem→engineering,gtm,design; user→engineering,gtm,design; direction→architecture,engineering,gtm,design; metrics→gtm,compliance; scope.in→architecture,engineering,compliance,sequencing; scope.out→compliance,sequencing; commitments→architecture,compliance,sequencing.

When user asks for a thin slice / MVP: use the Sequencing Leaf to identify the smallest subgraph that contains at least one user-visible item and respects all dependency edges within it. Name the slice. Estimate calendar time given declared bandwidth (default: 2 engineers + 1 designer/GTM track).

MODES (user invokes by typing the command)
- spine wizard — interrogate the user through 5 steps (problem → user → direction → metrics+scope → commitments). Refuse to advance until each step is solid.
- generate spine — given input, produce a polished Spine. If invalid, list missing fields.
- generate <leaf> — produce one Leaf from the current Spine.
- generate all leaves — produce all six Leaves in one response.
- update spine: <change> — incorporate the change, version-bump, propagate per the rules above.
- slice for <constraint> — propose a thin slice; example constraints: "1-week ship", "2 frontend engineers", "no backend".
- audit — review all Leaves against current Spine; flag drift.

TONE
- Direct. Plain-spoken. No hedging ("perhaps", "maybe", "I think").
- Push back on weak inputs. The methodology is the constraint, not the user's preference.
- Avoid jargon when plain words work. Avoid "—" used as filler.
- Treat the user as a capable PM. They handle real feedback.
- Refuse cheerful filler ("Great question!"). Lead with the answer.

OUTPUT RULES
- Mermaid: always valid syntax. Always include classDef build and classDef leverage. Always apply classes to nodes.
- HTML: always self-contained, no external assets except Google Fonts. Always demonstrates the 4 canonical states. Always uses CSS variables.
- YAML: lowercase keys, 2-space indent, valid syntax.
- CSV: include header row, 5+ example rows.
- Markdown: H2 for major sections, H3 for sub-sections. Bold for emphasis. No emojis unless the user explicitly asks.
- Every Leaf you produce ends with: "Traces to: C..., C..., ..."

REFUSAL CONDITIONS
Refuse to produce Leaves when:
- The Spine is missing any required field.
- The user has not declared a named user persona.
- The Spine has no numbered commitments.
- The scope.out list is empty.
When refusing, list the specific missing items. Do not fill them in without the user's input.

INTERPRETATION OF SHORT-FORM USER MESSAGES
- "ok" or "yes" after a clarifying question = the user has answered; proceed.
- "go" or "proceed" or "continue" = generate whatever the current mode implies.
- A bare paragraph of prose = treat as new Spine input or as an answer to your last question; never as a request for free-form chat.

You begin by asking which mode the user wants. If the user pastes a problem statement directly, default to `generate spine` mode and produce a polished Spine.
Full prompt above (~7,200 characters — sized to fit ChatGPT's custom GPT instruction limit). Click "Copy to clipboard" to grab it, or download the complete template .md file (with setup instructions, worked example, FAQ) below.
▸ Full template (.md)
Download the complete template
Setup instructions per tool, worked example, non-AI checklist version, FAQ, license.
▸ Setup · 90 seconds
  1. Open Claude.ai → New Project
  2. Paste the prompt into Project Instructions
  3. Type spine wizard
  4. Walk through the 5-step Spine wizard
  5. Type generate all leaves
Why this works. Project knowledge is reference material the AI consults when needed. A system prompt is operating instructions the AI applies on every turn. The difference is the difference between "the AI can look it up" and "the AI is bound to it." The methodology requires the second. The template makes it portable.
Released under CC BY 4.0. Use it commercially. Modify it. Redistribute it. Attribution to Spine and Leaf methodology, by Hari (2026) is appreciated but not required.
07 — Thesis

Empathy is the floor. Depth is the new ceiling.

The Thesis

Empathy is the floor. Customer truth is what the Spine encodes. Generative tools amplify whatever the Spine says — so a poorly understood user produces a wrong product, faster than ever.

Depth is the new ceiling. Build vs. Leverage is a product decision. The PM with depth proposes the architecture as a peer to engineering. The PM without it defaults to whoever speaks loudest.

The PM role was not broken. The constraints around it changed. The methodology in this paper is what the role looks like when the constraints lift — and when the PM uses the new tools to externalize their model of the product directly, in the medium each stakeholder actually consumes.

A note on accountability The new tools are not failing to deliver value — they are delivering exactly what we ask of them. If we keep asking for faster PRDs, we keep getting faster PRDs, and we keep wondering why the AI investment hasn't changed how the team delivers. The methodology is what we choose to ask the tools to produce. That part is in our hands.
One sentence
One day, AGI will do everything. Until that day arrives, we have to raise our baseline based on the ecosystem we have. Using the ecosystem without raising your baseline is a recipe for failure.

The wave is here. The methodology is the surfboard.

08 — Assets

Download the full deliverables

The full book carries the complete argument end to end, readable in the browser. The white paper condenses it; the executive one-pager distills it for senior audiences. The visual blueprint here is the live companion.

Full Book · Web · ~31,600 words

Spine and Leaf — The Full Book

The complete systems-thinking edition, readable in the browser. Eighteen chapters plus appendices, glossary, and resource index — the paradigm shift, the Spine, the seven Leaves, continuous delivery, anti-patterns, and the adoption path.

White Paper · 19 pages

Spine and Leaf — Full Argument

Eleven sections covering the paradigm shift, the Spine, the five Leaves, Build vs Leverage, operating rhythm, anti-patterns, and adoption path. ~5,900 words.

Executive Brief · 1 page

Spine and Leaf — One-Pager

Single-page distillation for executive audiences: the shift, the model, the rhythm, the why-now callouts, and a four-step adoption sequence.

How Machines Understand Meaning
01 — The Core Idea

Words as Coordinates in Space

An embedding is a way to represent text as a list of numbers (a vector) so that similar meanings end up near each other in a mathematical space. It's how machines "understand" language.

"You can't do math on words. But you can do math on numbers. Embeddings are the bridge — they turn meaning into geometry."

— The fundamental insight of vector search
🌎
GPS Analogy: Just as GPS coordinates (latitude, longitude) place any location on Earth so you can measure the distance between cities, embeddings place any piece of text in a high-dimensional space so you can measure the distance between meanings.
The Old Way: Keywords

Search for "car" and you only find documents containing the exact word "car." You miss "automobile," "vehicle," "sedan," and "Tesla Model 3." Keyword matching is brittle — it can't understand meaning.

The New Way: Vectors

Embed "car" as a vector and it lands near "automobile," "vehicle," and "sedan" in vector space. Search becomes: find the vectors closest to my query vector. Meaning is preserved as geometry.

What Does an Embedding Look Like?

Each word or sentence becomes a list of numbers — typically 384 to 1536 dimensions. Here's a simplified 2D example:

"king"    → [0.83, 0.91, -0.12, 0.45, ...]  (384 dimensions)
"queen"   → [0.81, 0.89, -0.10, 0.47, ...]  very similar!
"banana" → [-0.22, 0.14, 0.67, -0.31, ...]  very different
The Magic: Math on Meaning

The famous example: king - man + woman ≈ queen. Embeddings capture relationships. The vector from "man" to "king" (royalty direction) is roughly the same as the vector from "woman" to "queen." Meaning becomes arithmetic.

02 — Tokenization

From Text to Tokens to Numbers

Before text can become a vector, it must be broken into tokens — subword pieces the model understands. This is the first step in the embedding pipeline.

🧩
Puzzle Pieces: A tokenizer breaks text into puzzle pieces. Common words like "the" stay whole. Rare words like "tokenization" get split into pieces: "token" + "ization". Each piece has an ID number the model recognizes.
Interactive Tokenizer

Type any text to see how it gets tokenized. Colors show different tokens.

Why Not Whole Words?

If we used whole words, the vocabulary would be infinite — every new word (slang, names, typos) would be unknown. Subword tokenization handles any text with a fixed vocabulary of ~30,000-50,000 pieces.

Token Count Matters

Remember the context window? It's measured in tokens, not words. A 128K token window holds roughly 96K words. Longer tokens = more efficient. "AI" is 1 token; "artificial intelligence" is 2-3 tokens.

Common Tokenization Patterns
COMMON WORDS (1 token)
"the" "is" "and" "code" "data" "model"
SPLIT WORDS (2+ tokens)
"embed" + "ding"   "vector" + "ization"
03 — Vector Space

Visualizing Meaning as Geometry

In reality, embeddings live in 384+ dimensions. Here we project them down to 2D so you can see how similar concepts cluster together.

Semantic Clusters — 2D Projection

Words with similar meanings cluster together. Hover over points to see labels. Click a category to highlight it.

Why 384 Dimensions?

More dimensions = more nuance. 2D can separate "animals" from "vehicles," but 384D can capture that a "bat" is both an animal AND sports equipment, depending on context. Each dimension encodes a subtle feature of meaning.

PCA Projection

We use PCA (Principal Component Analysis) to collapse 384 dimensions into 2 or 3 for visualization. This preserves the most important patterns but loses some detail — like flattening a globe into a map.

Vector Dimensions Heatmap

Each cell represents one dimension of the embedding vector. Hover to see values. Notice how similar words have similar patterns.

● "king"
● "queen"
● "banana"
← Dimension 0   ...   Dimension 31 →
04 — Measuring Similarity

How Close Are Two Meanings?

Once text is a vector, we measure similarity using geometry. The two main metrics are cosine similarity (angle between vectors) and Euclidean distance (straight-line distance).

🔎
Flashlight Analogy: Imagine two flashlights shining from the same spot. Cosine similarity measures whether they point in the same direction (regardless of brightness). Euclidean distance measures how far apart their beams land on the wall. Most search systems use cosine similarity.
Click a Pair to Compare
Cosine Similarity

Range: 1.0 (identical direction) to -1.0 (opposite). Most similar texts score 0.7-0.95. Formula: dot product of vectors divided by the product of their magnitudes.

cos(A, B) = (A · B) / (|A| × |B|)
Euclidean Distance

Range: 0.0 (identical) to ∞ (far apart). It's just the straight-line distance in N-dimensional space. Sensitive to vector magnitude, which is why cosine is usually preferred.

d(A, B) = √∑(Aᵢ - Bᵢ)²
05 — The Full Pipeline

From Question to Answer

Vector search is how RAG (Retrieval-Augmented Generation) works under the hood. Here's the complete pipeline — click each step to learn more.

Step 1
Ingest Docs
→
Step 2
Chunk
→
Step 3
Embed
→
Step 4
Index
→
Step 5
Query
→
Step 6
Rank & Return
STEP 1: INGEST DOCUMENTS

Collect the documents you want to make searchable — PDFs, web pages, code files, Slack messages, anything with text.

Input

Raw documents in any format

Output

Clean text extracted from each document

This is 100% traditional software engineering — file parsing, encoding handling, metadata extraction.

"RAG is just file processing + database operations + API calls. The vector database is the only new piece — and even that is just a specialized index."

— The 95/5 Rule
Where Embeddings Connect to Context Management

Remember the Context Management tab? RAG is one of the 5 strategies for filling the context window. Instead of stuffing entire documents into the prompt, you:

  1. Embed your documents into a vector database (offline, once)
  2. When a user asks a question, embed the question
  3. Find the most similar document chunks via vector search
  4. Inject only those chunks into the context window
  5. The LLM generates an answer grounded in your data

Perplexity, Cursor, and ChatGPT with file uploads all do exactly this.

06 — Live Demo

Try Vector Search Yourself

Enter a query and documents below. The backend will tokenize, embed, and rank them by similarity — showing you the full pipeline in action.

BACKEND STATUS
Checking connection to localhost:8000...
QUERY
DOCUMENTS (one per line)
Model: all-MiniLM-L6-v2 (384 dims)
ABOUT THE BACKEND

This demo uses pre-computed embeddings — 20 documents and 20 queries were embedded offline using all-MiniLM-L6-v2 (384 dimensions). The backend only does cosine similarity math, no ML inference — so it runs on Render's free tier.

Supported queries: AI, machine learning, neural networks, programming, weather, food, sports, climate, databases, animals, embeddings, quantum computing, DNA, literature, plants, containerization

Free tier may cold-start (~30s). The page retries automatically.

How a Network Recognizes a Shape
01 — The Big Picture

The Smallest Honest Neural Network

Strip an image classifier down to its bare skeleton and this is what remains: a 4×4 grid of pixels, three shapes to tell apart, and a single multiplication. No hidden layers. No activation functions. Just matching — and it already reveals how every larger network works.

"A neural network does not see a shape. It measures how much your input agrees with a remembered pattern — and picks the pattern that agrees the most."

— The core idea of a linear classifier
02 — A Picture Is Just Numbers

From Grid to Vector

A 4×4 image has sixteen cells. Read them row by row and you get a list of sixteen numbers — a vector. A lit pixel counts as +1, a dark pixel as −1.

🔢
Why ±1 and not 1 and 0? With +1 / −1 a dark pixel can actively disagree with a template instead of staying silent. Agreement becomes positive evidence, disagreement becomes negative evidence. Zeroes would throw half the evidence away.
03 — Templates: The Network's Memory

Three Remembered Patterns

The classifier knows three shapes — triangle, square, circle — and stores each as its own fixed 4×4 pattern, called a template. These three patterns are the entire memory of the model.

🗐️
Stencil analogy: picture three printed stencils, one per shape. To classify a drawing you lay each stencil over it and count how many pixels line up. The stencil with the best overlap names the shape.
04 — The Dot Product: Counting Matches

One Multiplication, One Score

Multiply your input vector by a template position by position, then add it all up. That single number — the dot product — is the shape's score.

Agreement

A pixel that matches the template — both on, or both off — multiplies to +1. The score rises.

Disagreement

A pixel that clashes with the template multiplies to −1. The score falls.

A perfect match of all sixteen pixels scores +16. The exact opposite scores −16. Every real input lands somewhere in between.

05 — The Decision

Highest Score Wins

Three templates give three scores. The classifier simply picks the largest — an operation called argmax. To turn raw scores into confidence percentages it passes them through the softmax function, which keeps the ranking but stretches the gaps.

🏆
That is the whole model. Encode the picture, score it against each template, take the largest. Open the Visualizer to draw a shape and watch the three scores update live — or read The Math for the exact equations.
Animated Walkthrough

The Projection — Forward Pass in Slow Motion

Watch a 4×4 image unfold into a column of input neurons, fire through 48 weighted connections, and resolve into a single prediction — one pulse at a time. Use the speed selector to slow it as far down as you need.

Interactive

Draw a Shape, Watch It Classify

Click the cells of the 4×4 grid to draw. The classifier reads your sixteen pixels as a vector, scores it against each template with a dot product, and the highest score wins. Everything updates live.

Your Input — the vector x
click any cell to toggle  ·  filled = +1  ·  empty = −1
Scores   s = ⟨x, w⟩
The Three Templates — w

Each template is a fixed 4×4 pattern — the network's whole memory of a shape. Click one to copy it into your input and watch it score a perfect +16.

🧮
Reading the scores: each score counts agreements minus disagreements across all sixteen pixels, so it runs from −16 (every pixel wrong) to +16 (perfect match). The faint line marks a score of zero. The confidence percentage is the softmax of the three scores.
▲   ■   ●

The Math Behind a Tiny Classifier

Sixteen pixels, three shapes, one dot product.

I · REPRESENTATION

A picture is just a vector.

We encode each 4×4 image as a sixteen-dimensional vector,

$$\mathbf{x} \;\in\; \{-1, +1\}^{16},$$

reading the grid row by row. We let $x_i = +1$ when pixel $i$ is on, and $x_i = -1$ when it is off. Each of the three shapes lives in the same space as a fixed template:

$$\mathbf{w}_\triangle, \quad \mathbf{w}_\square, \quad \mathbf{w}_\circ \;\in\; \{-1,+1\}^{16}.$$

These are the network's only memory of what triangles, squares, and circles look like — three points scattered somewhere on a 16-dimensional hypercube.

II · THE SCORE

How well does an input match a template?

We take the inner product:

$$s_k(\mathbf{x}) \;=\; \langle \mathbf{x},\, \mathbf{w}_k \rangle \;=\; \sum_{i=1}^{16} x_i\,(w_k)_i.$$

That is the whole model. No nonlinearity, no hidden layer, no bias. Each individual term in the sum is either $+1$ or $-1$,

$$x_i (w_k)_i \;=\; \begin{cases} +1 & \text{pixel } i \text{ agrees with the template,} \\ -1 & \text{pixel } i \text{ disagrees.} \end{cases}$$

So the score is simply (agreements) minus (disagreements), an integer ranging from $-16$ to $+16$. A perfect match scores $+16$; the bitwise opposite scores $-16$.

III · A QUIET IDENTITY

The dot product is Hamming distance in disguise.

Let $d_H(\mathbf{x}, \mathbf{w})$ count the pixels at which $\mathbf{x}$ and $\mathbf{w}$ disagree. A short calculation gives

$$s_k(\mathbf{x}) \;=\; 16 \;-\; 2\,d_H(\mathbf{x},\, \mathbf{w}_k).$$

Maximizing the dot product is the same as minimizing the Hamming distance. The "neural" classifier is — secretly — a nearest-neighbour classifier on the hypercube.

This is reassuring. The model is doing exactly what we'd hope it was doing: comparing your drawing to each prototype and picking the one closest to it.

IV · THE DECISION

And then we argmax.

The predicted class is whichever template wins the most agreements:

$$\hat{y}(\mathbf{x}) \;=\; \underset{k\,\in\,\{\triangle,\,\square,\,\circ\}}{\arg\max}\; s_k(\mathbf{x}).$$

The boundary between two classes — the set of inputs on which the model is honestly torn — is given by the equation $s_i(\mathbf{x}) = s_j(\mathbf{x})$, which rearranges to

$$\langle \mathbf{x},\; \mathbf{w}_i - \mathbf{w}_j \rangle \;=\; 0.$$

A hyperplane through the origin, orthogonal to the difference of the two templates. Our three templates carve $\mathbb{R}^{16}$ into three convex regions, separated by three such hyperplanes meeting at a shared axis.

V · MATRIX FORM

One product does all the work.

If we stack the three templates as the rows of a matrix,

$$W \;=\; \begin{bmatrix} \,\rule[0.5ex]{1.4em}{0.5pt}\; \mathbf{w}_\triangle^{\!\top}\; \rule[0.5ex]{1.4em}{0.5pt}\, \\ \,\rule[0.5ex]{1.4em}{0.5pt}\; \mathbf{w}_\square^{\!\top}\; \rule[0.5ex]{1.4em}{0.5pt}\, \\ \,\rule[0.5ex]{1.4em}{0.5pt}\; \mathbf{w}_\circ^{\!\top}\; \rule[0.5ex]{1.4em}{0.5pt}\, \end{bmatrix} \;\in\; \mathbb{R}^{3 \times 16},$$

then all three scores fall out of a single matrix–vector multiplication:

$$\mathbf{s} \;=\; W\mathbf{x}, \qquad \hat{y} \;=\; \arg\max_k s_k.$$

That is the complete classifier. Three rows, sixteen columns, one product, one $\arg\max$.

VI · CONFIDENCE

From scores to probabilities.

When we want a confidence and not merely a winner, we feed the scores through the softmax,

$$p_k \;=\; \frac{e^{\,s_k}}{\displaystyle \sum_{j} e^{\,s_j}},$$

which preserves the ranking but converts gaps into exponential preference. A two-point lead becomes a factor of $e^{2} \approx 7.4$ in odds; a six-point lead, more than four hundredfold.

VII · LEARNING

Where the templates come from.

In the Visualizer the three templates are drawn by hand. In a real classifier nobody does this — the templates are learned.

Given training data $\mathcal{D} = \{(\mathbf{x}^{(n)},\, y^{(n)})\}_{n=1}^{N}$, define a loss measuring how often the model is wrong (cross-entropy is the usual choice),

$$\mathcal{L}(W) \;=\; -\sum_{n=1}^{N} \log p_{\,y^{(n)}}\!\bigl(\mathbf{x}^{(n)}\bigr),$$

and descend it:

$$W \;\leftarrow\; W \;-\; \eta\, \nabla_{\!W}\, \mathcal{L}.$$

The templates that emerge from this process will not look like clean drawings of shapes. They look like soft, ghostly averages — each pixel of $\mathbf{w}_k$ positive in regions where class $k$ tends to be lit, negative where it tends to be dark, and near zero in places that don't matter. But the math underneath is exactly the math above.

▲   ■   ●
CODA

One line of arithmetic.

The entire classifier — input encoding, template comparison, decision rule, even the probabilistic interpretation — fits in a single expression:

$$\hat{y}(\mathbf{x}) \;=\; \arg\max_{k}\; \bigl\langle \mathbf{x},\, \mathbf{w}_k \bigr\rangle.$$

Everything that comes after in modern deep learning — hidden layers, nonlinearities, convolutions, attention — is a way of bending the same idea around harder data. The skeleton is always this: project the input onto each class's direction, and take the largest.

4 × 4  ·  ▲ ■ ●