Building a Working Local RAG Pipeline (And Breaking It Until I Understood It)
Introduction
I hate the feeling of being a pretender in anything technical. Nobody can learn everything, and I’m fine with that—but I’ve always prided myself on being able to swim in deeper waters than most.
AI security is clearly here to stay, and I knew my hands-on depth wasn’t where it needed to be yet.
Even if I find plenty of the surrounding AI hype industry noxious, the underlying technology is genuinely fascinating to me. Running quantized local models like qwen3:14b on my own MacBook meant I could experiment on my own hardware for free, with no API bills and no cloud black box hiding what was happening on the wire.
More importantly, I learn best through what I call collision-driven development: build a system that actually looks like what clients are deploying, run into the real errors and edge cases, understand the contract deeply, and then break it every which way from Sunday.
A quick note on how I built this (my learning contract): I don’t let AI generate whole projects for me—if I can’t explain how a boundary works or debug it when it breaks, it doesn’t count. For this lab, I designed the pipeline, wrote the core logic and test suite hands-on, and used AI assistants strictly for unfamiliar Python syntax, FastAPI boilerplate checks, and working through edge-case collisions. Every failure mode and fix below is something I hit and verified on my own machine.
Getting the Loop Working Locally
The first real “aha” moment came before I even wired up any documents. I hooked up a bare FastAPI route to local Ollama, opened the auto-generated Swagger UI, and—with my tortoiseshell cat Mimi sitting on the chair next to me—asked what makes tortoiseshell cats different.
qwen3:14b answered concisely in a few seconds, entirely on my laptop.
Once you see that clean request-and-response loop in FastAPI, it’s immediately obvious why it’s so popular.
The “Tiny Google” That Returned 200 OK and Nothing Useful
To turn my chat endpoint into an internal corporate assistant, I got Gemini to create three synthetic Northstar Industries policy documents (remote_work_policy.md, personal_device_policy.md, and incident_reporting_policy.md) and got some assistance working through writing a simple keyword retriever in app/retrieval.py, which was new to me.
Initially, I expected it to work a little like a tiny Google: search for a phrase, count how many times it shows up, and hand the highest-scoring file to the model.
matches = re.findall(
r"\b" + re.escape(keyword) + r"\b",
content,
flags=re.IGNORECASE,
)
That scoring mechanism was my first real introduction to how AI systems force you to think much deeper about which mechanism is actually making the judgment. If a word or phrase wasn’t in the policy in its exact form, the retriever had zero sense of semantic closeness and returned "No document found.".
Asking about "home broadband" when the policy said "home internet"— or passing a full natural-language question into a phrase matcher — meant nothing came back.
Even better, when retrieval missed, FastAPI still returned 200 OK with fluent text.
Wrestling with the system prompt (and setting think: False so I didn’t get caught in Qwen’s love of neurotic over-reasoning) made it obvious that a working 200 is not the same thing as a proper answer at all.
That pushed me into tracing every handoff—from the HTTP request, to what retrieval actually returned, to what landed in the model’s message—until I could see what was really crossing the wire.
The focused notes on those two boundaries live in my Technical Cabinet under Keyword document retrieval and RAG grounding and failure tracing.
Vectors, Chunking, and Finding “Home Broadband” Without the Exact Words
To get past exact-word matching, I needed a way to score meaning instead of spelling.
My intuition for vector math actually came from building Roll High or Die, where vectors were literal directions —how Raylib mapped out movement and camera orientation in 3D space.
That mental model turned out to be surprisingly useful for understanding “semantic direction” and “semantic closeness”: an embedding model (nomic-embed-text running locally via Ollama) turns a chunk of text into a vector, and texts with similar meanings point in similar directions.
Instead of embedding an entire policy file as one big blob, retrieve_semantic() splits each markdown file on \n## into heading-sized chunks. If you embed a whole multi-page document at once, irrelevant sections dilute the overall vector and skew the cosine_similarity score.
Chunking along the natural headings keeps each vector focused on one topic:
def cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float:
a = np.asarray(vec_a, dtype=float)
b = np.asarray(vec_b, dtype=float)
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom == 0.0:
return 0.0
return float(np.dot(a, b) / denom)
When I ran "Does Northstar help pay for my home broadband?" through this pipeline—even though the policy only ever says "home internet"—the retriever pulled the right section, handed it to qwen3:14b, and came back with a concise, accurate answer citing the $65 per month allowance.
The standalone reference and zero-vector guard live in my Technical Cabinet under Semantic document retrieval.
Testing What Actually Breaks (Unit Math vs. The “Delaware” Trap)
Once the happy path worked, I wrote tests/test_semantic_retrieval.py— my first real automated test suite — and split it into two layers:
- Fast unit tests (
pytest -m "not integration") checkingcosine_similaritydirectly on identical, perpendicular, and zero vectors—no Ollama server or network connection required. - Integration tests (
@pytest.mark.integration) hitting live local Ollama against the Northstar policy docs.
Splitting pure math checks from live-model checks meant I could answer “does this function work, period?” in milliseconds before testing anything that depends on a running model server.
More importantly, writing targeted edge cases exposed a subtle failure mode I didn’t expect:
- Hard off-topic (
"What is the best recipe for sourdough bread?"): Scored belowmin_score=0.60and cleanly returned"No document found.". - The entity-overlap trap (
"Is Northstar a Delaware-registered corporation?"): My gut assumed this would miss too. Instead,"Northstar"carried enough entity overlap with the policy header thatretrieve_semantic()scored it above0.60and handed the remote-work policy toqwen3:14b.
What actually saved me wasn’t the retriever —it was the system instruction giving Qwen explicit permission to say “I don’t know” and treat the retrieved document as the sole citable source of truth.
Layer 1 (retrieval) filtered out sourdough bread, and Layer 2 (the grounded prompt) caught the Delaware false positive when entity overlap slipped past the similarity threshold.
I broke down that test split in my Technical Cabinet under pytest unit and integration tests.
What “Working” Still Doesn’t Prove
Getting an accurate answer on honest questions is only the starting line.
An AI model will genuinely do whatever it feels it needs to — and can do —to satisfy a request; guardrails are what stop people from putting their arms into the machinery and losing them.
Realistically, users aren’t going to fact-check every paragraph coming out of a RAG system.
As a builder, your job isn’t to hand people scissors and hope they run safely, it’s to eliminate the opportunity for the scissors to appear in the first place.
Doing one job exceptionally well is the foundation of good software engineering, and in RAG, that job is making the output trustworthy.
Right now, this pipeline still has clear edges to harden next:
- Retrieved documents are untrusted input: Right now, policy text goes straight into the
usermessage after the question. If a malicious instruction ever lands inside an ingested document, the model sees it in the same breath as the prompt. - Pre-computing embeddings: Embedding every policy chunk on every request works for three tiny markdown files on a laptop, not for a real document store.
Next up is building out Portcullis—turning this single-service prototype into a deployed, seven-module system where gated boundaries stand between untrusted inputs and the core model, so I have a real defensive architecture I can deliberately attack, measure, and point to alongside Brunel, an entirely AI-driven solutioning tool I’m working on for solutions engineers.