Module 04 · Lesson 4.4
Vector Search, Metadata Filters and Source Grounding
On this page
- What you will learn
- What are embeddings? Meaning as a place on a map
- How vector search ranks results with similarity scores
- Metadata filters: who is allowed to see which document
- Source grounding: every claim traces back to a passage
- Try it: filter, rank and check citations in Python
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
In the last lesson our little search missed a customer who wrote "I want my money back", because the help centre says "refund". The two mean the same thing, but they share no word. Search by meaning fixes that. It brings a new worry, though. Meaning does not care who is allowed to read a document, and a staff-only page about refund limits is very close in meaning to a customer's refund question.
This lesson covers three ideas that work together. Vector search finds passages by meaning. Metadata filters decide which documents a user may see at all. Source grounding makes sure each claim in an answer points to a passage that was really retrieved. Most of it needs no coding. One short Python example puts all three in about forty lines.
What you will learn
- Explain embeddings and vector search in plain words, with a similarity score and a cut-off.
- Say when keyword search, vector search or both together is the better fit.
- Use metadata filters before ranking so that staff-only documents never reach the customer agent.
- Check in code that every cited ID was really retrieved, and reject an answer with no citation.
Before you start
- The previous lesson, Retrieval-Augmented Generation for Agent Knowledge.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What are embeddings? Meaning as a place on a map
Imagine a map of a town where every shop stands near similar shops. Bakeries sit in one street, bike shops in another. You do not need a shop's name to find a bakery. You walk to the bakery street and look around.
An embedding does this for text. A special model reads a passage and turns it into a list of numbers, which is its position on a "map of meaning". Texts with similar meaning get nearby positions. "Refund" and "money back" land close together, even though they share no letters.
- Embedding
- A list of numbers that stands for the meaning of a piece of text. It comes from an embedding model.
- Vector
- Another word for that list of numbers. A vector with 3 numbers is a point in 3 directions, like a spot on a map plus a height.
- Vector search
- Turn the question into a vector, then find the stored vectors that are nearest to it.
- Similarity score
- A number that says how close two vectors are. Higher means closer in meaning.
Real embeddings have hundreds or thousands of numbers, not three. They are made by an embedding model, not written by hand. You can read how to get them in Google's Embeddings (opens in a new tab) guide and Anthropic's Embeddings (opens in a new tab) page. In this lesson we use three-number toy vectors that we invent ourselves, so you can see the idea with your own eyes.
How vector search ranks results with similarity scores
Search works in the same three steps every time. Index time: turn each passage into a vector and store it. Question time: turn the question into a vector. Then compare it with every stored vector and rank the passages from nearest to farthest.
A popular way to compare two vectors is cosine similarity. Picture two arrows starting from the same point. If they point the same way, the score is 1. If they point at right angles, it is 0. You do not need the maths now, because a function in the example does it for you.
Keyword search or vector search?
| Keyword search | Vector search | |
|---|---|---|
| Finds | Passages that contain the same words. | Passages with a similar meaning. |
| Strong at | Exact things: order numbers, product codes, error messages. | Different wording: "money back" and "refund". |
| Weak at | Different wording for the same idea. | Exact codes and rare names, which carry little "meaning". |
| Easy to explain | Yes. You can point at the shared words. | Harder. The score is a number from a model. |
Our help centre has both kinds of question. "Where is QF-1042?" is exact, and the order tool handles it. "Can I get my money back?" is about meaning, so vector search helps. Start with the simplest method that passes your tests, and add the other only if the tests show a gap.
Metadata filters: who is allowed to see which document
Metadata is a set of labels attached to each document. It is data about the data, like the sticker on a file folder. Each Quillfeather help-centre document has three labels: audience, topic and updated.
| id | title | audience | topic |
|---|---|---|---|
| KB-05 | Refund timing | customer | refunds |
| KB-03 | Returns policy | customer | returns |
| KB-14 | Warehouse packing checklist | staff | internal |
| KB-15 | Refund approval limits | staff | internal |
A metadata filter removes documents whose labels do not match before the search ranks anything. For the customer agent the filter is audience == "customer". Staff-only documents are never even considered.
- All documents
KB-01 to KB-16
- Metadata filter
audience == customer
- Rank by similarity
Only the allowed documents
- Minimum score
Drop weak matches
- Top few passages
Sent to the model
The order matters. A document that was filtered out can never appear in the results.
Also decide where the filter value comes from. It must come from your program, based on who is logged in. It must never come from the model or from the customer's message, because a message can say anything. This is the same "least privilege" idea you saw in Authentication, Secrets and Least-Privilege Access.
Source grounding: every claim traces back to a passage
Source grounding means every claim in an answer can be traced to a retrieved passage. In our agent, the answer names the passage IDs, for example "The refund reaches your payment method within 5 working days (KB-05)."
You can build a cheap check in ordinary code. It cannot judge whether the sentence is true, but it can catch two clear failures:
- No citation. The answer cites nothing. Reject it, or hand the customer to a person.
- A citation that was never retrieved. The answer cites KB-15, but KB-15 was not in the results. The model invented it or got it from somewhere it should not. Reject it.
The agent keeps the list of IDs it retrieved. After the model answers, a short function finds every ID in the answer and compares the two lists. If the check fails, the agent does not send the answer. It can ask the model to try again once, and then hand over to a person.
Try it: filter, rank and check citations in Python
The script below uses toy vectors. We invented these numbers to show the idea. Real embeddings are much longer and come from an embedding model. Roughly, the three numbers stand for delivery, money and product, but that is only our own labelling.
import math
import re
# Toy 3-number vectors, invented to show the idea. Real embeddings come from a model.
DOCS = [
{"id": "KB-01", "audience": "customer", "vec": (0.9, 0.1, 0.1)},
{"id": "KB-03", "audience": "customer", "vec": (0.3, 0.7, 0.5)},
{"id": "KB-05", "audience": "customer", "vec": (0.1, 0.9, 0.2)},
{"id": "KB-07", "audience": "customer", "vec": (0.0, 0.3, 0.9)},
{"id": "KB-14", "audience": "staff", "vec": (0.5, 0.1, 0.6)},
{"id": "KB-15", "audience": "staff", "vec": (0.1, 0.95, 0.15)},
]
MIN_SCORE = 0.85
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def search(query_vec, audience, top_k=2):
allowed = [d for d in DOCS if audience in (None, d["audience"])] # filter BEFORE ranking
ranked = sorted(((cosine(query_vec, d["vec"]), d["id"]) for d in allowed), reverse=True)
return [(round(score, 3), doc_id) for score, doc_id in ranked if score >= MIN_SCORE][:top_k]
def check_citations(answer, retrieved_ids):
cited = re.findall(r"KB-\d{2}", answer)
if not cited:
return "REJECT: no citation"
bad = sorted(set(cited) - set(retrieved_ids))
return "OK" if not bad else "REJECT: not retrieved " + ", ".join(bad)
query = (0.1, 0.9, 0.2) # toy vector for "How long until my refund arrives?"
print("Staff and customer documents mixed:", search(query, None))
hits = search(query, "customer")
print("Customer search:", hits)
ids = [doc_id for _, doc_id in hits]
print(check_citations("The refund arrives within 5 working days (KB-05).", ids))
print(check_citations("Refunds above 500 need a manager (KB-15).", ids))
print(check_citations("The refund arrives within 5 working days.", ids))Standard library only. Save it and run python vsearch.py.
What each part does
DOCSlists six documents. Each has anid, anaudiencelabel (the metadata) and a toy vector invec. KB-14 and KB-15 are staff-only.MIN_SCORE = 0.85is the cut-off. Matches below it are dropped.cosine(a, b)multiplies the vectors number by number, adds the results, and divides by the lengths of both vectors. The answer is the similarity score.audience in (None, d["audience"])is the metadata filter. It keeps a document only when its audience matches. PassingNoneturns the filter off, which we do once, only to show the danger.sorted(..., reverse=True)ranks the allowed documents from highest score to lowest. Theif score >= MIN_SCOREpart applies the cut-off, and[:top_k]keeps the best two.check_citationsuses the regular expressionKB-\d{2}to find every ID such as KB-05 in the answer.set(cited) - set(retrieved_ids)leaves the IDs that were cited but never retrieved.- The last three lines test a good answer, an answer that cites a staff-only ID, and an answer with no citation.
Staff and customer documents mixed: [(1.0, 'KB-05'), (0.998, 'KB-15')]
Customer search: [(1.0, 'KB-05'), (0.9, 'KB-03')]
OK
REJECT: not retrieved KB-15
REJECT: no citationWith the filter off, the staff-only KB-15 takes second place. With the filter on, it is gone and KB-03 takes its place. The good answer passes. The second answer cites KB-15, which was never retrieved for this customer, so it is rejected. The third cites nothing, so it is rejected too.
Conclusion and your next step
Embeddings turn text into positions on a map of meaning, and vector search returns the nearest ones. A minimum score lets the agent admit that nothing fits. Metadata filters are applied before ranking, because they decide what a user may see. Source grounding adds a last check: every claim cites a passage, and every cited ID was really retrieved.
Your next step: change the query vector in vsearch.py to (0.9, 0.1, 0.1), the "delivery" corner, and see which documents come back. Then raise MIN_SCORE until the results disappear. Then continue to Memory Retention, Privacy and Data Lifecycle, where you decide what an agent may store about people and for how long.
Want to see the whole retrieval idea first? Revisit Retrieval-Augmented Generation for Agent Knowledge, or read RAG vs Fine-Tuning vs Prompting: Which Should You Use?.
Common errors and how to fix them
A customer sees information meant for staff.
Why it happens: The filter was applied after ranking, or only in the instructions, or the staff documents were in the same index with no label.
Fix: Label every document with its audience and filter before ranking. Take the filter value from the logged-in user, never from the model.
The agent answers confidently from a weak match.
Why it happens: There is no minimum score, so the nearest passage is always returned.
Fix: Set a cut-off from test questions. Return "nothing relevant found" below it.
Exact codes such as order numbers are not found.
Why it happens: Vector search is tuned for meaning and handles rare codes poorly.
Fix: Use a keyword search or a tool for exact lookups, or combine both in a hybrid search.
An answer is sent even though its citation is wrong.
Why it happens: Nothing checks the cited IDs against the retrieved ones.
Fix: Run a check such as check_citations before sending. Retry once, then hand over to a person.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a document and test the filter
Add a new staff-only document and a new customer document to the DOCS list in vsearch.py. Then show that the staff document never reaches the customer search, and that a wrong citation is rejected.
You will need
- A staff-only document KB-16 (Supplier escalation contacts) with the toy vector (0.1, 0.25, 0.9).
- A customer document KB-09 (Brake safety) with the toy vector (0.1, 0.2, 0.95).
- A query vector for "My brakes feel weak": (0.1, 0.2, 0.95).
- The file vsearch.py from this lesson.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Copy an existing line in DOCS and change the id, audience and vector.
- Pass
Noneas the audience to see the unfiltered results. - Compute the retrieved IDs from the search result, as the script does with
ids.
Show a model answer
Add {"id": "KB-16", "audience": "staff", "vec": (0.1, 0.25, 0.9)} and {"id": "KB-09", "audience": "customer", "vec": (0.1, 0.2, 0.95)}. Searching with the brake query and "customer" ranks KB-09 first, because its vector is identical to the query. KB-16 is removed by the filter before any score is computed. Searching with None lets KB-16 compete, and it scores high enough to appear, which shows why the filter must come first. Finally, check_citations on an answer that cites (KB-16) returns REJECT because KB-16 is not in the retrieved IDs. Check the printed lists, not only your guess, because exact scores depend on the numbers you chose.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A filter is about permission. It runs before ranking so a staff-only document can never be retrieved for a customer. It is tempting to think filters improve relevance, but a staff page can be highly relevant and still not be allowed.
Show the answer and explanation
Answer: B. A citation to something never retrieved is a sign of an invented or leaked source. Having a citation is not enough, which is why the first option is wrong. Changing the list to make the check pass would defeat the purpose of the check.
Show the answer and explanation
Answer: B. Some passage is always the nearest, so without a cut-off the agent would answer an unrelated question from an unrelated passage. The first option has it backwards. The cut-off is what makes an empty result possible.
Frequently asked questions
What is an embedding in simple terms?
An embedding is a list of numbers that stands for the meaning of a piece of text. Texts with similar meanings get similar numbers, so a program can compare meaning by comparing numbers.
What is the difference between keyword search and vector search?
Keyword search looks for the same words. Vector search looks for the same meaning. Keyword search is better for exact codes and names. Vector search is better when people phrase the same idea in different words. Many systems use both.
What are metadata filters in RAG?
They are rules based on the labels attached to documents, such as audience, topic or date. A filter removes documents that do not match before the search ranks them. They are the main way to keep private documents away from users who should not see them.
How do I know an AI answer is grounded in the sources?
Ask the model to cite passage IDs, then check in code that each cited ID was really retrieved and that the answer has at least one citation. That catches missing and invented sources. For whether the passage really supports the claim, a person or a test set must read it.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Embeddings(opens in a new tab)
Google · Official documentation · Explains what embeddings are and how to create them with the Gemini API.
- Embeddings(opens in a new tab)
Anthropic · Official documentation · Anthropic's page on embeddings and how text embeddings are used.
- LLM08:2025 Vector and Embedding Weaknesses(opens in a new tab)
OWASP Foundation · Official documentation · Risks in vector stores, including access control and data leaks.
- LLM09:2025 Misinformation(opens in a new tab)
OWASP Foundation · Official documentation · Why unsupported answers are a risk and how grounding in sources helps.
- Introducing Contextual Retrieval(opens in a new tab)
Anthropic · Official documentation · Discusses combining meaning-based and keyword search to retrieve better passages.
- re: Regular expression operations(opens in a new tab)
Python Software Foundation · Official documentation · Background for the `re.findall` line in the example.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.