Introduction
Hey everyone, I'm Oil. This guide explains how LLMs work underneath—with zero math formulas—covering Tokens, Attention, and KV Cache.
Every daily AI user runs into the same puzzles: why does an Agent forget early constraints and write worse code the longer a chat runs? Why do experienced builders keep saying "use progressive Skills," "isolate scouting in subagents," and "never mutate the top of your system prompt"?
Every one of those habits traces directly to two mechanics: Self-Attention and KV Cache.
How an LLM Actually Generates a Reply
Three baseline facts clear up everything that follows:
1. Models Read Chunks Called Tokens, Not Sentences
LLMs slice text and code into small pieces called Tokens (roughly a common English word, part of a long word, or 1–2 Chinese characters). Context window limits (200K, 1M) and billing both count Tokens.
2. LLMs Are Completely Stateless ("Zero Built-In Memory")
Even after 10 smooth turns in a chat window, the model itself retains zero memory between requests. On Turn 10, your client software glues Turns 1–9, every file read, every tool log, and your Turn 10 message into one giant text payload and resends all of it from scratch.
3. Answers Are Predicted One Token at a Time (Autoregressive)
Models don't compose a full reply upfront—they predict just the single next most likely Token, append it to the prompt, and repeat. For example, ask "What is the capital of France?": the model reads the question and predicts "The", appends it and predicts " capital", then " is", then " Paris", looping token by token until it outputs an end-of-reply marker.
Self-Attention & Why Long Contexts Degrade
1. What Attention Does in One Sentence
Read: "The puppy ran out of breath chasing the cat, because it was too tired."
As the model reaches "it" and "tired", Self-Attention compares the current token back against every earlier token, scoring relevance—assigning heavy weight to "puppy" (out of breath) and almost zero to unrelated words.
2. Query, Key, and Value Demystified
For every token, the model computes three sets of features:
Query(What am I looking for?): e.g., "the running subject from earlier."Key(What label describes me?): e.g., "noun, animal, main subject."Value(What actual meaning do I carry?): the token's semantic payload.
The current token matches its Query against every earlier token's Key, converts match scores into percentage weights, and blends the earlier tokens' Values accordingly.
3. Why Long Chats Forget Early Instructions
At every single generation step, total attention weights across all prior tokens always sum to 100%.
Early in a thread, your core requirements get a generous slice of that 100%. After dozens of file reads and noisy terminal logs inflate context to 100K+ tokens, outdated logs compete for that exact same 100% pool—diluting the weight left for your original rules even when you're nowhere near the advertised 200K or 1M max window.
KV Cache & Prompt Caching
Suppose you hand an LLM a 10,000-token document and ask for a 200-token summary. Generating token #1 computes Key and Value for all 10,000 input tokens; without caching, generating token #2 would recompute all 10,000 unchanged tokens from scratch—meaning a 200-token summary would reprocess the entire document 200 times.
1. KV Cache: Stop Recomputing Unchanged History
Because LLMs process strictly left-to-right, token #101 never alters the Key and Value already computed for tokens #1–100. Storing those already-computed K and V results in GPU memory is KV Cache.
- The brief pause right after hitting Enter is Prefill (computing
KV Cachefor your input in parallel). - The fast streaming words that follow are Decode (reusing cached
K/Vand computing only one new token per step).
2. Cross-Request Reuse: Prompt Caching
Early KV Cache only lived for a single response and cleared afterward. An AI Agent, however, loops 20–30 tool calls per task, resending the exact same [System Prompt + Tools + Project Rules + Prior Turns] with only one new tool output appended at the bottom. Prompt Caching (supported by providers like OpenAI, Anthropic, and DeepSeek) keeps that prefix's KV Cache warm on provider servers across requests—cutting latency dramatically and discounting cached input tokens by roughly 90%.
3. Why Editing Anything at the Start Busts the Entire Cache
Prompt Caching requires an Exact Prefix Match. Because each token's K/V depends on every token before it, placing a changing timestamp at the very top of your system prompt invalidates the entire cache behind it—forcing full recomputation on every single turn.
Turning These Mechanics into Better Agent Habits
1. Use Progressive Skills Instead of Bloated Global Rules
Keep AGENTS.md or CLAUDE.md lean and move specialized specs into Skills that load only when needed (see What Are Skills? A Practical Guide).
2. Offload Noisy Scouting & Log Triage to Subagents
Keep dozens of file reads and giant stack traces inside isolated subagent threads so main context stays sharp (see How to Use Subagents Effectively).
3. Start Fresh Threads Between Unrelated Tasks—or /compact Mid-Run
Don't carry dead debugging history into your next feature. Running /compact mid-task does rebuild the prefix cache on that one turn, yet it still saves substantial time and quota over subsequent turns compared to carrying tens of thousands of stale tokens.
4. Static Rules at the Top, Dynamic Updates Strictly at the Bottom
Keep system prompts, tool definitions, and global rules untouched up front and append dynamic state, new turns, and loaded Skills at the tail to maximize KV Cache hits.
Summary
- Models are stateless—every turn resends full history.
- Attention sums to 100%—keep context clean via Skills, subagents, and fresh threads.
- KV Cache needs an exact prefix—freeze static context up front and append dynamic content at the end.


