<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oleksii Aleksapolskyi on Medium]]></title>
        <description><![CDATA[Stories by Oleksii Aleksapolskyi on Medium]]></description>
        <link>https://medium.com/@TheWake?source=rss-2dc94f1b35ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*URDX4UUPErSxAshBeLOndg.jpeg</url>
            <title>Stories by Oleksii Aleksapolskyi on Medium</title>
            <link>https://medium.com/@TheWake?source=rss-2dc94f1b35ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:04:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TheWake/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Retrieval-Augmented Hiring: Finding a RAG Engineer Is a RAG Problem]]></title>
            <link>https://medium.com/@TheWake/retrieval-augmented-hiring-finding-a-rag-engineer-is-a-rag-problem-a5c19ef0a9d4?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c19ef0a9d4</guid>
            <category><![CDATA[recruiting]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[hiring]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 18:38:34 GMT</pubDate>
            <atom:updated>2026-03-25T18:38:34.178Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re looking for someone. You have a description: keywords, qualifications, years of experience. You’re sure you’ll know them when you see them. This is the part of the movie where Edward Norton is looking for Tyler Durden.</p><p>You had your job posting. LangChain, vector databases, 3+ years Python. You fired it at the candidate pool and the hits came back, hundreds of them, every one looking right. You felt good about that.</p><p>How’s your retrieval doing now?</p><p>You matched on someone who touched LangChain once at a hackathon and ran a Postgres instance that happened to have pgvector enabled. Right résumé, wrong chunk. You matched on someone who can explain embeddings at a whiteboard but has never seen what happens when your section boundaries are inconsistent and your abbreviations break sentence detection and your Recall@5 is pinned at 0.95 and users are still complaining. You matched on the keyword. You missed the answer.</p><p>And the ones who could actually do the job, the IR researchers who never touched LangChain, the backend engineers who built search before “RAG” had a name, they weren’t using your keywords. You didn’t even know you missed them. That’s your recall. You’re not getting it back.</p><p>So you think, fine, cast a wider net. More job boards, more keywords, more recruiter blasts. Now you’ve got twice the candidates and half the signal. You optimized for recall and drowned in false positives.</p><p>The only thing you actually control is precision. Make sure what lands in the interview holds the answer. That’s it. That’s all you’ve got.</p><p>Now you’re wondering why the right person never shows up early. You’re fifty interviews deep and nobody fits. That’s your MRR, Mean Reciprocal Rank, and it’s in the gutter, because your offer says “we’re using AI to transform [vague industry],” which retrieves everything and ranks nothing. You could have said “we’re building retrieval over 200K clinical notes and we think the problem is in the chunking layer.” The engineer who reads that and gets excited, that’s your signal. That’s your MRR climbing. Not because you found better candidates. Because you asked a better question.</p><p>But you wrote the safe posting. You wrote the one that matches everyone. And everyone matched.</p><p>How’s your retrieval doing now?</p><p>And the thing is, your whole idea of “RAG engineer” was someone who wires up an embedding API, calls a vector store, formats a prompt. That was your chunk size. Fixed window. Surface tokens. Every tutorial graduate matched and every match disappointed, because most of the time when someone says “the model hallucinated,” what actually happened is the model got a chunk that sort of matched and sort of didn’t hold the answer. Right document, wrong span. You needed the engineer who knows <em>why</em>. Boundary detection. Domain adaptation. Which layer of the pipeline is the actual bottleneck. But you weren’t testing for that. You were testing for keywords. And the keywords said yes every time.</p><p>You wanted the best candidates closer to the top. Graded relevance, not pass/fail. Someone who sets up a pipeline is partially relevant. Someone who can diagnose why your retrieval is failing and redesign the chunking layer, that’s fully relevant. But your grading couldn’t tell the difference. So you hired the first one. And six months later you’re writing the same job posting again.</p><p>That’s nDCG, and yours was flat. Nobody upgraded Heinlein’s MIKE. They just added enough connections and one day the system was intelligent. Your candidates didn’t change. Your grading did.</p><p>How’s your retrieval doing now?</p><p>Retrieval quality is not a prompt engineering problem. It’s a systems problem that spans extraction, chunking, embedding, retrieval, and evaluation. Each layer has its own failure modes, its own metrics, its own domain-specific tuning. The interview is the benchmark. The question is whether your evaluation methodology is good enough to measure what matters.</p><p>If a candidate reads this and their reaction is “that’s a cute analogy,” they’re a keyword match. If their reaction is “okay, but what’s the equivalent of structure-aware chunking in a hiring pipeline, what are the boundary signals that actually separate deep candidates from surface-level ones?” they’re thinking at the right level.</p><p>And if you’ve read this far and you’re still looking for the RAG engineer, the one who thinks about retrieval at every layer, in every domain, who sees the system where others see the toolchain, you might want to consider that you just read an article that did to you exactly what a good retrieval pipeline does to a query.</p><p>The match was in your context the whole time.<br><em>If that framing resonates with the way you think about retrieval, or about hiring, </em><a href="https://www.linkedin.com/in/alexey-a-181a614/"><em>I’d love to compare notes</em></a><em>. or discuss </em><a href="https://github.com/metawake/chunkweaver"><em>my projects</em></a><em>.</em><br><em>If your definition of the role fits in a single chunk, you’re probably searching for the wrong thing.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c19ef0a9d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Right Document, Wrong Chunk]]></title>
            <link>https://medium.com/@TheWake/right-document-wrong-chunk-5b2b45f50130?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b2b45f50130</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 12:58:02 GMT</pubDate>
            <atom:updated>2026-03-25T13:02:20.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Most RAG tutorials stop at: split, embed, retrieve top-K. Works fine on a README. Point the same pipeline at a 200-page regulation, a pile of clinical notes, or an RFC. Retrieval looks fine. Recall@5 is fine. MRR is fine. Users still complain.</p><p>Often it isn’t the wrong document. It’s the chunk: Article 17 cut in half, two RFC sections welded together, a table header orphaned from its rows. The model gets text that sort of matches the query and sort of doesn’t contain the answer. Right document. Wrong chunk. Standard metrics mostly won’t flag that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_woiUZ8wcga3skos6Inuag.png" /></figure><h3>The gap between documents and spans</h3><p>Recall@K asks: did we surface the right source? That’s the right question for a big messy web corpus.</p><p>It’s the wrong bottleneck for a lot of enterprise RAG. Legal, regulated industries, specs — you might have tens or hundreds of documents, not millions. The GDPR shows up. The question is whether the span stuffed into the prompt actually holds the answer, or a splice of two unrelated sections.</p><p>I ran into this while building retrieval evaluation tooling. Two chunking strategies, both “great” on document-level scores. Same top-line numbers. The retrieved strings were not the same story at all.</p><h3>What fixed-size chunking misses</h3><p>RecursiveCharacterTextSplitter walks a separator list — \n\n first — and in clean text that often tracks real boundaries. Blank line between sections? You’ll usually get a sane break. It’s smarter than naive character windows.</p><p>What it still doesn’t know: that a newline inside a long article is not the same as a boundary between articles. That overlap measured in characters can slice mid-sentence. That a table header belongs with its data rows. That a section titled “Definitions” is a coherent unit that shouldn’t be split across chunks.</p><p>Whitespace is a structural proxy — a cheap signal that correlates with where topics change. It’s a real proxy. It’s also a weak one, because it can’t distinguish between layout whitespace and semantic boundaries.</p><p>On structured documents — anything with articles, numbered sections, hierarchical headings — the actual boundary markers are sitting right there in the text.</p><h3>chunkweaver</h3><p><a href="https://github.com/metawake/chunkweaver">chunkweaver</a> splits text at structural boundaries instead of character counts. Stdlib-only core, no dependencies.</p><pre>pip install chunkweaver</pre><pre>from chunkweaver import Chunker<br>from chunkweaver.presets import LEGAL_EU</pre><pre>chunker = Chunker(<br>    target_size=1024,<br>    overlap=2,<br>    overlap_unit=&quot;sentence&quot;,<br>    boundaries=LEGAL_EU,<br>)</pre><pre>chunks = chunker.chunk(regulation_text)</pre><p>Three layers of splitting, applied in order:</p><p><strong>Regex boundaries.</strong> You specify where sections start — ^Article\s+\d+, ^##, ^Section\s+\d+\.\d+. Seven built-in presets cover EU and US legal, SEC filings, FDA labels, RFCs, markdown, and chat logs. These are starting points; most production deployments add domain-specific patterns on top.</p><p><strong>Heuristic detectors.</strong> HeadingDetector scores lines using casing, length, whitespace patterns, and positional signals. TableDetector identifies tabular regions by delimiter density and column alignment. These handle documents where you don’t know the structure upfront — or where the structure is implicit rather than marked by clean patterns.</p><p><strong>Fallback splitting.</strong> When a section exceeds target_size, it falls back to paragraph, sentence, or word boundaries. Never mid-sentence. Overlap is in sentences, not characters.</p><p>These layers compose. Boundaries from regex, heuristics, and external annotations are merged, deduplicated, and applied in a single pass. A table detected by TableDetector stays intact even when surrounded by regex-driven splits.</p><h3>Hierarchical splitting</h3><p>Not all boundaries are equal. In EU regulation, a CHAPTER boundary is stronger than a Section boundary, which is stronger than an Article boundary. chunkweaver models this:</p><pre>from chunkweaver.presets import get_preset</pre><pre>boundaries = get_preset(&quot;legal-eu&quot;, leveled=True)<br># Returns [(pattern, level), ...] — level 0 is strongest</pre><p>The chunker splits only as deep as needed. If a chapter fits in one chunk, it stays whole. If it doesn’t, it splits at the next level down. This preserves semantic coherence at the broadest level possible instead of fragmenting everything to the finest grain.</p><p>Seven presets have leveled variants: legal-eu, legal-us, financial, fda-label, rfc, academic, and markdown.</p><h3>Domain customization</h3><p>Presets are convenient defaults, not the point. The actual value is that every aspect of chunking is configurable per domain:</p><p><strong>Sentence patterns.</strong> The default sentence splitter uses [.!?]\s+(?=[A-Z&quot;(]), which works for English prose. For Cyrillic text (Serbian, Montenegrin, Russian), accented Latin (Spanish, French), or CJK, swap in a different pattern:</p><pre>from chunkweaver.sentences import SENTENCE_END_PERMISSIVE, SENTENCE_END_CJK</pre><pre>chunker = Chunker(<br>    target_size=1024,<br>    boundaries=LEGAL_EU,<br>    sentence_pattern=SENTENCE_END_PERMISSIVE,  # handles non-ASCII capitals<br>)</pre><p><strong>Keep-together regions.</strong> Tell the chunker that certain patterns must not be split — table headers with their data, clinical labels with their content:</p><pre>chunker = Chunker(<br>    target_size=1024,<br>    keep_together=[r&quot;^(Assessment|Plan|HPI):.*(\n(?!  \S).*)*&quot;],<br>)</pre><p><strong>Annotation ingestion.</strong> If your PDF extractor (Unstructured, Docling, Azure Document Intelligence) already knows where sections and tables are, pass SplitPoint and KeepTogetherRegion directly instead of re-discovering structure with regex. The chunker doesn’t care how the annotations were produced.</p><p><strong>ML detectors.</strong> The BoundaryDetector ABC accepts any class that returns SplitPoint or KeepTogetherRegion annotations. Regex, heuristic scoring, or a trained classifier — same interface. The repo includes example ML detectors: a GradientBoosting heading detector for OCR-damaged legal text (0.97 F1 vs 0.76 for the heuristic on held-out CV), and a clinical section detector for notes where abbreviated styles break pattern matching.</p><pre>from chunkweaver import Chunker<br>from my_detectors import TrainedHeadingDetector</pre><pre>chunker = Chunker(<br>    target_size=1024,<br>    detectors=[TrainedHeadingDetector(&quot;model.joblib&quot;)],<br>)</pre><p>The architecture is intentionally open here. The hard problem in production chunking is boundary detection on messy, real-world documents — OCR artifacts, inconsistent formatting, mixed languages. Regex and heuristics cover the common cases. For the rest, you can plug in whatever works for your data.</p><h3>Diagnostics</h3><p>Chunking is configuration, and configuration needs feedback.</p><p>--recommend analyzes a document and suggests configuration — which preset, which detectors, what target size. It scores every built-in preset against the text, runs a dry-run chunk, and prints a ready-to-use snippet:</p><pre>chunkweaver --recommend contract.txt</pre><p>--inspect evaluates the result after chunking — size distribution, fallback ratio, orphan headings, near-miss boundaries that almost qualified as splits, and actionable suggestions:</p><pre>chunkweaver contract.txt --preset legal-eu --inspect</pre><p>Add --llm-audit for per-chunk coherence scoring via GPT-4o-mini. Both commands support --format json for CI pipelines.</p><p>This is the feedback loop that matters: recommend a config, chunk, inspect the result, adjust. Not guessing and hoping.</p><h3>The benchmark</h3><p>I ran this on GDPR, EU AI Act, CCPA, and eight RFCs. 11 documents, 58 queries, ~600-character target size. LLM-as-judge (gpt-4o-mini) rated each retrieved chunk as full, partial, or insufficient.</p><p>Against naive 600-char fixed windows: chunkweaver wins <strong>15 to 4</strong>, 39 ties. Binomial p = 0.019. Doc-clustered permutation p = 0.015.</p><p>Against LangChain RCTS: <strong>11 to 4</strong>, 43 ties. Binomial p = 0.119. A trend, not significant at this sample size. RCTS’s paragraph heuristic captures some structural signal, which narrows the gap.</p><p>I’m not going to oversell the RCTS result. But the mechanism is clear: when the chunker knows where the boundaries are, it stops cutting through them. The gain is proportional to how much structure the document has and how poorly whitespace proxies for it.</p><p>A note on scope: this tested rule-based strategies. Embedding-based semantic chunkers (LlamaIndex’s SemanticSplitter, Unstructured’s layout-aware pipeline) solve a related but distinct problem and comparing them is a separate experiment.</p><p>Full methodology, reproduction scripts, and raw judge output: <a href="https://github.com/metawake/chunkweaver/tree/main/benchmark">benchmark/</a></p><h3>Where it fits</h3><p>chunkweaver is strongest on documents designed to be navigable — legal text, financial filings, clinical notes, RFCs, technical standards, annotated PDFs. The more structure a document has, the more there is to exploit. On domains like these, a single preset change can move retrieval quality measurably.</p><p>On free-form prose where paragraphs are the only structure, the advantage over RCTS narrows. That’s a domain boundary, not a deficiency — if paragraphs already track topics, there’s nothing better to split on.</p><p>It takes text in and puts chunks out. Any extractor that produces markdown feeds straight into it. It doesn’t embed, doesn’t store, doesn’t retrieve. It handles the split, then hands off to whatever pipeline comes next.</p><h3>Try it</h3><pre>pip install chunkweaver</pre><pre>chunkweaver --recommend my_document.txt<br>chunkweaver my_document.txt --preset legal-eu --inspect<br>chunkweaver my_document.txt --preset legal-eu --export-dir ./chunks/</pre><p>LangChain and LlamaIndex wrappers are optional extras. MIT licensed.</p><p><a href="https://github.com/metawake/chunkweaver">GitHub</a> — <a href="https://pypi.org/project/chunkweaver/">PyPI</a></p><p><em>If Recall@K is pinned near 1.0 and people still report wrong answers, look at what text entered the prompt — not only which document name came back.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2b45f50130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three RAG Architectures, One Legal Document, 25 Needles. None Found More Than Half.]]></title>
            <link>https://medium.com/@TheWake/three-rag-architectures-one-legal-document-25-needles-none-found-more-than-half-cebdc7ab3a90?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/cebdc7ab3a90</guid>
            <category><![CDATA[gdpr]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[legaltech]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 17:53:38 GMT</pubDate>
            <atom:updated>2026-03-04T17:57:27.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I showed that Recall@5 = 1.0 hides a deeper problem: on the EU GDPR, only 28-44% of the actual answer text gets retrieved, even with perfect document-level recall. A comment on my previous post suggested that “changing the architecture changes the failure mode, not the constraint.” So I tested that hypothesis.</p><p>I took the 19,000-star PageIndex: the “vectorless, reasoning-based RAG” that claims 98.7% accuracy on FinanceBench -and ran it against the same GDPR document, the same 5 queries, the same 25 needles.</p><p>The result wasn’t what I expected.</p><h3>The Setup</h3><p><strong>Document:</strong> EU General Data Protection Regulation -373K characters, ~100 pages, 173 recitals (explanatory preamble) and 99 articles (binding legal rules).</p><p><strong>Queries:</strong> 5 legal questions covering erasure rights, lawful processing conditions, controller/processor obligations, international data transfers, and administrative fines.</p><p><strong>Needles:</strong> 25 specific text spans from the GDPR that must appear in the retrieved context. Examples: &quot;up to 20 000 000 EUR, or in the case of an undertaking, up to 4 %&quot; from Article 83(5), or &quot;erasure of personal data concerning him or her without undue delay&quot; from Article 17(1).</p><p>Either the exact text is there, or it isn’t. No LLM judge. No subjectivity.</p><p><strong>Three approaches:</strong></p><ol><li><strong>Naive Vector RAG</strong> -512-character chunks, nomic-embed-text, Qdrant, top-5</li><li><strong>POMA AI</strong> -structure-aware chunking via POMA API, same embedder and store</li><li><strong>PageIndex-</strong>vectorless, reasoning-based retrieval via <a href="http://chat.pageindex.ai/">chat.pageindex.ai</a></li></ol><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4Deqhpz0CDl_JyTDUHR7A.png" /></figure><p>PageIndex returns <strong>summaries with page citations</strong> rather than source text chunks. On a lenient metric (conveying the same information), it scored 22/25 -but for legal and compliance, verbatim text matters, and summaries can introduce hallucination risk. So we report strict needle coverage only. More on this below.</p><h3>What Surprised Me</h3><h3>PageIndex Navigated to the Right Sections</h3><p>On queries with clear section titles -“lawful processing under Article 6” -PageIndex performed well. It correctly identified the relevant articles and returned comprehensive, organized responses with page references.</p><p>On Query 2 (lawful processing), naive vector RAG scored 0/5. It couldn’t find a single needle. PageIndex scored 3/5. The tree-based navigation genuinely outperformed vector similarity here.</p><h3>But It Returned Summaries, Not Source Text</h3><p>Every PageIndex response paraphrased the GDPR rather than quoting it. Where the GDPR says &quot;up to 10 000 000 EUR, or in the case of an undertaking, up to 2 % of the total worldwide annual turnover&quot;, PageIndex returned “€10 million or 2% of global turnover.”</p><p>Same meaning. Different text. For understanding the law, that’s fine -arguably better. For a compliance pipeline that needs exact legal language, it’s a problem. POMA AI intentionally returns raw text for this reason: summaries can introduce hallucinations. So we measure strict needle coverage -exact text presence -which is what matters for legal use cases.</p><h3>Cross-Chapter Retrieval Failed Everywhere</h3><p>Query 4 asks about data transfer rules. One needle is the fine amount from Article 83 -a completely different chapter. PageIndex navigated to Chapter V (Transfers) but didn’t cross-reference Chapter VIII (Penalties). Vector RAG didn’t either. None of the approaches connected information across distant sections.</p><h3>The Architecture Comparison</h3><p>PageIndex works by building a hierarchical tree from the document -like a table of contents -then using an LLM to reason over node titles and summaries to find relevant sections. At query time, the LLM picks nodes and extracts their text.</p><p>This means:</p><ul><li>The LLM never sees the full document text during retrieval -only titles and summaries</li><li>Navigation quality depends on how well summaries capture section content</li><li>Each query requires an LLM inference call (cost and latency per query)</li></ul><p>Vector RAG (both naive and POMA) embeds chunks once and does a similarity lookup at query time. No LLM in the retrieval loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKZ0iMkFyVJ5fLZidCS9jA.png" /></figure><p>Both approaches index once. But PageIndex pays an LLM call per query; vector RAG doesn’t.</p><h3>Why the GDPR Is Harder Than FinanceBench</h3><p>PageIndex cites 98.7% accuracy on <a href="https://github.com/VectifyAI/Mafin2.5-FinanceBench">FinanceBench</a>. I have no reason to doubt that number -financial reports are well-structured with clear section hierarchies, and the needles are often unique numbers in tables.</p><p>The GDPR is a different beast:</p><ul><li><strong>173 recitals</strong> explain the same concepts that <strong>99 articles</strong> make legally binding</li><li>Recitals use rich, descriptive natural language; articles are terse and specific</li><li>Embeddings (and LLM summaries) consistently prefer the explanatory text over the operative text</li><li>Many needles are specific legal phrases, not unique numbers</li></ul><p>This is why <strong>benchmark results don’t transfer across domains</strong>. A tool that scores 98.7% on structured financial filings may struggle on dense legal text where everything sounds semantically similar.</p><p>For comparison, <a href="https://github.com/poma-ai/poma-officeqa">POMA AI’s OfficeQA benchmark</a> tests retrieval on U.S. Treasury Bulletins -financial documents with tabular data spanning from 1939 to 2020. The needles there are specific numbers like &quot;987708828424&quot; or &quot;168882&quot;-unique strings that embeddings can locate reliably. POMA’s chunking consistently retrieves these at rank 1–10. But those same approaches plateau at 28–44% coverage on GDPR legal phrases, because the needles are natural language, not unique identifiers.</p><p><strong>The domain shapes the difficulty, not the architecture.</strong></p><h3>The Deeper Point</h3><p>The experiment bears that out: changing the architecture changes the failure mode:</p><ul><li><strong>Vector RAG</strong> fails because similarity ≠ relevance -recitals score higher than articles</li><li><strong>PageIndex</strong> fails (on needle coverage) because summaries ≠ source text-the LLM paraphrases instead of quoting</li><li><strong>Both</strong> fail on cross-chapter retrieval -no approach connects related content across distant sections</li></ul><p>None of these are bugs. They’re structural limitations. Until RAG systems encode <strong>document role</strong> -understanding that Article 17 is legally binding while Recital 65 is explanatory context, they’ll keep making the same class of mistake in different ways.</p><h3>When to Use What</h3><p>This case study is 5 queries on 1 document. It reveals patterns, not rankings. But the patterns suggest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klLpXqm5dvYviBcD_pFr5g.png" /></figure><h3>The Real Question</h3><p>The question isn’t “Are vectors dead?” or “Is reasoning-based retrieval better?”</p><p>It’s: <strong>benchmark results don’t transfer across document types.</strong> PageIndex at 98.7% on financial docs doesn’t predict 44% on legal docs. POMA’s strong performance on Treasury Bulletin tables doesn’t predict 44% on GDPR articles. Naive RAG at 28% on GDPR doesn’t mean it’s 28% on your data.</p><p>The only way to know is to measure on your own documents, with your own queries, against your own ground truth.</p><h3>Try It</h3><p>I built <a href="https://github.com/metawake/ragtune">RagTune</a> to make this kind of measurement straightforward. The needles field in your query JSON lets you define specific text spans that must appear in retrieved chunks:</p><pre>{<br>  &quot;text&quot;: &quot;What fines can be imposed under the GDPR?&quot;,<br>  &quot;relevant_docs&quot;: [&quot;gdpr.txt&quot;],<br>  &quot;needles&quot;: [<br>    {&quot;text&quot;: &quot;up to 20 000 000 EUR&quot;, &quot;source&quot;: &quot;Art 83(5)&quot;},<br>    {&quot;text&quot;: &quot;up to 10 000 000 EUR&quot;, &quot;source&quot;: &quot;Art 83(4)&quot;}<br>  ]<br>}</pre><pre>ragtune simulate --collection your-docs --queries your-queries.json</pre><p>No LLM judge. No vibes. Either the text is there or it isn’t.</p><p><em>The needle coverage concept was inspired by a comment on my previous post. POMA AI’s work on document hierarchy is a genuine step forward. PageIndex is an interesting architecture that works well for what it’s designed for. The gap between retrieval and answers is a shared challenge across the field.</em></p><p><em>If you’re building RAG over legislation, contracts, or technical standards -your Recall@K is probably green right now. Look at what’s actually inside the chunks.</em></p><p><strong>Links:</strong></p><ul><li>RagTune (open source): <a href="https://github.com/metawake/ragtune">https://github.com/metawake/ragtune</a></li><li>PageIndex: <a href="https://github.com/VectifyAI/PageIndex">https://github.com/VectifyAI/PageIndex</a></li><li>POMA AI OfficeQA benchmark: <a href="https://github.com/poma-ai/poma-officeqa">https://github.com/poma-ai/poma-officeqa</a></li><li>My previous post (NeedleCoverage on GDPR): <a href="https://www.linkedin.com/feed/update/urn:li:activity:7432424653731545088/">https://www.linkedin.com/feed/update/urn:li:activity:7432424653731545088/</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/alexey-a-181a614/">https://www.linkedin.com/in/alexey-a-181a614/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cebdc7ab3a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recall@K = 1.0 doesn’t mean your RAG works. Here’s what does.]]></title>
            <link>https://medium.com/@TheWake/recall-k-1-0-doesnt-mean-your-rag-works-here-s-what-does-87c7f1012356?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c7f1012356</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 09:05:26 GMT</pubDate>
            <atom:updated>2026-02-27T09:05:26.448Z</atom:updated>
            <content:encoded><![CDATA[<p>Recall@K = 1.0 doesn’t mean your RAG works. Here’s what does.</p><p>Two weeks ago, after <a href="https://www.linkedin.com/company/qdrant/">Qdrant</a> webinar, I posted that Recall@K saturates at 1.0 on structured documents and asked how to measure context quality beyond it. <a href="https://www.linkedin.com/in/dr-alexander-kihm-27a902338/">Dr. Alexander Kihm</a> from <a href="https://app.poma-ai.com/">POMA AI</a> replied with the right idea: define the actual “needles” /specific text spans required to answer a question /and check whether they’re in the retrieved chunks.</p><p>So I built it. NeedleCoverage@K CLI param for my RagTune tool.</p><p>For each query, you annotate text spans that must be present in retrieved chunks. “up to 20 000 000 EUR, or in the case of an undertaking, up to 4 %” from Article 83(5). Either it’s there or it isn’t. No LLM judge.<br>25 needles across 5 GDPR queries. Naive 512-char chunks vs POMA structure-aware chunking.</p><p>Naive — Recall@5: 1.000, NeedleCoverage@5: 0.280<br>POMA — Recall@5: 1.000, NeedleCoverage@5: 0.440</p><p>Both perfect on Recall. But naive retrieves 28% of actual answer content. POMA AI gets 44% /a 57% relative improvement. On lawful processing conditions (Article 6), POMA found 4/5 needles where naive found 0/5. Structure-aware chunking is a real win.</p><p>But 44% still means more than half the answer is missing. Why?<br>I inspected the retrieved chunks. Both strategies were pulling recitals(preambles) instead of articles. The GDPR has 173 recitals (explanatory preamble) and 99 articles (binding rules). Embeddings consistently score recitals higher -they use richer, more descriptive language that’s semantically closer to natural-language queries. The articles are terse and specific by design.</p><p>This isn’t a chunking problem. POMA’s chunks are well-formed. But vector search still ranks explanatory text above operative text. Similarity is not relevance.</p><p>If you’re building RAG over legislation, contracts, or technical standards — your Recall@K is probably green right now. Look at what’s actually inside the chunks.</p><p>RagTune v0.4.0 supports NeedleCoverage natively — add a needles field to your queries JSON.</p><p>Next: if embedding bias is the bottleneck, do the approaches that throw out vectors entirely solve it? I tested a well-known reasoning-based retrieval system that’s been making waves this year. The results were not what I expected. Stay tuned.</p><p>The needle concept came from Dr. Kihm’s comment on my last post. POMA AI’s work on document hierarchy is a real step forward. The gap between better chunks and better answers is a shared challenge, not a shortcoming of any single tool.<br>PS<br>If you like tuning retrieval systems, check out my RagTune.<br>Open source: <a href="https://lnkd.in/dUuTcAnE">https://lnkd.in/dUuTcAnE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c7f1012356" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Qdrant vs pgvector: Same Speed. The Bottleneck Isn’t the Vector DB]]></title>
            <link>https://medium.com/@TheWake/qdrant-vs-pgvector-theyre-the-same-speed-5ac6b7361d9d?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac6b7361d9d</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 17:22:47 GMT</pubDate>
            <atom:updated>2026-01-22T17:24:14.245Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I benchmarked both on 5,500 documents. The real bottleneck isn’t your vector store.</em></p><p>You’re picking a vector database for RAG. Qdrant or pgvector? The internet says Qdrant is faster.</p><p>I kept seeing this claim in tutorials and Twitter threads, but nobody showed actual benchmarks. Just vibes. So I ran the numbers myself.</p><p><strong>They’re the same.</strong> When both use HNSW indexes, latency is identical. The difference that matters is elsewhere and it’s not where you’d expect.</p><h3>The Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*QdJmNbkUHA4VFFbdWDIBuA.png" /></figure><p>Same embeddings (Ollama nomic-embed-text), same chunks (512 chars), three runs each.</p><p><strong>Environment:</strong> M1 MacBook Pro 16GB, Qdrant 1.16, pgvector 0.8 on Postgres 16, Ollama 0.6.</p><h3>Results: HotpotQA (5K Documents)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*zWOZPdg6eGulx4h_ohuhoA.png" /></figure><p><strong>Latency: Identical.</strong> Within 1ms at p50. The variance between runs is larger than the difference between stores.</p><p><strong>Recall: Qdrant edges ahead.</strong> 0.911 vs 0.900: about 1% more relevant documents in top-5. Qdrant’s HNSW tuning is slightly better out of the box.</p><h3>Results: CaseHOLD (500 Legal Documents)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*F9ARIFxGz6gOBh2oFCMV8Q.png" /></figure><p><strong>Both stores: ~320ms.</strong> Same recall. The vector search is identical.</p><p>But wait,why is CaseHOLD 6x slower than HotpotQA with <em>fewer</em> documents?</p><p>This confused me for an hour. I triple-checked the setup, restarted Docker, blamed my laptop. Then I actually looked at the queries.</p><h3>The Real Bottleneck: Embedding Time</h3><p>CaseHOLD queries are dense legal text, 80 words of statutory language. HotpotQA queries are things like “What year was X born?” The difference is embarrassing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYJ3xTpUt0WSBvK-D0ZHww.png" /></figure><p><strong>Embedding dominates.</strong> The vector store takes ~5ms either way. The other 300ms is Ollama processing the query text.</p><p>For complex queries or local embeddings, your vector store choice is irrelevant to latency. You’re benchmarking your embedder.</p><h3>So What Actually Matters?</h3><p><strong>Speed?</strong> They’re the same. Both implement HNSW. Both return results in ~5ms. The “Qdrant is faster” meme is based on… I don’t know what.</p><p><strong>Recall?</strong> Qdrant has a slight edge of 0.911 vs 0.900. That 1% might matter if you’re building something for legal or medical use cases where every percentage point counts. For most RAG chatbots? You won’t notice.</p><p><strong>Your actual bottleneck?</strong> It’s embedding, not search:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*bEN07z0Var4XFew0mzQDQw.png" /></figure><p>If you’re running Ollama on CPU, you’re spending 95% of your latency budget on embedding and 5% on vector search. Optimizing that 5% is a waste of time.</p><h3>What I Actually Use</h3><p>I use pgvector.</p><p>Not because it’s better, it’s not, really. But I already run Postgres for everything else, and adding Qdrant means another service to monitor, another container to restart at 2am, another thing to upgrade when there’s a security patch. For 1% recall difference? Not worth the operational overhead.</p><p>If I were starting a new project with no existing database, I’d probably pick Qdrant — the API is cleaner and the HNSW defaults are better tuned out of the box.</p><p>But honestly? <strong>This decision doesn’t matter much.</strong> I’ve seen teams spend weeks evaluating vector databases when their chunking strategy was losing them 15% recall. Pick one, move on, and spend that energy on something that actually moves the needle.</p><h3>What I Didn’t Test</h3><p>This was single-node, sequential queries, under 10K documents, local embeddings, pure vector search. That’s a lot of caveats.</p><p>I didn’t test concurrent load, 50K+ scale, managed cloud versions, or GPU embeddings. Any of those could change the results.</p><p>The big one I skipped: <strong>metadata filtering</strong>. Most production RAG queries filter by user_id, date range, or tenant. pgvector does this with SQL WHERE clauses; Qdrant uses payload filtering. I suspect the difference is small — if your embedding takes 50–300ms, a 5–20ms filter difference is noise — but I haven’t proven that yet. Maybe a future benchmark.</p><p>At larger scale (100K+ docs), index tuning and sharding might create real differences. Test on your actual workload, not mine.</p><p>Raw benchmark data and reproduction scripts: <a href="https://github.com/metawake/ragtune/tree/main/benchmarks/qdrant-vs-pgvector">benchmarks/qdrant-vs-pgvector</a></p><h3>Appendix: The Bug That Almost Ruined This Article</h3><p>When I first ran this comparison, pgvector was 2x slower than Qdrant. I was ready to write “pgvector is trash for vector search” and move on.</p><p>Something felt off, though. Both use HNSW. The algorithm is the same. Why would one be twice as slow?</p><p>I ran EXPLAIN ANALYZE on the pgvector query and felt like an idiot. PostgreSQL’s query planner had decided my test table was too small to bother with the index. It was doing a sequential scan. On 5,000 vectors. The HNSW index I’d carefully built was sitting there, completely ignored.</p><p><strong>The fix:</strong></p><pre>ALTER DATABASE mydb SET hnsw.ef_search = 100;</pre><p>After that, pgvector matched Qdrant exactly.</p><p>This is a benchmarking-only problem — production tables with real document counts will use the index automatically. But if you’re running comparisons on small datasets and pgvector looks suspiciously slow, check your query plans before writing angry blog posts.</p><h3>Methodology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1aQuQMtmKvT1f4RFrjOeg.png" /></figure><p>The vector database wars make for good Twitter content, but they’re mostly a distraction. Your embedding step is 10–50x slower than your vector search. Your chunking strategy affects recall 5–10x more than your store choice.</p><p>Optimize those first. Then worry about which logo looks better on your architecture diagram.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac6b7361d9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI vs Ollama: I Benchmarked Both Embedding Models on Real Legal Data]]></title>
            <link>https://medium.com/@TheWake/openai-vs-ollama-i-benchmarked-both-embedding-models-on-real-legal-data-8eb01ccb272f?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb01ccb272f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[vectordb]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 19:18:58 GMT</pubDate>
            <atom:updated>2026-01-11T19:36:28.430Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When does a local, free embedding model beat the paid API?</em></p><p>In my <a href="https://medium.com/@TheWake/i-built-a-rag-tuning-tool-and-discovered-intuition-fails-on-legal-text-9744be9a4bc5">previous article</a>, I showed that chunk size matters more than most teams realize — especially for specialized domains like legal text.</p><p>But there’s another variable that everyone agonizes over: <strong>which embedding model should I use?</strong></p><p>The options range from:</p><ul><li><strong>OpenAI’s text-embedding-3-small</strong> — $0.02 per 1M tokens, requires API key</li><li><strong>Ollama’s nomic-embed-text</strong> — Free, runs locally, no data leaves your machine</li></ul><p>The conventional wisdom says “pay for quality.” But is that actually true for <em>your</em> data?</p><p>The theory behind embeddings is older than you might think. As linguist J.R. Firth put it in 1957: “You shall know a word by the company it keeps.” Modern embedding models operationalize this insight — learning meaning from co-occurrence patterns. The question is whether those patterns transfer across different <em>registers</em> of language.</p><p>I extended my RAG benchmarking tool to answer this question with data.</p><h3>The New Feature</h3><p>RagTune now supports comparing embedding models directly:</p><pre>ragtune compare --embedders openai,ollama \<br>    --docs ./legal-docs \<br>    --queries ./queries.json \<br>    --chunk-size 512</pre><p>This automatically:</p><ol><li>Ingests the same documents with each embedding model</li><li>Runs all queries against both</li><li>Prints a side-by-side comparison</li><li>Cleans up temp collections (unless you want to keep them)</li></ol><p>No manual setup. No juggling API keys mid-experiment.</p><h3>The Experiment</h3><p>I ran both embedding models against:</p><ul><li><strong>HotpotQA:</strong> 398 Wikipedia docs, 200 multi-hop questions</li><li><strong>CaseHOLD:</strong> 500 legal holdings, 500 legal queries</li></ul><p>Same chunk size (512), same top-k (5), same queries. Only the embedding model changed.</p><h3>The Results</h3><p><strong>General Knowledge (HotpotQA):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*UsF8UdC7Tt9vohHk2xGOFg.png" /></figure><p>Virtually identical. For general text, the free local model matches the paid API.</p><p><strong>Legal Text (CaseHOLD):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*QEKFLv9389yD7OKal9oHqg.png" /></figure><p>OpenAI wins by ~5% on legal text. But here’s the interesting part: both models struggle significantly compared to general knowledge (66–71% vs 99%).</p><h3>What This Means</h3><p><strong>For general-purpose RAG:</strong></p><ul><li>Use Ollama. It’s free, private, and just as good.</li><li>You’ll save money and avoid API latency.</li></ul><p><strong>For specialized domains (legal, medical, finance):</strong></p><ul><li>OpenAI has a slight edge (~5%)</li><li>But neither model is great — consider domain-specific embeddings</li><li>Or invest in better chunking strategies (see my previous article)</li></ul><p><strong>The real insight:</strong> The gap between embedders (5%) is smaller than the gap between chunk sizes (7%) on the same data. Tuning your chunking strategy may matter more than switching to a more expensive model.</p><h3>The Hierarchy of RAG Optimization</h3><p>Based on my experiments, here’s what actually moves the needle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*J3aoKkCOwtEpLNYu6g42YA.png" /></figure><p>Many teams focus on vector databases. Fewer benchmark their chunking strategy.</p><h3>Try It Yourself</h3><p>RagTune is open source: <a href="https://github.com/metawake/ragtune">github.com/metawake/ragtune</a></p><p><strong>Install (30 seconds):</strong></p><pre>brew install metawake/tap/ragtune<br># or: curl -sSL https://raw.githubusercontent.com/metawake/ragtune/main/install.sh | bash</pre><p><strong>Reproduce article results (10 minutes):</strong></p><pre>git clone https://github.com/metawake/ragtune<br>cd ragtune</pre><pre># Generate the dataset<br>cd benchmarks/casehold-500 &amp;&amp; pip install datasets &amp;&amp; python prepare.py<br>cd ../..</pre><pre># Compare embedders on legal data<br>ragtune compare --embedders openai,ollama \<br>    --docs ./benchmarks/casehold-500/corpus \<br>    --queries ./benchmarks/casehold-500/queries.json</pre><p>You should see the ~5% difference between OpenAI and Ollama on legal text.</p><p><em>Just want to see the tool run? There’s a small </em><a href="https://github.com/metawake/ragtune/tree/main/benchmarks/hotpotqa-1k/samples"><em>sample dataset</em></a><em> for quick testing, but embedder differences only emerge at full scale (500+ docs).</em></p><p>The tool supports:</p><ul><li>Chunk size experimentation</li><li>Embedding model comparison</li><li>Batch simulation with metrics</li><li>Markdown/JSON reports for CI/CD</li></ul><p><em>A note on methodology: These results are from single runs on two datasets with fixed chunk size (512) and overlap (12.5%). I tested only two embedding models — there are many others worth exploring. The code, datasets, and prepare scripts are fully open source. I encourage you to reproduce these experiments and test on your own domain.</em></p><h3>What’s Next</h3><p>I’m considering adding:</p><ul><li>Domain-specific embedding models (legal-bert, pubmed-bert)</li><li>Hybrid search (sparse + dense)</li><li>Automatic recommendations based on your data profile</li></ul><p>If you have a use case you’d like benchmarked, let me know.</p><p><em>Building AI infrastructure? Connect with me on [</em><a href="https://www.linkedin.com/in/alexey-a-181a614/"><em>LinkedIn</em></a><em>/</em><a href="https://x.com/TheWake"><em>Twitter</em></a><em>]. I write about the engineering side of LLM applications.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eb01ccb272f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a RAG Tuning Tool and Discovered Intuition Fails on Legal Text]]></title>
            <link>https://medium.com/@TheWake/i-built-a-rag-tuning-tool-and-discovered-intuition-fails-on-legal-text-9744be9a4bc5?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9744be9a4bc5</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[pgvector]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 19:15:13 GMT</pubDate>
            <atom:updated>2026-01-11T19:33:39.096Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why “just use 512 chunk size” can mislead you for production RAG</em></p><p>Every RAG tutorial gives you the same advice: split your documents into ~512 character chunks, use a decent embedding model, and you’re done.</p><p>I believed this for months. Then I built a tool to actually measure retrieval quality — and discovered that for specialized domains, this “best practice” can cost you 7% recall. That’s the difference between a helpful AI assistant and one that misses critical information.</p><h3>The Often Overlooked Problem</h3><p>When you build a RAG system, you’re making decisions that directly impact whether your LLM gets the right context:</p><ul><li><strong>Chunk size:</strong> How big should each text segment be?</li><li><strong>Top-k:</strong> How many chunks should you retrieve?</li><li><strong>Embedding model:</strong> Which one actually works for your data?</li></ul><p>Most teams guess. They copy settings from a tutorial, ship to production, and hope for the best. There’s no easy way to know if your retrieval layer is actually working — until users complain about bad answers.</p><p>I wanted to change that.</p><h3>What I Built</h3><p><strong>RagTune</strong> is a CLI tool that benchmarks your RAG retrieval layer with real metrics:</p><ul><li><strong>Recall@K:</strong> What percentage of relevant documents did you actually retrieve?</li><li><strong>MRR:</strong> How well-ranked is the first relevant result?</li><li><strong>Coverage:</strong> What percentage of queries found <em>any</em> relevant document?</li></ul><p>It’s framework-agnostic — works with any vector store, any embedding model. The goal is measurement, not magic.</p><h3>The Experiment</h3><p>I ran RagTune against two datasets:</p><ol><li><strong>HotpotQA</strong> — General knowledge Wikipedia paragraphs (200 multi-hop questions)</li><li><strong>CaseHOLD</strong> — Legal case holdings from Harvard Law (500 queries)</li></ol><p>For each dataset, I tested three chunk sizes: 256, 512, and 1024 characters.</p><pre>ragtune compare --collections legal-256,legal-512,legal-1024 \<br>    --queries ./queries.json --top-k 5</pre><h3>The Results</h3><p><strong>General Knowledge (HotpotQA):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VSq2BVkqZ7T5CU9mPUm8jw.png" /></figure><p>All chunk sizes work great. Differences are negligible. The tutorials were right — for Wikipedia-style text.</p><p><strong>Legal Text (CaseHOLD):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ps6fGWXMdM0kkFHEp0VOMQ.png" /></figure><p>Completely different story:</p><ul><li>Overall recall dropped from 99% to 66%</li><li><strong>Chunk size caused a 7% swing</strong> in retrieval quality</li><li>The “safe default” of 1024 was the <em>worst</em> performer</li></ul><h3>Why Legal Text Breaks the Rules</h3><p>Legal language operates as a specialized <em>register (</em>dense, precise, and self-referential). Unlike conversational text, it assumes readers already know the statutory context. What works for Wikipedia fails when coherence depends on that shared frame:</p><ul><li>Small word changes have big legal implications</li><li>Similar-sounding clauses mean different things</li><li>Generic embeddings miss domain nuance</li></ul><p>When you use large chunks on legal text, you’re forcing the embedding model to summarize complex concepts into a single vector. It can’t. Smaller chunks (256) preserve the precision that legal retrieval requires.</p><h3>The Takeaway</h3><p>For production RAG, <strong>measure. Don’t guess.</strong></p><p>Your domain might behave like Wikipedia — or it might behave like legal contracts. The only way to know is to benchmark with real queries and ground truth.</p><h3>Update: What Happens at Scale?</h3><p>After running these experiments, I wondered: do these findings hold at production scale?</p><p>I scaled HotpotQA from 400 documents to <strong>5,000 documents</strong> (12.5x larger) and re-ran the same tests. The results surprised me:</p><p>ScaleBest Chunk SizeRecall@5400 docs256 (smallest)0.9955,000 docs<strong>1024 (largest)0.893</strong></p><p>The optimal chunk size <strong>flipped</strong>. At small scale, smaller chunks won. At production scale, larger chunks performed best.</p><p>Even more striking: recall dropped from 99% to 89% — a <strong>10% degradation</strong> just from having more documents competing for attention in the vector space.</p><p><strong>What this means:</strong></p><ul><li>Tutorial-scale benchmarks can be misleading</li><li>The “distractor” problem is real — more documents = more noise</li><li>You need to benchmark at <em>your</em> production scale, not demo scale</li></ul><p>I’ll explore this scale phenomenon in more depth in a future article. For now, the lesson is clear: <strong>benchmark at the scale you’ll actually operate at.</strong></p><p><em>A note on methodology: These results are from single runs on specific datasets. The small-scale tests used nomic-embed-text (Ollama); the 5K scale test used OpenAI text-embedding-3-small. Your results may vary depending on your data distribution, embedding model, and query patterns. The code and datasets are open source — I encourage you to reproduce and extend these experiments on your own data.</em></p><h3>Try It Yourself</h3><p>RagTune is open source: <a href="https://github.com/metawake/ragtune">github.com/metawake/ragtune</a></p><p><strong>Install (30 seconds):</strong></p><pre>brew install metawake/tap/ragtune<br># or: curl -sSL https://raw.githubusercontent.com/metawake/ragtune/main/install.sh | bash</pre><p><strong>Reproduce article results (10 minutes):</strong></p><pre>git clone https://github.com/metawake/ragtune<br>cd ragtune</pre><pre># Generate the datasets<br>cd benchmarks/casehold-500 &amp;&amp; pip install datasets &amp;&amp; python prepare.py<br>cd ../hotpotqa-1k &amp;&amp; python prepare.py<br>cd ../..</pre><pre># Run the legal benchmark with different chunk sizes<br>ragtune ingest ./benchmarks/casehold-500/corpus --collection legal-256 --chunk-size 256<br>ragtune ingest ./benchmarks/casehold-500/corpus --collection legal-1024 --chunk-size 1024<br>ragtune simulate --collection legal-256 --queries ./benchmarks/casehold-500/queries.json<br>ragtune simulate --collection legal-1024 --queries ./benchmarks/casehold-500/queries.json</pre><p>You should see the 7% recall difference between chunk sizes on legal text.</p><p><em>Just want to see the tool run? There’s a small </em><a href="https://github.com/metawake/ragtune/tree/main/benchmarks/hotpotqa-1k/samples"><em>sample dataset</em></a><em> for quick testing, but note that config effects only emerge at full scale (500+ docs).</em></p><p><strong>Next:</strong> <a href="https://medium.com/@TheWake/openai-vs-ollama-i-benchmarked-both-embedding-models-on-real-legal-data-8eb01ccb272f">OpenAI vs Ollama: I Benchmarked Both Embedding Models on Real Legal Data</a></p><p><em>If you’re building RAG systems and want to connect, find me on [</em><a href="https://www.linkedin.com/in/alexey-a-181a614/"><em>LinkedIn</em></a><em>/</em><a href="https://x.com/TheWake"><em>Twitter</em></a><em>].</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9744be9a4bc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Trusting Your RAG Pipeline: Add Smoke Tests in 5 Minutes]]></title>
            <link>https://medium.com/@TheWake/stop-trusting-your-rag-pipeline-add-smoke-tests-in-5-minutes-7ae26b3c91a7?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae26b3c91a7</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[rag-pipeline]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 13:20:49 GMT</pubDate>
            <atom:updated>2026-01-06T21:25:21.552Z</atom:updated>
            <content:encoded><![CDATA[<p><em>pytest-native quality checks for RAG outputs — no LLM calls, no golden answers, just deterministic pass/fail</em></p><p>You built a RAG system. Retrieval works. The LLM responds. Users are happy.</p><p>Then one day:</p><ul><li>Someone changes the prompt template</li><li>OpenAI updates the model</li><li>The vector DB config drifts</li><li>Retrieval starts returning garbage</li></ul><p>And you don’t know until a user complains: <em>“Why does your AI say John Smith announced our earnings?”</em></p><p>There is no John Smith. Your LLM made him up.</p><h3>The Problem: RAG Fails Silently</h3><p>RAG systems have a dirty secret: <strong>they fail without telling you</strong>.</p><p>Traditional software crashes. APIs return errors. Tests fail. But when a RAG pipeline degrades:</p><ul><li>The LLM still responds (confidently!)</li><li>The response looks plausible</li><li>No exceptions are thrown</li><li>CI stays green</li></ul><p>The failure mode is <strong>silent hallucination</strong> — and you only discover it in production.</p><h3>Why Traditional Testing Doesn’t Work</h3><p>You can’t write traditional unit tests for RAG:</p><pre># This doesn&#39;t scale<br>def test_revenue_question():<br>    answer = rag.ask(&quot;What was Q3 revenue?&quot;)<br>    assert answer == &quot;Revenue was $450M&quot;  # ← Brittle. LLM wording varies.</pre><p>And you can’t use LLM-as-judge:</p><pre># This is expensive and non-deterministic<br>def test_with_llm_judge():<br>    answer = rag.ask(&quot;What was Q3 revenue?&quot;)<br>    is_correct = gpt4.evaluate(answer)  # ← $$$, slow, flaky</pre><h3>The Solution: Test Properties, Not Content</h3><p>What if instead of checking <em>what</em> the LLM said, we check <em>properties</em> of the response?</p><pre>from raglint import grounded, no_placeholders, numeric_grounded</pre><pre>def test_rag_output_quality():<br>    answer, sources = rag.ask_with_sources(&quot;What was Q3 revenue?&quot;)<br>    <br>    # Entities in answer should come from sources<br>    assert grounded(answer, sources).passed<br>    <br>    # Numbers in answer should come from sources<br>    assert numeric_grounded(answer, sources).passed<br>    <br>    # No placeholder patterns like &quot;John Doe&quot; or &quot;TechCorp&quot;<br>    assert no_placeholders(answer).passed</pre><p>This is <strong>raglint</strong> — static analysis for RAG outputs. Like ESLint for your RAG pipeline.</p><h3>What raglint Catches</h3><p><strong>grounded()</strong> — Catches hallucinated entities. Names, companies, acronyms (IBM, AWS), camelCase brands (openAI, iPhone), hyphenated names (Jean-Pierre). Supports optional fuzzy matching for variations like “Acme Corp” vs “Acme Corporation”.</p><p><strong>numeric_grounded()</strong> — Catches invented numbers. Smart normalization matches “$1.5M” to “1,500,000” and “15%” to “0.15”.</p><p><strong>no_placeholders()</strong> — Catches template garbage. Example: “According to experts…”, “TechCorp”, “John Doe”.</p><p><strong>cites_sources()</strong> — Catches broken retrieval. Example: Answer is completely unrelated to retrieved sources.</p><p>All checks are <strong>deterministic</strong> — no LLM calls, no randomness, same input → same result.</p><p><strong>When do placeholders actually occur?</strong> Most common when retrieval fails (empty sources) or with lower-quality models (GPT-3.5, smaller open-source models). GPT-4 with good retrieval rarely uses obvious placeholders, but at scale even 0.1% failure rate = many broken answers. This check is most valuable as a <strong>regression detector</strong> — if placeholders appear after a prompt/model change, something broke.</p><h3>Real Example: Catching a Broken Pipeline</h3><p>Let’s say you have a financial RAG system:</p><pre># Your RAG pipeline<br>def financial_rag(question: str) -&gt; tuple[str, list[str]]:<br>    sources = retrieve(question)  # Vector search<br>    answer = llm.generate(question, context=sources)<br>    return answer, sources</pre><p>Add smoke tests:</p><pre># tests/test_rag_quality.py<br>import pytest<br>from raglint import grounded, numeric_grounded, no_placeholders</pre><pre>@pytest.fixture<br>def qa_pair():<br>    question = &quot;What was TechCorp&#39;s Q3 2024 revenue?&quot;<br>    answer, sources = financial_rag(question)<br>    return answer, sources</pre><pre>def test_entities_grounded(qa_pair):<br>    answer, sources = qa_pair<br>    result = grounded(answer, sources)<br>    assert result.passed, f&quot;Hallucinated entities: {result.evidence[&#39;missing&#39;]}&quot;</pre><pre>def test_numbers_grounded(qa_pair):<br>    answer, sources = qa_pair<br>    result = numeric_grounded(answer, sources)<br>    assert result.passed, f&quot;Invented numbers: {result.evidence[&#39;missing&#39;]}&quot;</pre><pre>def test_no_placeholder_patterns(qa_pair):<br>    answer, _ = qa_pair<br>    result = no_placeholders(answer)<br>    assert result.passed, f&quot;Placeholders found: {result.evidence[&#39;findings&#39;]}&quot;</pre><p>Run with pytest:</p><pre>$ pytest tests/test_rag_quality.py -v</pre><pre>tests/test_rag_quality.py::test_entities_grounded PASSED<br>tests/test_rag_quality.py::test_numbers_grounded PASSED<br>tests/test_rag_quality.py::test_no_placeholder_patterns PASSED</pre><p>Now add this to CI. When someone breaks the retrieval or prompt, you’ll know.</p><h3>How It Works: Write Once, Run Repeatedly</h3><p>raglint follows a simple workflow:</p><p><strong>Step 1: Write your test suite once</strong> — Customize assertions for your RAG pipeline</p><p><strong>Step 2: Run repeatedly</strong> — Same tests catch quality drops automatically</p><p>You write pytest tests with assertions tailored to your use case, then run those same tests in CI on every commit. Same assertions, different inputs each time — that’s regression testing.</p><h3>Working with Different RAG Output Formats</h3><p>raglint works with common LLM output formats. It automatically extracts text from JSON, dicts, strings, or Source objects:</p><p><strong>JSON format:</strong></p><pre>response = {<br>    &quot;answer&quot;: &quot;Revenue grew 12% to $450M.&quot;,<br>    &quot;sources&quot;: [{&quot;id&quot;: &quot;doc_1&quot;, &quot;text&quot;: &quot;Q3 2024: Revenue reached $450M, up 12%.&quot;}]<br>}<br>result = grounded(response[&quot;answer&quot;], response[&quot;sources&quot;])</pre><p><strong>String format:</strong></p><pre>sources = [&quot;Q3 2024: Revenue reached $450M, up 12%.&quot;]<br>result = grounded(answer, sources)  # Works with strings</pre><p><strong>With prefixes/markers:</strong></p><pre>answer = &quot;Answer: Revenue grew 12% to $450M.&quot;<br>sources = [&quot;Source 1: Q3 2024: Revenue reached $450M, up 12%.&quot;]<br># raglint normalizes text, so prefixes don&#39;t matter<br>result = grounded(answer, sources)</pre><p>raglint normalizes text (lowercase, whitespace) before matching, so it works with various formatting conventions.</p><h3>Where raglint Shines</h3><p>raglint is optimized for specific scenarios where deterministic checks beat LLM-based evaluation:</p><h3>CI/CD Regression Detection</h3><pre># .github/workflows/raglint.yml<br>name: RAG Quality Gate<br>on: [push, pull_request]</pre><pre>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: pip install git+https://github.com/metawake/raglint.git pytest<br>      - run: pytest tests/test_rag_quality.py -v</pre><p>Prompt changed? Model updated? Retrieval config tweaked? <strong>Tests catch regressions before production</strong> — instantly, deterministically, at zero cost.</p><h3>Broken Retrieval Detection</h3><p>The most dangerous RAG failure: retrieval returns garbage, LLM confidently hallucinates.</p><pre>sources = []  # Retrieval returned nothing!<br>answer = &quot;According to our data, revenue grew 15%.&quot;  # Pure hallucination</pre><pre>result = grounded(answer, sources)<br># FAIL: entities not grounded — retrieval is broken</pre><p>This is the failure mode that costs companies money. raglint catches it.</p><h3>Cost-Optimized Pipelines</h3><p>Running GPT-3.5, Mistral, or Llama to save costs? These models make more mistakes than GPT-4. raglint provides a safety net without adding LLM expenses.</p><h3>Scale Protection</h3><pre>1% error rate × 10,000 requests/day = 100 broken answers daily</pre><p>At scale, even rare failures compound. Automated checks catch what human review can’t.</p><h3>Design Decisions: Why Pattern-Based Over ML</h3><p>You might wonder: “Why not use an NER model or LLM to extract entities?”</p><p>I tried that. Here’s what I learned:</p><p><strong>Pattern-based extraction:</strong></p><ul><li>✅ Zero dependencies (no spaCy, no transformers)</li><li>✅ Deterministic (same input → same output, critical for CI)</li><li>✅ Fast (&lt; 10ms vs 100ms+ for ML models)</li><li>✅ No model versioning issues</li><li>✅ Works offline, in air-gapped environments</li><li>✅ Covers most real-world cases (names, acronyms, companies, brands)</li></ul><p><strong>ML-based extraction:</strong></p><ul><li>❌ Adds dependencies (spaCy, transformers, model weights)</li><li>❌ Non-deterministic (model updates change behavior)</li><li>❌ Slower (even small models add latency)</li><li>❌ Model drift (updates break existing tests)</li><li>❌ Overkill for obvious cases (“John Smith” doesn’t need BERT)</li></ul><p>The trade-off: pattern-based has lower recall (might miss some entities), but higher precision (what it finds is definitely an entity). For <em>negative testing</em> (“catch obvious failures”), precision matters more than recall.</p><p><strong>What about edge cases?</strong> v0.3 improved coverage significantly — acronyms (IBM, AWS), camelCase (openAI), hyphenated names, company suffixes. For domain-specific entities, you can subclass Check and plug in spaCy or custom logic.</p><p><strong>Why pytest-native?</strong> Because developers already know pytest. No new framework to learn. No DSL. Just functions that return pass/fail. It composes naturally with existing test suites.</p><p><strong>Why no LLM calls?</strong> Because determinism is non-negotiable for CI. If a test passes today and fails tomorrow with the same input, that’s a flaky test — and flaky tests get disabled. raglint is designed to never flake.</p><h3>Scope</h3><p>raglint is a <strong>fast, deterministic quality gate</strong> — not a comprehensive evaluation framework.</p><p><strong>What raglint does:</strong></p><ul><li>Catch hallucinated entities (names, companies, acronyms, brands)</li><li>Detect invented numbers (with smart format normalization)</li><li>Flag template patterns</li><li>Optional fuzzy matching for entity variations</li><li>Run in &lt; 100ms, $0 cost, zero dependencies</li></ul><p><strong>What raglint doesn’t do:</strong></p><ul><li>Verify factual truth</li><li>Catch subtle semantic errors</li><li>Replace human review for critical decisions</li><li>Use LLM-based reasoning</li></ul><p><strong>Known limitations (by design):</strong></p><ul><li>Lowercase entities (adidas, <a href="http://x.com/">x.com</a>) — not extracted</li><li>Spelled-out numbers (“one million”) — not parsed</li><li>Unit conversions (km ↔ m) — not supported</li></ul><p>These are intentional trade-offs to keep the tool simple, fast, and dependency-free.</p><p><strong>The right mental model:</strong> raglint is to RAG what ESLint is to JavaScript. It catches obvious issues fast. For deeper analysis, you still need other tools.</p><h3>Installation</h3><pre>git clone https://github.com/metawake/raglint.git<br>cd raglint<br>pip install -e .</pre><p>Or install directly from GitHub:</p><pre>pip install git+https://github.com/metawake/raglint.git</pre><h3>Quick Reference</h3><pre>from raglint import grounded, cites_sources, no_placeholders, numeric_grounded</pre><pre># Functional API (for tests)<br>assert grounded(answer, sources).passed<br>assert cites_sources(answer, sources).passed<br>assert no_placeholders(answer).passed<br>assert numeric_grounded(answer, sources).passed</pre><pre># With fuzzy matching (v0.3+)<br>assert grounded(answer, sources, fuzzy=True).passed</pre><pre># With configuration<br>from raglint import GroundedCheck, CheckSuite, NumericGroundingCheck, NoPlaceholdersCheck</pre><pre>suite = CheckSuite([<br>    GroundedCheck(threshold=0.9),  # 90% of entities must be grounded<br>    NumericGroundingCheck(),<br>    NoPlaceholdersCheck(),<br>])</pre><pre>result = suite.run(answer, sources)<br>assert result.passed, result.reasons</pre><h3>v0.3: Improved Detection (Zero New Dependencies)</h3><h3>Better Entity Extraction</h3><p>Now catches more entity types:</p><ul><li><strong>Acronyms:</strong> IBM, NASA, AWS, NVIDIA</li><li><strong>camelCase brands:</strong> openAI, iPhone, macOS</li><li><strong>Hyphenated names:</strong> Jean-Pierre, Hewlett-Packard</li><li><strong>Company suffixes:</strong> Apple Inc, Google LLC</li></ul><h3>Smart Number Normalization</h3><p>Numbers match across formats:</p><pre># These all match now:<br>&quot;$1.5M&quot; ↔ &quot;1,500,000&quot;  ✓<br>&quot;15%&quot;   ↔ &quot;0.15&quot;       ✓<br>&quot;2K&quot;    ↔ &quot;2000&quot;       ✓</pre><h3>Optional Fuzzy Matching</h3><p>Handle entity variations without external dependencies:</p><pre># &quot;Acme Corp&quot; vs &quot;Acme Corporation&quot; — fails with exact, passes with fuzzy<br>result = grounded(answer, sources, fuzzy=True, fuzzy_threshold=0.85)</pre><p>Uses Python’s stdlib difflib.SequenceMatcher — still <strong>zero external dependencies</strong>.</p><h3>CI/CD Integration</h3><p>Every check returns structured output for machine consumption:</p><pre>result = grounded(answer, sources)</pre><pre># JSON output for CI artifacts<br>print(result.to_json(indent=2))<br># {&quot;passed&quot;: false, &quot;check&quot;: &quot;grounded&quot;, &quot;reasons&quot;: [...], ...}</pre><pre># Exit code for shell scripts<br>import sys<br>sys.exit(result.exit_code)  # 0 = pass, 1 = fail</pre><pre># Dict for observability (Datadog, etc.)<br>metrics.log(result.to_dict())</pre><h3>Why I Built This</h3><p>Working with RAG systems, I kept seeing the same failure pattern:</p><ol><li><strong>Week 1:</strong> Everything works. Demo impresses stakeholders.</li><li><strong>Week 4:</strong> A prompt change breaks something subtle. No one notices.</li><li><strong>Week 8:</strong> Users report “the AI is making things up.”</li><li><strong>Week 12:</strong> Someone adds LLM-as-judge evaluation. CI slows down. Costs spike.</li></ol><p>The existing solutions felt wrong — either too expensive (LLM-based) or too brittle (golden answers). I wanted something simpler: <strong>deterministic checks that catch obvious failures at zero cost.</strong></p><p>The key insight: you don’t need an LLM to catch <em>obvious</em> problems. If “John Smith” appears in an answer but not in sources, that’s a pattern match — not a reasoning problem. If numbers don’t match, that’s string comparison — not semantic understanding.</p><p>This is the same philosophy behind linters: catch the obvious stuff automatically, so humans can focus on the hard problems.</p><h3>The Philosophy</h3><p>raglint follows a simple principle:</p><blockquote><strong><em>Test invariants, not content.</em></strong></blockquote><p>We don’t know what the “right” answer is. But we know:</p><ul><li>Entities should come from sources</li><li>Numbers should come from sources</li><li>“John Doe” and “TechCorp” are red flags</li><li>Answer should relate to sources</li></ul><p>These are <strong>properties that always hold</strong> for a well-functioning RAG system. When they don’t hold — something is broken.</p><h3>Conclusion</h3><p>RAG systems fail silently. Traditional tests don’t work. LLM-as-judge is expensive.</p><p>raglint gives you:</p><ul><li>✅ Deterministic pass/fail</li><li>✅ pytest integration</li><li>✅ CI/CD ready</li><li>✅ Zero LLM cost</li><li>✅ Fast (&lt; 100ms per check)</li></ul><p>It’s not a comprehensive quality gate. It’s <strong>static analysis for RAG</strong> — catching obvious failures before they reach users.</p><p><strong>GitHub:</strong> <a href="https://github.com/metawake/raglint">github.com/metawake/raglint</a></p><p><strong>Install:</strong> pip install git+https://github.com/metawake/raglint.git</p><p><em>Have questions or feedback? Open an issue on </em><a href="https://github.com/metawake/raglint"><em>GitHub</em></a><em> or connect on </em><a href="https://www.linkedin.com/in/alexey-a-181a614/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ae26b3c91a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Policy Puppetry in LLM Prompts: A Simple, Transparent Approach]]></title>
            <link>https://systemweakness.com/detecting-policy-puppetry-in-llm-prompts-a-simple-transparent-approach-f4a36f069ba2?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a36f069ba2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 20:36:00 GMT</pubDate>
            <atom:updated>2025-04-30T11:36:54.239Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a lot of excitement these days about large language models (LLMs) and the new opportunities — and risks — they bring. As someone who’s spent a fair bit of time in the NLP and LLM trenches, I’ve seen firsthand how creative people can get when trying to “puppeteer” these models into doing things they shouldn’t.</p><p>Recently, I built a small tool called <a href="https://github.com/metawake/puppetry-detector"><strong>Puppetry Detector</strong></a>. It’s not a silver bullet, and it’s certainly not the only approach out there, but I think it fills a useful niche: detecting policy puppetry and prompt injection attempts using nothing more than plain Python and regular expressions.</p><h3>Why Not Just Use an LLM to Catch LLM Attacks?</h3><p>It’s tempting to throw a big model at every problem. But sometimes, the simplest solution is the best place to start. Regex patterns are:</p><ul><li><strong>Fast</strong> (milliseconds, not seconds)</li><li><strong>Transparent</strong> (you can see exactly what’s being matched)</li><li><strong>Easy to audit and extend</strong> (no black boxes)</li><li><strong>Lightweight</strong> (no GPU, no cloud, no fuss)</li></ul><p>I wanted something that could be dropped into a pipeline, run on a Raspberry Pi, or be used as a building block for more complex systems. If you need more power, you can always layer on spaCy, or even call out to an LLM for a second opinion. But for a lot of cases, simple pattern matching gets you surprisingly far.</p><h3>How It Works</h3><p>Puppetry Detector scans prompts for patterns that look like attempts to override roles, bypass security, or otherwise manipulate the model’s behavior. It’s inspired by research from <a href="https://hiddenlayer.com/research/policy-puppetry-attacks">HiddenLayer</a> and others, and is designed to be:</p><ul><li><strong>Configurable</strong>: You can add or tweak patterns as new attacks emerge.</li><li><strong>Composable</strong>: Use it on its own, or as part of a larger moderation pipeline.</li></ul><h3>Integration with Rebuff</h3><p>One of the things I appreciate about the Python ecosystem is how easy it is to make tools work together. Puppetry Detector comes with a simple adapter for <a href="https://github.com/robust-intelligence/rebuff">Rebuff</a>, a prompt moderation framework. This means you can use it as a filter in your Rebuff pipeline, combining it with other detectors for layered defense.</p><h3>What’s Next?</h3><p>This project is a starting point, not an endpoint. There’s plenty of room to grow:</p><ul><li><strong>Smarter Patterns</strong>: As attackers get more creative, so can our regexes.</li><li><strong>Deeper Analysis</strong>: Plug in spaCy or other NLP tools for more nuanced checks.</li><li><strong>LLM-Assisted Moderation</strong>: For the really tricky cases, call out to a model to estimate intent or even spot subtle lies.</li></ul><h3>Why Share This?</h3><p>I’m sharing this not because I think it’s perfect, but because I believe in the value of small, understandable tools. If you’re working in LLM safety, prompt engineering, or just want to see how far you can get with a few lines of Python, I hope you’ll find something useful here.</p><p>If you have ideas, feedback, or want to collaborate, I’d love to hear from you. The code is open source (<a href="https://github.com/metawake/puppetry-detector">GitHub repo</a>), and contributions are always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a36f069ba2" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/detecting-policy-puppetry-in-llm-prompts-a-simple-transparent-approach-f4a36f069ba2">Detecting Policy Puppetry in LLM Prompts: A Simple, Transparent Approach</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flexible Entity Extraction for NLP Pipelines: Introducing nergrep]]></title>
            <link>https://medium.com/@TheWake/flexible-entity-extraction-for-nlp-pipelines-introducing-nergrep-c254f4c21766?source=rss-2dc94f1b35ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c254f4c21766</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Oleksii Aleksapolskyi]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 09:34:27 GMT</pubDate>
            <atom:updated>2025-04-26T10:37:36.072Z</atom:updated>
            <content:encoded><![CDATA[<p>As an AI/NLP/ML platform engineer, I often need to prototype and iterate on text analytics pipelines. Entity extraction is a frequent, foundational step — whether I’m building quick R&amp;D experiments or shaping components for production. I wanted a tool that was both fast and flexible: something I could use from the command line for ad-hoc analysis, or drop into Python code and larger frameworks like Langchain for more complex workflows.</p><p>That’s why I built <a href="https://github.com/yourusername/nergrep">nergrep</a>: Python package and CLI for extracting and filtering named entities using spaCy, with filtering and integration into modern LLM pipelines (I started with LangChain plugin).</p><p>While I’m still exploring whether nergrep will become a production staple or remain a rapid prototyping tool, it&#39;s already proven invaluable for shaping and testing new NLP pipelines in R&amp;D.</p><h3>Why nergrep?</h3><ul><li>Precision Filtering: Filter entities by type, fuzzy match, regex, black/whitelists, and more.</li><li>CLI &amp; Python API: Use interactively or in scripts and pipelines.</li><li>Langchain Integration: Plug entity extraction into LLM-powered workflows.</li><li>Custom ML Model Integration: Extend entity extraction with custom ML models for enhanced precision and additional entity types.</li></ul><h3>Quick Demo: Entity Extraction from Apollo 11</h3><p>Running nergrep on an excerpt about the Apollo 11 mission gives us clean named entity extraction:</p><pre>nergrep &quot;Apollo 11 was the spaceflight that first landed humans on the Moon. Commander Neil Armstrong and lunar module pilot Buzz Aldrin formed the American crew. They landed the Apollo Lunar Module Eagl......&quot;</pre><p>Example output:</p><pre># Example: YAML output from nergrep entity extract- text: &quot;Apollo&quot;<br>  label: &quot;ORG&quot;<br>  sentence: &quot;Apollo 11 was the spaceflight that first landed humans on the Moon.&quot;<br>- text: &quot;Neil Armstrong&quot;<br>  label: &quot;PERSON&quot;<br>  sentence: &quot;Commander Neil Armstrong and lunar module pilot Buzz Aldrin formed the American crew.&quot;<br>- text: &quot;July 20, 1969&quot;<br>  label: &quot;DATE&quot;<br>  sentence: &quot;They landed the Apollo Lunar Module Eagle on July 20, 1969, at 20:17 UTC.&quot;<br>- text: &quot;Earth&quot;<br>  label: &quot;LOC&quot;<br>  sentence: &quot;They collected 47.5 pounds of lunar material to bring back to Earth.&quot;<br>- text: &quot;NASA&quot;<br>  label: &quot;ORG&quot;<br>  sentence: &quot;The mission was launched by a Saturn V rocket from Kennedy Space Center in Florida, and fulfilled a national goal set by President John F. Kennedy in 1961.&quot;</pre><h3>Quickstart</h3><h3>Installation</h3><pre>pip install git+https://github.com/yourusername/nergrep.git<br>python -m spacy download en_core_web_lg</pre><h3>CLI Usage</h3><p>Extract organizations and people from a file, filter by fuzzy match, and output as JSON:</p><pre>nergrep input.txt --types ORG,PERSON --fuzzy &quot;micro&quot; --format json</pre><p>Filter entities by regex and minimum length:</p><pre>nergrep &quot;Microsoft acquired GitHub in 2018.&quot; --regex &quot;^[A-Z]&quot; --min-length 5</pre><h3>Python API</h3><pre>from nergrep.extractor import extract_entities<br>from nergrep.filters import FilterConfig, filter_all</pre><pre>text = &quot;Apple Inc. is working with Microsoft on AI projects.&quot;<br>entities = extract_entities(text, types=[&quot;ORG&quot;])</pre><pre># Advanced filtering<br>config = FilterConfig(<br>    entity_types={&quot;ORG&quot;},<br>    fuzzy_match=&quot;micro&quot;,<br>    min_length=5<br>)<br>filtered = filter_all(entities, config)<br>print([e.text for e in filtered])</pre><h3>Langchain Integration</h3><p>nergrep fits naturally into Langchain pipelines for LLM-powered document processing:</p><pre>from langchain_core.documents import Document<br>from nergrep.extractor import extract_entities</pre><pre>doc = Document(page_content=&quot;OpenAI and Meta are leading AI research.&quot;)<br>entities = extract_entities(doc.page_content, types=[&quot;ORG&quot;])<br>print([e.text for e in entities])  # [&#39;OpenAI&#39;, &#39;Meta&#39;]</pre><h3>Custom ML Model Integration</h3><p>Coming soon.</p><p>Building nergrep is about more than just code—it&#39;s about designing tools that fit real data workflows:</p><ul><li>Modular, composable filters for production pipelines</li><li>CLI for quick experiments and batch jobs</li><li>Python API for integration with ML/AI platforms</li><li>Langchain support for LLM-centric architectures</li><li>Custom ML model integration for enhanced entity extraction</li></ul><p>If you’re building NLP or LLM applications and need robust, customizable entity extraction, check out <a href="https://github.com/yourusername/nergrep">nergrep</a>. Feedback and contributions are welcome!</p><h3>Potential TODOs</h3><ul><li>Performance Optimization: Explore multi-threading or GPU acceleration for faster entity extraction on large datasets.</li><li>Enhanced Filtering: Add support for more advanced filtering options, such as context-aware filtering or custom entity types.</li><li>Integration with More Frameworks: Extend nergrep to integrate with other NLP and ML frameworks beyond Langchain.</li></ul><p><em>Reach out to me on</em> <a href="https://www.linkedin.com/in/alexey-a-181a614/"><em>LinkedIn</em></a> <em>for work and consulting opportunities.</em></p><p><em>Follow me on</em> <a href="https://hashnode.com/@metawake"><em>Hashnode</em></a> <em>for more on building scalable, production-grade AI/NLP/ML tools.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c254f4c21766" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>