
Agent Context Basics
The Problem
Imagine you have an AI agent, and you want to ask it a question about information it was never trained on. Maybe it’s your company’s internal documentation, last week’s product changes, or data that updates every hour. The model simply doesn’t know about any of it.
So what do you do?
The Two Obvious Answers (and Why They Fall Short)
The easiest thing is to paste the information into your prompt. For a small amount of text, that works. But it falls apart fast: the context window is limited, and the more you stuff in, the more expensive and slower every call becomes. You can’t paste an entire knowledge base into every question.
The second instinct is fine-tuning: retraining the model on your data. This is problematic on several fronts. It’s expensive, it’s genuinely hard to do well, and if your information changes quickly, fine-tuning can’t keep up. You’d be retraining constantly and still be out of date.
What we actually want is a way to give the agent fresh, relevant information on demand, without baking it into the model and without drowning the prompt.
The Core Idea: Context as a Separate Component
Instead of giving the agent the knowledge directly, you give it a tool (for example, an MCP tool) that queries a separate component. That component is responsible for holding and retrieving the context.
This separation is the heart of the approach. Why not just wire retrieval directly into the agent? Because the separation buys you a lot: you can swap the underlying implementation, control access to the data, and let the agent decide when it actually needs to reach for the information. The agent asks a question; the context component answers.
It also solves the problems from before. Because the knowledge lives outside the model, you can update it at any time without retraining, which removes both the cost and the freshness pain of fine-tuning.
So how does the context component work? There are two main approaches.
Approach One: RAG (Retrieval-Augmented Generation)
The most common approach is RAG, and its core idea is cleverer than it looks: instead of matching keywords, you search by meaning. You take the information you want the agent to know and index it: the text is converted into embeddings, numerical representations of meaning, and stored in a vector database.
What is an embedding?
An embedding is just a list of numbers that captures what a piece of text means. A simple way to picture it is a map. Imagine placing every sentence you have on a giant map, where sentences with similar meanings land close together and unrelated ones land far apart. The embedding is the sentence’s coordinates on that map.
For example, “How do I reset my password?” and “I forgot my login credentials” share almost no words, but they mean nearly the same thing, so they land right next to each other. “What’s our Q3 revenue?” lands somewhere else entirely. That’s the trick that lets RAG search by meaning instead of by keywords.
One level deeper: a real map has two coordinates (east-west, north-south), but an embedding typically has hundreds or thousands of them. You can’t picture that many dimensions, but the idea is the same: each number captures some aspect of meaning, and together they position the text in a “meaning space.” These coordinates are produced by an embedding model, a neural network trained specifically so that texts with similar meanings get similar numbers.
When the agent needs something, its query is turned into an embedding too, and the system finds the stored chunks whose meaning is closest. Those chunks are handed to the agent, and it answers using them.
How “closest” is measured: cosine similarity
So how does the system decide which chunks are “closest” in meaning? The most common measure is cosine similarity.
Picture each embedding as an arrow pointing out from the center of the map. Cosine similarity ignores how long the arrows are and only asks: how much do they point in the same direction? Arrows pointing the same way score 1 (very similar meaning), arrows at a right angle score 0 (unrelated), and arrows pointing in opposite directions score -1.
One level deeper, the formula is:
cos(θ) = (A · B) / (|A| × |B|)
The top part, the dot product, multiplies the two vectors number by number and adds the results. The bottom part divides by the length of each vector, which is what removes the effect of length and leaves only direction. A tiny two-dimensional example:
- A = (1, 2) and B = (2, 4): B is just A stretched to twice the length, so they point the same way. Similarity = 1.
- A = (1, 2) and C = (2, -1): the dot product is 1×2 + 2×(-1) = 0, so they’re at a right angle. Similarity = 0.
Why direction rather than plain distance? In embedding space, direction is what carries meaning, while length can be influenced by things that don’t matter for your question. Many embedding models also output vectors already scaled to length 1, in which case cosine similarity is simply the dot product, which makes it very cheap to compute.
And one more level: with millions of chunks, comparing the query against every single vector would be slow. Vector databases use approximate nearest-neighbor indexes (HNSW is a popular one) that find the closest vectors very quickly while skipping most of the comparisons, trading a tiny bit of accuracy for a huge gain in speed.
One level deeper, this is where the real engineering challenges appear:
- Chunking. How do you split documents? Chunks that are too large make retrieval noisy; chunks that are too small lose their surrounding context.
- Embedding quality. Retrieval is only as good as the model that turns text into vectors.
- Irrelevant results. When the closest match isn’t what the user needed, the agent can answer confidently from the wrong source.
Approach Two: Graph Database
The second approach is to store the information in a graph database. Instead of indexing text as vectors, you represent knowledge as entities and the relationships between them. When the agent wants something, it generates a query against the graph and gets back the answer.
What is a graph, exactly?
Forget charts with axes. In this context, a graph is simply dots connected by labeled arrows. Think of a whiteboard where you write people, teams, and projects as circles, and draw arrows between them that say how they’re related.
For example: Dana reports to Avi. Avi worked on Project Atlas. Project Atlas uses PostgreSQL. Each circle is a node (an entity), and each arrow is an edge (a relationship). That’s the whole model.
One level deeper: most graph databases, such as Neo4j, use what’s called a property graph. Nodes have a type (Employee, Project) and properties (name: "Dana", start_date: 2024), and edges have a type (REPORTS_TO, WORKED_ON) and can carry properties too (since: 2023). Another common way to store the same idea is as triples: subject, predicate, object, as in (Dana, reports to, Avi). Either way, the relationships are stored as first-class data, not inferred from text.
The strength here is different. RAG shines at “find me information relevant to this topic.” A graph shines when the question requires hopping between connected entities, like “who is the employee who reported to the manager who worked on the project that…”. Those relationship-chaining questions are exactly where vector similarity struggles and a graph excels.
How the agent asks a graph a question
With RAG, the agent’s question is turned into an embedding and matched by meaning. With a graph, the agent instead writes a small query that describes the path it’s looking for, a bit like giving directions: “start at a project called Atlas, go back along worked on to whoever worked on it, then go back along reports to to find their direct reports.”
One level deeper, that query is written in a graph query language. The most popular is Cypher, which literally draws the path in ASCII art:
MATCH (e:Employee)-[:REPORTS_TO]->(m:Employee)-[:WORKED_ON]->(p:Project {name: "Atlas"})
RETURN e.name
Round brackets are nodes, square brackets are edges, and the arrows show direction. The LLM is good at writing these, as long as it knows the graph’s schema: which node types, edge types and properties exist. In the tool setup, that schema typically goes into the MCP tool’s description, so the agent sees it before it writes a query.
And one more level: this is where the graph’s performance story comes from. In a relational database, each hop is a JOIN, and a chain of five hops is five JOINs whose cost grows with table size. A graph database stores each node’s connections directly next to it, so each hop just follows pointers to neighbors. The cost depends on how much of the graph you actually walk, not on how big the whole graph is. The practical risks are on the query side: the LLM can write a query that is wrong, or one that explodes by walking too many hops. Read-only credentials, hop limits and query timeouts are cheap safeguards worth putting in the tool.
One level deeper, the hard part is up front: building the graph from raw information. Reliably extracting entities and relationships from unstructured text is a challenge of its own.
In practice, today this is usually done with an LLM too: it reads each chunk of your documents and extracts triples like (Dana, reports to, Avi). Two problems show up fast:
- Entity resolution. “Dana Levi,” “Dana,” and “D. Levi” need to become one node, not three. Get this wrong and the graph splits into disconnected fragments, and multi-hop questions silently fail.
- Schema design. You need to decide up front which entity and relationship types matter. Too loose, and the LLM invents a hundred near-duplicate relationship names; too strict, and useful facts get dropped.
One more pattern worth knowing is GraphRAG (from Microsoft Research). It builds a graph from your documents, groups densely connected nodes into communities, and writes a summary for each one. That lets it answer “big picture” questions, like “what are the main themes across all our incident reports?”, which neither plain RAG nor a plain graph query handles well.
A Middle Ground: The LLM Wiki
There’s a useful pattern between these two worlds, popularized by Andrej Karpathy under the name LLM Wiki. You store your knowledge as Markdown files, and when one file references another, for example with a wiki-style [[link]], you’re encoding a relationship between two units of information. Together, those links form a hidden graph on top of plain text.
The twist is who writes the wiki: the LLM does. You drop raw material (articles, papers, notes, transcripts) into a folder, and the LLM reads it, writes a page per topic, links related pages together, and keeps index files and short summaries up to date. You mostly read, ask questions, and steer.
Answering a question works like a person browsing a wiki. The agent reads the index to find the most relevant page, and instead of stopping there, it can follow the links leaving that file and pull in the connected files too. The agent gets not only the direct match but the context around it.
One level deeper, notice what’s missing: at the scale Karpathy describes (on the order of a hundred articles and a few hundred thousand words on one topic), there’s no vector database at all. The index files and summaries the LLM maintains are enough for it to find its way. As the wiki grows past that, you can bring embeddings back in: use vector search to find the entry page, then follow links from there, which is the bridge back to RAG.
Karpathy also describes periodic “linting” passes, where the LLM scans the wiki for inconsistencies, fills gaps, and adds links between pages that should be connected. That maintenance step is what keeps the wiki from slowly going stale.
This gives you much of the best of both worlds: the readability of plain text plus navigation across linked information, without running a full graph database. Karpathy uses Obsidian as the front end for browsing his wiki, since it shows Markdown links as a navigable graph.
The catch: permissions and sources
The LLM Wiki has a real weakness that the other two approaches don’t. Picture two common requirements: each user should only see what they’re allowed to see, and every answer should link back to the documents it came from.
With RAG and a graph, both are straightforward, because every piece of stored context still points back to one original document. You can attach that document’s permissions and link to each embedding, each node, and each edge, filter by the user’s identity before anything reaches the LLM, and show the sources next to the answer. It’s classic software engineering, and the tooling for it already exists.
The LLM Wiki can’t do this cleanly, because its pages aren’t copies of your documents. They’re text the LLM wrote by blending many sources together. Once a public document and a restricted one are merged into a single page, there’s no clean way to say who may read that page, or which sentence came from where.
One level deeper, there are workarounds. A page can inherit the strictest permissions of everything it was built from, or you can keep a separate wiki for each team or access level. These work when permissions are coarse: one person, as in Karpathy’s personal setup, or a team where everyone has the same access. They break down with per-document permissions, where you can’t keep a separate wiki for every combination of access rights. Sources have a similar problem: a page can list what it was built from, but the agent is citing the LLM’s summary, not the original text.
So the rule of thumb: if you need per-document authorization, or want the agent to cite its sources with every answer, the LLM Wiki is not the way to go. It shines when everyone reading it shares the same access.
Choosing, and Combining
So which should you pick? Often it isn’t either-or. It depends on the questions you expect:
- Topic-style lookups: RAG.
- Relationship-chaining questions: a graph.
- Navigable context without heavy infrastructure: an LLM Wiki.
Increasingly, teams combine them in hybrid setups: vector retrieval finds the entry points, and graph traversal expands the context around them. The right choice depends on your data and your questions, not on which technique is trendiest.
Takeaway
RAG, graphs, the LLM Wiki, and hybrids all aim at the same goal: give your agent fresh, relevant information on demand, without retraining and without overflowing the prompt. Get the separation between agent and context right, and the rest is tuning.