<?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 Salifyanji Taala on Medium]]></title>
        <description><![CDATA[Stories by Salifyanji Taala on Medium]]></description>
        <link>https://medium.com/@salifyataala?source=rss-10e547a2ce57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vTMeFIjJ7dAF9mMe.jpg</url>
            <title>Stories by Salifyanji Taala on Medium</title>
            <link>https://medium.com/@salifyataala?source=rss-10e547a2ce57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:31:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salifyataala/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[Building a Finance RAG Assistant, Part 4: Hybrid Search]]></title>
            <link>https://salifyataala.medium.com/building-a-finance-rag-assistant-part-4-hybrid-search-3e96e59574c4?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e96e59574c4</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 20:50:05 GMT</pubDate>
            <atom:updated>2026-11-03T20:50:05.936Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://salifyataala.medium.com/building-a-finance-rag-assistant-part-3-embeddings-and-chromadb-d9be42cc869d">Part 3</a> the chunks became numbers and went into ChromaDB. Today we start asking questions. We search the chunks two ways, <em>by meaning</em> and <em>by keywords</em>, and then combine the two. By the end of this post you will have a hybrid search that returns the best chunks for a question, plus tests that prove the pieces work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjTB58tEYwwKtQHkz7AfqA.png" /><figcaption>RAG Search Pipeline</figcaption></figure><h3>What we are building today</h3><p>Each kind of search has a blind spot. <strong><em>Search by meaning</em></strong>, which uses the embeddings from Part 3, understands that “costs” and “expenses” are close, but it can be vague about exact words and figures. <strong><em>Keyword search</em></strong> is precise about the words you type, but blind to different wording: in <a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-1-draw-the-system-then-run-one-question-by-hand-74578caf9d1e">Part 1</a>, Ctrl+F found the 2024 report and missed the 2025 one.</p><p>So we use both. Each search ranks the chunks, and then we merge the two rankings with a method called <strong><em>Reciprocal Rank Fusion</em></strong>. A chunk near the top of both lists wins.</p><p><strong>What you need:</strong> your <a href="https://salifyataala.medium.com/building-a-finance-rag-assistant-part-3-embeddings-and-chromadb-d9be42cc869d">Part 3 project</a>, with python -m pytest passing and the database built by python build_index.py.</p><h3>Step 1: Create the branch and install the new package</h3><p>Branch from your Part 3 work:</p><pre>git switch -c part-04-hybrid-search part-03-embeddings-and-chromadb</pre><p>Add one line to requirements.txt, so the file reads:</p><pre>pytest&gt;=8.0<br>chromadb&gt;=1.0<br>sentence-transformers&gt;=3.0<br>rank-bm25&gt;=0.2.2</pre><p>Install (with your virtual environment active) and commit:</p><pre>pip install -r requirements.txt<br>git add .<br>git commit -m &quot;Add rank-bm25 for keyword search&quot;</pre><p>If the chroma_db/ folder from Part 3 is missing, run python build_index.py once to rebuild it.</p><h3>Step 2: Ask a question by meaning</h3><p>Questions need a small change to the embedding helper. The BGE model works best when a short question gets a fixed sentence in front of it, while chunks are embedded as they are. Replace src/embeddings.py with this version:</p><pre>&quot;&quot;&quot;Turn text into embeddings (lists of numbers) with the BGE model.&quot;&quot;&quot;<br>from sentence_transformers import SentenceTransformer</pre><pre>MODEL_NAME = &quot;BAAI/bge-base-en-v1.5&quot;<br># BGE works best when a short question gets this sentence in front of it.<br># Chunks are embedded as they are, without a prefix.<br>QUERY_PREFIX = &quot;Represent this sentence for searching relevant passages: &quot;<br><br>def load_model():<br>    &quot;&quot;&quot;Load the embedding model. The first call downloads it (about 440 MB).&quot;&quot;&quot;<br>    return SentenceTransformer(MODEL_NAME)<br><br>def make_embed_fn(model, prefix=&quot;&quot;):<br>    &quot;&quot;&quot;Return a function that turns a list of texts into a list of embeddings.&quot;&quot;&quot;<br>    def embed(texts):<br>        prefixed = [prefix + text for text in texts]<br>        return model.encode(prefixed, normalize_embeddings=True).tolist()<br>    return embed</pre><p>build_index.py still works unchanged, because the prefix defaults to nothing. Now add the search function to the end of src/vector_store.py:</p><pre>def search(collection, embed_query, question, n_results=3):<br>    &quot;&quot;&quot;Return the chunks closest in meaning to the question, best first.&quot;&quot;&quot;<br>    result = collection.query(query_embeddings=embed_query([question]), n_results=n_results)<br>    hits = []<br>    for chunk_id, text, meta, distance in zip(<br>        result[&quot;ids&quot;][0], result[&quot;documents&quot;][0], result[&quot;metadatas&quot;][0], result[&quot;distances&quot;][0]<br>    ):<br>        hits.append({<br>            &quot;id&quot;: chunk_id,<br>            &quot;source&quot;: meta[&quot;source&quot;],<br>            &quot;section&quot;: meta[&quot;section&quot;],<br>            &quot;distance&quot;: distance,<br>            &quot;text&quot;: text,<br>        })<br>    return hits</pre><p>Then create ask_by_meaning.py in the project folder:</p><pre>import sys</pre><pre>from src.embeddings import load_model, make_embed_fn, QUERY_PREFIX<br>from src.vector_store import open_collection, search<br>question = &quot; &quot;.join(sys.argv[1:]) or &quot;How did operating costs change between 2024 and 2025?&quot;<br>embed_query = make_embed_fn(load_model(), QUERY_PREFIX)<br>hits = search(open_collection(), embed_query, question, n_results=3)<br>print(f&quot;Question: {question}\n&quot;)<br>for rank, hit in enumerate(hits, start=1):<br>    print(f&quot;{rank}. {hit[&#39;source&#39;]} / {hit[&#39;section&#39;]}  (distance {hit[&#39;distance&#39;]:.3f})&quot;)</pre><p>Run it with two questions:</p><pre>python ask_by_meaning.py<br>python ask_by_meaning.py &quot;What will revenue be in 2027?&quot;</pre><p>Each run prints the question and three lines, best first, with a report, a section and a <strong>distance</strong>. Smaller means closer in meaning. Your exact distances depend on the model, so read the order. What to look for:</p><ul><li><strong>First question:</strong> does a 2025 chunk about operating expenses appear? Keyword search could not find one.</li><li><strong>Second question:</strong> the reports say nothing about 2027, yet you still get three chunks. A search always returns the closest chunks it has, whether or not they contain the answer.</li></ul><pre>git add .<br>git commit -m &quot;Add search by meaning&quot;</pre><h3>Step 3: Ask a question by keywords</h3><p>The keyword method is called <strong><em>BM25</em></strong>. It scores each chunk by how many of the question’s words it contains. Rare words count for more than common ones, and a long chunk isn’t favoured just for being long. Create src/keyword_search.py:</p><pre>&quot;&quot;&quot;Keyword search over the chunks with BM25.&quot;&quot;&quot;<br>import re</pre><pre>from rank_bm25 import BM25Okapi<br><br>def tokenize(text):<br>    &quot;&quot;&quot;Split text into lowercase words and numbers, keeping decimals like 4.8 whole.&quot;&quot;&quot;<br>    return re.findall(r&quot;\d+(?:\.\d+)?|[a-z]+&quot;, text.lower())<br><br>class KeywordIndex:<br>    def __init__(self, chunks):<br>        self.chunks = chunks<br>        self.bm25 = BM25Okapi([tokenize(chunk[&quot;text&quot;]) for chunk in chunks])<br>    def search(self, question, n_results=3):<br>        &quot;&quot;&quot;Return the chunks with the best keyword score, best first.&quot;&quot;&quot;<br>        scores = self.bm25.get_scores(tokenize(question))<br>        best = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:n_results]<br>        return [<br>            {<br>                &quot;id&quot;: f&quot;{self.chunks[i][&#39;source&#39;]}::{self.chunks[i][&#39;section&#39;]}&quot;,<br>                &quot;source&quot;: self.chunks[i][&quot;source&quot;],<br>                &quot;section&quot;: self.chunks[i][&quot;section&quot;],<br>                &quot;score&quot;: float(scores[i]),<br>                &quot;text&quot;: self.chunks[i][&quot;text&quot;],<br>            }<br>            for i in best<br>        ]</pre><p>In plain words: tokenize chops text into words and numbers. KeywordIndex builds a BM25 index over all 12 chunks, and search returns the chunks with the highest scores. Now create ask_by_keywords.py:</p><pre>import sys</pre><pre>from src.chunking import load_all_chunks<br>from src.keyword_search import KeywordIndex<br>question = &quot; &quot;.join(sys.argv[1:]) or &quot;How did operating costs change between 2024 and 2025?&quot;<br>hits = KeywordIndex(load_all_chunks()).search(question, n_results=3)<br>print(f&quot;Question: {question}\n&quot;)<br>for rank, hit in enumerate(hits, start=1):<br>    print(f&quot;{rank}. {hit[&#39;source&#39;]} / {hit[&#39;section&#39;]}  (score {hit[&#39;score&#39;]:.2f})&quot;)</pre><p>Run python ask_by_keywords.py. You should see:</p><pre>Question: How did operating costs change between 2024 and 2025?</pre><pre>1. report_2024.md / Operating costs breakdown  (score 2.81)<br>2. report_2024.md / Overview  (score 1.82)<br>3. report_2024.md / Financial highlights  (score 1.62)</pre><p>All three results come from the 2024 report. The 2025 report says “<em>operating expenses</em>”, so a search for “<em>costs</em>” walks straight past it. This is the gap from <a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-1-draw-the-system-then-run-one-question-by-hand-74578caf9d1e">Part 1</a>, now measured. Now change one word:</p><pre>python ask_by_keywords.py &quot;How did operating expenses change?&quot;</pre><pre>Question: How did operating expenses change?</pre><pre>1. report_2025.md / Operating expenses breakdown  (score 1.67)<br>2. report_2025.md / Financial highlights  (score 1.12)<br>3. report_2025.md / Overview  (score 1.01)</pre><p>Now every result is from 2025. <em>Keyword search</em> sees only the words you give it, and the reports don’t agree on which word to use.</p><pre>git add .<br>git commit -m &quot;Add keyword search with BM25&quot;</pre><h3>Step 4: Combine the two with Reciprocal Rank Fusion</h3><p>We now have two ranked lists for the same question. We can’t simply add their scores, because a BM25 score and a distance are measured on different scales. <strong>Reciprocal Rank Fusion</strong> (RRF) sidesteps this by ignoring the scores and using only the positions. Each list gives a chunk 1 / (60 + position) points, and a chunk’s points are added up across the lists.</p><p>Create src/fusion.pythis is where the merging code lives. It has two functions:</p><ul><li>reciprocal_rank_fusion merges ranked lists into one. It knows nothing about models or databases, so it can be tested alone.</li><li>hybrid_search runs the keyword and meaning searches for a question and passes their rankings to that merge function.</li></ul><p>Keeping it in its own file keeps the search files small, makes the merging testable, and lets the next projects reuse it.</p><p><strong>fusion.py</strong></p><pre>&quot;&quot;&quot;Combine several ranked lists into one with Reciprocal Rank Fusion.&quot;&quot;&quot;<br>from src.vector_store import search</pre><pre><br><br>def reciprocal_rank_fusion(rankings, k=60):<br>    &quot;&quot;&quot;rankings: a list of ranked lists of ids, best first. Returns (id, score) pairs, best first.&quot;&quot;&quot;<br>    scores = {}<br>    for ranking in rankings:<br>        for rank, item in enumerate(ranking, start=1):<br>            scores[item] = scores.get(item, 0.0) + 1.0 / (k + rank)<br>    return sorted(scores.items(), key=lambda pair: pair[1], reverse=True)<br><br><br>def hybrid_search(question, keyword_index, collection, embed_query, n_results=3, pool=6):<br>    &quot;&quot;&quot;Search by keywords and by meaning, then merge the two rankings.&quot;&quot;&quot;<br>    keyword_hits = keyword_index.search(question, n_results=pool)<br>    meaning_hits = search(collection, embed_query, question, n_results=pool)<br><br>    keyword_rank = {hit[&quot;id&quot;]: r for r, hit in enumerate(keyword_hits, start=1)}<br>    meaning_rank = {hit[&quot;id&quot;]: r for r, hit in enumerate(meaning_hits, start=1)}<br>    by_id = {hit[&quot;id&quot;]: hit for hit in keyword_hits + meaning_hits}<br><br>    fused = reciprocal_rank_fusion([list(keyword_rank), list(meaning_rank)])<br>    return [<br>        {<br>            &quot;id&quot;: chunk_id,<br>            &quot;source&quot;: by_id[chunk_id][&quot;source&quot;],<br>            &quot;section&quot;: by_id[chunk_id][&quot;section&quot;],<br>            &quot;fused_score&quot;: score,<br>            &quot;keyword_rank&quot;: keyword_rank.get(chunk_id),<br>            &quot;meaning_rank&quot;: meaning_rank.get(chunk_id),<br>            &quot;text&quot;: by_id[chunk_id][&quot;text&quot;],<br>        }<br>        for chunk_id, score in fused[:n_results]<br>    ]</pre><p>Before using it on real chunks, watch it work on a made-up example. Create rrf_by_hand.py: which is a teaching script, not part of the assistant. It merges two made-up rankings of five fake chunks, with no model and no database, so readers can check the result on paper before trusting the formula on real chunks.</p><p>rrf_by_hand.py</p><pre>from src.fusion import reciprocal_rank_fusion</pre><pre>keyword_ranking = [&quot;chunk A&quot;, &quot;chunk B&quot;, &quot;chunk C&quot;]<br>meaning_ranking = [&quot;chunk D&quot;, &quot;chunk B&quot;, &quot;chunk E&quot;]<br>print(&quot;Keyword search says:&quot;, keyword_ranking)<br>print(&quot;Meaning search says:&quot;, meaning_ranking)<br>print()<br>for chunk, score in reciprocal_rank_fusion([keyword_ranking, meaning_ranking]):<br>    print(f&quot;{score:.4f}  {chunk}&quot;)</pre><p>Run python rrf_by_hand.py. You should see:</p><pre>Keyword search says: [&#39;chunk A&#39;, &#39;chunk B&#39;, &#39;chunk C&#39;]<br>Meaning search says: [&#39;chunk D&#39;, &#39;chunk B&#39;, &#39;chunk E&#39;]</pre><pre>0.0323  chunk B<br>0.0164  chunk A<br>0.0164  chunk D<br>0.0159  chunk C<br>0.0159  chunk E</pre><p><em>Chunk B</em> was second in both lists, so it earns 1/62 twice, which is 0.0323. <em>Chunk A</em> was first in only one list and earns 1/61, which is 0.0164. Agreement between the two searches beats a single first place.</p><p>In hybrid_search, the <a href="https://salifyataala.medium.com/hybrid-search-what-does-pool-mean-f17f4ef97d30?postPublishedType=initial">pool=6</a> setting means each search contributes its top six chunks to the merge, and we keep the best three after fusion.</p><pre>git add .<br>git commit -m &quot;Add Reciprocal Rank Fusion and hybrid search&quot;</pre><h3>Step 5: Ask the hybrid search</h3><p>Create ask_hybrid.py in the project folder — this the script you run from the terminal to ask the system a question.:</p><pre>import sys</pre><pre>from src.chunking import load_all_chunks<br>from src.embeddings import load_model, make_embed_fn, QUERY_PREFIX<br>from src.fusion import hybrid_search<br>from src.keyword_search import KeywordIndex<br>from src.vector_store import open_collection<br>question = &quot; &quot;.join(sys.argv[1:]) or &quot;How did operating costs change between 2024 and 2025?&quot;<br>keyword_index = KeywordIndex(load_all_chunks())<br>embed_query = make_embed_fn(load_model(), QUERY_PREFIX)<br>hits = hybrid_search(question, keyword_index, open_collection(), embed_query, n_results=3)<br>print(f&quot;Question: {question}\n&quot;)<br>for rank, hit in enumerate(hits, start=1):<br>    print(f&quot;{rank}. {hit[&#39;source&#39;]} / {hit[&#39;section&#39;]}&quot;)<br>    print(f&quot;   score {hit[&#39;fused_score&#39;]:.4f}  (keyword rank: {hit[&#39;keyword_rank&#39;]}, meaning rank: {hit[&#39;meaning_rank&#39;]})&quot;)</pre><p>Run python ask_hybrid.py. Each result shows where each search ranked it. None means that search didn’t put the chunk in its top six. What to look for:</p><ul><li><strong>Both years:</strong> does the top three now include chunks from 2024 and from 2025? Keyword search alone gave you only 2024.</li><li><strong>The ranks:</strong> for each result, which search found it, or did both?</li><li><strong>A chunk with two numbers:</strong> a chunk ranked by both searches should sit above chunks ranked by only one.</li></ul><p>Write down what you see. It is the “<em>what I measured</em>” part of your own notes.</p><pre>git add .<br>git commit -m &quot;Add hybrid search script&quot;</pre><h3>Step 6: Prove it with tests</h3><p>Create tests/test_keyword_search.py:</p><pre>from src.chunking import load_all_chunks<br>from src.keyword_search import KeywordIndex, tokenize</pre><pre>QUESTION = &quot;How did operating costs change between 2024 and 2025?&quot;<br><br>def test_tokenize_keeps_decimals_whole():<br>    assert tokenize(&quot;Operating expenses rose to USD 4.8 million&quot;) == [<br>        &quot;operating&quot;, &quot;expenses&quot;, &quot;rose&quot;, &quot;to&quot;, &quot;usd&quot;, &quot;4.8&quot;, &quot;million&quot;,<br>    ]<br><br>def test_costs_question_finds_the_2024_breakdown_first():<br>    hits = KeywordIndex(load_all_chunks()).search(QUESTION)<br>    assert (hits[0][&quot;source&quot;], hits[0][&quot;section&quot;]) == (&quot;report_2024.md&quot;, &quot;Operating costs breakdown&quot;)<br><br>def test_keyword_search_misses_2025_when_the_wording_differs():<br>    # This documents the gap that fusion closes: the 2025 report says &quot;expenses&quot;, not &quot;costs&quot;.<br>    hits = KeywordIndex(load_all_chunks()).search(QUESTION)<br>    assert all(hit[&quot;source&quot;] == &quot;report_2024.md&quot; for hit in hits)</pre><p>The last test records a weakness on purpose. It passes , and it shows exactly what the hybrid search is there to fix. Now create tests/test_fusion.py:</p><pre>from src.chunking import load_all_chunks<br>from src.fusion import reciprocal_rank_fusion, hybrid_search<br>from src.keyword_search import KeywordIndex<br>from src.vector_store import open_collection, index_chunks<br>from test_vector_store import fake_embed  # reuse the stand-in embedder from the vector store tests</pre><pre>def test_a_chunk_in_both_lists_beats_a_chunk_that_is_first_in_only_one():<br>    fused = reciprocal_rank_fusion([[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], [&quot;d&quot;, &quot;b&quot;, &quot;e&quot;]])<br>    assert fused[0][0] == &quot;b&quot;<br><br>def test_scores_follow_the_formula():<br>    fused = dict(reciprocal_rank_fusion([[&quot;a&quot;]], k=60))<br>    assert abs(fused[&quot;a&quot;] - 1 / 61) &lt; 1e-9<br><br>def test_hybrid_search_merges_both_lists(tmp_path):<br>    chunks = load_all_chunks()<br>    collection = open_collection(path=str(tmp_path))<br>    index_chunks(collection, chunks, fake_embed)<br>    hits = hybrid_search(&quot;operating costs&quot;, KeywordIndex(chunks), collection, fake_embed, n_results=3)<br>    assert len(hits) == 3<br>    assert len({hit[&quot;id&quot;] for hit in hits}) == 3<br>    assert hits[0][&quot;fused_score&quot;] &gt;= hits[1][&quot;fused_score&quot;] &gt;= hits[2][&quot;fused_score&quot;]<br>    assert any(hit[&quot;keyword_rank&quot;] is not None for hit in hits)</pre><p>Run them:</p><pre>python -m pytest</pre><p>You should see 17 passed: the 11 from Part 3, 3 for keyword search and 3 for fusion. As in Part 3, the tests use the small stand-in embedder, so they run in seconds without the big model.</p><pre>git add .<br>git commit -m &quot;Add keyword search and fusion tests&quot;</pre><h3>Step 7: Push the branch</h3><pre>git push -u origin part-04-hybrid-search</pre><p>You can find the full code <a href="https://github.com/SalifyaTaala/financial_ai_rag/tree/part-04-hybrid-search"><strong>here</strong></a>.</p><h3>Your turn</h3><ol><li>Ask all three searches the cash question: How much cash did the company have at the end of 2025? Which year’s Cash flow chunk comes first in each? Does the keyword search put the wrong year second?</li><li>Ask the hybrid search What will revenue be in 2027?. You still get three chunks. What does the fused score tell you about whether they answer the question?</li><li>In hybrid_search, change pool=6 to pool=3 and rerun ask_hybrid.py. What changes in the results?</li></ol><p>Happy learning.</p><h3>Common problems</h3><ul><li><strong>ModuleNotFoundError: No module named &#39;rank_bm25&#39;:</strong> the package is installed as rank-bm25 but imported as rank_bm25. Run pip install -r requirements.txt with your virtual environment active.</li><li><strong>ask_by_meaning.py returns an error or nothing:</strong> run python build_index.py first, so the database exists.</li><li><strong>ModuleNotFoundError: No module named &#39;test_vector_store&#39; when testing:</strong> run the tests from the project folder with python -m pytest, not from inside tests/.</li><li><strong>A question with quotes doesn’t work on Windows:</strong> wrap the question in double quotes, as in the examples.</li></ul><h3>What you just learned</h3><ul><li><strong>Keyword search is exact but literal, and search by meaning is flexible but fuzzy.</strong> Each one works where the other fails.</li><li><strong>Reciprocal Rank Fusion merges rankings, not scores.</strong> So we never have to compare a BM25 score with a distance, and a chunk both searches like rises to the top.</li><li><strong>A search always returns something.</strong> Being ranked first doesn’t mean a chunk answers the question, which is why the checks from the <a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-1-draw-the-system-then-run-one-question-by-hand-74578caf9d1e">Part 1</a> drawing come later.</li></ul><h3>Glossary</h3><ul><li><strong>BM25:</strong> a keyword-based ranking method that scores chunks by the question’s words they contain.</li><li><strong>Hybrid search:</strong> keyword search and search by meaning, merged into one ranking.</li><li><strong>Rank:</strong> a result’s position in a list: 1 is the best.</li><li><strong>Reciprocal Rank Fusion:</strong> a way to merge ranked lists by giving each chunk 1 / (60 + position) points per list and adding them up.</li><li><strong>Token:</strong> one word or number after a text has been chopped up for searching.</li></ul><p>Next, in Part 5, we hand the best chunks to the language model so it can write an answer, and we check what it says.</p><p><em>If you run a small business and are curious about how an AI assistant could improve your customer experience, I’d love to connect and explore the possibilities with you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e96e59574c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hybrid Search : What Does “pool” Mean?]]></title>
            <link>https://salifyataala.medium.com/hybrid-search-what-does-pool-mean-f17f4ef97d30?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17f4ef97d30</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 20:47:00 GMT</pubDate>
            <atom:updated>2026-11-03T20:47:00.599Z</atom:updated>
            <content:encoded><![CDATA[<p>When you build a hybrid search, one small setting quietly decides how well its two searches can agree with each other: the pool. It goes by different names in code, and beginners tend to skip over it. This post explains it from scratch, with a small example you can run in a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwMa-cl5y6DGBJZujUzNLA.png" /><figcaption>Hybrid Search Results Pool</figcaption></figure><h3>The situation</h3><p>Hybrid search runs two searches on the same question: <em>a keyword search</em>, and a <em>search by meaning</em>. Each one produces a ranked list of chunks, with the best chunk first. A chunk is a short piece of a document. Then we merge the two lists into one and keep the best few.</p><p>One popular way to merge them is <em>Reciprocal Rank Fusion</em>. A chunk in position p of a list earns 1 / (60 + p) points, and the points from both lists are added up. A chunk that sits high on both lists wins.</p><h3>What is the pool?</h3><p>Before the merge, each search hands in a shortlist of its best chunks. The <strong>pool</strong> is the length of that shortlist.</p><p>With pool=6, the keyword search hands in its best six chunks, and the search by meaning hands in its best six. The merge only looks at those shortlists. A chunk that is on neither of them can’t win.</p><p>There are two separate settings, and it helps to keep them apart:</p><ul><li><strong>pool</strong> is how long each shortlist is. In the example below it is 6.</li><li><strong>n_results</strong> is how many chunks we keep after the merge. In the example below it is 3.</li></ul><h3>Why not ask each search for only three?</h3><p>The merge rewards agreement. A chunk that both searches like rises to the top. But agreement needs overlap, and short shortlists leave little room for overlap.</p><p>Here is one question, with the two shortlists written out. The letters stand for chunks:</p><pre>pool=3   keyword: A, B, C            meaning: G, B, H<br>pool=6   keyword: A, B, C, D, E, F   meaning: G, B, H, A, I, J</pre><p>Chunk A is first for the keyword search and fourth for the search by meaning. With pool=3, the second list is cut off before A, so A only gets credit from one search. With pool=6, A appears on both lists. Using the points described above, the scores come out like this:</p><pre>Chunk   pool=3    pool=6<br>A       0.0164    0.0320<br>B       0.0323    0.0323<br>G       0.0164    0.0164</pre><p>Chunk B is second on both lists either way, so nothing changes for it. Chunk G is only on one list either way. But chunk A nearly doubles its score, and it moves from a tie for second place to a clear second. The longer shortlists gave the two searches a chance to agree about A.</p><h3>Why not use every chunk?</h3><p>A small project might have only 12 chunks, so a pool of six is half of them. A real project may have thousands, and ranking all of them is slow. Chunks far down a list also add almost nothing. A chunk in position 7 earns 1/67 points, which is 0.0149. A chunk in position 12 earns 1/72, which is 0.0139. The difference is tiny, so we cap the shortlist.</p><h3>How do you choose the pool?</h3><p>There is no magic number. A reasonable starting point is a pool a few times bigger than the number of chunks you keep. In the example above we keep 3 and use a pool of 6. If the pool is too small, the searches have little chance to agree. If it is too large, you do more work for very little gain.</p><h3>Try it yourself</h3><p>You don’t need a full search system to see the effect. This short script merges the two shortlists from the example above, once with a pool of 3 and once with a pool of 6. Save it as pool_demo.py and run it with python pool_demo.py:</p><pre>def fuse(rankings, k=60):<br>    scores = {}<br>    for ranking in rankings:<br>        for position, chunk in enumerate(ranking, start=1):<br>            scores[chunk] = scores.get(chunk, 0.0) + 1.0 / (k + position)<br>    return sorted(scores.items(), key=lambda pair: pair[1], reverse=True)</pre><pre>keyword = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;]<br>meaning = [&quot;G&quot;, &quot;B&quot;, &quot;H&quot;, &quot;A&quot;, &quot;I&quot;, &quot;J&quot;]<br>for pool in (3, 6):<br>    print(f&quot;pool={pool}&quot;)<br>    for chunk, score in fuse([keyword[:pool], meaning[:pool]])[:3]:<br>        print(f&quot;  {score:.4f}  chunk {chunk}&quot;)<br></pre><p>You should see:</p><pre>pool=3<br>  0.0323  chunk B<br>  0.0164  chunk A<br>  0.0164  chunk G<br>pool=6<br>  0.0323  chunk B<br>  0.0320  chunk A<br>  0.0164  chunk G</pre><p>Chunk A jumps from 0.0164 to 0.0320 when the pool grows from 3 to 6. Now make it your own: change the two shortlists, for example by moving A further down the meaning list, and watch where a longer pool stops helping.</p><h3>The short version</h3><ul><li><strong>The pool is the length of the shortlist each search hands in before the merge.</strong></li><li><strong>n_results is how many chunks you keep after the merge.</strong></li><li><strong>A longer pool gives the two searches more chances to agree,</strong> and a pool that is too long just costs time.</li></ul><p><em>If you run a small business and are curious about how an AI assistant could improve your customer experience, I’d love to connect and explore the possibilities with you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17f4ef97d30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Finance RAG Assistant, Part 3: Embeddings and ChromaDB]]></title>
            <link>https://salifyataala.medium.com/building-a-finance-rag-assistant-part-3-embeddings-and-chromadb-d9be42cc869d?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9be42cc869d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 17:29:39 GMT</pubDate>
            <atom:updated>2026-11-01T17:29:39.507Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-2-setup-and-chunking-fcb4ef114dab">Part 2</a> we cut the reports into chunks. Today those chunks become numbers a computer can compare by meaning, and we store them in <strong>ChromaDB</strong>. By the end of this post you will have all 12 chunks saved in a database on your computer, each one stored together with the numbers that describe its meaning, plus tests that prove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL3O3JStNjo5mAnwAz1suw.png" /><figcaption>Finance RAG Assistant Pipeline</figcaption></figure><h3>What we are building</h3><p><a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-2-setup-and-chunking-fcb4ef114dab">Part 2</a> ended with 12 chunks, six per report. A computer can’t read a chunk the way you do, so we give every chunk a list of numbers that captures what it means. That list is called an <strong>embedding</strong>. Chunks that talk about similar things get similar numbers, even when the words differ, so a computer can compare two chunks by meaning. Then we save each chunk and its numbers in <strong>ChromaDB</strong>, a database built for exactly this.</p><p><strong>What you need:</strong> your <a href="https://github.com/SalifyaTaala/financial_ai_rag/tree/part-02-setup-and-chunking">Part 2 project</a>, with python -m pytest passing. The first install downloads PyTorch, which is large, and the first run downloads the embedding model, about 440 MB. Allow a few GB of disk space.</p><h3>Step 1: Create the branch and install the packages</h3><p>Branch from your Part 2 work so you keep the chunker:</p><pre>git switch -c part-03-embeddings-and-chromadb </pre><p>Replace requirements.txt with:</p><pre>pytest&gt;=8.0<br>chromadb&gt;=1.0<br>sentence-transformers&gt;=3.0</pre><p>Add one line to .gitignore, because the database folder is generated and shouldn’t be uploaded:</p><pre>chroma_db/</pre><p>Install (with your virtual environment active) and make the first commit:</p><pre>pip install -r requirements.txt<br>git add .<br>git commit -m &quot;Add embedding and vector database packages&quot;</pre><h3>Step 2: Load the chunks from Part 2</h3><p>First, check that the chunks from Part 2 are what we expect. Add a small helper to the end of src/chunking.py, so every script today can load all the chunks in one line:</p><pre>def load_all_chunks(folder=&quot;data/reports&quot;):<br>    &quot;&quot;&quot;Chunk every report in the folder by section. Returns one list of chunks.&quot;&quot;&quot;<br>    chunks = []<br>    for path in sorted(Path(folder).glob(&quot;report_*.md&quot;)):<br>        chunks += section_chunks(load_report(path), path.name)<br>    return chunks</pre><p>Now a script to look at them. Create show_chunks.py in the project folder:</p><pre>from src.chunking import load_all_chunks</pre><pre>chunks = load_all_chunks()<br>print(len(chunks), &quot;chunks&quot;)<br>for chunk in chunks:<br>    print(f&quot;{chunk[&#39;source&#39;]} / {chunk[&#39;section&#39;]}&quot;)</pre><p>Run python show_chunks.py. You should see:</p><pre>12 chunks<br>report_2024.md / Overview<br>report_2024.md / Financial highlights<br>report_2024.md / Revenue by segment<br>report_2024.md / Operating costs breakdown<br>report_2024.md / Cash flow<br>report_2024.md / Outlook<br>report_2025.md / Overview<br>report_2025.md / Financial highlights<br>report_2025.md / Revenue by segment<br>report_2025.md / Operating expenses breakdown<br>report_2025.md / Cash flow<br>report_2025.md / Outlook</pre><p>Twelve chunks, six sections per report. Notice that the 2024 report has “Operating costs breakdown” and the 2025 report has “Operating expenses breakdown”. Keep those two in mind for step 4.</p><pre>git add .<br>git commit -m &quot;Add load_all_chunks helper&quot;</pre><h3>Step 3: Turn a chunk into numbers</h3><p>We use BAAI/bge-base-en-v1.5, a free embedding model that runs on your own computer. Create src/embeddings.py:</p><pre>&quot;&quot;&quot;Turn text into embeddings (lists of numbers) with the BGE model.&quot;&quot;&quot;<br>from sentence_transformers import SentenceTransformer</pre><pre>MODEL_NAME = &quot;BAAI/bge-base-en-v1.5&quot;<br><br>def load_model():<br>    &quot;&quot;&quot;Load the embedding model. The first call downloads it (about 440 MB).&quot;&quot;&quot;<br>    return SentenceTransformer(MODEL_NAME)<br><br>def make_embed_fn(model):<br>    &quot;&quot;&quot;Return a function that turns a list of texts into a list of embeddings.&quot;&quot;&quot;<br>    def embed(texts):<br>        return model.encode(texts, normalize_embeddings=True).tolist()<br>    return embed</pre><p>In plain words: load_model fetches the model, and make_embed_fn gives you a function that turns a list of texts into a list of embeddings. normalize_embeddings=True scales every list to the same length, so comparing two of them later is just multiply-and-add.</p><p>Now embed one chunk and look at the result. Create one_embedding.py in the project folder, financial_ai_rag/, next to compare_chunking.py and the src/ and tests/ folders.</p><pre>from src.chunking import load_all_chunks<br>from src.embeddings import load_model, make_embed_fn</pre><pre>chunk = load_all_chunks()[0]<br>embed = make_embed_fn(load_model())<br>vector = embed([chunk[&quot;text&quot;]])[0]<br>print(&quot;Chunk:&quot;, chunk[&quot;source&quot;], &quot;/&quot;, chunk[&quot;section&quot;])<br>print(&quot;It became&quot;, len(vector), &quot;numbers.&quot;)<br>print(&quot;The first five:&quot;, [round(x, 3) for x in vector[:5]])</pre><p>Run python one_embedding.py. The first run downloads the model, so expect progress bars. You should see:</p><pre>Chunk: report_2024.md / Overview<br>It became 768 numbers.<br>The first five: [-0.013, 0.002, 0.026, -0.015, 0.058]</pre><p>Your five numbers should match these or be very close. Tiny differences in the last digit can come from your computer or library versions. The 768 is the point: this model describes every chunk with a list of exactly 768 numbers, however long the chunk is. Most of the numbers are close to zero, and no single one means anything on its own. The meaning is in the whole list.</p><pre>git add .<br>git commit -m &quot;Add embedding helpers and a one-chunk demo&quot;</pre><h3>Step 4: Compare chunks by meaning</h3><p>Now the payoff. We embed all 12 chunks and ask: which chunks are closest in meaning to the 2024 “Operating costs breakdown”? Create compare_by_meaning.py in the project folder:</p><pre>from src.chunking import load_all_chunks<br>from src.embeddings import load_model, make_embed_fn</pre><pre>chunks = load_all_chunks()<br>embed = make_embed_fn(load_model())<br>vectors = embed([chunk[&quot;text&quot;] for chunk in chunks])<br><br>def similarity(a, b):<br>    # the vectors have length 1, so multiplying and adding gives the cosine similarity<br>    return sum(x * y for x, y in zip(a, b))<br><br>reference = next(<br>    i for i, c in enumerate(chunks)<br>    if c[&quot;source&quot;] == &quot;report_2024.md&quot; and c[&quot;section&quot;] == &quot;Operating costs breakdown&quot;<br>)<br>print(f&quot;Compared with: {chunks[reference][&#39;source&#39;]} / {chunks[reference][&#39;section&#39;]}\n&quot;)<br>scores = [(similarity(vectors[reference], v), i) for i, v in enumerate(vectors) if i != reference]<br>for score, i in sorted(scores, reverse=True):<br>    print(f&quot;{score:.2f}  {chunks[i][&#39;source&#39;]} / {chunks[i][&#39;section&#39;]}&quot;)</pre><p>The similarity function multiplies the two lists of numbers position by position and adds the results. The higher the score, the closer the two chunks are in meaning.</p><p>Run python compare_by_meaning.py. You will see 11 lines, best match first, each with a score and a chunk label. The exact scores depend on the model, so look at the order instead of the values. What to look for:</p><ul><li><strong>Near the top:</strong> report_2025.md / Operating expenses breakdown. It lists the same three costs as the 2024 chunk, even though its heading says “expenses” instead of “costs”. A keyword search could not make that link.</li><li><strong>Near the bottom:</strong> chunks about other things, such as the Outlook sections.</li></ul><p>If your order surprises you, write it down. That is useful material for your own notes.</p><pre>git add .<br>git commit -m &quot;Compare chunks by meaning&quot;</pre><h3>Step 5: Store the chunks in ChromaDB</h3><p>Embedding all 12 chunks takes a moment, and we don’t want to repeat it every time. So we save each chunk with its numbers in ChromaDB. Create src/vector_store.py:</p><pre>&quot;&quot;&quot;Store chunks, and the numbers that describe them, in ChromaDB.&quot;&quot;&quot;<br>import chromadb</pre><pre>def open_collection(path=&quot;chroma_db&quot;, name=&quot;reports&quot;):<br>    &quot;&quot;&quot;Open (or create) the collection that holds our chunks.&quot;&quot;&quot;<br>    client = chromadb.PersistentClient(path=path)<br>    return client.get_or_create_collection(name=name, metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;})<br><br>def index_chunks(collection, chunks, embed_passages):<br>    &quot;&quot;&quot;Embed every chunk and store it. Safe to run twice: same ids are overwritten.&quot;&quot;&quot;<br>    texts = [chunk[&quot;text&quot;] for chunk in chunks]<br>    collection.upsert(<br>        ids=[f&quot;{chunk[&#39;source&#39;]}::{chunk[&#39;section&#39;]}&quot; for chunk in chunks],<br>        documents=texts,<br>        embeddings=embed_passages(texts),<br>        metadatas=[{&quot;source&quot;: chunk[&quot;source&quot;], &quot;section&quot;: chunk[&quot;section&quot;]} for chunk in chunks],<br>    )<br></pre><p>A <strong>collection</strong> is like a table. Each row holds an id (the report and section name), the chunk text, its 768 numbers, and a label saying where it came from. &quot;hnsw:space&quot;: &quot;cosine&quot; tells ChromaDB to measure closeness the same way our similarity function did in step 4. upsert means insert or update, so running the script twice doesn’t create duplicates.</p><p>Now a script that loads the chunks and stores them. Create build_index.py in the project folder :</p><pre>from src.chunking import load_all_chunks<br>from src.embeddings import load_model, make_embed_fn<br>from src.vector_store import open_collection, index_chunks</pre><pre>chunks = load_all_chunks()<br>collection = open_collection()<br>index_chunks(collection, chunks, make_embed_fn(load_model()))<br>print(f&quot;Indexed {len(chunks)} chunks. The collection now holds {collection.count()}.&quot;)</pre><p>Run python build_index.py. You should see:</p><pre>Indexed 12 chunks. The collection now holds 12.</pre><p>Run it a second time. It should still say 12. A new chroma_db/ folder has appeared: that is your database, saved on disk.</p><p>Let’s look inside it. Create inspect_index.py in the project folder:</p><pre>from src.vector_store import open_collection</pre><pre>collection = open_collection()<br>print(&quot;Chunks stored:&quot;, collection.count())<br>record = collection.get(<br>    ids=[&quot;report_2025.md::Financial highlights&quot;],<br>    include=[&quot;documents&quot;, &quot;metadatas&quot;, &quot;embeddings&quot;],<br>)<br>print(&quot;\nOne stored record&quot;)<br>print(&quot;id:     &quot;, record[&quot;ids&quot;][0])<br>print(&quot;label:  &quot;, record[&quot;metadatas&quot;][0])<br>print(&quot;text:   &quot;, record[&quot;documents&quot;][0][:60].replace(&quot;\n&quot;, &quot; &quot;), &quot;...&quot;)<br>print(&quot;numbers:&quot;, len(record[&quot;embeddings&quot;][0]))</pre><p>Run python inspect_index.py. You should see:</p><pre>Chunks stored: 12<br>One stored record<br>id:      report_2025.md::Financial highlights<br>label:   {&#39;section&#39;: &#39;Financial highlights&#39;, &#39;source&#39;: &#39;report_2025.md&#39;}<br>text:    Annual Report 2025 - Financial highlights | Item | 2025 (USD ...<br>numbers: 768</pre><p>This script doesn’t load the embedding model at all. The chunk, its label and its 768 numbers all come straight from the database, so from now on we embed once and reuse.</p><pre>git add .<br>git commit -m &quot;Store the chunks and their embeddings in ChromaDB&quot;</pre><h3>Step 6: Prove it with tests</h3><p>The real model is slow to load, so the tests use a tiny stand-in that turns words into numbers in a crude way. It isn’t smart, but it is fast, runs offline and gives the same result every time. That works because index_chunks receives the embedding function as an argument.</p><p>First add one test to the end of tests/test_chunking.py:</p><pre>def test_load_all_chunks_gives_twelve():<br>    from src.chunking import load_all_chunks<br>    assert len(load_all_chunks()) == 12</pre><p>Then create tests/test_vector_store.py:</p><pre>&quot;&quot;&quot;Tests for the vector store. A tiny stand-in embedder keeps them fast and offline.&quot;&quot;&quot;<br>import hashlib<br>import math</pre><pre>from src.chunking import load_all_chunks<br>from src.vector_store import open_collection, index_chunks<br><br>def fake_embed(texts, dim=64):<br>    &quot;&quot;&quot;Stand-in for the real model: counts words into 64 buckets. Not smart, but deterministic.&quot;&quot;&quot;<br>    vectors = []<br>    for text in texts:<br>        v = [0.0] * dim<br>        for word in text.lower().split():<br>            v[int(hashlib.md5(word.encode()).hexdigest(), 16) % dim] += 1.0<br>        norm = math.sqrt(sum(x * x for x in v)) or 1.0<br>        vectors.append([x / norm for x in v])<br>    return vectors<br><br>def test_index_holds_every_chunk(tmp_path):<br>    collection = open_collection(path=str(tmp_path))<br>    index_chunks(collection, load_all_chunks(), fake_embed)<br>    assert collection.count() == 12<br><br>def test_indexing_twice_does_not_duplicate(tmp_path):<br>    collection = open_collection(path=str(tmp_path))<br>    index_chunks(collection, load_all_chunks(), fake_embed)<br>    index_chunks(collection, load_all_chunks(), fake_embed)<br>    assert collection.count() == 12<br><br>def test_each_chunk_is_stored_with_its_numbers_and_label(tmp_path):<br>    collection = open_collection(path=str(tmp_path))<br>    index_chunks(collection, load_all_chunks(), fake_embed)<br>    record = collection.get(<br>        ids=[&quot;report_2025.md::Financial highlights&quot;],<br>        include=[&quot;documents&quot;, &quot;metadatas&quot;, &quot;embeddings&quot;],<br>    )<br>    assert len(record[&quot;embeddings&quot;][0]) == 64<br>    assert record[&quot;metadatas&quot;][0][&quot;section&quot;] == &quot;Financial highlights&quot;<br>    assert &quot;Annual Report 2025&quot; in record[&quot;documents&quot;][0]</pre><p>Run them:</p><pre>python -m pytest</pre><p>You should see 11 passed: the 7 from Part 2, the new chunk-count test, and 3 for the database. The tests promise that every chunk is stored, that storing twice doesn’t duplicate anything, and that each chunk is saved with its numbers and its label.</p><pre>git add .<br>git commit -m &quot;Add vector store tests&quot;</pre><h3>Step 7: Push the branch</h3><pre>git push -u origin part-03-embeddings-and-chromadb</pre><p>The code for this post can now be found <a href="https://github.com/SalifyaTaala/financial_ai_rag/tree/part-03-embeddings-and-chromadb">here</a>.</p><h3>Your turn</h3><ol><li>In compare_by_meaning.py, change the reference chunk to report_2025.md and Cash flow. Which chunk comes out closest now? Is it the one you expected?</li><li>Compare against the 2024 Outlook chunk instead. Which chunks are closest to it?</li><li>Delete the chroma_db/ folder, run python build_index.py, then python inspect_index.py. Do you get the same 12 chunks?</li></ol><h3>Common problems</h3><ul><li><strong>The install takes a long time:</strong> sentence-transformers brings PyTorch with it, which is a large download. Let it finish once.</li><li><strong>A warning about symlinks on Windows:</strong> the model downloader prints it, and it is harmless.</li><li><strong>ModuleNotFoundError: No module named &#39;sentence_transformers&#39;:</strong> your virtual environment isn’t active, or pip install -r requirements.txt didn’t finish.</li><li><strong>inspect_index.py shows 0 chunks or an </strong><strong>IndexError:</strong> run python build_index.py first.</li><li><strong>You want a fresh database:</strong> delete the chroma_db/ folder and run python build_index.py again.</li></ul><h3>What you just learned</h3><ul><li><strong>An embedding is a list of numbers that describes what a chunk means.</strong> This model uses 768 of them for every chunk.</li><li><strong>Similar meaning gives similar numbers.</strong> That is how “costs” and “expenses” end up close together, which a keyword search can’t do.</li><li><strong>ChromaDB keeps each chunk together with its numbers and its label, on disk.</strong> We embed once and reuse.</li></ul><h3>Glossary</h3><ul><li><strong>Collection:</strong> a named set of stored chunks in ChromaDB, like a table.</li><li><strong>Cosine similarity:</strong> a score for how close two embeddings are in meaning. Higher is closer.</li><li><strong>Embedding:</strong> a list of numbers that captures the meaning of a text.</li><li><strong>Upsert:</strong> insert a record, or update it if it already exists.</li><li><strong>Vector database:</strong> a database built to store embeddings and find the ones closest to a new one.</li></ul><p>Next, in Part 4, we ask questions of this collection: we search it by meaning, add keyword search with BM25, and combine the two.</p><p><em>If you run a small business and are curious about how an AI assistant could improve your customer experience, I’d love to connect and explore the possibilities with you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9be42cc869d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Finance RAG Assistant, Part 2: Setup and Chunking]]></title>
            <link>https://salifyataala.medium.com/building-a-finance-rag-assistant-part-2-setup-and-chunking-fcb4ef114dab?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcb4ef114dab</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rag-chatbot]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 20:19:35 GMT</pubDate>
            <atom:updated>2026-10-28T20:19:35.455Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@salifyataala/building-a-finance-rag-assistant-part-1-draw-the-system-then-run-one-question-by-hand-74578caf9d1e">Part 1</a> you ran the idea by hand. Today you start building. By the end of this post you will have a working project, two ways of cutting a report into chunks, and tests that prove the better way works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wo46mBn7lOTgdgL05Nwwaw.png" /><figcaption>Financial Report to Indexed Chunks</figcaption></figure><p>The code for this post is on the <a href="https://github.com/SalifyaTaala/financial_ai_rag">part-02-setup-and-chunking branch</a> of the financial_ai_rag repo. Every step below ends with one commit, so the branch history reads like this article.</p><h3>What we are building today</h3><p>Before the assistant can search a report, the report has to be cut into small pieces called <strong>chunks</strong>. The search then finds the best chunks and hands them to the model. If the cutting is careless, a number gets separated from its label and the model answers from half a table. Today you build the chunker and see why.</p><p><strong>What you need:</strong> Python 3.10 or newer, <a href="https://git-scm.com/">Git</a>, a free <a href="https://github.com/">GitHub</a> account and a code editor such as <a href="https://code.visualstudio.com/?_exp_home=e855cfac50">VS Code</a>. Check the first two:</p><pre>python --version<br>git --version</pre><p>On Mac or Linux the first command may be python3.</p><h3>Step 1: Create the project and the branch</h3><pre>mkdir financial_ai_rag<br>cd financial_ai_rag<br>git init<br>git checkout -b part-02-setup-and-chunking</pre><p>If you already have a financial_ai_rag repository, cd into it and run only the last command to create the branch.</p><p>Next, a <strong>virtual environment</strong>: a private folder for this project’s Python packages, so they don’t clash with other projects.</p><pre>python -m venv .venv</pre><p>Activate it. On Windows Git Bash:</p><pre>source .venv/Scripts/activate</pre><p>On Mac or Linux:</p><pre>source .venv/bin/activate</pre><p>You should now see (.venv) at the start of your prompt.</p><p>Create these folders and files:</p><pre>financial_ai_rag/<br>├── .gitignore<br>├── requirements.txt<br>├── data/reports/<br>├── src/__init__.py      (an empty file)<br>└── tests/</pre><p>.gitignore tells Git what not to upload:</p><pre>.venv/<br>__pycache__/<br>.pytest_cache/<br>.env</pre><p>requirements.txt lists the packages the project needs. Today there is only one, a testing tool:</p><pre>pytest&gt;=8.0</pre><p>Install it and make the first commit:</p><pre>pip install -r requirements.txt<br>git add .<br>git commit -m &quot;Set up project structure&quot;</pre><h3>Step 2: Add the reports</h3><p>Download report_2024.md and report_2025.md from the <a href="https://github.com/SalifyaTaala/financial_ai_rag">git repo</a> in the data/reports folder. They are made-up annual reports, in US dollars, with no company name.</p><p>Open report_2025.md. It is plain text with ## headings and tables drawn with | characters:</p><pre>## Financial highlights</pre><pre>| Item | 2025 (USD million) |<br>| --- | --- |<br>| Revenue | 12.0 |<br>| Cost of sales | 4.5 |</pre><p>Notice that the 2024 report says “operating costs” and the 2025 report says “operating expenses”. That is deliberate. Real companies are not consistent either.</p><pre>git add .<br>git commit -m &quot;Add sample reports&quot;</pre><h3>Step 3: Read a report in Python</h3><p>Create src/chunking.py:</p><pre>from pathlib import Path</pre><pre>def load_report(path):<br>    &quot;&quot;&quot;Read a report as text. Normalise line endings so Windows and Mac/Linux behave the same.&quot;&quot;&quot;<br>    return Path(path).read_text(encoding=&quot;utf-8&quot;).replace(&quot;\r\n&quot;, &quot;\n&quot;)<br></pre><p>Test it from the project folder:</p><pre>python -c &quot;from src.chunking import load_report; print(len(load_report(&#39;data/reports/report_2024.md&#39;)))&quot;</pre><p>You should see a number close to 1835, the number of characters in the 2024 report.</p><h3>Step 4: Cut it the naive way</h3><p>The simplest chunker slices the text every 500 characters. So that an idea sitting exactly on a cut isn’t lost, each chunk starts 50 characters before the previous one ended. That shared stretch is called <strong>overlap</strong>. Add this to src/chunking.py:</p><pre>def fixed_size_chunks(text, size=500, overlap=50):<br>    &quot;&quot;&quot;Naive method: cut every `size` characters, overlapping a little.&quot;&quot;&quot;<br>    if overlap &gt;= size:<br>        raise ValueError(&quot;overlap must be smaller than size&quot;)<br>    chunks, start = [], 0<br>    while start &lt; len(text):<br>        chunks.append(text[start:start + size])<br>        start += size - overlap<br>    return chunks</pre><p>Now a small script to look at the damage. Create compare_chunking.py in the project folder:</p><pre>from pathlib import Path</pre><pre>from src.chunking import load_report, fixed_size_chunks<br>for path in sorted(Path(&quot;data/reports&quot;).glob(&quot;report_*.md&quot;)):<br>    text = load_report(path)<br>    chunks = fixed_size_chunks(text)<br>    print(f&quot;{path.name}: {len(text)} characters -&gt; {len(chunks)} chunks&quot;)<br>    for i, chunk in enumerate(chunks):<br>        last_line = chunk.splitlines()[-1]<br>        if last_line.startswith(&quot;|&quot;) and not last_line.rstrip().endswith(&quot;|&quot;):<br>            print(f&quot;  chunk {i} ends in the middle of a table row: {last_line!r}&quot;)</pre><p>Run python compare_chunking.py. You should see:</p><pre>report_2024.md: 1835 characters -&gt; 5 chunks<br>  chunk 0 ends in the middle of a table row: &#39;| Interest expense | 0.2 &#39;<br>  chunk 2 ends in the middle of a table row: &#39;| Item | 2024 (USD&#39;<br>report_2025.md: 1772 characters -&gt; 4 chunks<br>  chunk 0 ends in the middle of a table row: &#39;| Income tax (20%) | 0.5&#39;<br>  chunk 1 ends in the middle of a table row: &#39;| Ex&#39;<br>  chunk 2 ends in the middle of a table row: &#39;| Cash at start&#39;</pre><p>Five of the nine chunks cut a table row. Look at the 2025 one: | Income tax (20%) | 0.5 should read 0.50, so the knife sliced a number. The chunk after it starts in the middle of a row, with no heading and no table header to say what the numbers mean. If the search hands that chunk to the model, the model is reading half a table.</p><pre>git add .<br>git commit -m &quot;Add report loader and fixed-size chunker&quot;</pre><h3>Step 5: Cut along the headings</h3><p>The reports already have structure: every section starts with ## . Use it. Add this to src/chunking.py:</p><pre>def section_chunks(text, source):<br>    &quot;&quot;&quot;Structure-aware method: one chunk per section, labelled with its report.&quot;&quot;&quot;<br>    title = text.splitlines()[0].lstrip(&quot;# &quot;).strip()<br>    chunks = []<br>    for block in text.split(&quot;\n## &quot;)[1:]:<br>        heading, _, body = block.partition(&quot;\n&quot;)<br>        chunks.append({<br>            &quot;source&quot;: source,<br>            &quot;section&quot;: heading.strip(),<br>            &quot;text&quot;: f&quot;{title} - {heading.strip()}\n{body.strip()}&quot;,<br>        })<br>    return chunks</pre><p>In plain words: take the title from the first line, split the text at every ## , and make one chunk per section. Each chunk gets the report title in front, such as “Annual Report 2025 - Financial highlights”, so it carries its own label even when it travels alone.</p><p>Now replace compare_chunking.py with this version, which compares both methods:</p><pre>from pathlib import Path</pre><pre>from src.chunking import load_report, fixed_size_chunks, section_chunks<br><br>def count_cut_rows(chunk_texts):<br>    &quot;&quot;&quot;Count chunks whose last line is a table row cut in half.&quot;&quot;&quot;<br>    count = 0<br>    for chunk in chunk_texts:<br>        last_line = chunk.splitlines()[-1]<br>        if last_line.startswith(&quot;|&quot;) and not last_line.rstrip().endswith(&quot;|&quot;):<br>            count += 1<br>    return count<br><br>for path in sorted(Path(&quot;data/reports&quot;).glob(&quot;report_*.md&quot;)):<br>    text = load_report(path)<br>    fixed = fixed_size_chunks(text)<br>    by_section = section_chunks(text, path.name)<br>    print(f&quot;{path.name}&quot;)<br>    print(f&quot;  fixed-size: {len(fixed)} chunks, {count_cut_rows(fixed)} cut a table row&quot;)<br>    print(f&quot;  by section: {len(by_section)} chunks, &quot;<br>          f&quot;{count_cut_rows([c[&#39;text&#39;] for c in by_section])} cut a table row&quot;)<br>    hits = [c[&quot;section&quot;] for c in by_section if &quot;operating costs&quot; in c[&quot;text&quot;].lower()]<br>    print(f&quot;  keyword search for &#39;operating costs&#39;: {len(hits)} hit(s)&quot;)<br># show one finished chunk<br>text = load_report(&quot;data/reports/report_2025.md&quot;)<br>chunk = next(c for c in section_chunks(text, &quot;report_2025.md&quot;) if c[&quot;section&quot;] == &quot;Financial highlights&quot;)<br>print(&quot;\nOne section chunk:\n&quot;)<br>print(chunk[&quot;text&quot;])</pre><p>Run it. You should see:</p><pre>report_2024.md<br>  fixed-size: 5 chunks, 2 cut a table row<br>  by section: 6 chunks, 0 cut a table row<br>  keyword search for &#39;operating costs&#39;: 3 hit(s)<br>report_2025.md<br>  fixed-size: 4 chunks, 3 cut a table row<br>  by section: 6 chunks, 0 cut a table row<br>  keyword search for &#39;operating costs&#39;: 0 hit(s)</pre><pre>One section chunk:</pre><pre>Annual Report 2025 - Financial highlights<br>| Item | 2025 (USD million) |<br>| --- | --- |<br>| Revenue | 12.0 |<br>| Cost of sales | 4.5 |<br>| Operating expenses | 4.8 |<br>| Operating profit | 2.7 |<br>| Interest expense | 0.2 |<br>| Profit before tax | 2.5 |<br>| Income tax (20%) | 0.50 |<br>| Net income | 2.00 |</pre><p>Two things to see. First, the section chunks cut no rows, and every table keeps its title and header. Second, the keyword search for “operating costs” finds three hits in 2024 and none in 2025. That is the gap from Part 1, now in real data. Parts 3 and 4 close it.</p><pre>git add .<br>git commit -m &quot;Add section chunker and comparison&quot;</pre><h3>Step 6: Prove it with tests</h3><p>A <strong>test</strong> is a small program that checks your code and fails loudly when something breaks. Create tests/test_chunking.py:</p><pre>from pathlib import Path</pre><pre>import pytest<br>from src.chunking import load_report, section_chunks<br>REPORTS = sorted(Path(&quot;data/reports&quot;).glob(&quot;report_*.md&quot;))<br><br>def test_reports_exist():<br>    assert len(REPORTS) == 2, &quot;expected report_2024.md and report_2025.md in data/reports&quot;<br><br>@pytest.mark.parametrize(&quot;path&quot;, REPORTS, ids=lambda p: p.name)<br>def test_no_chunk_cuts_a_table_row(path):<br>    for chunk in section_chunks(load_report(path), path.name):<br>        for line in chunk[&quot;text&quot;].splitlines():<br>            if line.startswith(&quot;|&quot;):<br>                assert line.rstrip().endswith(&quot;|&quot;), f&quot;cut row: {line!r}&quot;<br><br>@pytest.mark.parametrize(&quot;path&quot;, REPORTS, ids=lambda p: p.name)<br>def test_every_chunk_names_its_report(path):<br>    year = path.stem.split(&quot;_&quot;)[1]<br>    for chunk in section_chunks(load_report(path), path.name):<br>        assert f&quot;Annual Report {year}&quot; in chunk[&quot;text&quot;]<br><br>@pytest.mark.parametrize(&quot;path&quot;, REPORTS, ids=lambda p: p.name)<br>def test_each_report_gives_six_chunks(path):<br>    assert len(section_chunks(load_report(path), path.name)) == 6</pre><p>Run them:</p><pre>python -m pytest</pre><p>You should see 7 passed. The tests guard three promises: no table row is ever cut, every chunk names its report and year, and each report gives six chunks. When we change the chunker in later parts, these tests tell us immediately if we broke a promise.</p><pre>git add .<br>git commit -m &quot;Add chunking tests&quot;</pre><h3>Step 7: Push the branch</h3><p>Create an empty repository called financial_ai_rag on GitHub, then connect your project to it and upload the branch:</p><pre>git remote add origin https://github.com/YOUR-USERNAME/financial_ai_rag.git<br>git push -u origin part-02-setup-and-chunking</pre><p>Your code for this post is now at github.com/YOUR-USERNAME/financial_ai_rag/tree/part-02-setup-and-chunking. Anyone can open it, check out the branch and follow along.</p><h3>Your turn</h3><p>In compare_chunking.py, change size=500 to 300, then 1000 (add size=300 to the fixed_size_chunks(text) call). Rerun and count the chunks that cut a table row. <em>Does any size avoid cutting? Why can’t a bigger size fix the problem by itself?</em></p><h3>Common problems</h3><ul><li><strong>ModuleNotFoundError: No module named &#39;src&#39;:</strong> run commands from the project’s main folder, the one that contains src, and make sure src/__init__.py exists. Run tests with python -m pytest, not just pytest.</li><li><strong>python is not recognized:</strong> try python3, or py on Windows.</li><li><strong>Bash won’t activate the environment:</strong> see the tip in step 1.</li></ul><h3>What you just learned</h3><ul><li><strong>A chunk has to make sense on its own,</strong> because the search hands it to the model without the rest of the document.</li><li><strong>A document’s own structure is a free guide for cutting it.</strong> Headings and tables tell you where the natural edges are.</li><li><strong>A small test turns “it looked fine” into “it is checked.”</strong> We will rerun these tests every time the chunker changes.</li></ul><h3>Glossary</h3><ul><li><strong>Branch:</strong> a separate line of work in Git, so each part of the series lives in its own place.</li><li><strong>Chunk:</strong> a short piece of a document that can be searched on its own.</li><li><strong>Overlap:</strong> the stretch of text two neighbouring chunks share, so an idea on a cut isn’t lost.</li><li><strong>Test:</strong> a small program that checks your code and fails when something breaks.</li><li><strong>Virtual environment:</strong> a private folder of Python packages for one project.</li></ul><p>Next, in Part 3, the chunks become numbers a computer can compare by meaning, and we store them in <strong>ChromaDB</strong>.</p><p><em>If you run a small business and are curious about how an AI assistant could improve your customer experience, I’d love to connect and explore the possibilities with you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcb4ef114dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Finance RAG Assistant, Part 1: Draw the System, Then Run One Question by Hand]]></title>
            <link>https://salifyataala.medium.com/building-a-finance-rag-assistant-part-1-draw-the-system-then-run-one-question-by-hand-74578caf9d1e?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/74578caf9d1e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 19:28:38 GMT</pubDate>
            <atom:updated>2026-10-26T19:28:38.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>What we are building</h3><p>By the end of this series you will have built a finance assistant. You type a question about a company’s annual report, and it answers from the report, shows where each figure came from, and says “I don’t know” instead of guessing.</p><p>This first post has no code. You will do one small exercise by hand, so that when we start building in Part 2 you already know what every piece of code is for. It takes about 30 minutes or less to do so.</p><p><strong>What you need:</strong> any AI chat assistant (ChatGPT, Claude or Gemini all work) and a plain text editor. From Part 2 onward the assistant reads two fictional annual reports, 2024 and 2025, with every figure in US dollars (USD). Today you only need a tiny excerpt, which is provided below.</p><h3>The problem</h3><p>Ask a language model “How did operating costs change between 2024 and 2025?” and it will answer confidently, even though it has never seen the company’s reports. In finance, an invented number is worse than no answer. <strong>RAG</strong> (retrieval-augmented generation) fixes this: find the right pages first, then hand them to the model with the instruction to answer from those pages only.</p><h3>The system on one page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSdbFeDooxUQFHprPhOfTw.png" /><figcaption>rag_data_flow</figcaption></figure><p>The top row happens once: the reports are cut into pieces, turned into numbers a computer can compare, and stored. The bottom row happens for every question, and nothing reaches the customer without passing the two highlighted checks.</p><h3>Try it: five steps, no code</h3><p>You will work with a made-up mini report. Copy it into a text editor and save it as mini_report.txt.</p><pre>ANNUAL REPORT 2024 (excerpt)<br>Revenue for 2024 was USD 10.5 million.<br>Operating costs for 2024 were USD 4.2 million, mainly staff salaries and office rent.</pre><pre>ANNUAL REPORT 2025 (excerpt)<br>Revenue for 2025 was USD 12.0 million.<br>Operating expenses rose to USD 4.8 million in 2025, mainly because of hiring in the sales team.</pre><p>The question we want answered: <strong>“How did operating costs change between 2024 and 2025?”</strong></p><h3>Step 1. Search it the way a keyword search would</h3><p>Press Ctrl+F (Cmd+F on a Mac) and search for “operating costs”. You get one hit: the 2024 line. The 2025 line says “operating expenses”, so the search misses it even though it answers the same question. Remember this. It is why the finished system searches by meaning as well as by keywords.</p><h3>Step 2. Ask the model using only what the search found</h3><p>Open your chat assistant and send this prompt. Where it says to paste the passages, paste only the 2024 line you found in step 1.</p><pre>Answer the question using only the passages below.<br>If the passages do not contain the answer, say you don’t know.<br>Quote figures exactly and say which passage each one came from.</pre><pre>Passages:<br>[paste the passages here]</pre><pre>Question: How did operating costs change between 2024 and 2025?</pre><p>A well-behaved model says it cannot tell how costs changed, because it only has 2024. That is the right answer. The model did not fail; the search handed it an incomplete page.</p><h3>Step 3. Give it both passages</h3><p>Send the same prompt again, but this time paste both the 2024 and the 2025 operating lines. Now the model can answer: costs rose from USD 4.2 million to USD 4.8 million.</p><h3>Step 4. Check every number</h3><p>Every figure in the answer must appear in the passages you pasted. If the model also says costs rose by about 14%, that figure is not in the passages, so check the arithmetic yourself: (4.8 − 4.2) ÷ 4.2 is about 0.143, or 14.3%. A number you cannot trace back to the passages or to arithmetic on them is one the model made up.</p><h3>Step 5. Try to break it</h3><p>Paste all the lines from the mini report into the prompt and ask: “What will revenue be in 2027?” The report says nothing about 2027, so the right answer is “I don’t know.” If your model gives a number, it ignored the instruction. Note which assistant you used and what it did.</p><h3>What you just learned</h3><ul><li><strong>A search can miss a relevant passage.</strong> The model can only be as good as the passages it receives, so retrieval quality matters most.</li><li><strong>A clear instruction changes behaviour.</strong> “Use only these passages, otherwise say you don’t know” is what made the model refuse to guess.</li><li><strong>Checking numbers against the source can be automated.</strong> That is what the output checks in the drawing will do.</li></ul><h3>How the session maps to the build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JaPKYesU-EKVOFmGLu_CQ.png" /><figcaption>session_to_build_table</figcaption></figure><h3>Glossary</h3><ul><li><strong>ChromaDB:</strong> a database that stores the number lists for each passage and finds the ones closest in meaning to a question.</li><li><strong>Chunker:</strong> the code that cuts a document into short passages.</li><li><strong>Embedder:</strong> the model that turns a piece of text into a list of numbers (an embedding) that captures its meaning, so a computer can compare texts by meaning.</li><li><strong>Grounded:</strong> an answer is grounded when everything in it is supported by the passages the model was given.</li><li><strong>Hybrid search:</strong> keyword search and search by meaning, combined, so each covers the other’s blind spot.</li><li><strong>Input and output checks:</strong> automatic checks (also called guardrails) that run before a question enters the system and before an answer reaches the customer.</li><li><strong>Keyword search:</strong> finds the exact words you type, like Ctrl+F.</li><li><strong>LLM (large language model):</strong> the AI that writes the answer, like the chat assistant you used in the exercise.</li><li><strong>Prompt:</strong> the text you send to the model: your instructions, the passages and the question.</li><li><strong>RAG (retrieval-augmented generation):</strong> finding the relevant passages first, then asking the model to answer from them only.</li></ul><p><em>If you run a small business and are curious about how an AI assistant could improve your customer experience, I’d love to connect and explore the possibilities with you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74578caf9d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling a Multilingual Agent From One Language to Five]]></title>
            <link>https://salifyataala.medium.com/scaling-a-multilingual-agent-from-one-language-to-five-dc50bd128d68?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc50bd128d68</guid>
            <category><![CDATA[language-classification]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[multilingual-ai-agent]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 11:48:57 GMT</pubDate>
            <atom:updated>2026-09-01T11:48:57.434Z</atom:updated>
            <content:encoded><![CDATA[<p>A working system in one local language and a working system in five are not the same amount of effort, even when the underlying architecture classify, then fill a verified template is identical. This round took that architecture from a single local language, tested extensively, to five, and surfaced two lessons worth recording: one about what “translation” actually means for structured data, and one about what happens when verification effort isn’t evenly distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmQ_Co7uWOWPLjaOSzp3Og.png" /><figcaption>Language Architecture Progress Flowchart</figcaption></figure><h3>The bug that wasn’t really about language</h3><p>Extending the hours-response template to multiple languages exposed a category of bug that had nothing to do with translation quality. A business’s operating days were stored as plain text “<em>Monday to Friday</em>” and inserted directly into whichever language template matched the customer’s message. The result: grammatically correct local-language sentences with an untranslated English day-range sitting in the middle of them, jarring in a way that a single-language system would never have revealed, because there was never a second language for the mismatch to become visible against.</p><p>The actual fix wasn’t more translation. It was recognizing that “<em>Monday to Friday</em>” was never really free text to begin with. It’s one of a small number of common patterns (<em>weekdays, every day, weekends only</em>) that any small business is likely to fall into. Storing a <strong>code</strong> representing the pattern, and letting each language have its own pre-written, verified phrase for that code, turned an open-ended translation problem into a small, closed, checkable one. This is the same principle that’s shaped nearly every piece of this project: a small, verified set of known cases is more trustworthy than an attempt to handle arbitrary input correctly on the fly.</p><h3>Verification doesn’t scale evenly, and that’s fine if you notice</h3><p>Testing across all five local languages surfaced something worth naming honestly: two were detected reliably from the first test, matching classification and correct template selection immediately. Two others failed classification outright, misread as English despite genuinely being in-language messages, with correct intent detection wasted because the language check gated it out first.</p><p>This wasn’t a flaw in the architecture it was a direct, visible consequence of how much real testing each language had actually been through. The languages that worked well were the ones with the most cumulative rounds of real native-speaker correction behind them, going back to the very first version of this system. The two that failed were newly added, tested for the first time, with reference material the classifier had never actually been checked against.</p><p>The lesson isn’t “add more languages carefully.” It’s more specific than that: <strong>a system’s reliability in each language is a direct function of how much it’s actually been tested in that language, not of how similar the architecture is across all of them.</strong> Adding a new language to an already-working system doesn’t inherit the other languages’ reliability it starts from zero, the same as the first one did.</p><h3>Why this gets pinned, not immediately fixed</h3><p>Two language-detection gaps are now documented, reproducible, and deliberately deferred rather than fixed in the moment. That’s a real, considered choice, not neglect: fixing a detection gap requires the same anchoring-words technique used successfully for the first language concrete, real phrases the classifier can match against and that requires either the same iterative back-and-forth testing that made the first language reliable, or a native speaker’s time to supply better reference material. Patching it with a guess would just repeat the exact mistake: producing something that looks fixed without being verified.</p><h3>What actually changed this round</h3><p>Not the architecture, the same classify-then-fill pattern from the very first version still holds, still works, still correctly declines to guess when nothing matches. What changed is the scale at which its actual weak point becomes visible: <strong>a pattern that’s genuinely solid in one well-tested language will show real, specific gaps the moment it’s asked to do the same job in a language it’s never actually been checked against.</strong> That’s not a reason to distrust the architecture. It’s the reason testing has to scale alongside the ambition, one language at a time, the same way it did the first time.</p><p><em>I’m currently open for contract and consulting work in AI automation, AI consultancy. If you’re a small business curious about what an AI assistant like this could look like for your own customers, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc50bd128d68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From One Business to Many: Building a System That Can Serve More Than One Customer]]></title>
            <link>https://salifyataala.medium.com/from-one-business-to-many-building-a-system-that-can-serve-more-than-one-customer-72a844489f94?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a844489f94</guid>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[muilttenancy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 19:00:42 GMT</pubDate>
            <atom:updated>2026-08-22T19:00:42.882Z</atom:updated>
            <content:encoded><![CDATA[<p>A prototype built for one business and a system built to support many are different things, even when the underlying logic is identical. This round of work took a WhatsApp assistant built and tested for one business and rebuilt its foundation to support many then added a genuinely new capability on top: <strong><em>an agent that can take a real action, not just answer a question, while keeping a human firmly in control of anything that actually commits the business</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj8jvxn1IMSZinVBrd-NMQ.png" /><figcaption>WhatsApp booking agent flow</figcaption></figure><h3>Proving multi-tenancy, not assuming it</h3><p>The original version had a business’s menu, hours, and delivery zones hardcoded into a single file. Before adding anything new, that had to change: <em>a real database table, one row per business, looked up dynamically by which WhatsApp number a message arrived on.</em> The code for this is simple. The discipline that mattered was refusing to call it done just because it worked for the one business already being tested.</p><p>The actual test: add a second, completely different business, different products, different hours, nothing in common with the first and confirm, directly, that each number returns only its own data with zero bleed-through. That’s the difference between “<em>works</em>” and “<em>provably</em> <em>works</em>,” and it’s worth insisting on before building anything else on top, because every feature added afterward inherits whatever’s broken underneath it.</p><p>One thing this pass also caught: a leftover assumption in the prompt itself, describing the business by a specific type that only applied to the original single-business version. Multi-tenancy isn’t just a database change, it’s checking every place an old, narrower assumption might still be quietly baked into the system’s language, not just its data.</p><h3>Giving the agent something real to do</h3><p>Answering questions grounded in real data was the whole scope of the earlier version. This round added something categorically different: the ability to take an action , reserving a pre-order or booking, using the same tool-calling pattern built and tested earlier in this series. The agent recognizes a booking request, calls a tool, and a real row lands in a database.</p><p>The one rule that mattered most here, stated explicitly and repeated in testing until it held: <strong>the agent reserves, it never confirms.</strong> A booking touches real capacity, real stock, real money commitments an AI agent has no business making unilaterally on a business’s behalf. Every customer facing message was checked specifically for language that might imply otherwise, and the tool itself was designed so a “successful” call only ever produces a pending record, never an approved one.</p><h3>Where the human actually sits in the loop</h3><p>A pending booking that sits invisibly in a database isn’t useful. Closing this properly needed two more pieces: the business owner gets notified the moment a request comes in, and a simple, private dashboard lets them review and confirm with one click at which point, and only then, the customer receives a real confirmation.</p><p>The dashboard itself needed the same tenant-isolation discipline as the very first step. It’s accessed by a private, unguessable token tied to one specific business, and every action it allows is checked against that same business ownership before anything executes, not just at the page level, but on the confirmation action itself. A business should never be able to act on another business’s booking, even by accident, even if they somehow guessed an ID.</p><h3>A production lesson that had nothing to do with AI</h3><p>Testing the confirmation flow surfaced a genuinely important, ordinary engineering issue: the outbound customer-notification call depends on a third-party service, and that service being unavailable caused the whole confirmation action to fail even though the actual, correct thing (<em>marking the booking confirmed in the database</em>) had already succeeded before the failing call ever happened.</p><p>The fix was to decouple the two:<em> let the core action succeed on its own, and treat the outbound notification as something that can fail independently without undoing or blocking anything that already correctly happened</em>. This is a basic, well-known principle in reliable system design, and it’s worth naming plainly here anyway, because it’s exactly the kind of thing that’s easy to skip when a feature is being built quickly and the third-party service happens to be working during development. It only becomes visible the moment that service isn’t available which is precisely the moment you don’t want your core logic to break.</p><h3>What’s actually different now</h3><p>A single-business prototype and a multi-tenant system with a real, human-supervised action loop are not the same amount of work, even when most of the underlying pieces grounding, tool-calling, guardrails already existed . What changed wasn’t the intelligence of the system. It was making sure every part of it correctly scoped to the business it belonged to, correctly stopped short of commitments it shouldn’t make alone, and correctly kept working even when a piece of it outside anyone’s direct control temporarily didn’t.</p><p><em>I’m currently open for contract and consulting work in AI automation, AI consultancy. If you’re a small business curious about what an AI assistant like this could look like for your own customers, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a844489f94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing an Agent Against a Dataset Built to Trick It]]></title>
            <link>https://salifyataala.medium.com/testing-an-agent-against-a-dataset-built-to-trick-it-7f1e819b6e37?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1e819b6e37</guid>
            <category><![CDATA[ai-agent-loops]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[aiguardrails]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 19:45:21 GMT</pubDate>
            <atom:updated>2026-08-19T19:45:21.087Z</atom:updated>
            <content:encoded><![CDATA[<p>A small, hand-picked test tells you an agent can handle the cases you thought to check. It doesn’t tell you much about the cases you didn’t. This round used something different: a 20-entry synthetic log, built deliberately, with a documented list of exactly what should and shouldn’t get flagged, so the agent’s output could be scored against a known answer key instead of just read and reacted to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpgT9ZNaZJ0mL8_NLisgrw.png" /><figcaption>Near-duplicate decision rule</figcaption></figure><h3>What was actually planted</h3><p>Genuine duplicates, identical vendor, date, amount, items, appearing twice. Near-duplicates that look suspicious on the surface but shouldn’t be flagged, the same vendor and a similar amount, days apart, for an expense type that naturally recurs. A real outlier. Missing fields. Four different date formats. A couple of unresolved data-quality flags. And, deliberately repeated from an earlier finding in this series: an item listed as a quantity next to a total amount, worded in a way that invites the wrong assumption, that the quantity and amount should be multiplied together to get the real total, when in this system the amount shown is already the full line total, not a per-unit price. That’s the exact shape of a false positive documented in the <a href="https://salifyataala.medium.com/adding-a-real-agent-loop-three-rounds-of-finding-out-why-it-wasnt-enough-a314f0a3837c?postPublishedType=initial">previous post</a>.</p><h3>Round one: real judgment, one real gap</h3><p>The first pass against this dataset caught almost everything correctly, both genuine duplicate pairs, the real outlier, every missing field, every date-format inconsistency both unresolved low-confidence flags. It also correctly did not repeat the earlier item-description false positive; that guardrail held cleanly.</p><p>One thing it got wrong: two fuel purchases, a day apart, same vendor, same amount, got flagged as a likely duplicate. This is exactly the trap it was designed to expose. Fuel, groceries, daily meals, anything genuinely recurring will naturally produce similar-looking entries close together in time, as a completely ordinary consequence of normal spending, not an error. The agent had no explicit basis for telling that apart from an actual duplicate, so it defaulted to flagging it, which sounds cautious but is actually a real false positive a human reviewer would find frustrating to keep dismissing.</p><h3>The fix, and a bug found while making it</h3><p>Closing this gap needed a concrete rule, not a vague caution. The instruction added was specific: don’t treat “similar vendor and amount, close dates” as inherently suspicious for expense types that naturally recur, reserve the duplicate flag for an identical date and exact amount, or some other detail (an identical, unusually specific item description) that actually suggests the same transaction recorded twice.</p><p>While making this change, a second, unrelated issue turned up. An earlier guardrail, an explicit instruction never to claim a tool was used unless it genuinely was, had been added to the wrong function during an earlier edit. It was sitting in the plain, non-tool-using review path, where it did nothing, while the tool-calling path it was actually meant to protect had no such instruction at all. This is worth naming plainly: a correctly-written guardrail provides zero protection if it’s attached to code that was never exposed to the risk it addresses<strong><em>.</em></strong> Worth checking not just “<em>did I write this rule,</em>” but “<em>is this rule actually reachable by the thing it’s supposed to guard</em>.”</p><h3>Round two: the gap closed, and something unplanned showed up</h3><p>Retesting against the same dataset, the fuel pair was no longer flagged at all correctly recognized as ordinary. The genuine duplicate pairs were still caught, with more precise reasoning this time: the equipment duplicate was labeled a “potential” duplicate specifically because of the identical item description, not just a similar amount, the exact distinction the new instruction was meant to teach.</p><p>One additional result wasn’t planned or asked for. One entry in the dataset had its total_matches_items field deliberately marked false to see whether the agent would repeat that flag uncritically. Instead, it recalculated the actual item sum, found that it matched the stated total, and flagged the recorded field itself as apparently incorrect, not the transaction, the data quality of the flag meant to catch data quality issues. That&#39;s a level of scrutiny beyond what was asked for: the agent treated its own input data as something to verify, not just something to summarize.</p><h3>What a planted test actually buys you</h3><p>Testing with real or arbitrary data tells you whether an agent produces plausible-sounding output. Testing with data built around a known answer key tells you something more specific: exactly which categories of judgment hold up and which don’t, at a scale too large to fully anticipate every result. The near-duplicate trap wasn’t found by accident, it was placed there because the earlier, smaller tests in this series hadn’t tested for it yet, and a bigger dataset was the way to surface a failure mode that a small, tidy example never would have revealed.</p><p>You can find the code <a href="https://github.com/SalifyaTaala/spending-review-agent/tree/Guardrails">here</a></p><p><em>I’m currently open for contract and consulting work in AI automation, AI consultancy. If you’re a small business curious about what an AI assistant like this could look like for your own customers, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1e819b6e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a Real Agent Loop: Three Rounds of Finding Out Why It Wasn’t Enough]]></title>
            <link>https://salifyataala.medium.com/adding-a-real-agent-loop-three-rounds-of-finding-out-why-it-wasnt-enough-a314f0a3837c?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/a314f0a3837c</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-agent-loops]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 19:39:56 GMT</pubDate>
            <atom:updated>2026-08-19T19:39:56.730Z</atom:updated>
            <content:encoded><![CDATA[<p>A model that only ever answers the question in front of it has a real limit: it can’t decide, mid-thought, that it actually needs more information before it can answer well. This round adds something structurally different, <em>an agent that can </em><strong><em>decide</em></strong><em>,</em><strong><em> mid-reasoning</em></strong><em>, </em><strong><em>that it needs more information</em></strong><em>, </em><strong><em>call a real function to get it</em></strong><em>, and </em><strong><em>factor the result into its final answer</em></strong><em> before responding.</em> That’s the actual definition of an agent loop, and getting it to genuinely earn its complexity took three honest rounds of finding out exactly where a good idea wasn’t yet good enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2UCeoM9Yip0kRIvHVKMEQ.png" /><figcaption>Three rounds of tuning</figcaption></figure><h3>Round one: it worked, and it was worse</h3><p>The mechanics came together cleanly on the first attempt, a tool definition, a loop that checks for tool calls and feeds results back to the model, a hard cap so it can’t run forever. Run against a real <em>expense log</em> next to the original single-prompt version for comparison, the tool-calling version came back thinner: <strong><em>one vague flag, generic reasoning, none of the specificity the original prompt reliably produced</em></strong>.</p><p>The instinct here could have been to distrust tool-calling itself. It wasn’t the right instinct. Adding a debug line to confirm what was actually happening showed the tool genuinely was being called, with sensible arguments, the mechanism worked. The problem was much simpler: the prompt driving the tool-calling version was far less detailed than the original, because it had been written to demonstrate the tool mechanics not to carry the same careful instructions the original had accumulated over its own testing. Comparing a thin prompt against a well-tuned one was never a fair test of tool-calling versus not . It was a test of prompt quality wearing a tool-calling costume.</p><h3>Round two: the tool call became the whole answer</h3><p>Bringing the original prompt’s full instruction set into the tool-calling version fixed the vagueness immediately, specific vendor, amount, and date now appeared correctly in the output. But a new, more precise problem replaced it:<strong> <em>the agent used the tool to confirm one specific suspicion, then stopped.</em></strong> One flag, the one it had just verified, with nothing else from the rest of the log , even though the earlier version working from the same data, reliably found two or three distinct things worth flagging.</p><p>This is a genuinely different failure than the first round, worth naming as its own thing: <strong>a tool call can satisfy the model’s sense that the task is complete, even when the task was always broader than the thing the tool verified.</strong> Confirming one suspicion started to function, unintentionally, like a finish line.</p><h3>Round three: told to keep going, but only partway</h3><p>An explicit instruction addressing this directly, after using a tool, continue reviewing the rest of the log, don’t let tool use shorten the final analysis improved things again, but only partially. The summary now correctly described everything in the log, including entries that had nothing to do with the tool call. The flag list, though, still only contained the single tool-verified issue. The model had clearly noticed the other issues; it just wasn’t formally flagging them the same way it had before tool-calling was introduced at all.</p><p>That gap between what the model <em>described</em> and what it <em>flagged</em> is worth sitting with. It suggests the tool-use instruction and the completeness instruction weren’t fully cooperating . The model may have been treating “verify the tool suspicion” as the primary task and “stay thorough” as secondary, even when both were stated with equal weight in the same prompt.</p><h3>What actually closed it</h3><p>One more instruction, stated as bluntly as possible: <strong><em>after any tool use, produce a complete flag list covering everything worth attention in the entire log, not only what the tool verified, and if the summary mentions something, it needs its own flag too if it’s genuinely worth attention</em>. </strong>That closed the gap. The next run called the tool twice, independently, for two separate suspicions, and returned three specific flags. Matching the original version’s breadth, and catching one thing the original had missed entirely: an unresolved data-quality flag on an entry the tool call happened to surface along the way.</p><p>That last detail is the actual point of this whole exercise. The final version didn’t just match a well-tuned single prompt. It found something the single prompt’s one static pass over the data didn’t catch because it investigated two separate suspicions independently rather than reasoning over everything in one undifferentiated read. That’s the real argument for an agent loop over a good prompt alone, not that it’s smarter in general, but that iterative, targeted investigation can surface things a single pass genuinely misses.</p><h3>The pattern underneath three different-looking bugs</h3><p>Every round of this looked like a different problem on the surface. Vague output, narrow output, incomplete output, but all three trace back to the same root: tool-calling adds a new competing objective to the prompt, and until that objective is explicitly reconciled with the original one, the model resolves the tension on its own, unpredictably, round by round. This is the same underlying lesson from every earlier post in this series, showing up again in a new shape: an unstated boundary here, “<em>how does tool use relate to the rest of the task</em>” gets filled by the model’s own guess, and that guess needs to be tested and corrected explicitly, not assumed to work itself out.</p><h3>Addendum: A False Positive From Correct Math, Wrong Meaning</h3><p>Guardrail testing after this round surfaced one more finding worth recording on its own, because it’s a different failure shape than anything above. The agent flagged what looked like a real arithmetic inconsistency a line item showing a quantity of 2 at a stated amount that, multiplied out, didn’t match the recorded total. The math itself was correct. The flag was still wrong.</p><p>The actual data followed a convention established earlier in this project : for this system, an item’s recorded amount already represents the full line total, not a per-unit price meant to be multiplied by quantity. That convention lives in the code and in earlier documentation, not in the flattened text summary the agent was actually reasoning over, which showed only a quantity and a number, with no indication of what that number meant. Seeing “quantity 2” next to a dollar figure, the agent made the most natural-seeming assumption available to it, multiplied, and flagged a discrepancy that didn’t actually exist.</p><p>This is worth separating clearly from every fabrication bug earlier. The agent didn’t invent a number, misread a field, or guess at something absent from the data. It performed a correct calculation on real data and arrived at a wrong conclusion, because the number’s real meaning that it was already a total, not a per-unit price to multiply lived in the system’s own code, not in the plain text summary the agent was actually reading. A confident, well-reasoned false positive can come from stripped-out context just as easily as it can come from a missing fact. The fix isn’t a fact-grounding instruction; it’s making sure the format handed to an agent still carries the meaning a human reading the same numbers would rely on.</p><p>You can find the code <a href="https://github.com/SalifyaTaala/spending-review-agent/tree/Tool-calling-agent-loop"><strong>here</strong></a></p><p><em>I’m currently open for contract and consulting work in AI automation, AI consultancy. If you’re a small business curious about what an AI assistant like this could look like for your own customers, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a314f0a3837c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a Real Agent Loop: Three Rounds of Finding Out Why It Wasn’t Enough]]></title>
            <link>https://salifyataala.medium.com/adding-a-real-agent-loop-three-rounds-of-finding-out-why-it-wasnt-enough-cd242bfffc3f?source=rss-10e547a2ce57------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd242bfffc3f</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-loop]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Salifyanji Taala]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 08:55:07 GMT</pubDate>
            <atom:updated>2026-08-15T08:55:07.369Z</atom:updated>
            <content:encoded><![CDATA[<p>A model that only ever answers the question in front of it has a real limit: i<em>t can’t decide, mid-thought, that it actually needs more information before it can answer well</em>. This round adds something structurally different, an agent that <strong><em>can decide,</em></strong> <strong><em>mid-reasoning</em></strong>, <strong><em>that it needs more information, call a real function to get it, and factor the result into its final answer before responding.</em></strong> That’s the actual definition of an agent loop, and getting it to genuinely earn its complexity took three honest rounds of finding out exactly where a good idea wasn’t yet good enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPNBXvKlfZ698IP4vEeKIw.png" /><figcaption>Agent tool calling loop</figcaption></figure><h3>Round one: it worked, and it was worse</h3><p>The mechanics came together cleanly on the first attempt, a tool definition, a loop that checks for tool calls and feeds results back to the model, a hard cap so it can’t run forever. Run against a real expense log next to the original single-prompt version for comparison, the tool-calling version came back thinner: <em>one vague flag, generic reasoning, none of the specificity the original prompt reliably produced</em>.</p><p>The instinct here could have been to distrust tool-calling itself. It wasn’t the right instinct. Adding a debug line to confirm what was actually happening showed the tool genuinely was being called, with sensible arguments, the mechanism worked. The problem was much simpler: <strong><em>the prompt driving the tool-calling version was far less detailed than the original, because it had been written to demonstrate the tool mechanics, not to carry the same careful instructions the original had accumulated over its own testing</em></strong>. Comparing a thin prompt against a well-tuned one was never a fair test of tool-calling versus not. It was a test of prompt quality wearing a tool-calling costume.</p><h3>Round two: the tool call became the whole answer</h3><p>Bringing the original prompt’s full instruction set into the tool-calling version fixed the vagueness immediately, specific vendor, amount, and date now appeared correctly in the output. But a new, more precise problem replaced it: <strong><em>the agent used the tool to confirm one specific suspicion, then stopped</em></strong>. One flag, the one it had just verified, with nothing else from the rest of the log, even though the earlier version, working from the same data, reliably found two or three distinct things worth flagging.</p><p>This is a genuinely different failure than the first round, worth naming as its own thing: <strong>a tool call can satisfy the model’s sense that the task is complete, even when the task was always broader than the thing the tool verified.</strong> Confirming one suspicion started to function, unintentionally, like a finish line.</p><h3>Round three: told to keep going, but only partway</h3><p>An explicit instruction addressing this directly, after using a tool, continue reviewing the rest of the log, don’t let tool use shorten the final analysis, improved things again, but only partially. The summary now correctly described everything in the log, including entries that had nothing to do with the tool call. The flag list, though, still only contained the single tool-verified issue. The model had clearly noticed the other issues; it just wasn’t formally flagging them the same way it had before tool-calling was introduced at all.</p><p>That gap between what the model <em>described</em> and what it <em>flagged</em> is worth sitting with. It suggests the tool-use instruction and the completeness instruction weren’t fully cooperating. The model may have been treating “<em>verify the tool suspicion</em>” as the primary task and “<em>stay thorough</em>” as secondary, even when both were stated with equal weight in the same prompt.</p><h3>What actually closed it</h3><p>One more instruction, stated as bluntly as possible: after any tool use, produce a complete flag list covering everything worth attention in the entire log, not only what the tool verified and if the summary mentions something, it needs its own flag too if it’s genuinely worth attention. That closed the gap. The next run called the tool twice, independently, for two separate suspicions, and returned three specific flags matching the original version’s breadth, and catching one thing the original had missed entirely: <strong><em>an unresolved data-quality flag on an entry the tool call happened to surface along the way</em></strong>.</p><p>That last detail is the actual point of this whole exercise. The final version didn’t just match a well-tuned single prompt. It found something the single prompt’s one static pass over the data didn’t catch, because it investigated two separate suspicions independently rather than reasoning over everything in one undifferentiated read. That’s the real argument for an agent loop over a good prompt alone, not that it’s smarter in general, but that iterative, targeted investigation can surface things a single pass genuinely misses.</p><h3>The pattern underneath three different-looking bugs</h3><p>Every round of this, looked like a different problem on the surface, vague output, narrow output, incomplete output. But all three trace back to the same root: <strong><em>tool-calling adds a new competing objective to the prompt, and until that objective is explicitly reconciled with the original one, the model resolves the tension on its own, unpredictably, round by round</em></strong>. This is the same underlying lesson from every earlier post in this series, showing up again in a new shape: an unstated boundary here, “how does tool use relate to the rest of the task?” Gets filled by the model’s own guess, and that guess needs to be tested and corrected explicitly, not assumed to work itself out.</p><p>Check out the code <a href="https://github.com/SalifyaTaala/spending-review-agent/tree/Tool-calling-agent-loop">here</a></p><p><em>I’m currently open for contract and consulting work in AI automation, AI consultancy. If you’re a small business curious about what an AI assistant like this could look like for your own customers, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd242bfffc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>