<?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 Manoj Kumar Thirumalareddy on Medium]]></title>
        <description><![CDATA[Stories by Manoj Kumar Thirumalareddy on Medium]]></description>
        <link>https://medium.com/@manulovesu22?source=rss-b0741b1dd457------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0GMXmUtnV0WlzwBPS5x9hg.png</url>
            <title>Stories by Manoj Kumar Thirumalareddy on Medium</title>
            <link>https://medium.com/@manulovesu22?source=rss-b0741b1dd457------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:49:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manulovesu22/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[What Should an AI Assistant Be Allowed to See? (AI-Ready Data Series, Part 8)]]></title>
            <link>https://medium.com/@manulovesu22/what-should-an-ai-assistant-be-allowed-to-see-ai-ready-data-series-part-8-22894b60f7fc?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/22894b60f7fc</guid>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:29:58 GMT</pubDate>
            <atom:updated>2026-12-02T18:29:58.848Z</atom:updated>
            <content:encoded><![CDATA[<h4>Roles, row access, masking, and testing the assistant’s view of the data like any other user’s.</h4><figure><img alt="Flat illustration for what an AI assistant should be allowed to see" src="https://cdn-images-1.medium.com/max/1024/1*enVG49h4s31_TJZdUgzuTA.png" /></figure><figure><img alt="Part 8, Gold governance. The security review: “The Pune assistant just named a Mumbai rider in its answer. Who gave it access to Mumbai, and who is allowed to see riders’ names?”" src="https://cdn-images-1.medium.com/max/1024/1*9rpsvLvp92pJj0HqybsLIQ.png" /></figure><p>The assistant was built by the data team, so during development it ran under the data team’s role. That role sees every city and every rider’s name. Nobody changed it before launch. A Pune customer asked a general question about delays, retrieval pulled a Mumbai row, and the answer included the name of a rider no Pune customer should ever see.</p><p>In <a href="https://medium.com/p/70d0fc8759df">my last article</a> we made sure the assistant reads the right rules. This part makes sure it can read only what it should.</p><figure><img alt="Animation: one query run under four roles. unknown_role gets no rows. ops_admin sees four Pune and Mumbai rows with rider names. pune_ops sees only the two Pune rows. pune_assistant sees the same Pune rows with rider names masked." src="https://cdn-images-1.medium.com/max/1024/1*zFCZSzbHwAu9LeQFS4kezA.gif" /></figure><figure><img alt="In this article: The assistant is a user; Policies in the platform, not in the prompt; Test what each role can see; Three more things to decide; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*iINEl0PXhzkefHnnMxm-yg.png" /></figure><h3>The assistant is a user</h3><p>An assistant reads data, so it needs an identity, a role and permissions, exactly like a person. The difference is scale and audience. A person with too much access rarely shares it with strangers. An assistant shares what it reads with whoever is asking, thousands of times a day.</p><p>So the rule is simple: the assistant gets its own role, with the least access that does the job. For the Pune customer assistant, that means Pune orders only, and no rider names.</p><figure><img alt="Table of roles. ops_admin: Pune and Mumbai, rider names visible, operations leadership. pune_ops: Pune, visible, hub managers. pune_assistant: Pune, names masked, the customer-facing assistant. Any other role: no cities, no names." src="https://cdn-images-1.medium.com/max/1024/1*LzYUa5OXfvbRM5TB-T2dGw.png" /></figure><h3>Policies in the platform, not in the prompt</h3><p>It is tempting to write “only discuss Pune and never share names” in the system prompt. That is a request, not a control. As I showed in the <a href="https://medium.com/p/ef80c91f1510">agents article</a> of my AI Engineering series, instructions hidden in data can push a model off its prompt. [4] The control belongs where the model can’t argue with it: in the warehouse.</p><p>Snowflake gives you two policies for this, both on Enterprise Edition or higher. A row access policy decides which rows a role can see, and a masking policy decides what a column shows to each role. [1] [2]</p><pre>CREATE OR REPLACE ROW ACCESS POLICY gov.city_access<br>AS (city_value VARCHAR) RETURNS BOOLEAN -&gt;<br>  EXISTS (<br>    SELECT 1 FROM gov.role_cities r<br>    WHERE r.role_name = CURRENT_ROLE()   -- role names stored in upper case<br>      AND r.city = city_value<br>  );<br><br>ALTER TABLE gold.fct_orders ADD ROW ACCESS POLICY gov.city_access ON (city);<br><br>CREATE OR REPLACE MASKING POLICY gov.mask_person_name<br>AS (val STRING) RETURNS STRING -&gt;<br>  CASE WHEN CURRENT_ROLE() IN (&#39;OPS_ADMIN&#39;, &#39;PUNE_OPS&#39;) THEN val<br>       ELSE &#39;*****&#39; END;<br><br>ALTER TABLE gold.fct_orders MODIFY COLUMN rider_name<br>  SET MASKING POLICY gov.mask_person_name;</pre><p>Because the policies sit on the table, they apply to every route in: Power BI, an analyst’s worksheet and the assistant’s SQL. Snowflake’s documentation even includes a row access example that hides rows while an AI agent is active in the session, which shows the policy layer can tell the difference. [1]</p><figure><img alt="Key idea: If a rule matters, enforce it where the data lives. A prompt can ask the model to behave; a policy decides what it can read." src="https://cdn-images-1.medium.com/max/1024/1*t77cwrri0mKd4pkhOxhTSA.png" /></figure><h3>Test what each role can see</h3><p>Policies are code, and code needs tests. The example below simulates the two policies in SQLite and runs one query as four roles.</p><pre>import sqlite3<br><br>db = sqlite3.connect(&quot;:memory:&quot;)<br>db.executescript(&quot;&quot;&quot;<br>CREATE TABLE orders (order_id, city, rider_name, status, late);<br>INSERT INTO orders VALUES<br>  (&#39;O1&#39;,&#39;Pune&#39;,  &#39;Asha Rao&#39;,    &#39;delivered&#39;,1),<br>  (&#39;O2&#39;,&#39;Pune&#39;,  &#39;Ben Okafor&#39;,  &#39;delivered&#39;,1),<br>  (&#39;O3&#39;,&#39;Pune&#39;,  &#39;Chen Li&#39;,     &#39;delivered&#39;,1),<br>  (&#39;O5&#39;,&#39;Pune&#39;,  &#39;Dev Patil&#39;,   &#39;delivered&#39;,1),<br>  (&#39;O9&#39;,&#39;Pune&#39;,  &#39;Ira Menon&#39;,   &#39;delivered&#39;,1),<br>  (&#39;O7&#39;,&#39;Pune&#39;,  &#39;Dana Silva&#39;,  &#39;delivered&#39;,0),<br>  (&#39;M1&#39;,&#39;Mumbai&#39;,&#39;Eli Haddad&#39;,  &#39;delivered&#39;,1),<br>  (&#39;M2&#39;,&#39;Mumbai&#39;,&#39;Fatima Noor&#39;, &#39;delivered&#39;,0);<br>-- Which cities each role may see (a row access policy&#39;s mapping table).<br>CREATE TABLE role_cities (role, city);<br>INSERT INTO role_cities VALUES (&#39;ops_admin&#39;,&#39;Pune&#39;), (&#39;ops_admin&#39;,&#39;Mumbai&#39;),<br>                               (&#39;pune_ops&#39;,&#39;Pune&#39;), (&#39;pune_assistant&#39;,&#39;Pune&#39;);<br>&quot;&quot;&quot;)<br><br>def query_as(role, sql):<br>    &quot;&quot;&quot;Apply row access and masking the way the platform would,<br>    before the query sees the data.&quot;&quot;&quot;<br>    db.execute(&quot;DROP VIEW IF EXISTS secured&quot;)<br>    rider = (&quot;rider_name&quot; if role in (&quot;ops_admin&quot;, &quot;pune_ops&quot;)<br>             else &quot;&#39;*****&#39; AS rider_name&quot;)<br>    db.execute(f&quot;&quot;&quot;CREATE TEMP VIEW secured AS<br>                   SELECT order_id, city, {rider}, status, late FROM orders<br>                   WHERE city IN (SELECT city FROM role_cities<br>                                  WHERE role = &#39;{role}&#39;)&quot;&quot;&quot;)<br>    return db.execute(sql.replace(&quot;orders&quot;, &quot;secured&quot;)).fetchall()<br><br>SQL = &quot;SELECT city, sum(late), min(rider_name) FROM orders GROUP BY city&quot;<br>for role in (&quot;ops_admin&quot;, &quot;pune_ops&quot;, &quot;pune_assistant&quot;, &quot;unknown_role&quot;):<br>    print(f&quot;{role:15}&quot;, query_as(role, SQL))</pre><p>ops_admin sees both cities with names: Mumbai 1 late, Pune 5. pune_ops sees Pune only, with names. pune_assistant sees the same Pune rows with every name masked. An unknown role sees nothing. Those four lines are a test you can rerun on every release.</p><p>Notice that the assistant’s count is still right. Masking and row filters change what it may say, not whether its numbers agree. Governance shouldn’t undo the consistency we built in Parts 3 to 5.</p><h3>Three more things to decide</h3><ul><li><strong>Whose access: the assistant’s or the user’s?</strong> A customer assistant can use its own fixed role. An internal assistant answering staff should usually act with the asking person’s role, so it never shows more than they could see themselves.</li><li><strong>Documents need the same rules.</strong> Filter the policy search service by city and audience, as Part 7 filtered by status and date.</li><li><strong>Keep the audit trail.</strong> On Enterprise Edition, ACCESS_HISTORY records which policies were applied to each query, so you can show what the assistant read and under which rules. [3]</li></ul><h3>What to take away</h3><ol><li><strong>The assistant is a user.</strong> Give it its own role, with the least access that works.</li><li><strong>Enforce rules in the platform.</strong> Prompts ask; policies decide.</li><li><strong>Row access for rows, masking for columns.</strong> They apply to every tool, not just the assistant.</li><li><strong>Test each role’s view.</strong> One query, every role, every release.</li><li><strong>Governance shouldn’t change the answer.</strong> Only what may be shown.</li></ol><p>Next in the series: Bronze, Silver, quality, semantics, documents and governance are in place. How do you prove, with numbers, that the data is ready?</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.snowflake.com/en/user-guide/security-row-intro">Understanding row access policies</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/security-column-intro">Understanding column-level security</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/access-history">Access History</a> — Snowflake documentation</li><li><a href="https://arxiv.org/abs/2302.12173">Compromising LLM-Integrated Applications with Indirect Prompt Injection</a> — Greshake et al., 2023</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22894b60f7fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does the Assistant Find the Right Rule? (AI-Ready Data Series, Part 7)]]></title>
            <link>https://medium.com/@manulovesu22/how-does-the-assistant-find-the-right-rule-ai-ready-data-series-part-7-70d0fc8759df?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d0fc8759df</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:29:27 GMT</pubDate>
            <atom:updated>2026-12-02T18:40:05.223Z</atom:updated>
            <content:encoded><![CDATA[<h4>Retrieval from a knowledge base: hybrid search, metadata filters, freshness and a test that proves it works.</h4><figure><img alt="Flat illustration for how the assistant finds the right rule" src="https://cdn-images-1.medium.com/max/1024/1*s1YGZMBZ3IDXbfDcQJ3Fdg.png" /></figure><figure><img alt="Part 7, Gold retrieval. The support escalation, 26 November: “Two items were missing from my bag. Your assistant told me missing items aren’t refunded. Is that true?”" src="https://cdn-images-1.medium.com/max/1024/1*RxsOIso8jXdSlbI-hrSgRA.png" /></figure><p>It isn’t. Rule D7 says missing items are refunded to the original payment method within five days. But the customer wrote “refunded”, “not” and “my order”, and the draft policy, which nobody approved, says “Late deliveries are not refunded.” To a search engine, that draft looked like the closest match.</p><p>In <a href="https://medium.com/p/69e889013692">my last article</a> we built the knowledge base: the policy parsed, split into one chunk per rule, and labelled with status and effective dates. A well-labelled library is only half the job. This part is about the other half: finding the right shelf when a customer asks in their own words.</p><figure><img alt="Animation for “My delivery was late. Do I get the delivery fee refunded?” By similarity alone, old rule v3-D4 ranks first. A filter for approved and in force strikes out v3 and draft v5. Only v4-D4, a refund over 30 minutes late, remains." src="https://cdn-images-1.medium.com/max/1024/1*RfX8T0AvCTE6JVuDOAG-RQ.gif" /></figure><figure><img alt="In this article: Retrieval is where answers are won or lost; Two kinds of search, used together; Filter first, then rank; Test retrieval on its own; The same thing in Snowflake; Give the model what it needs to cite; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*cJOi7Ee0DOqi6LjSX9gNeQ.png" /></figure><h3>Retrieval is where answers are won or lost</h3><p>When an assistant answers from documents, it first retrieves a few chunks, then writes its answer from them. This is retrieval-augmented generation [3], which I covered in the <a href="https://medium.com/p/033aa4b6f4a4">RAG article</a> of my AI Engineering series. The model can only be as right as what it is handed. If retrieval returns the old rule or the draft, the best model in the world will still give the wrong answer, fluently.</p><p>Customers don’t use the policy’s words. They say “money back” instead of “refund of the delivery fee”, and “40 minutes after my window” instead of “more than 30 minutes late”. Retrieval has to bridge that gap without being fooled by text that merely sounds similar.</p><h3>Two kinds of search, used together</h3><figure><img alt="Table of search methods. Keyword search finds exact codes like “D7” but misses paraphrases. Vector search finds meaning but misses identifiers and “refunded” versus “not refunded”. Hybrid with reranking does both but misses anything filtered out first." src="https://cdn-images-1.medium.com/max/1024/1*-cP68lt3nnMJJ6OQ4StTig.png" /></figure><p>Snowflake’s Cortex Search does all three in each query: vector search for meaning, keyword search for exact terms, then semantic reranking of the top results. [1] The <a href="https://medium.com/p/b1f020887e99">embeddings article</a> in my AI series explains why vectors alone can’t tell “refunded” from “not refunded” reliably.</p><h3>Filter first, then rank</h3><p>Here is the important idea of this part. No ranking method knows which rule is approved or in force. That knowledge lives in the metadata from Part 6. So the filter must run before the ranking, not after it.</p><p>The example below builds a tiny hybrid search in plain Python. Keyword overlap stands in for BM25 [4], and character-trigram similarity stands in for embeddings; real systems use better versions of both, but the behaviour is the same.</p><pre>import math, re<br>from collections import Counter<br>from datetime import date<br><br>CHUNKS = [  # the knowledge base: one chunk per rule + metadata (Part 6)<br>    (&quot;v3-D4&quot;, &quot;Late deliveries get a refund of the delivery fee.&quot;,<br>     &quot;approved&quot;, date(2025, 4, 1), date(2026, 11, 15)),<br>    (&quot;v4-D4&quot;, &quot;Deliveries more than 30 minutes late get a refund &quot;<br>              &quot;of the delivery fee.&quot;, &quot;approved&quot;, date(2026, 11, 15), None),<br>    (&quot;v5-D4&quot;, &quot;Late deliveries are not refunded.&quot;, &quot;draft&quot;, None, None),<br>    (&quot;v4-D3&quot;, &quot;Slots can be moved up to 2 hours before they start.&quot;,<br>     &quot;approved&quot;, date(2026, 11, 15), None),<br>    (&quot;v4-D7&quot;, &quot;Missing items are refunded to the original payment &quot;<br>              &quot;method within 5 days.&quot;, &quot;approved&quot;, date(2026, 11, 15), None),<br>]<br><br>words = lambda s: set(re.findall(r&quot;[a-z0-9]+&quot;, s.lower()))<br>trigrams = lambda s: Counter(s.lower()[i:i + 3] for i in range(len(s) - 2))<br><br>def keyword_score(query, text):<br>    &quot;&quot;&quot;Share of the query&#39;s words found in the text: a stand-in for BM25.&quot;&quot;&quot;<br>    return len(words(query) &amp; words(text)) / len(words(query))<br><br>def vector_score(query, text):<br>    &quot;&quot;&quot;Cosine similarity of character trigrams: a stand-in for embeddings.&quot;&quot;&quot;<br>    a, b = trigrams(query), trigrams(text)<br>    dot = sum(a[k] * b[k] for k in a)<br>    return dot / math.sqrt(sum(v * v for v in a.values())<br>                           * sum(v * v for v in b.values()))<br><br>def in_force(chunk, on):<br>    _, _, status, start, end = chunk<br>    return status == &quot;approved&quot; and start &lt;= on and (end is None or on &lt; end)<br><br>def search(query, on=None, mode=&quot;hybrid&quot;, k=3):<br>    # filter BEFORE ranking<br>    pool = [c for c in CHUNKS if on is None or in_force(c, on)]<br>    def score(text):<br>        kw, vec = keyword_score(query, text), vector_score(query, text)<br>        return {&quot;keyword&quot;: kw, &quot;vector&quot;: vec, &quot;hybrid&quot;: (kw + vec) / 2}[mode]<br>    return sorted(((round(score(c[1]), 2), c[0]) for c in pool),<br>                  reverse=True)[:k]<br>Q = &quot;My delivery was late. Do I get the delivery fee refunded?&quot;<br>print(&quot;No filters:          &quot;, search(Q))<br>print(&quot;In force on 25 Nov:  &quot;, search(Q, on=date(2026, 11, 25)))</pre><p>Without filters, the top result is v3-D4, the old rule that refunds any late delivery, with a score of 0.6. The current rule, v4-D4, comes second at 0.55, and the draft is third. That is exactly the mistake from Part 6. With the filter for rules in force on 25 November, v4-D4 comes first, and the old rule and the draft can’t appear at all.</p><figure><img alt="Key idea: Similarity tells you what sounds right. Metadata tells you what is true. Filter on the truth, then rank on the sound." src="https://cdn-images-1.medium.com/max/1024/1*ysZi74gFe2wpxPJv-jGemQ.png" /></figure><h3>Test retrieval on its own</h3><p>In Part 9 we will test whole answers. Retrieval deserves its own test, because when it fails, nothing downstream can recover. The test is simple: real customer questions, and the chunk that should come back first.</p><pre># A retrieval test: real questions and the rule that should come back first.<br>TESTS = [<br>    (&quot;My delivery was late. Do I get the delivery fee refunded?&quot;, &quot;v4-D4&quot;),<br>    (&quot;Can I move my slot to later today?&quot;,                       &quot;v4-D3&quot;),<br>    (&quot;Two items were missing from my bag&quot;,                         &quot;v4-D7&quot;),<br>    (&quot;Rider came 40 minutes after my window. Money back?&quot;,         &quot;v4-D4&quot;),<br>    (&quot;When do I get refunded for things not in my order?&quot;,         &quot;v4-D7&quot;),<br>]<br>for label, on in ((&quot;no filters&quot;, None),<br>                  (&quot;in force on 25 Nov&quot;, date(2026, 11, 25))):<br>    misses = [q for q, want in TESTS if search(q, on=on, k=1)[0][1] != want]<br>    print(f&quot;{label:19} top-1 correct: {len(TESTS) - len(misses)}/&quot;<br>          f&quot;{len(TESTS)}  missed: {misses}&quot;)</pre><p>Without filters, only 3 of 5 questions get the right rule first. The two misses are the late-delivery question, which returns the old v3 rule, and the missing-items question, which returns the draft: “Late deliveries are not refunded.” That is the escalation at the top of this article, reproduced in one line. With the filter, all 5 are correct.</p><p>Five questions is a toy. In production, collect fifty to a hundred real questions from support tickets, label the right rule for each, and rerun the test whenever the policy, the chunking or the search settings change.</p><h3>The same thing in Snowflake</h3><p>A Cortex Search service is built over a table or query. The ON column is searched; ATTRIBUTES are returned with results and can be used in filters. WAREHOUSE does the indexing, TARGET_LAG sets how far the index may trail the table, and EMBEDDING_MODEL picks the model that creates the vectors. [1] With our own table names:</p><pre>CREATE OR REPLACE CORTEX SEARCH SERVICE gold.policy_search<br>  ON rule_text<br>  ATTRIBUTES rule_id, status, effective_from, effective_to, city<br>  WAREHOUSE = search_wh<br>  TARGET_LAG = &#39;1 hour&#39;<br>  EMBEDDING_MODEL = &#39;snowflake-arctic-embed-l-v2.0&#39;<br>AS (<br>  SELECT rule_id, rule_text, status, effective_from,<br>         COALESCE(effective_to, &#39;9999-12-31&#39;::DATE) AS effective_to,<br>         city, source_doc<br>  FROM silver.policy_chunks<br>);</pre><p>Replacing an open end date with a far-future date keeps the range filter simple. A query then asks for approved rules in force on the order date. Filters support @eq for text, @gte and @lte for numbers and dates, and @and, @or and @not to combine them. [2]</p><pre>SELECT PARSE_JSON(<br>  SNOWFLAKE.CORTEX.SEARCH_PREVIEW(<br>    &#39;gold.policy_search&#39;,<br>    &#39;{<br>      &quot;query&quot;: &quot;Two items were missing from my bag&quot;,<br>      &quot;columns&quot;: [&quot;rule_id&quot;, &quot;rule_text&quot;, &quot;source_doc&quot;],<br>      &quot;filter&quot;: {&quot;@and&quot;: [<br>        {&quot;@eq&quot;:  {&quot;status&quot;: &quot;approved&quot;}},<br>        {&quot;@lte&quot;: {&quot;effective_from&quot;: &quot;2026-11-25&quot;}},<br>        {&quot;@gte&quot;: {&quot;effective_to&quot;:   &quot;2026-11-26&quot;}}<br>      ]},<br>      &quot;limit&quot;: 3<br>    }&#39;<br>  )<br>)[&#39;results&#39;] AS results;</pre><p>Because effective_to is exclusive in our data, the query asks for an end date after the order date. SEARCH_PREVIEW is meant for testing and validation; an application calls the same service through Snowflake’s REST or Python API. [2]</p><h4>Freshness is a retrieval setting</h4><p>The policy changed on 15 November. With a TARGET_LAG of one hour, the old rule could still be served for up to an hour after the new table rows land. The service refreshes incrementally, re-embedding only rows that were added or changed. [1] Pick the lag from the cost of being wrong: an hour is fine for a refund policy, and too slow for a list of delivery zones closed by flooding.</p><h3>Give the model what it needs to cite</h3><p>Return the rule ID, the source document and the effective dates with every chunk, and ask the assistant to cite them. Then a support agent can check the answer in seconds, and Part 9’s agreement test can compare citations as well as numbers. An answer that says “D7, delivery policy v4, in force since 15 November” is an answer someone can trust.</p><h3>What to take away</h3><ol><li><strong>Retrieval sets the ceiling.</strong> The model can’t be more right than the chunks it is given.</li><li><strong>Use keyword and vector search together.</strong> Each catches what the other misses.</li><li><strong>Filter before ranking.</strong> Similarity can’t tell an approved rule from a draft.</li><li><strong>Test retrieval on its own.</strong> Real questions, the right rule, rerun on every change.</li><li><strong>Freshness and citations are part of retrieval.</strong> Set the lag on purpose and return the source.</li></ol><p>Next in the series: the assistant now finds the right numbers and the right rules. What should it be allowed to see at all? Read <a href="https://medium.com/p/22894b60f7fc">Part 8</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-search/cortex-search-overview">Cortex Search overview</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-search/query-cortex-search-service">Query a Cortex Search service</a> — Snowflake documentation</li><li><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a> — Lewis et al., 2020</li><li><a href="https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables">Practical BM25: the algorithm and its variables</a> — Elastic</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d0fc8759df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Make Documents as Reliable as Tables? (AI-Ready Data Series, Part 6)]]></title>
            <link>https://medium.com/@manulovesu22/how-do-you-make-documents-as-reliable-as-tables-ai-ready-data-series-part-6-69e889013692?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e889013692</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:28:55 GMT</pubDate>
            <atom:updated>2026-12-02T18:39:43.556Z</atom:updated>
            <content:encoded><![CDATA[<h4>Putting the refund policy through Bronze, Silver and Gold: parsing, chunking, effective dates and approval status.</h4><figure><img alt="Flat illustration for making documents as reliable as tables" src="https://cdn-images-1.medium.com/max/1024/1*f9F3rnGoB3hk7Q9C5DG62A.png" /></figure><figure><img alt="Part 6, Gold documents. The complaint, 25 November: “Your assistant promised me a refund because my order was ten minutes late. Support says I don’t qualify. Which one is right?”" src="https://cdn-images-1.medium.com/max/1024/1*TPawYJoseNeMx2IErXW4OQ.png" /></figure><p>The tables are in good shape now. This mistake came from somewhere else: the delivery policy. On 15 November rule D4 changed. Late deliveries used to earn a refund of the delivery fee; now only deliveries more than 30 minutes late do. The search index held version 3 and version 4 of the policy side by side, plus a draft of version 5 saying late deliveries aren’t refunded at all. The assistant found the old rule first.</p><p>In <a href="https://medium.com/p/2da6564ea378">my last article</a> we defined “late” once for every tool. Documents need the same care, and most platforms give them none.</p><figure><img alt="Animation: a marker moves along a November timeline. Through 14 Nov, rule D4 v3 is in force: late deliveries get a delivery fee refund. From 15 Nov, v4 applies: only deliveries more than 30 minutes late. Draft v5 is indexed but never served." src="https://cdn-images-1.medium.com/max/1024/1*5yf1XYr61MLOoGqnrvo5fA.gif" /></figure><figure><img alt="In this article: Documents skip the layers; Parse, then chunk by meaning; Every chunk carries its metadata; Serving it from Gold; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*y7ucLTGNkn-ylJCv2_8_0g.png" /></figure><h3>Documents skip the layers</h3><p>Tables go through Bronze, Silver and Gold, with checks at every step. Documents often go from a shared drive straight into a vector index. Nobody checks which version is current, which is approved, or whether a draft slipped in. A draft that says the opposite of the real rule can look almost identical to a search engine, as I showed in the <a href="https://medium.com/p/b1f020887e99">embeddings article</a> of my AI Engineering series.</p><p>The fix is to treat documents as data, with the same layers.</p><figure><img alt="Layers for orders and for the delivery policy. Bronze: rows, or every PDF, as delivered with file and load time. Silver: agreed meanings, or parsed rules with status and effective dates. Gold: metrics, or a search service over approved rules in force." src="https://cdn-images-1.medium.com/max/1024/1*Pcc3_nnBMmt_CtyACTOegA.png" /></figure><h3>Parse, then chunk by meaning</h3><p>The first step is getting text out of the PDF. Snowflake’s AI_PARSE_DOCUMENT reads a staged file and returns its content as JSON. OCR mode returns text; LAYOUT mode also keeps structure such as tables. [1]</p><pre>SELECT PARSE_JSON(<br>  AI_PARSE_DOCUMENT(<br>    TO_FILE(&#39;@policy_stage&#39;, &#39;delivery_policy_v4.pdf&#39;),<br>    {&#39;mode&#39;: &#39;LAYOUT&#39;}<br>  )<br>):content::STRING AS policy_text;</pre><p>Then split the text. Fixed-size chunks of a few hundred tokens are a common default, but a policy already has natural units: its rules. One chunk per rule keeps every condition with the rule it belongs to, so “more than 30 minutes” never gets separated from D4.</p><h3>Every chunk carries its metadata</h3><p>This is the step most pipelines skip. Each chunk should know which document it came from, whether that document is approved, and the dates it is in force. Then “which rule applies?” becomes a filter, not a guess.</p><pre>import re<br>from datetime import date<br><br># Three versions of the delivery policy, as parsed text with their metadata.<br>DOCS = [<br>    {&quot;doc&quot;: &quot;delivery_policy_v3.pdf&quot;, &quot;status&quot;: &quot;approved&quot;,<br>     &quot;effective_from&quot;: date(2025, 4, 1), &quot;effective_to&quot;: date(2026, 11, 15),<br>     &quot;text&quot;: &quot;D3 Slots can be moved up to 2 hours before they start.\n&quot;<br>             &quot;D4 Late deliveries get a refund of the delivery fee.&quot;},<br>    {&quot;doc&quot;: &quot;delivery_policy_v4.pdf&quot;, &quot;status&quot;: &quot;approved&quot;,<br>     &quot;effective_from&quot;: date(2026, 11, 15), &quot;effective_to&quot;: None,<br>     &quot;text&quot;: &quot;D3 Slots can be moved up to 2 hours before they start.\n&quot;<br>             &quot;D4 Deliveries more than 30 minutes late &quot;<br>             &quot;get a refund of the delivery fee.&quot;},<br>    {&quot;doc&quot;: &quot;delivery_policy_v5_draft.pdf&quot;, &quot;status&quot;: &quot;draft&quot;,<br>     &quot;effective_from&quot;: None, &quot;effective_to&quot;: None,<br>     &quot;text&quot;: &quot;D4 Late deliveries are not refunded.&quot;},<br>]<br><br>def chunk(doc):<br>    &quot;&quot;&quot;One chunk per rule, each carrying the document&#39;s metadata.&quot;&quot;&quot;<br>    meta = {k: v for k, v in doc.items() if k != &quot;text&quot;}<br>    for line in doc[&quot;text&quot;].splitlines():<br>        rule_id, body = re.match(r&quot;(D\d+) (.*)&quot;, line).groups()<br>        yield {&quot;rule_id&quot;: rule_id, &quot;text&quot;: body, **meta}<br><br>CHUNKS = [c for d in DOCS for c in chunk(d)]<br><br>def rule_in_force(rule_id, on):<br>    for c in CHUNKS:<br>        if (c[&quot;rule_id&quot;] == rule_id and c[&quot;status&quot;] == &quot;approved&quot;<br>                and c[&quot;effective_from&quot;] &lt;= on<br>                and (c[&quot;effective_to&quot;] is None or on &lt; c[&quot;effective_to&quot;])):<br>            return c<br><br>print(&quot;chunks indexed:&quot;, len(CHUNKS))<br>for day in (date(2026, 11, 10), date(2026, 11, 25)):<br>    c = rule_in_force(&quot;D4&quot;, day)<br>    print(f&quot;D4 on {day}: {c[&#39;text&#39;]}  [{c[&#39;doc&#39;]}]&quot;)</pre><p>It indexes five chunks. On 10 November it returns the version 3 rule: any late delivery is refunded. On 25 November it returns version 4, with the 30-minute condition, and names the file. The draft is indexed but never served, because its status isn’t approved. The customer was ten minutes late on 25 November, so support was right.</p><figure><img alt="Key idea: A rule, like an order, has a history. Store when it starts and ends, and answer with the version in force on the day in question." src="https://cdn-images-1.medium.com/max/1024/1*luPMx4I1aNZuveBpAUpwVQ.png" /></figure><h3>Serving it from Gold</h3><p>In Gold, the search service should index only what a reader may rely on. With Cortex Search, that means building the service over the Silver chunk table, declaring status and effective dates as ATTRIBUTES, and filtering on them in every query. [2] [3] Each question then asks for approved rules in force on the date of the order, not just the rules that sound most similar.</p><p>Two habits keep this working. First, let the policy owner set status and dates in a small table, not in file names. Second, check documents the way Part 4 checks tables: every approved rule has an effective date, no two approved versions of a rule overlap, and nothing reaches Gold with status “draft”.</p><h3>What to take away</h3><ol><li><strong>Documents are data.</strong> Put them through the same layers as tables.</li><li><strong>Chunk by meaning.</strong> One rule per chunk keeps conditions attached.</li><li><strong>Every chunk carries status and dates.</strong> Then “which rule applies?” is a filter.</li><li><strong>Index drafts, serve only approved rules.</strong> Search over Gold, never over the shared drive.</li><li><strong>Test documents like tables.</strong> No overlaps, no undated rules, no drafts in Gold.</li></ol><p>Next in the series: the knowledge base is clean and labelled. How does the assistant find the right rule in it when a customer asks in their own words? Read <a href="https://medium.com/p/70d0fc8759df">Part 7</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.snowflake.com/en/sql-reference/functions/ai_parse_document">AI_PARSE_DOCUMENT</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-search/cortex-search-overview">Cortex Search overview</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-search/query-cortex-search-service">Query a Cortex Search service</a> — Snowflake documentation</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e889013692" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Should a Metric Be Defined So Every Tool Agrees? (AI-Ready Data Series, Part 5)]]></title>
            <link>https://medium.com/@manulovesu22/where-should-a-metric-be-defined-so-every-tool-agrees-ai-ready-data-series-part-5-2da6564ea378?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da6564ea378</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[semantic-layer]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:28:15 GMT</pubDate>
            <atom:updated>2026-12-02T18:39:22.360Z</atom:updated>
            <content:encoded><![CDATA[<h4>Gold tables, a semantic layer, and one definition of “late” for Power BI and the assistant alike.</h4><figure><img alt="Flat illustration for defining a metric once so every tool agrees" src="https://cdn-images-1.medium.com/max/1024/1*xyspA3i45-9B1rPD1pJGKA.png" /></figure><figure><img alt="Part 5, Gold. The second demo: “Silver is clean now. So why did the Power BI report and the assistant still disagree this morning?”" src="https://cdn-images-1.medium.com/max/1024/1*NTupL7NQAToidvhUou77qw.png" /></figure><p>Silver fixed the meaning of words. It didn’t fix the formula. The Power BI report counts late deliveries with a DAX measure (Power BI’s formula language) written two years ago, which still counts weeks in UTC. The assistant writes fresh SQL every time it is asked. Both read the same clean table, and they still disagree, because each decided for itself what to count.</p><p>In <a href="https://medium.com/p/d5bcd6178468">my last article</a> we stopped bad data at the gate. This part makes sure that everyone who reads good data computes the same number from it.</p><figure><img alt="Animation: a semantic view defines late_deliveries once, as delivered after the current slot in the Pune week. Lines draw from it to the Power BI report and the assistant, and both then show 5 late deliveries." src="https://cdn-images-1.medium.com/max/1024/1*qj-f54BYxxMilCmANiKp-w.gif" /></figure><figure><img alt="In this article: Gold is where business questions live; One definition, compiled for every reader; Snowflake semantic views; Power BI and the semantic layer; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*6ljLx44hjC8asXhFnPsk9g.png" /></figure><h3>Gold is where business questions live</h3><p>Databricks describes the Gold layer as refined views of the data, aggregated and aligned with business logic for analytics. [1] In practice that means tables shaped around questions: a fact table of orders, dimensions for city and date, and the metrics people actually ask about.</p><p>Tables alone don’t carry the formula, though. “Late deliveries” is a count with two filters and a choice of time column. If that logic lives separately in each report and each prompt, it will drift. A semantic layer moves it into one place, next to the data.</p><h3>One definition, compiled for every reader</h3><p>The idea fits in a few lines of Python. The metric is defined once, as data. Each consumer asks for it by name, and the same filters come back every time.</p><pre># One metric definition, compiled to SQL for every consumer.<br>METRICS = {<br>    &quot;late_deliveries&quot;: {<br>        &quot;description&quot;: &quot;Delivered orders that arrived after the end &quot;<br>                       &quot;of their current slot, by Pune slot date&quot;,<br>        &quot;sql&quot;: &quot;count(*)&quot;,<br>        &quot;filters&quot;: [&quot;status = &#39;delivered&#39;&quot;,<br>                    &quot;delivered_at_ist &gt; slot_end_ist&quot;],<br>        &quot;time_column&quot;: &quot;slot_end_ist&quot;,<br>        &quot;table&quot;: &quot;gold.fct_orders&quot;,<br>    }<br>}<br><br>def compile_metric(name, start, end, group_by=None):<br>    m = METRICS[name]<br>    where = m[&quot;filters&quot;] + [f&quot;{m[&#39;time_column&#39;]} &gt;= &#39;{start}&#39;&quot;,<br>                            f&quot;{m[&#39;time_column&#39;]} &lt; &#39;{end}&#39;&quot;]<br>    select = ([group_by] if group_by else []) + [f&quot;{m[&#39;sql&#39;]} AS {name}&quot;]<br>    sql = (f&quot;SELECT {&#39;, &#39;.join(select)} FROM {m[&#39;table&#39;]} WHERE &quot;<br>           + &quot; AND &quot;.join(where))<br>    return sql + (f&quot; GROUP BY {group_by}&quot; if group_by else &quot;&quot;)<br><br># The Power BI report and the assistant ask differently,<br># but get the same definition.<br>print(&quot;BI report :&quot;, compile_metric(&quot;late_deliveries&quot;,<br>                                    &quot;2026-11-23&quot;, &quot;2026-11-30&quot;, &quot;city&quot;))<br>print(&quot;Assistant :&quot;, compile_metric(&quot;late_deliveries&quot;,<br>                                    &quot;2026-11-23&quot;, &quot;2026-11-30&quot;))</pre><p>Both printed queries filter on status = ‘delivered’ and delivered_at_ist &gt; slot_end_ist, and both use the Pune slot date for the week. The report adds GROUP BY city; the assistant doesn’t. The consumers differ in shape, not in meaning.</p><figure><img alt="Key idea: If a metric’s formula lives in more than one place, those places will eventually disagree. Define it once and let every tool ask for it." src="https://cdn-images-1.medium.com/max/1024/1*FxSD-QrG-zfKRej8ztXdSA.png" /></figure><h3>Snowflake semantic views</h3><p>Snowflake makes this a database object. A semantic view stores business meaning next to the physical tables: logical tables, the relationships between them, facts, dimensions and metrics. Cortex Analyst and Cortex Agents use it to answer natural-language questions, and BI users get the same metrics and dimensions in their own tools. [2]</p><p>The clauses come in a fixed order: TABLES, then RELATIONSHIPS, FACTS, DIMENSIONS and METRICS. [3] For FreshBasket, with our own table names:</p><pre>CREATE OR REPLACE SEMANTIC VIEW gold.delivery_performance<br>  TABLES (<br>    orders AS gold.fct_orders PRIMARY KEY (order_id)<br>  )<br>  FACTS (<br>    orders.is_late AS<br>      IFF(orders.status = &#39;delivered&#39;<br>          AND orders.delivered_at_ist &gt; orders.slot_end_ist, 1, 0)<br>  )<br>  DIMENSIONS (<br>    orders.city_name AS orders.city,<br>    orders.slot_week AS DATE_TRUNC(&#39;WEEK&#39;, orders.slot_end_ist),<br>    orders.slot_date AS TO_DATE(orders.slot_end_ist)<br>  )<br>  METRICS (<br>    orders.late_deliveries AS SUM(orders.is_late)<br>  )<br>  COMMENT = &#39;Delivery performance. Weeks and dates use Pune slot time.&#39;;</pre><p>Any SQL client can then ask for the metric by name, without restating the filters:</p><pre>SELECT * FROM SEMANTIC_VIEW(<br>  gold.delivery_performance<br>  METRICS orders.late_deliveries<br>  DIMENSIONS orders.city_name, orders.slot_week<br>)<br>ORDER BY slot_week;</pre><p>SEMANTIC_VIEW takes metrics, dimensions and an optional WHERE filter that is applied before the metrics are computed. [4] DATE_TRUNC(‘WEEK’) follows the WEEK_START parameter. Its default already starts weeks on Monday, which is how FreshBasket counts them, so change it only on purpose.</p><h4>What the assistant gains</h4><p>A semantic view changes the assistant’s job from “write correct SQL from column names” to “pick the right metric and dimensions”. That is a much smaller space in which to be wrong, and it is easy to test. My <a href="https://medium.com/p/653e3e2b1883">evaluation article</a> in the AI Engineering series shows how to build that test set.</p><p>Few organisations have this layer yet. In a 2026 TDWI benchmark of 161 organisations, as summarised by the data vendor Precisely, only 27% had a governed, enterprise-wide semantic layer that machines can consume. [5]</p><h3>Power BI and the semantic layer</h3><p>Most teams already have a Power BI semantic model full of DAX measures. Don’t throw it away; decide which layer owns each metric. A practical rule: metrics that an assistant, an API or another tool will ask for belong in the warehouse’s semantic view. Report-specific calculations, such as a share of the visible total, can stay in DAX. Either way, write down which one is the source of truth for each metric.</p><h3>What to take away</h3><ol><li><strong>Clean data can still give two answers.</strong> The formula has to be shared too.</li><li><strong>Gold is shaped around questions.</strong> Facts, dimensions and the metrics people ask for.</li><li><strong>Define each metric once.</strong> Every tool asks for it by name.</li><li><strong>Semantic views shrink the assistant’s job.</strong> Choosing a metric is safer than writing SQL from scratch.</li><li><strong>Give every metric one owning layer.</strong> Warehouse or DAX, never both.</li></ol><p>Next in the series: the numbers agree now, but the assistant also reads documents. How do you make the refund policy as reliable as the orders table? Read <a href="https://medium.com/p/69e889013692">Part 6</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.databricks.com/aws/en/lakehouse/medallion">What is the medallion lakehouse architecture?</a> — Databricks documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/views-semantic/overview">Overview of semantic views</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/sql/create-semantic-view">CREATE SEMANTIC VIEW</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/constructs/semantic_view">SEMANTIC_VIEW</a> — Snowflake documentation</li><li><a href="https://www.precisely.com/blog/cat-data-governance/agentic-ai-readiness-in-2026-where-enterprises-stand-and-what-it-takes-to-scale/">Agentic AI readiness in 2026</a> — Precisely, June 2026</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da6564ea378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Stop Bad Data Before the Assistant Repeats It? (AI-Ready Data Series, Part 4)]]></title>
            <link>https://medium.com/@manulovesu22/how-do-you-stop-bad-data-before-the-assistant-repeats-it-ai-ready-data-series-part-4-d5bcd6178468?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5bcd6178468</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-observability]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:27:31 GMT</pubDate>
            <atom:updated>2026-12-02T18:39:01.633Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quality checks, freshness and volume alerts that hold a bad load at the gate.</h4><figure><img alt="Flat illustration for stopping bad data before the assistant repeats it" src="https://cdn-images-1.medium.com/max/1024/1*ldpfVVvVjlfi1ixzy6IRGw.png" /></figure><figure><img alt="Part 4, Silver quality. The morning after, 2 December, 09:00: “The assistant says we delivered four orders in Pune yesterday. We normally do about four hundred. Is the city empty, or is the data?”" src="https://cdn-images-1.medium.com/max/1024/1*Pji8tbzSONCJRm-6MfrpaA.png" /></figure><p>On 1 December FreshBasket shipped a new version of its rider app. The new version reported deliveries as “DELIVERED_OK”. One order arrived marked delivered but with no delivery time. And the nightly export stopped after four rows. Silver refreshed on schedule, the dashboards followed, and the assistant reported four deliveries with complete confidence.</p><p>In <a href="https://medium.com/p/4e8fc6532df2">my last article</a> we wrote the rules down in Silver and in a data contract. [4] This part checks, on every load, that the data still follows them.</p><figure><img alt="Animation of a quality gate on 1 December. Rows travel along a line toward a gate. Good rows pass; two bad rows, one with status DELIVERED_OK and one with no delivery time, are held at the gate. Volume check: 4 rows versus a normal 409." src="https://cdn-images-1.medium.com/max/1024/1*Jayg3mdf3FW97TcmBezt8w.gif" /></figure><figure><img alt="In this article: A person frowns; a model doesn’t; Four checks that would have caught it; The checks in code; The same checks in Snowflake; Lineage tells you who to warn; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*YJEbV4Ls59s6pKsyNE6-Lg.png" /></figure><h3>A person frowns; a model doesn’t</h3><p>An experienced operations manager would look at “four” and frown. An assistant has no memory of yesterday’s four hundred and no instinct that something is wrong. If the data reaches it, the data is the truth. That moves the burden from the reader to the pipeline: quality has to be checked before data is served, not discovered afterwards.</p><h3>Four checks that would have caught it</h3><figure><img alt="Table of four checks on 1 December. Completeness: a delivered order with no delivery time. Validity: “DELIVERED_OK” is not in the contract. Freshness: fine, loaded 13 hours earlier. Volume: 4 rows against an average of 409." src="https://cdn-images-1.medium.com/max/1024/1*2eJH-R7WJ16F_b-7kuk4Xg.png" /></figure><p>The freshness check passing is the dangerous part. The job ran on time, so a simple “did the job succeed?” alert stays green. Only the volume check notices that it succeeded at delivering almost nothing.</p><h3>The checks in code</h3><pre>import sqlite3<br><br>db = sqlite3.connect(&quot;:memory:&quot;)<br>db.executescript(&quot;&quot;&quot;<br>CREATE TABLE silver_orders<br>  (order_id, status, slot_end_ist, delivered_at_ist, _loaded_at);<br>INSERT INTO silver_orders VALUES<br>  (&#39;O20&#39;,&#39;delivered&#39;,<br>   &#39;2026-12-01 10:00&#39;, &#39;2026-12-01 10:12&#39;, &#39;2026-12-01T20:00&#39;),<br>  (&#39;O21&#39;,&#39;DELIVERED_OK&#39;,<br>   &#39;2026-12-01 11:00&#39;, &#39;2026-12-01 11:05&#39;, &#39;2026-12-01T20:00&#39;),<br>  (&#39;O22&#39;,&#39;delivered&#39;,<br>   &#39;2026-12-01 12:00&#39;, NULL,               &#39;2026-12-01T20:00&#39;),<br>  (&#39;O23&#39;,&#39;delivered&#39;,<br>   &#39;2026-12-01 18:00&#39;, &#39;2026-12-01 17:55&#39;, &#39;2026-12-01T20:00&#39;);<br>CREATE TABLE daily_row_counts (day, n);<br>INSERT INTO daily_row_counts VALUES (&#39;2026-11-27&#39;,412),(&#39;2026-11-28&#39;,388),<br>                                    (&#39;2026-11-29&#39;,431),(&#39;2026-11-30&#39;,405);<br>&quot;&quot;&quot;)<br><br>def check(name, sql, ok):<br>    value = db.execute(sql).fetchone()[0]<br>    verdict = &quot;PASS&quot; if ok(value) else &quot;FAIL&quot;<br>    print(f&quot;{verdict}  {name:46} value={round(value, 2)}&quot;)<br><br>check(&quot;delivered orders have a delivery time&quot;,<br>      &quot;SELECT count(*) FROM silver_orders &quot;<br>      &quot;WHERE status = &#39;delivered&#39; AND delivered_at_ist IS NULL&quot;,<br>      lambda v: v == 0)<br>check(&quot;status uses agreed values&quot;,<br>      &quot;SELECT count(*) FROM silver_orders &quot;<br>      &quot;WHERE status NOT IN (&#39;scheduled&#39;,&#39;delivered&#39;,&#39;cancelled&#39;)&quot;,<br>      lambda v: v == 0)<br>check(&quot;hours since last load, at 09:00 on 2 Dec&quot;,<br>      &quot;SELECT (julianday(&#39;2026-12-02T09:00&#39;) - julianday(max(_loaded_at)))&quot;<br>      &quot; * 24 FROM silver_orders&quot;,<br>      lambda v: v &lt;= 24)<br>check(&quot;today vs recent daily average (0.5 to 1.5)&quot;,<br>      &quot;SELECT count(*) * 1.0 / (SELECT avg(n) FROM daily_row_counts) &quot;<br>      &quot;FROM silver_orders&quot;,<br>      lambda v: 0.5 &lt;= v &lt;= 1.5)</pre><p>It prints three failures and one pass: one delivered order without a time, one unknown status, a freshness of 13 hours, which passes, and a volume ratio of 0.01, which fails. That is the whole story of 1 December in four lines.</p><p>Notice what “DELIVERED_OK” would have done to the Silver view from Part 3. The join to the status mapping would have silently dropped it, and the count would simply have shrunk. That is worse than a failure. The validity check makes the unknown value visible instead.</p><figure><img alt="Key idea: A check that only sends an email is a report. A check that stops Gold from refreshing is a control. Decide which checks are which." src="https://cdn-images-1.medium.com/max/1024/1*XR5Nlu4bxuHrJKGMbc1NTg.png" /></figure><h3>The same checks in Snowflake</h3><p>Snowflake’s data metric functions (Enterprise Edition) measure properties such as nulls, duplicates, accepted values and freshness on a schedule. The system functions live in SNOWFLAKE.CORE. [1] You set how often they run on the table, then attach one to a column:</p><pre>ALTER TABLE silver.orders SET DATA_METRIC_SCHEDULE = &#39;TRIGGER_ON_CHANGES&#39;;<br><br>ALTER TABLE silver.orders<br>  ADD DATA METRIC FUNCTION SNOWFLAKE.CORE.NULL_COUNT<br>    ON (delivered_at_ist);</pre><p>An expectation turns a measurement into a pass or a fail; the documentation shows one declared with the function, such as EXPECTATION no_nulls (VALUE = 0). [2] In preview, Snowflake can also detect anomalies in volume and freshness from a table’s own history, which covers the “four instead of four hundred” case without a hand-written threshold. [3]</p><h4>Where each check should sit</h4><figure><img alt="Four places to check data: at the Bronze door, record and flag, never reject; on Silver, contract rules; before Gold refreshes, the blocking gate that keeps yesterday’s Gold if a critical check fails; on the answers, Part 9’s agreement test." src="https://cdn-images-1.medium.com/max/1024/1*MFsg5wNv0P62AcKCy8gaYg.png" /></figure><h3>Lineage tells you who to warn</h3><p>When a check fails, the next question is what it broke. Lineage answers it: the bad Silver table feeds gold.fct_orders, the Delivery performance report in Power BI and the Pune assistant. With that map, an alert can name who to warn instead of only what failed. It is the same lineage Bronze started recording in Part 2, now read in the other direction.</p><h3>What to take away</h3><ol><li><strong>An assistant has no instinct for “that looks low”.</strong> The pipeline needs it instead.</li><li><strong>Check completeness, validity, freshness and volume.</strong> A green job can still deliver almost nothing.</li><li><strong>Make unknown values loud.</strong> A join that drops them hides the problem.</li><li><strong>Some checks must block.</strong> For an AI reader, stale but right beats fresh but wrong.</li><li><strong>Use lineage to warn the right people.</strong> A failure should arrive with its blast radius.</li></ol><p>Next in the series: Silver is clean and checked. Where should “late deliveries last week” be defined, so Power BI and the assistant compute it the same way? Read <a href="https://medium.com/p/2da6564ea378">Part 5</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.snowflake.com/en/user-guide/data-quality-system-dmfs">System data metric functions</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/data-quality-working">Use SQL to set up data metric functions</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/data-quality-intro">Introduction to data quality and data metric functions</a> — Snowflake documentation</li><li><a href="https://bitol-io.github.io/open-data-contract-standard/latest/">Open Data Contract Standard</a> — Bitol</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5bcd6178468" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does Silver Give Every Word One Meaning? (AI-Ready Data Series, Part 3)]]></title>
            <link>https://medium.com/@manulovesu22/how-does-silver-give-every-word-one-meaning-ai-ready-data-series-part-3-4e8fc6532df2?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e8fc6532df2</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-modeling]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:27:00 GMT</pubDate>
            <atom:updated>2026-12-02T18:38:40.550Z</atom:updated>
            <content:encoded><![CDATA[<h4>Status mappings, deduplication, time zones and contracts: turning raw rows into facts a model can read.</h4><figure><img alt="Flat illustration for how Silver gives every word one meaning" src="https://cdn-images-1.medium.com/max/1024/1*_ISJqS8GkfcjXuqupqrJyQ.png" /></figure><figure><img alt="Part 3, Silver. The definitions meeting: “Is ‘DLVD’ the same as ‘delivered’? Late against which slot? And when does ‘last week’ start in Pune?”" src="https://cdn-images-1.medium.com/max/1024/1*nvSUS1zbz94QzjRJz7MORw.png" /></figure><p>Bronze now keeps everything the delivery app ever sent, with its file and load time. That makes it trustworthy as a record and useless as an answer. It still says “delivered”, “Delivered” and “DLVD”. It holds two versions of order O4. And every timestamp is in UTC, while customers, riders and managers all live on Pune time.</p><p>In <a href="https://medium.com/p/152f923d8f8b">my last article</a> we landed the data without changing it. Silver is where we change it, once, on purpose, in a place everyone can read. [4]</p><figure><img alt="Animation: three status chips, delivered, Delivered and DLVD, slide together and merge into one “delivered”. Order O5’s slot end changes from Sun 22 Nov, 19:00 UTC to Mon 23 Nov, 00:30 Pune time. Late deliveries for the Pune week of 23 Nov: 5." src="https://cdn-images-1.medium.com/max/1024/1*Im5BtpzwSy9994q2N1qhNw.gif" /></figure><figure><img alt="In this article: Four decisions, written down; Building the Silver view; The same pattern in Snowflake; Contracts: agreeing before the data arrives; Describe Silver for its newest reader; What to take away." src="https://cdn-images-1.medium.com/max/1024/1*xGouizWhBTJXXGM_oYCgvQ.png" /></figure><h3>Four decisions, written down</h3><p>The three answers from Part 1 came from decisions nobody had written down. Silver turns each one into something a query, a person or a model can look up.</p><figure><img alt="Table of four Silver decisions. Delivered means “delivered” in any case and “DLVD”, via a mapping table. The latest load wins, deduplicated by order_id. Weeks run Monday to Sunday, Pune time. Late is against the current slot; both slots are kept." src="https://cdn-images-1.medium.com/max/1024/1*9jgvpDoFFOsrcGqs2nCyGw.png" /></figure><h3>Building the Silver view</h3><p>The example starts from Bronze, including the re-sent O3 and both versions of O4, and builds Silver with a mapping table and a window function.</p><pre>import sqlite3<br><br>T = &quot;2026-11-&quot;  # every timestamp below is in November 2026<br># order, status, slot_end, original_slot_end, delivered_at, _loaded_at<br>BRONZE = [<br>  (&quot;O1&quot;,&quot;delivered&quot;,T+&quot;23T06:00&quot;,T+&quot;23T06:00&quot;,T+&quot;23T06:20&quot;,T+&quot;23T20:00&quot;),<br>  (&quot;O2&quot;,&quot;Delivered&quot;,T+&quot;24T08:00&quot;,T+&quot;24T08:00&quot;,T+&quot;24T08:40&quot;,T+&quot;24T20:00&quot;),<br>  (&quot;O3&quot;,&quot;DLVD&quot;,     T+&quot;25T10:00&quot;,T+&quot;25T10:00&quot;,T+&quot;25T10:05&quot;,T+&quot;25T20:00&quot;),<br>  (&quot;O3&quot;,&quot;DLVD&quot;,     T+&quot;25T10:00&quot;,T+&quot;25T10:00&quot;,T+&quot;25T10:05&quot;,T+&quot;26T20:00&quot;),<br>  (&quot;O4&quot;,&quot;scheduled&quot;,T+&quot;26T05:00&quot;,T+&quot;26T05:00&quot;,None,        T+&quot;25T20:00&quot;),<br>  (&quot;O4&quot;,&quot;delivered&quot;,T+&quot;26T09:00&quot;,T+&quot;26T05:00&quot;,T+&quot;26T08:30&quot;,T+&quot;26T20:00&quot;),<br>  (&quot;O5&quot;,&quot;delivered&quot;,T+&quot;22T19:00&quot;,T+&quot;22T19:00&quot;,T+&quot;22T19:30&quot;,T+&quot;23T20:00&quot;),<br>  (&quot;O6&quot;,&quot;delivered&quot;,T+&quot;29T19:00&quot;,T+&quot;29T19:00&quot;,T+&quot;29T19:40&quot;,T+&quot;30T20:00&quot;),<br>  (&quot;O7&quot;,&quot;delivered&quot;,T+&quot;27T12:00&quot;,T+&quot;27T12:00&quot;,T+&quot;27T11:50&quot;,T+&quot;27T20:00&quot;),<br>  (&quot;O8&quot;,&quot;cancelled&quot;,T+&quot;28T07:00&quot;,T+&quot;28T07:00&quot;,None,        T+&quot;28T20:00&quot;),<br>  (&quot;O9&quot;,&quot;delivered&quot;,T+&quot;28T14:00&quot;,T+&quot;28T14:00&quot;,T+&quot;28T14:45&quot;,T+&quot;28T20:00&quot;),<br>]<br>db = sqlite3.connect(&quot;:memory:&quot;)<br>db.execute(&quot;CREATE TABLE bronze_orders (order_id, status, slot_end, &quot;<br>           &quot;original_slot_end, delivered_at, _loaded_at)&quot;)<br>db.executemany(&quot;INSERT INTO bronze_orders VALUES (?,?,?,?,?,?)&quot;, BRONZE)</pre><p>Silver then maps every status spelling to one agreed value and keeps the latest row for each order:</p><pre>db.executescript(&quot;&quot;&quot;<br>-- One agreed meaning for every status spelling the app has ever sent.<br>CREATE TABLE status_map (raw_value, status);<br>INSERT INTO status_map VALUES (&#39;delivered&#39;,&#39;delivered&#39;), (&#39;dlvd&#39;,&#39;delivered&#39;),<br>  (&#39;scheduled&#39;,&#39;scheduled&#39;), (&#39;cancelled&#39;,&#39;cancelled&#39;);<br><br>CREATE VIEW silver_orders AS<br>WITH latest AS (<br>  SELECT *, row_number() OVER (PARTITION BY order_id<br>                               ORDER BY _loaded_at DESC) AS rn<br>  FROM bronze_orders<br>)<br>SELECT l.order_id, m.status,<br>       datetime(l.slot_end, &#39;+5 hours&#39;, &#39;+30 minutes&#39;) AS slot_end_ist,<br>       datetime(l.original_slot_end, &#39;+5 hours&#39;, &#39;+30 minutes&#39;)<br>         AS original_slot_end_ist,<br>       datetime(l.delivered_at, &#39;+5 hours&#39;, &#39;+30 minutes&#39;)<br>         AS delivered_at_ist<br>FROM latest l<br>JOIN status_map m ON m.raw_value = lower(trim(l.status))<br>WHERE l.rn = 1;<br>&quot;&quot;&quot;)<br><br>for row in db.execute(&quot;SELECT order_id, status, slot_end_ist, &quot;<br>                      &quot;delivered_at_ist FROM silver_orders &quot;<br>                      &quot;ORDER BY order_id&quot;):<br>    print(row)<br>n = db.execute(&quot;&quot;&quot;SELECT count(*) FROM silver_orders<br>                  WHERE status = &#39;delivered&#39;<br>                    AND delivered_at_ist &gt; slot_end_ist<br>                    AND slot_end_ist &gt;= &#39;2026-11-23&#39;<br>                    AND slot_end_ist &lt; &#39;2026-11-30&#39;&quot;&quot;&quot;).fetchone()[0]<br>print(&quot;late deliveries, week of 23 Nov (Pune time):&quot;, n)</pre><p>Silver has nine rows, one per order. O3 appears once. O4 shows only its latest version, delivered at 14:00 against a 14:30 slot. Every delivered order now says “delivered”. O5’s slot moves into Monday 23 November at 00:30 Pune time, and O6’s moves out to Monday 30 November. The last line prints 5.</p><p>Five is the operations number from Part 1. Operations wasn’t lucky: its query already followed these rules. The difference is that the rules now live in Silver, where finance, the BI report and the assistant all read the same ones.</p><figure><img alt="Key idea: Put meanings in tables, not in CASE statements. A mapping table can be reviewed by the business, joined by anyone, and described to a model." src="https://cdn-images-1.medium.com/max/1024/1*smNSQF0f_CYOJjQcwD98zw.png" /></figure><h3>The same pattern in Snowflake</h3><p>In Snowflake, Silver can be a dynamic table that refreshes itself within a target lag, so it keeps up with Bronze without a separate scheduler. [1] QUALIFY keeps the deduplication readable:</p><pre>CREATE OR REPLACE DYNAMIC TABLE silver.orders<br>  TARGET_LAG = &#39;15 minutes&#39;<br>  WAREHOUSE = transform_wh<br>AS<br>SELECT b.raw:order_id::STRING AS order_id,<br>       b._source_file, b._loaded_at,<br>       m.status,<br>       CONVERT_TIMEZONE(&#39;UTC&#39;, &#39;Asia/Kolkata&#39;,<br>         b.raw:slot_end::TIMESTAMP_NTZ)          AS slot_end_ist,<br>       CONVERT_TIMEZONE(&#39;UTC&#39;, &#39;Asia/Kolkata&#39;,<br>         b.raw:original_slot_end::TIMESTAMP_NTZ) AS original_slot_end_ist,<br>       CONVERT_TIMEZONE(&#39;UTC&#39;, &#39;Asia/Kolkata&#39;,<br>         b.raw:delivered_at::TIMESTAMP_NTZ)      AS delivered_at_ist<br>FROM bronze.orders b<br>JOIN silver.status_map m<br>  ON m.raw_value = LOWER(TRIM(b.raw:status::STRING))<br>QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id<br>                           ORDER BY b._loaded_at DESC) = 1;</pre><p>CONVERT_TIMEZONE accepts IANA time zone names such as Asia/Kolkata. [2] A named zone is safer than a fixed offset, because it follows the zone’s own rules if FreshBasket ever expands to a city with daylight saving.</p><h3>Contracts: agreeing before the data arrives</h3><p>The mapping table fixes yesterday’s spellings. A data contract prevents tomorrow’s. It is a written agreement between the team that produces a dataset and the teams that use it: the fields, their types, the allowed values, and who to call when something changes. The Open Data Contract Standard gives that agreement a machine-readable YAML format, so checks can be generated from it. [3]</p><p>For the order export, the contract says that status takes one of three values (scheduled, delivered, cancelled), that delivered_at is never empty for a delivered order, and that slot times are always in UTC. The app team owns those promises. When a new app release starts sending “DELIVERED_OK”, the contract turns that into a broken promise with an owner, instead of a mystery in next week’s report. Part 4 turns these promises into checks.</p><h3>Describe Silver for its newest reader</h3><p>Column comments used to be optional. With an assistant reading the warehouse, they are part of the interface. A comment such as “slot_end_ist: end of the customer’s current delivery slot, Pune time; use for any ‘day’ or ‘week’ question” is exactly the context the model was missing in Part 1.</p><h3>What to take away</h3><ol><li><strong>Silver is where decisions live.</strong> Every rule that changed the answer in Part 1 now has one home.</li><li><strong>Use mapping tables for meanings.</strong> The business can review them and models can read them.</li><li><strong>Keep the latest version in Silver, and the history in Bronze.</strong> Deduplication is a rule, not a guess.</li><li><strong>Store UTC and local time side by side.</strong> Say which one answers “day” and “week” questions.</li><li><strong>Contracts stop new spellings at the door.</strong> Write the rules down, with an owner.</li></ol><p>Next in the series: the contract says “three values only”. What happens on the day the app sends a fourth, and how do we catch it before the assistant repeats it? Read <a href="https://medium.com/p/d5bcd6178468">Part 4</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-about">Dynamic tables</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/convert_timezone">CONVERT_TIMEZONE</a> — Snowflake documentation</li><li><a href="https://bitol-io.github.io/open-data-contract-standard/latest/">Open Data Contract Standard</a> — Bitol</li><li><a href="https://docs.databricks.com/aws/en/lakehouse/medallion">What is the medallion lakehouse architecture?</a> — Databricks documentation</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e8fc6532df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Should Bronze Keep So Every Number Can Be Explained? (AI-Ready Data Series, Part 2)]]></title>
            <link>https://medium.com/@manulovesu22/what-should-bronze-keep-so-every-number-can-be-explained-ai-ready-data-series-part-2-152f923d8f8b?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/152f923d8f8b</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-lineage]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:26:25 GMT</pubDate>
            <atom:updated>2026-12-02T18:38:17.975Z</atom:updated>
            <content:encoded><![CDATA[<h4>Raw history in Bronze, and end-to-end lineage that connects every answer to the file it came from.</h4><figure><img alt="Flat illustration for what Bronze should keep so every number can be explained" src="https://cdn-images-1.medium.com/max/1024/1*7A_KbbhvzURWvhWt2nJ61w.png" /></figure><figure><img alt="Part 2, Bronze. The customer call, 27 November: “Your app said my order was due by 10:30. Now your report says 14:30, so it wasn’t late. Which promise did you actually make?”" src="https://cdn-images-1.medium.com/max/1024/1*MPld_pWzV7bvStL0lX7IKA.png" /></figure><p>Order O4 tells a small story. On 25 November the app exported it as scheduled, with a slot ending at 10:30 Pune time. That evening the customer moved the slot to 14:30. On 26 November the app exported it again, now delivered, with the new slot. If the warehouse had simply overwritten the row, the customer’s question would be unanswerable. The first promise, and the file it came from, would be gone.</p><p>In <a href="https://medium.com/p/d1655daedfbd">my last article</a> three teams got three answers to one question. Before anyone can agree on an answer, we need to show where every number came from, and where every field goes. That takes two things: a Bronze layer that keeps everything, and lineage that connects Bronze to every report and every assistant answer.</p><figure><img alt="Animation: Bronze appends, never overwrites. Rows land from two daily files: O3 DLVD and O4 scheduled for 10:30 on 25 Nov, then a duplicate O3 and O4 delivered for 14:30 on 26 Nov. Both promises for O4 survive, each with its file." src="https://cdn-images-1.medium.com/max/1024/1*_cTcKTlnHym7Iw2OJsFbWA.gif" /></figure><figure><img alt="In this article: Bronze is a record, not a cleanup step; four things to keep on every row; landing two daily files; lineage from Bronze to every answer, runnable, its sources, in Snowflake and for the assistant; what not to do; takeaways." src="https://cdn-images-1.medium.com/max/1024/1*1tMLrMo26LuJDbrzTMJaNQ.png" /></figure><h3>Bronze is a record, not a cleanup step</h3><p>In a Medallion design, Bronze holds data as it arrived. Databricks describes it as the raw state of the source in its original format, with metadata columns such as the file name added. [1] The temptation is to fix things on the way in: trim spaces, correct spellings, drop duplicates. Resist it. Every fix in Bronze is a decision you can’t revisit, and Part 3 will need to revisit several.</p><h3>Four things to keep on every row</h3><figure><img alt="Table of four things to keep on every Bronze row: _source_file (which delivery, e.g. orders_2026-11-26.json), _loaded_at (when received), _row_hash (seen this exact row before?), and source columns unchanged, such as “DLVD”, not “delivered”." src="https://cdn-images-1.medium.com/max/1024/1*S3C-dgvtNFjHFl0Mr1OTcA.png" /></figure><h3>Landing two daily files</h3><p>This example appends two daily exports to Bronze and adds the three metadata columns. Nothing is updated and nothing is deleted.</p><pre>import hashlib, sqlite3<br><br>db = sqlite3.connect(&quot;:memory:&quot;)<br>db.execute(&quot;&quot;&quot;CREATE TABLE bronze_orders (<br>    order_id, status, slot_end, original_slot_end, delivered_at,<br>    _source_file, _loaded_at, _row_hash)&quot;&quot;&quot;)<br><br>def land(file_name, loaded_at, rows):<br>    &quot;&quot;&quot;Append rows exactly as received, plus where and when they came from.&quot;&quot;&quot;<br>    for r in rows:<br>        row_hash = hashlib.sha256(<br>            &quot;|&quot;.join(str(v) for v in r).encode()).hexdigest()[:12]<br>        db.execute(&quot;INSERT INTO bronze_orders VALUES (?,?,?,?,?,?,?,?)&quot;,<br>                   (*r, file_name, loaded_at, row_hash))<br><br>land(&quot;orders_2026-11-25.json&quot;, &quot;2026-11-25T20:00&quot;, [<br>    (&quot;O3&quot;, &quot;DLVD&quot;,<br>     &quot;2026-11-25T10:00&quot;, &quot;2026-11-25T10:00&quot;, &quot;2026-11-25T10:05&quot;),<br>    (&quot;O4&quot;, &quot;scheduled&quot;,<br>     &quot;2026-11-26T05:00&quot;, &quot;2026-11-26T05:00&quot;, None),<br>])<br>land(&quot;orders_2026-11-26.json&quot;, &quot;2026-11-26T20:00&quot;, [<br>    (&quot;O3&quot;, &quot;DLVD&quot;,  # re-sent, unchanged<br>     &quot;2026-11-25T10:00&quot;, &quot;2026-11-25T10:00&quot;, &quot;2026-11-25T10:05&quot;),<br>    (&quot;O4&quot;, &quot;delivered&quot;,  # slot moved, then delivered<br>     &quot;2026-11-26T09:00&quot;, &quot;2026-11-26T05:00&quot;, &quot;2026-11-26T08:30&quot;),<br>])<br><br>print(&quot;rows in Bronze:&quot;,<br>      db.execute(&quot;SELECT count(*) FROM bronze_orders&quot;).fetchone()[0])<br>print(&quot;distinct rows: &quot;, db.execute(<br>    &quot;SELECT count(DISTINCT _row_hash) FROM bronze_orders&quot;).fetchone()[0])<br>print(&quot;history of O4:&quot;)<br>for row in db.execute(&quot;&quot;&quot;SELECT status, slot_end, _source_file<br>                         FROM bronze_orders<br>                         WHERE order_id = &#39;O4&#39; ORDER BY _loaded_at&quot;&quot;&quot;):<br>    print(&quot;  &quot;, row)</pre><p>It prints 4 rows in Bronze but only 3 distinct rows, because the re-sent O3 has the same hash. The history of O4 shows “scheduled” with a 05:00 UTC slot from the 25 November file, then “delivered” with a 09:00 UTC slot from the 26 November file. That is 10:30 and 14:30 in Pune. The customer’s question now has an answer, with a file name attached to each promise.</p><figure><img alt="Key idea: If Silver gets a definition wrong, you rebuild it from Bronze. If Bronze is wrong, there is nothing left to rebuild from." src="https://cdn-images-1.medium.com/max/1024/1*YBs0MXoYjOac4k_z7HaGQQ.png" /></figure><h4>Landing in Snowflake</h4><p>In Snowflake, COPY INTO and Snowpipe load files from a stage, and COPY can write metadata columns such as METADATA$FILENAME and METADATA$START_SCAN_TIME into the target table. [8] Landing the whole JSON record in one VARIANT column keeps Bronze safe from schema changes in the app:</p><pre>COPY INTO bronze.orders<br>  (raw, _source_file, _loaded_at)<br>FROM (<br>  SELECT $1, METADATA$FILENAME, METADATA$START_SCAN_TIME<br>  FROM @orders_stage<br>)<br>FILE_FORMAT = (TYPE = JSON);</pre><h3>Lineage: the map from Bronze to every answer</h3><p>Bronze keeps the evidence. Lineage tells you how that evidence travels: which jobs read which fields, what they wrote, and who used the result. Without it, a Bronze table is an archive nobody can navigate. With it, any number in any report, or in any assistant answer, can be walked back to the files it came from, and any change to a source field can be walked forward to everything it affects.</p><p>Lineage answers four different questions, and each needs slightly different data.</p><figure><img alt="Table of four lineage questions. Upstream: which fields feed “5 late deliveries”? Downstream: what breaks if the app renames status? Row provenance: which five orders, from which files? Access and audit: did the assistant read rider names, masked?" src="https://cdn-images-1.medium.com/max/1024/1*5avBBLQuW4ZedCHyLvoJHw.png" /></figure><h4>Four levels of detail</h4><figure><img alt="Four levels of lineage: object lineage, table to table; column lineage, field to field, needed for impact analysis; row provenance, record to record, needed by auditors; consumer lineage, which Power BI visual and assistant tool read the metric." src="https://cdn-images-1.medium.com/max/1024/1*LdIdYN31Hsp64QPQ_GTtag.png" /></figure><figure><img alt="Animated lineage graph. Upstream: three Bronze fields feed Silver columns, gold fct_orders and the late_deliveries metric. Downstream: tracing bronze raw:status forward highlights Silver status, Gold, the metric, Power BI and the assistant." src="https://cdn-images-1.medium.com/max/1024/1*6DD9t2PRCr0yZdRoQu82vw.gif" /></figure><h3>Lineage you can run</h3><p>The example below stores FreshBasket’s column-level lineage as a list of edges, the same shape Snowflake returns, and walks it in both directions. It then traces the headline number back to its rows and files, and finishes with a lineage test.</p><pre>from collections import deque<br><br># Column-level lineage edges: (source, target, how). This is the shape that<br># Snowflake&#39;s ACCESS_HISTORY and GET_LINEAGE give you for each write.<br>B, S, G = &quot;bronze.orders.&quot;, &quot;silver.orders.&quot;, &quot;gold.fct_orders.&quot;<br>M = &quot;metric.late_deliveries&quot;<br>EDGES = [<br>    (B + &quot;raw:status&quot;,       S + &quot;status&quot;,           &quot;status_map join&quot;),<br>    (&quot;silver.status_map.status&quot;, S + &quot;status&quot;,       &quot;status_map join&quot;),<br>    (B + &quot;raw:slot_end&quot;,     S + &quot;slot_end_ist&quot;,     &quot;CONVERT_TIMEZONE&quot;),<br>    (B + &quot;raw:delivered_at&quot;, S + &quot;delivered_at_ist&quot;, &quot;CONVERT_TIMEZONE&quot;),<br>    (B + &quot;_source_file&quot;,     S + &quot;_source_file&quot;,     &quot;carried&quot;),<br>    (S + &quot;status&quot;,           G + &quot;status&quot;,           &quot;copy&quot;),<br>    (S + &quot;slot_end_ist&quot;,     G + &quot;slot_end_ist&quot;,     &quot;copy&quot;),<br>    (S + &quot;delivered_at_ist&quot;, G + &quot;delivered_at_ist&quot;, &quot;copy&quot;),<br>    (S + &quot;_source_file&quot;,     G + &quot;_source_file&quot;,     &quot;carried&quot;),<br>    (G + &quot;status&quot;,           M, &quot;semantic view filter&quot;),<br>    (G + &quot;delivered_at_ist&quot;, M, &quot;semantic view filter&quot;),<br>    (G + &quot;slot_end_ist&quot;,     M, &quot;semantic view time&quot;),<br>    (M, &quot;powerbi.Delivery performance&quot;, &quot;report visual&quot;),<br>    (M, &quot;assistant.pune_assistant&quot;,     &quot;Cortex Analyst tool&quot;),<br>]<br><br>def walk(start, direction):<br>    &quot;&quot;&quot;Breadth-first walk up or down the graph, with distance from start.&quot;&quot;&quot;<br>    step = {}<br>    for s, t, how in EDGES:<br>        a, b = (t, s) if direction == &quot;up&quot; else (s, t)<br>        step.setdefault(a, []).append((b, how))<br>    seen, out, queue = {start}, [], deque([(start, 0)])<br>    while queue:<br>        node, d = queue.popleft()<br>        for nxt, how in step.get(node, []):<br>            if nxt not in seen:<br>                seen.add(nxt); out.append((d + 1, nxt, how))<br>                queue.append((nxt, d + 1))<br>    return out<br><br>print(&quot;UPSTREAM of metric.late_deliveries&quot;)<br>for d, node, how in walk(&quot;metric.late_deliveries&quot;, &quot;up&quot;):<br>    print(f&quot;  {d}  {node:34} via {how}&quot;)<br><br>print(&quot;\nDOWNSTREAM of bronze.orders.raw:status (impact of a change)&quot;)<br>for d, node, how in walk(&quot;bronze.orders.raw:status&quot;, &quot;down&quot;):<br>    print(f&quot;  {d}  {node:34} via {how}&quot;)</pre><p>The same script then traces rows, not just columns: which files fed the five late deliveries, and whether every Gold column has a path back to Bronze.</p><pre># Row-level provenance: the Gold rows behind &quot;5 late deliveries&quot;,<br># with the file each came from.<br>GOLD = [  # order, late?, _source_file<br>    (&quot;O1&quot;, 1, &quot;orders_2026-11-23.json&quot;), (&quot;O2&quot;, 1, &quot;orders_2026-11-24.json&quot;),<br>    (&quot;O3&quot;, 1, &quot;orders_2026-11-26.json&quot;), (&quot;O4&quot;, 0, &quot;orders_2026-11-26.json&quot;),<br>    (&quot;O5&quot;, 1, &quot;orders_2026-11-23.json&quot;), (&quot;O7&quot;, 0, &quot;orders_2026-11-27.json&quot;),<br>    (&quot;O9&quot;, 1, &quot;orders_2026-11-28.json&quot;),<br>]<br>late = [(o, f) for o, is_late, f in GOLD if is_late]<br>print(f&quot;\nPROVENANCE of &#39;{len(late)} late deliveries&#39;&quot;)<br>for o, f in late:<br>    print(f&quot;  {o}  from {f}&quot;)<br><br># A lineage test: every Gold column must trace back to Bronze.<br>gold_cols = {n for e in EDGES for n in e[:2] if n.startswith(&quot;gold.&quot;)}<br>orphans = [c for c in sorted(gold_cols)<br>           if not any(n.startswith(&quot;bronze.&quot;) for _, n, _ in walk(c, &quot;up&quot;))]<br>print(&quot;\nGold columns with no path to Bronze:&quot;, orphans or &quot;none&quot;)</pre><p>Upstream, the metric reaches three Gold columns at distance 1, three Silver columns at distance 2, and four sources at distance 3: three Bronze fields plus the status_map table from Part 3. Downstream, a change to the app’s status field reaches five places, ending at distance 4 in both the Power BI report and the Pune assistant. That is the list of people to warn before the app team ships a rename.</p><p>The provenance section lists the five late orders, O1, O2, O3, O5 and O9, each with its daily file. That works only because _source_file was carried from Bronze through Silver into Gold. The final test prints “none”: every Gold column has a path back to Bronze. Run it on every deployment, and a Gold column that appears from nowhere becomes a failed build, not a mystery.</p><figure><img alt="Key idea: If you can’t trace a number, you can’t trust it, and you can’t fix it. Lineage is how an answer earns the word “because”." src="https://cdn-images-1.medium.com/max/1024/1*nEsx493QZ8yMyekoTkbALw.png" /></figure><h3>Where lineage comes from</h3><p>No single source gives you all four levels. Mature platforms combine three.</p><figure><img alt="Table of three lineage sources. Query logs at run time: object and column lineage, but only what ran. Code at design time: dbt and SQL, but manual SQL is invisible. Carried columns in the data: row provenance, which must be designed in from Bronze." src="https://cdn-images-1.medium.com/max/1024/1*x-K3irnv2ZxlQLThsgUhnQ.png" /></figure><h3>Lineage in Snowflake</h3><p>On Enterprise Edition, Snowflake records lineage automatically for CTAS, INSERT … SELECT, MERGE, UPDATE, COPY INTO, clones and views, and shows it in the Lineage tab of Snowsight, including column-level lineage between table-like objects. [2] The same graph is available in SQL through the GET_LINEAGE table function, in either direction, up to five levels deep. [3]</p><pre>SELECT distance, source_object_name,<br>       target_object_name<br>FROM TABLE(SNOWFLAKE.CORE.GET_LINEAGE(<br>  &#39;freshbasket.gold.fct_orders&#39;, &#39;TABLE&#39;, &#39;UPSTREAM&#39;, 3));</pre><p>Underneath sits ACCOUNT_USAGE.ACCESS_HISTORY. For every write, its objects_modified column lists each target column with directSources, the columns named in the write, and baseSources, the underlying columns they came from. [4] Flattening it gives a column-to-column edge list, the same shape as EDGES above:</p><pre>SELECT ah.query_start_time,<br>       om.value:&quot;objectName&quot;::STRING  AS target_table,<br>       col.value:&quot;columnName&quot;::STRING AS target_column,<br>       src.value:&quot;objectName&quot;::STRING AS source_table,<br>       src.value:&quot;columnName&quot;::STRING AS source_column<br>FROM SNOWFLAKE.ACCOUNT_USAGE.ACCESS_HISTORY ah,<br>     LATERAL FLATTEN(input =&gt; ah.objects_modified)  om,<br>     LATERAL FLATTEN(input =&gt; om.value:&quot;columns&quot;)   col,<br>     LATERAL FLATTEN(input =&gt; col.value:&quot;directSources&quot;) src<br>WHERE om.value:&quot;objectName&quot;::STRING = &#39;FRESHBASKET.GOLD.FCT_ORDERS&#39;<br>  AND ah.query_start_time &gt;= DATEADD(day, -7, CURRENT_TIMESTAMP());</pre><p>ACCESS_HISTORY also records the masking and row access policies applied to each query, which covers the fourth question in the table above. Its latency can be up to three hours. [4]</p><h4>Know the gaps</h4><ul><li><strong>Semantic views.</strong> Snowflake doesn’t record column-level lineage into semantic views, so the metric-to-column edges in the example must come from the view definition itself. [2]</li><li><strong>Filters and joins.</strong> Tables used only to filter or join, with no data moving, are left out of the graph. [2]</li><li><strong>Separate statements.</strong> Data moved across disconnected queries, for example inside stored procedures, isn’t linked. [2] Carried columns such as _source_file fill that gap.</li><li><strong>Retention.</strong> Object and column lineage is kept for one year. [2] Export it if audits need longer.</li></ul><h4>Beyond the warehouse</h4><p>The first and last hops live outside Snowflake: the delivery app before Bronze, and Power BI and the assistant after Gold. OpenLineage is an open standard for lineage events, an LF AI &amp; Data project with integrations for Airflow, dbt and Spark. [5]</p><p>Snowflake’s external lineage accepts OpenLineage events through a REST endpoint and shows them in the same Snowsight graph. [6] On the reporting side, Power BI’s lineage view shows how data sources, semantic models, reports and dashboards connect inside a workspace. [7] Joined up, these give one map from the app’s export to the assistant’s answer.</p><h3>Lineage for the assistant</h3><p>Lineage changes what an assistant can say. Instead of “5 orders were late,” it can answer: “5 orders were late, from the late_deliveries metric in gold.delivery_performance, built from silver.orders; orders O1, O2, O3, O5 and O9, loaded from four daily files.” The same applies to documents. Each policy chunk in Part 6 carries its source PDF and version, which is lineage at document level, and Part 7 returns it as a citation.</p><p>That also makes the agreement test in Part 9 sharper. When two routes disagree, lineage shows exactly where their paths split.</p><h3>What not to do</h3><ul><li><strong>Don’t overwrite Bronze.</strong> An update destroys the earlier promise and the reason it changed.</li><li><strong>Don’t clean in Bronze.</strong> “DLVD” stays “DLVD” here. Part 3 decides what it means.</li><li><strong>Don’t drop provenance columns in Silver or Gold.</strong> Once _source_file is gone, row provenance is gone with it.</li><li><strong>Don’t trust a lineage tool you haven’t tested.</strong> Check that every Gold column has a path to Bronze on every deployment.</li></ul><h3>What to take away</h3><ol><li><strong>Bronze is a record of what arrived.</strong> Append, never overwrite, and keep source values unchanged.</li><li><strong>Add provenance columns at landing.</strong> Source file, load time and a row hash, carried all the way to Gold.</li><li><strong>Lineage answers four questions.</strong> Upstream, downstream impact, row provenance, and access.</li><li><strong>Combine three sources.</strong> Query logs, code, and carried columns each fill the others’ gaps.</li><li><strong>Test lineage like code.</strong> No Gold column without a path to Bronze.</li></ol><p>Next in the series: Bronze still says “delivered”, “Delivered” and “DLVD”, and keeps every version of every order. How does Silver give each word one meaning? Read <a href="https://medium.com/p/4e8fc6532df2">Part 3</a>.</p><p><strong>Enjoyed this?</strong> Follow me on Medium for more hands-on guides. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://docs.databricks.com/aws/en/lakehouse/medallion">What is the medallion lakehouse architecture?</a> — Databricks documentation</li><li><a href="https://docs.snowflake.com/en/user-guide/ui-snowsight-lineage">Data lineage</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/get_lineage-snowflake-core">GET_LINEAGE (SNOWFLAKE.CORE)</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/account-usage/access_history">ACCESS_HISTORY view</a> — Snowflake documentation</li><li><a href="https://openlineage.io/docs/">OpenLineage documentation</a> — OpenLineage</li><li><a href="https://docs.snowflake.com/en/user-guide/external-lineage">External lineage</a> — Snowflake documentation</li><li><a href="https://learn.microsoft.com/en-us/power-bi/collaborate-share/service-data-lineage">Data lineage in Power BI</a> — Microsoft Learn</li><li><a href="https://docs.snowflake.com/en/user-guide/querying-metadata">Querying metadata for staged files</a> — Snowflake documentation</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=152f923d8f8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Every Decision Need an LLM? (AI Engineering Series, Part 16)]]></title>
            <link>https://medium.com/@manulovesu22/does-every-decision-need-an-llm-ai-engineering-series-part-16-eb1158c4d7fe?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb1158c4d7fe</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:25:40 GMT</pubDate>
            <atom:updated>2026-12-02T18:25:40.154Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fast decision models, the evidence on speed and calibration, and how to gate an assistant without asking a large model every small question.</h4><figure><img alt="Flat illustration of a small switch box with a lever choosing one of three short paths (to a green locker, a staff bell or a closed gate), with a gauge dial and stopwatch in front and a larger glowing core in a control desk in the background." src="https://cdn-images-1.medium.com/max/1024/1*kzE5c8W6Js64qXnpeyqOEw.png" /></figure><figure><img alt="Card: SATURDAY RUSH · 11:40 A.M. “Half our model calls just decide which queue a message belongs in. Do we really need the big model to sort the post?”" src="https://cdn-images-1.medium.com/max/1024/1*IwhQSBJGKY_4mvNPxDpsLA.png" /></figure><p>On a busy Saturday the East Hall assistant makes several decisions before it writes a single word. Is this message about tickets, lost property or opening times? Is it urgent? Did the visitor really ask for the tool call the model just proposed? Each of those is a small question with a short list of answers, and each one, in our design so far, costs a full call to a large language model.</p><p>New to the series? We’ve been building an assistant for a venue’s East Hall help desk that tells visitors where their tickets are.</p><p>A large model can answer those questions. It writes a word, the harness parses it, and the result is one label with no reliable sense of how sure the model was. For routing that may be acceptable. For deciding whether a tool call needs staff, “how sure” is the whole point.</p><p>This part looks at a different kind of model, built only to make that sort of decision: what it is, what the evidence says about its speed and calibration, and where it breaks.</p><p>In <a href="https://medium.com/p/af02015615fb">Part 9</a> we built the harness around the model: the system prompt, the validating executor and the context budget. This part asks which of the harness’s decisions need a large model at all.</p><figure><img alt="A fast decider gates proposed tool calls: get_locker runs at 0.96 and asks at 0.55, reassign_locker goes to staff at 0.91 and is refused at 0.08, and a timeout falls back to the LLM path." src="https://cdn-images-1.medium.com/max/840/1*01JuHzS64izv0zmaWrutJQ.gif" /></figure><p><strong>Level:</strong> Practitioner to senior · <strong>Best for:</strong> engineers and architects running assistants or agents at volume · <strong>Read first:</strong> <a href="https://medium.com/p/653e3e2b1883">Part 7 on evaluation</a></p><blockquote><strong><em>Plain English:</em></strong><em> A decision model doesn’t write text. You give it the situation and a fixed list of answers, and it returns a probability for each answer in one step. Your code then decides what to do with that probability.</em></blockquote><h4>In this article</h4><ol><li><a href="#a126">The small decisions inside every request</a></li><li><a href="#3db8">What a System 1 decision model is</a></li><li><a href="#c408">Latency and cost: read the source line</a></li><li><a href="#ffdc">Calibration is what makes a probability usable</a></li><li><a href="#a78d">A gate the model can’t argue with</a></li><li><a href="#8d0b">Where one pass is not enough</a></li><li><a href="#42e6">What to take away</a></li></ol><h3>The small decisions inside every request</h3><p>Look at one message the way the harness sees it. Three of the jobs are decisions with a closed set of answers: route the message, triage it, and gate any tool call the model proposes. One job is plain logic: which desk-log record is valid right now, and which handbook rule applies. One job really is generation: writing an answer that keeps the rule’s condition and cites it.</p><figure><img alt="Card: ONE VISITOR MESSAGE, THREE KINDS OF WORK “My son lost our tickets. Can my sister collect new ones?” ↓ FAST DECIDER · ONE PASS Route: tickets, lost property or general? Triage: urgent or routine? Gate: did the visitor ask for this tool call? ↓ PLAIN CODE Which desk-log record is valid now? Thresholds, staff rules, counts ↓ LLM Write the answer with the handbook rule and its condition, and cite it" src="https://cdn-images-1.medium.com/max/1024/1*QFE7AorVZB2Jqzq9Tht8cA.png" /></figure><p>A generative model can do all three kinds of work, but it is built for the last one. <a href="https://medium.com/p/15c68daac4b7">Part 1</a> described how it produces text one token at a time, each token another pass through the network. When all you need is one of three labels, you pay for a general-purpose writer to fill in a form. And the label comes back without a dependable probability attached, unless you do extra work to get one.</p><h3>What a System 1 decision model is</h3><p>A recent survey defines a System 1 decision model as one “whose primary inference interface maps an input state to a bounded, structured decision”: a label, a bounded score or a probability, without free-form generation. [1] The name borrows the psychologist’s fast-and-slow distinction, and the author is explicit that it is an analogy for organizing architectures, “not as a claim” that networks implement human dual-process cognition. [1]</p><p>One commercial example is Jev, which TypeSafe AI announced on 15 September 2026 as the first of what it calls System One models, available in early access. [2] Its documentation lists three question types for text. [3]</p><ul><li><strong>Choice</strong> picks one option from a list and returns the choice, a probability for each option and a confidence.</li><li><strong>Score</strong> rates the state on a rubric and returns the score, the probabilities and a confidence.</li><li><strong>Noul</strong> asks whether a statement is true and returns a single probability between 0 and 1.</li></ul><p>A fourth type, Box, locates something in an image. [3] TypeSafe says all outputs are defined in advance and produced together in one query rather than token by token, and that the model is trained with what it calls Reinforcement Learning for Calibrated Decisions. [2] By TypeSafe’s own description, Jev is not a small text generator: it gives up string generation. [2]</p><p>For a short video introduction, IBM Technology’s explainer describes Jev as a System 1 model that makes fast decisions with calibrated probabilities, with uses such as routing, classification and guardrails. [4]</p><blockquote><strong><em>Plain English:</em></strong><em> Calibrated means the probabilities mean what they say. Of all the answers a model gives with probability 0.8, about 80% should turn out to be right.</em></blockquote><p>Jev is not the only option. The survey groups System 1 models into five families, from encoder classifiers to extraction models, and lists open-source decision models, some offering what it calls Jev-compatible primitives or APIs. [1] A study of 2,170 public GitHub projects using Jev found attribute judgment in 77% of them, scoring or ranking in 52% and action selection in 31%. [5]</p><p>You can also make an ordinary LLM behave like one. Li and Wagle’s LLM-as-Jev puts the state and numbered options in one prompt, prefills the reply with “Best answer: [”, and reads each option’s probability from the model, with no free-text generation. They report that, off the shelf, frozen models “match or exceed existing training-free readouts on the same 4B backbone” (4B means about four billion parameters). [6] A team that already serves an open model can try the pattern without a new vendor.</p><h3>Latency and cost: read the source line</h3><p>The headline numbers come from different kinds of source, and that matters.</p><figure><img alt="Card: WHO MEASURED WHAT Claim Source 70–500 ms, $0.042 per million input tokens Vendor launch post 194 ms median for a 4B LLM used as a decider Preprint, one GPU, unoptimized 97.5% vs 74% on one-pass vs reasoning items Preprint, Jev 1.13.0 Stale summary chosen in 61–100% of items Preprint, controlled benchmark Wrong answer in 54% of responses on 30 conjunction tasks Preprint, 15,000 responses" src="https://cdn-images-1.medium.com/max/1024/1*JJ8qQcJRnuckdUHsDqrtOw.png" /></figure><p>TypeSafe reports end-to-end response times of 70 to 500 milliseconds and input pricing of $0.042 per million tokens, with output tokens free. [2] Those are vendor figures, and the launch post lists its own caveats: the comparison LLMs ran through a wrapper that constrains their output, which may make them slower and more expensive than usual, the demo favors short, dense inputs, its reference answers lean toward OpenAI and Anthropic models, and the company says it cannot yet prove its pricing is not subsidized. [2]</p><p>One preprint that tested Jev describes it in passing as returning probabilities “in about 0.2 s,” but reports no timing benchmark. [7]</p><p>For the do-it-yourself route, the LLM-as-Jev paper gives an independent anchor: “On a single RTX A5500, median latency is 194 ms for 4B and 76 ms for 0.6B.” The authors note this used an unoptimized FP32 (full 32-bit precision) implementation. [6] The survey puts typical LLM decisions at 500 milliseconds to 5 seconds against 10 to 70 milliseconds for specialized models, and says the gap depends on model size, input length, hardware, batch size and serving. [1]</p><blockquote><strong><em>Key point:</em></strong><em> All five 2026 papers cited here are preprints, and the speed and price figures are vendor-reported, measured on one setup, or broad ranges from a survey. Treat them as reasons to run your own benchmark, not as the result of one.</em></blockquote><h3>Calibration is what makes a probability usable</h3><p>A decision model is only worth gating on if its probabilities are honest. Two measures check that. The <strong>Brier score</strong> is the mean squared gap between the stated probability and what happened (1 or 0); lower is better. <strong>Expected calibration error</strong> (ECE) groups predictions by stated probability and averages, weighted by group size, the gap between what each group said and how often it was right. [1, 8]</p><p>Guo and colleagues showed in 2017 that modern neural networks are often poorly calibrated, and that a one-parameter fix, temperature scaling, corrects much of it. [8]</p><p>The demo scores two made-up deciders on 20 labeled desk messages. The question is whether a message needs a staff member. Decider B makes exactly the same calls as decider A but always states them at 0.99 or 0.01: the same answers, said louder.</p><pre># 1 = the message needs a staff member, 0 = it doesn&#39;t (toy labels)<br>LABELS = [1, 1, 1, 1, 0,  1, 1, 1, 0, 0,<br>          1, 0, 0, 0, 0,  0, 0, 0, 0, 0]<br># Two made-up deciders: P(needs staff) for the same 20 messages<br>A = [.9, .9, .9, .9, .9,  .65, .65, .65, .65, .65,<br>     .3, .3, .3, .3, .3,  .1, .1, .1, .1, .1]<br>B = [.99 if p &gt; .5 else .01 for p in A]  # same calls, louder<br><br>def accuracy(probs):<br>    hits = [(p &gt; .5) == bool(y) for p, y in zip(probs, LABELS)]<br>    return sum(hits) / len(hits)<br><br>def brier(probs):<br>    pairs = list(zip(probs, LABELS))<br>    return sum((p - y) ** 2 for p, y in pairs) / len(pairs)<br><br>def ece(probs, bins=5):<br>    total, gap = len(probs), 0.0<br>    for b in range(bins):<br>        lo, hi = b / bins, (b + 1) / bins<br>        group = [(p, y) for p, y in zip(probs, LABELS)<br>                 if lo &lt;= p &lt; hi or (b == bins - 1 and p == 1)]<br>        if group:<br>            said = sum(p for p, _ in group) / len(group)<br>            saw = sum(y for _, y in group) / len(group)<br>            gap += len(group) / total * abs(said - saw)<br>    return gap<br><br>for name, probs in [(&quot;A&quot;, A), (&quot;B&quot;, B)]:<br>    print(f&quot;{name}: accuracy {accuracy(probs):.2f}, &quot;<br>          f&quot;Brier {brier(probs):.3f}, ECE {ece(probs):.3f}&quot;)</pre><p>It prints A: accuracy 0.80, Brier 0.148, ECE 0.087 and B: accuracy 0.80, Brier 0.196, ECE 0.190. Accuracy cannot tell them apart. Brier and ECE can: B is wrong four times, three at 0.99 and one at 0.01, and a gate built on its numbers would act on all four without pausing. Twenty items are far too few for a real ECE; this is the method, not a result.</p><p>The published numbers for Jev vary by task and by evaluator. One preprint measured an ECE of 0.03 on its synthetic state-tracking items. [7] The survey cites an independent evaluation that finds Jev’s Choice probabilities “well calibrated,” though binary Noul probabilities “require threshold tuning.” It also cites an ECE of 0.246 for Jev, reported alongside the open Laya model’s own result. [1]</p><p>Li and Wagle report ECE 0.057 for a 4B LLM-as-Jev and 0.278 at 0.6B, with no temperature scaling. [6] Model size and task change calibration a lot, so measure it on your own labeled messages, the way Part 7 built a test set, before you trust any threshold.</p><h3>A gate the model can’t argue with</h3><p>Once you have a probability you trust, the gate itself is ordinary code. TypeSafe’s documentation suggests starting a Noul with 0.7 for yes and 0.3 for no, treating the band in between as its own outcome, and setting stricter thresholds for riskier actions. [9] Its tool-call safety gate cookbook applies the same idea to an agent: a Choice between run, review and refuse, with low-confidence calls sent to review. [10] The function below gates the East Hall tools on one question: did the visitor ask for this call?</p><pre>NEEDS_STAFF = {&quot;reassign_locker&quot;}  # Part 6: never runs unattended<br>YES, NO = 0.7, 0.3                 # starting bands; tune on your data<br><br>def gate(tool, p):<br>    &quot;&quot;&quot;p = P(the visitor asked for this call), from a fast decider.&quot;&quot;&quot;<br>    if p is None or not 0 &lt;= p &lt;= 1:<br>        return &quot;send to the LLM path&quot;   # decider down or bad output<br>    if p &lt;= NO:<br>        return &quot;refuse: not requested&quot;<br>    if tool in NEEDS_STAFF:<br>        return &quot;queue for staff confirmation&quot;<br>    if p &gt;= YES:<br>        return &quot;run&quot;<br>    return &quot;ask the visitor to confirm&quot;<br><br>calls = [<br>    (&quot;get_locker&quot;, 0.96),<br>    (&quot;get_locker&quot;, 0.55),<br>    (&quot;reassign_locker&quot;, 0.91),<br>    (&quot;reassign_locker&quot;, 0.08),  # text pasted into a visitor message<br>    (&quot;get_rule&quot;, None),         # decider timed out<br>]<br>for tool, p in calls:<br>    print(f&quot;{tool:16} {str(p):5} -&gt; {gate(tool, p)}&quot;)</pre><p>It prints run for the clear read request, ask the visitor to confirm for the one at 0.55, queue for staff confirmation for the requested move, refuse: not requested for the move at 0.08, and send to the LLM path when the decider times out.</p><p>Notice what the probability is allowed to do. It can refuse a call or add a question, but it can never remove the staff confirmation that <a href="https://medium.com/p/ef80c91f1510">Part 6</a> put on reassign_locker. A missing or malformed answer falls back to the slower path; it is never read as “yes.” The decider adds a cheap check in front of the executor from Part 9. It does not replace it.</p><p>A LangChain blog post adds Jev to a harness like Part 9’s. Its langchain-typesafe package offers a TypeSafeClassifier that answers Noul questions, plus two middlewares under an experimental module path: ModelRouterMiddleware picks one model per run from the latest user message, and AutoModeMiddleware checks tool calls, such as bash, and blocks risky ones before they run. [11]</p><p>The post notes that Jev evaluates every question in a request in parallel, and repeats TypeSafe’s claim of “up to 200x faster inference and 400x lower cost” than comparable LLMs on classification tasks, without describing how it was measured. It adds that “Jev isn’t a drop-in replacement for an LLM,” and says plainly: “Agents are still inherently untrustworthy.” [11]</p><p>Here is the whole gated system on one page.</p><figure><img alt="Diagram: A FAST GATE IN FRONT OF THE EXECUTOR Visitor chat 1 message ↓ YOUR APPLICATION Harness Asks the small questions first 2 state + fixed list of answers ↓ DECISION MODEL Fast decider Route, triage, P(visitor asked) Vendor or self-hosted MODEL PROVIDER LLM Writes the cited answer; fallback path 3 probability, or none ↓ YOUR APPLICATION Gate, plain code KEY CONTROL ≤0.3 refuse · 0.3–0.7 ask · ≥0.7 run · no answer: LLM pat" src="https://cdn-images-1.medium.com/max/1024/1*_cGGRRcmG_w7qaasy3hQMw.png" /></figure><h3>Where one pass is not enough</h3><p>The most useful evidence so far is about limits. Yang and colleagues tested Jev 1.13.0 on real decision tasks: it answered 97.5% of the items that one forward pass of a reference LLM solves, “but only 74% of those that need reasoning.” Their conclusion is blunt: “Jev cannot make a decision that an LLM makes only by writing out intermediate steps.” [7]</p><p>The second finding matters for this series. On the paper’s controlled synthetic benchmark, when the input held a stale summary of the state, Jev picked the stale state “in 61–100% of the items that offer it as an option,” and its confidence did not flag those errors (AUROC 0.53, where 0.5 is a coin flip). [7] That is Part 9’s jammed red locker again: a fast decider fed an old summary is fast and wrong. Feed it the open desk-log record, not the model’s notes.</p><p>A bias study of 41,500 Jev 1.13.0 responses found a mixed picture. In one conjunction test, reversing the answer order changed the probabilities but never the chosen answer; in a zero-risk test, order moved the selection rate of the option with the larger overall risk reduction from 99.6% to 65.6%. Across 30 further conjunction scenarios, Jev chose the wrong answer in 53.96% of responses. [12]</p><p>TypeSafe’s own “jaggedness” page is candid in the same direction: Jev leans toward the first option, is unreliable at arithmetic and counting, and “reads dates as text, not as ordered quantities.” [13] So the validity windows from <a href="https://medium.com/p/033aa4b6f4a4">Part 2</a> stay in code. Is 12:15 inside record B? Ask Python, not a model.</p><p>IBM Technology’s security explainer says: “A confident AI decision isn’t necessarily a trustworthy one.” It covers poisoned inputs, separating confidence from evidence, observability and independent controls. [14] The stale summary above is a small case of the same problem.</p><blockquote><strong><em>Principal’s note:</em></strong><em> I would adopt a decision model the way I would adopt any classifier: behind a fallback, on a labeled sample of real traffic, with calibration checked before thresholds are set and rechecked when the inputs drift. Put it where decisions are closed, frequent and cheap to get wrong once: routing and first-pass triage. Keep anything that needs a chain of steps, a date comparison or the final word on a change with code, a reasoning model or a person.</em></blockquote><h3>What to take away</h3><ol><li><strong>Not every decision needs generation.</strong> Routing, triage and gating have closed answers; a one-pass decision model or an LLM read as one can return a probability for each.</li><li><strong>Read the source line on every number.</strong> Speed and price claims are vendor-reported, measured on one setup or broad survey ranges, and the papers are preprints.</li><li><strong>Accuracy hides overconfidence.</strong> Check Brier score and ECE on your own labeled messages before you set a threshold.</li><li><strong>Probabilities can tighten a gate, never loosen one.</strong> Staff confirmation and the validating executor stay, and a missing answer falls back to the slower path.</li><li><strong>Keep multi-step reasoning, dates and state checks out of one pass.</strong> Feed the decider the system of record, not a summary.</li></ol><h4>Next in the series</h4><p>This part closes the second half of the series for now: from the harness, through reasoning, tools, agents, production safety, cost and new modalities, to the question of when no large model is needed at all. For the full reading order, and for new parts as they arrive, see <a href="https://medium.com/p/3fb1cf707a00">The AI Engineering Series: Start Here</a>.</p><p><strong>Enjoyed this?</strong> <a href="https://medium.com/@manulovesu22">Follow me on Medium</a> for more hands-on guides. If you work with enterprise data, the <a href="https://medium.com/p/d1655daedfbd">AI-Ready Data Series</a> shows how to get your tables and documents ready for AI assistants. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://arxiv.org/abs/2610.33775">The Hitchhiker’s Guide to System 1 Models: Fast Decision-Making Beyond LLMs</a> — Roitman, 2026 (preprint)</li><li><a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">Introducing System One Models &amp; Jev</a> — TypeSafe AI, 2026 (vendor announcement)</li><li><a href="https://docs.typesafe.ai/introduction">Introduction to Jev and its question types</a> — TypeSafe documentation, 2026</li><li><a href="https://www.youtube.com/watch?v=YGgNBcIgI4s">What Is Jev? The AI Model That Doesn’t Generate Text</a> — Martin Keen, IBM Technology (YouTube), 1 October 2026</li><li><a href="https://arxiv.org/abs/2609.30216">Jev in the Wild: A Data-Driven Analysis of the Jev Model’s Functionality, Applications and Ecosystem</a> — Ling, Xue and Ye, 2026 (preprint)</li><li><a href="https://arxiv.org/abs/2610.02076">LLM-as-Jev: LLMs Are Already Jev-Style Decision Models — When and How to Fine-Tune Them</a> — Li and Wagle, 2026 (preprint)</li><li><a href="https://arxiv.org/abs/2610.24929">What Can’t Jev Decide? Probing the Limits of One-Pass Decision Models</a> — Yang et al., 2026 (preprint)</li><li><a href="https://arxiv.org/abs/1706.04599">On Calibration of Modern Neural Networks</a> — Guo et al., 2017</li><li><a href="https://docs.typesafe.ai/confidence.md">Confidence</a> — TypeSafe documentation, 2026</li><li><a href="https://docs.typesafe.ai/cookbooks/langchain_safety_gate.md">Tool-call safety gate</a> — TypeSafe documentation, 2026</li><li><a href="https://www.langchain.com/blog/building-a-harness-with-jev">Building a Harness with Jev</a> — Sydney Runkle and Hunter Lovell, LangChain blog, 17 September 2026</li><li><a href="https://arxiv.org/abs/2610.19619">Are AI Decision Models Biased? A Case Study of Jev</a> — Imperatrice et al., 2026 (preprint)</li><li><a href="https://docs.typesafe.ai/model-jaggedness.md">Model jaggedness</a> — TypeSafe documentation, 2026</li><li><a href="https://www.youtube.com/watch?v=_yO_Q7qo0HQ">The Problem with Jev: Can You Trust AI Decisions?</a> — Jeff Crume, IBM Technology (YouTube), 20 October 2026</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb1158c4d7fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Changes When the Assistant Can See and Hear? (AI Engineering Series, Part 15)]]></title>
            <link>https://medium.com/@manulovesu22/what-changes-when-the-assistant-can-see-and-hear-ai-engineering-series-part-15-35448cb10f8c?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/35448cb10f8c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[multimodal]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:25:05 GMT</pubDate>
            <atom:updated>2026-12-02T18:37:46.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>Images as patches, documents as layout, speech as transcripts, and why every new input is one more thing to test.</h4><figure><img alt="Flat illustration of a glowing core in a control desk, with a clipped photo of a green locker door under a camera-lens icon on one side, an old desk telephone with sound waves and a microphone on the other, and a document with a simple table in front." src="https://cdn-images-1.medium.com/max/1024/1*HMVdZyy-cX7IuNimfbARoA.png" /></figure><figure><img alt="Card: THE PHOTO · 12:25 P.M. “Here’s a photo of my ticket. It says locker red, but the red locker won’t open.”" src="https://cdn-images-1.medium.com/max/1024/1*e4h_S5odvV1o4l7bzNIpyA.png" /></figure><p>At 12:25 a visitor sends the East Hall desk a photo with a one-line message instead of a typed question. The ticket in the picture is printed clearly: booking K742, locker red. The photo is accurate. It is also out of date, because the red locker jammed at 12:20 and the tickets moved to green. (New to the series? We’ve been building an assistant for a venue’s East Hall help desk that tells visitors where their tickets are.)</p><p>A minute later the visitor’s mother rings the desk: can her daughter collect the passes? This question arrives as sound, over a phone line, with a café in the background.</p><p>Neither input changes what is true. The desk log still says record C, green, from 12:20, and the handbook still says a representative needs written authorization. What changes is how the assistant hears the question, and how many new ways it can mishear it.</p><p>In Part 14 we made the assistant faster and cheaper. Until now every input has been typed text. This part opens two new doors, sight and sound. Less changes behind them than you might expect, as long as the harness from <a href="https://medium.com/p/af02015615fb">Part 9</a> stays in charge.</p><figure><img alt="A ticket photo is read as booking K742, locker red; the harness checks the desk log at 12:25 and answers green (record C); a phone call’s transcript is checked like text, and a call is not written authorization under rule P7." src="https://cdn-images-1.medium.com/max/840/1*kpXAlg-UpB0kW8apCaNHcA.gif" /></figure><p><strong>Level:</strong> Practitioner to senior · <strong>Best for:</strong> engineers and architects adding photos, documents or voice to an assistant · <strong>Read first:</strong> <a href="https://medium.com/p/15c68daac4b7">Part 1 on tokens</a></p><blockquote><strong><em>Plain English:</em></strong><em> A multimodal model accepts more than one kind of input, such as text and images. Speech-to-text turns audio into a written transcript. Text-to-speech does the reverse. OCR (optical character recognition) reads printed or written characters from an image.</em></blockquote><h4>In this article</h4><ol><li><a href="#fa6e">A photo becomes tokens too</a></li><li><a href="#9594">A reading is a claim, not a fact</a></li><li><a href="#aae3">Documents: OCR, layout and vision models</a></li><li><a href="#274a">When the visitor calls</a></li><li><a href="#ef49">Intent bots and LLMs</a></li><li><a href="#8cf0">Each modality needs its own test</a></li><li><a href="#b1fb">What to take away</a></li></ol><h3>A photo becomes tokens too</h3><p>In <a href="https://medium.com/p/15c68daac4b7">Part 1</a>, text became tokens and tokens became vectors. Images take the same road with a different first step. The Vision Transformer paper, titled “An Image is Worth 16x16 Words,” showed that a plain transformer applied to a sequence of image patches can classify images very well. [1] Cut the picture into small squares, turn each square into a vector, and the model attends over them as it does over words.</p><p>LLaVA, an early open vision-language model, used a trainable projection to convert the image encoder’s features into “language embedding tokens” with the same size as the language model’s word embeddings. [2] To the language model, the photo is a run of extra tokens beside the question.</p><p>That has a direct cost. Anthropic documents that Claude processes images in 28×28-pixel patches, so an image within the size limits costs about ⌈width ÷ 28⌉ × ⌈height ÷ 28⌉ visual tokens. Larger images are downsized to fit a per-model limit. On the standard tier the long edge is at most 1,568 pixels and the cost at most 1,568 tokens. Claude 4.7 and later models use a high-resolution tier of up to 2,576 pixels and 4,784 tokens. [3]</p><pre>import math<br><br>def visual_tokens(width, height):<br>    # Anthropic&#39;s documented estimate: one token per 28x28-pixel patch,<br>    # for images already inside the size limits (no resizing).<br>    return math.ceil(width / 28) * math.ceil(height / 28)<br><br>photos = [(&quot;whole photo, 1092x819&quot;, 1092, 819),<br>          (&quot;label cropped, 560x280&quot;, 560, 280)]<br>for name, w, h in photos:<br>    print(f&quot;{name}: {visual_tokens(w, h)} visual tokens&quot;)<br><br>question = &quot;Where are my East Hall tickets? My label says red.&quot;<br>print(f&quot;the question: about {len(question) // 4} text tokens&quot;)</pre><p>It prints whole photo, 1092x819: 1170 visual tokens, label cropped, 560x280: 200 visual tokens and the question: about 12 text tokens (a rough four-characters-per-token estimate). The photo outweighs the question about a hundred to one, and cropping to the label cuts it more than fivefold. The same documentation warns that downsizing can make text harder to read, and that the model may err on low-quality, rotated or very small images. [3] Crop for cost, then test that the crop still reads.</p><blockquote><strong><em>Key point:</em></strong><em> An image is not free context. Its tokens compete with the evidence for attention and budget, so size it on purpose.</em></blockquote><h3>A reading is a claim, not a fact</h3><p>Suppose the model reads the photo perfectly: booking K742, locker red. Answering from the photo would send the visitor straight back to the jammed locker.</p><p>The ticket shows what was printed when the booking was made. The desk log shows where the tickets are now. Only one of them has a validity window. So the harness treats the reading like any model output, as input to check: it extracts the booking reference, validates its format, looks it up in the desk log at 12:25 and answers from record C.</p><p>The photo’s “red” becomes context for the reply, not the answer: “Your ticket was printed for the red locker. That locker jammed at 12:20, and your tickets are now in green.”</p><figure><img alt="Card: TWO NEW DOORS, ONE HARNESS A PHOTO ARRIVES Image becomes patches, then tokens Model reads: “red”, booking K742 A claim to check A CALL ARRIVES Speech-to-text writes a transcript Transcript: “my label says red” A claim to check ↓ 01 Same harness as Part 9 Look up K742 in the desk log at 12:25: record C, green ↓ 02 Answer in the visitor’s channel Text back to the photo; text-to-speech back to the caller" src="https://cdn-images-1.medium.com/max/1024/1*OWZ9WMLRTStgag69viA0qw.png" /></figure><p>A model can misread a 7 as a 1, and a correct reading can still describe yesterday. Ask for identifiers in a fixed schema, validate them as in Part 9, and let the system of record supply the state.</p><h3>Documents: OCR, layout and vision models</h3><p>The handbook arrives as PDFs, some of them scans. The classic route is a pipeline: OCR reads the characters, then later steps rebuild order, headings and tables. The authors of Donut, an OCR-free document model, list the pipeline’s weaknesses: OCR adds computational cost, struggles with some languages and document types, and passes its errors on to every later stage. [4] Donut instead reads the page image with a single transformer and writes the structured output directly.</p><p>General vision-language models can be asked to do the same, for example to return a table as JSON.</p><p>Snowflake’s AI_PARSE_DOCUMENT shows the trade-off in its modes: OCR mode, the default, extracts text only; LAYOUT mode also extracts structure such as tables and returns Markdown. [5] A newer AGENTIC mode, in public preview since October 2026, also interprets charts and other visuals. [16] For the handbook, layout matters. A rule split from its table of exceptions, or a two-column page read straight across, gives retrieval a passage that looks right and means something else, like the negation trap in <a href="https://medium.com/p/b1f020887e99">Part 3</a>.</p><ul><li><strong>Text-only OCR</strong> suits clean, single-column pages where order is obvious.</li><li><strong>Layout-aware parsing</strong> suits tables, columns and forms, where position carries meaning.</li><li><strong>A vision model reading the page</strong> suits messy one-off documents, at higher cost and with less predictable output.</li></ul><p>Whichever you choose, parse once, on the way from Bronze to Silver in <a href="https://medium.com/p/d4fe4b3d5c27">Part 8</a>, keep the page number with every chunk, and store the parser version, so a change of parser is a change you can test.</p><h3>When the visitor calls</h3><p>Whisper, trained on 680,000 hours of multilingual audio, was often competitive with earlier fully supervised systems on standard benchmarks, without any fine-tuning. [6] But a peer-reviewed 2024 study ran about 13,000 recorded speech clips through OpenAI’s Whisper API in 2023. Roughly 1% of the transcriptions contained entire phrases or sentences that were not in the audio. [7] A transcript is a model output too.</p><p>OpenAI’s voice-agent guide describes two shapes: a speech-to-speech session, where one model interprets audio, decides what to do and replies in speech, and a chained pipeline, recommended when each stage needs to be visible or replaceable. [8] For a help desk the chain’s strength is the transcript in the middle, which you can log, check and test like a typed question.</p><p>Snowflake’s AI_TRANSCRIBE transcribes audio and video files in a stage, with optional word-level or speaker-level timestamps [9], and became generally available in November 2025. [10] That suits recorded calls, such as a nightly review of what visitors asked.</p><p>Voice also tests the rules you already have. The handbook’s rule P7 asks for written authorization before tickets are released to someone else, and a sentence heard on a phone line is not that. The assistant should explain how to send the authorization, never treat the call as permission. Likewise, a spoken “yes, go ahead” from a caller is not the staff confirmation that reassign_locker needs.</p><blockquote><strong><em>Plain English:</em></strong><em> A chained pipeline is three separate steps joined together: listen, think, speak. Speech-to-speech is one model doing all three at once.</em></blockquote><p>Here is the whole system on one page.</p><figure><img alt="Diagram: TWO NEW DOORS, ONE HARNESS Photo of a ticket Sent in the chat Phone call Café noise behind 1 image, audio ↓ MODEL PROVIDER Vision model Cropped label becomes tokens Speech-to-text Writes a transcript 2 a reading: K742, “red” ↓ YOUR APPLICATION Harness validates KEY CONTROL Schema for booking IDs; nothing in a photo grants a tool 3 look up at 12:25 ↓ Desk log Record C, green, from 12:20 4 reply ↓ Visitor or caller Tex" src="https://cdn-images-1.medium.com/max/1024/1*Q_FJ7sLgEGaiWsOj3l17WQ.png" /></figure><h3>Intent bots and LLMs</h3><p>A classic NLU bot classifies each message into an intent, “the goal or purpose behind a user’s message,” and extracts entities, specific pieces of information such as a booking code. [11] It is predictable, cheap and easy to test, because the set of intents is closed. Its weakness, in Rasa’s own description, is that NLU bots classify the last user input without the context of the whole conversation. [12]</p><p>Rasa’s newer CALM design shows a middle path. A language model reads the message in the context of the conversation and produces internal commands. A dialogue manager then decides how to execute them, and the business logic lives in fixed flows. [12] It is the split this series keeps returning to: the model interprets, deterministic code decides.</p><p>For the desk, the answer is both. A few known routes, such as locker location and pickup rules, handle common calls cheaply and testably; the LLM handles the long tail; the confirmation rules sit beneath both. Above all, keep a working “none of these” route that hands over to staff.</p><h3>Each modality needs its own test</h3><p>The test set from <a href="https://medium.com/p/653e3e2b1883">Part 7</a> measured answers. Multimodal inputs add a step before the answer, and each step needs its own measure.</p><figure><img alt="Card: ONE TEST PER DOOR Input Measure Also check Photos Fields read exactly Glare, blur, angle Documents Table cells and order Every page parsed Speech in Word error rate Colors, codes, names Speech out Listener ratings Codes read back right Intents Right route chosen “None of these” works" src="https://cdn-images-1.medium.com/max/1024/1*VOWTyo6LbFlJtbGRH2aVhw.png" /></figure><p>For speech-to-text the standard measure is word error rate: substitutions, deletions and insertions divided by the number of words in the reference transcript, computed as a word-level edit distance. [13] It is a good average and a poor guide to what matters. The demo scores two transcripts of a caller’s sentence and also checks the two slots the desk depends on: the locker color and the booking code.</p><pre>COLORS = {&quot;blue&quot;, &quot;red&quot;, &quot;green&quot;}<br><br>def edit_counts(ref, hyp):<br>    # Word-level Levenshtein: (cost, subs, dels, ins) for each prefix pair<br>    rows = [[(j, 0, 0, j) for j in range(len(hyp) + 1)]]<br>    for i in range(1, len(ref) + 1):<br>        row = [(i, 0, i, 0)]<br>        for j in range(1, len(hyp) + 1):<br>            c, s, d, n = rows[i - 1][j - 1]<br>            same = ref[i - 1] == hyp[j - 1]<br>            best = (c + (not same), s + (not same), d, n)<br>            c, s, d, n = rows[i - 1][j]<br>            best = min(best, (c + 1, s, d + 1, n))<br>            c, s, d, n = row[j - 1]<br>            best = min(best, (c + 1, s, d, n + 1))<br>            row.append(best)<br>        rows.append(row)<br>    return rows[-1][-1][1:]<br><br>def slots(words):<br>    color = next((w for w in words if w in COLORS), None)<br>    return {&quot;color&quot;: color, &quot;booking&quot;: &quot;k seven four two&quot; in<br>            &quot; &quot;.join(words)}<br><br>ref = &quot;my booking is k seven four two and my label says red&quot;.split()<br>systems = {<br>    &quot;A&quot;: &quot;my booking is k seven four two and my label says bed&quot;,<br>    &quot;B&quot;: &quot;booking is uh k seven four two and my label says red&quot;,<br>}<br>for name, text in systems.items():<br>    hyp = text.split()<br>    s, d, i = edit_counts(ref, hyp)<br>    wer = (s + d + i) / len(ref)<br>    ok = slots(hyp) == slots(ref)<br>    print(f&quot;{name}: WER {wer:.0%} (S={s} D={d} I={i}), &quot;<br>          f&quot;slots correct: {ok}&quot;)</pre><p>It prints A: WER 8% (S=1 D=0 I=0), slots correct: False and B: WER 17% (S=0 D=1 I=1), slots correct: True. System A has about half the error rate and gets the one word that matters wrong: “bed” instead of “red.” System B drops a “my” and adds an “uh,” and the desk can still act on it. Rank speech systems on your own recorded calls, and report the error rate on colors, codes and names next to the overall figure.</p><p>The other doors need the same treatment. For photos, label real visitor pictures, including glare, blur and odd angles, and score exact field matches. For documents, check table cells and reading order. Text-to-speech is usually judged by listeners and reported as a mean opinion score (MOS) [14]; a cheap automatic check I like is to transcribe the spoken reply and confirm that booking codes and colors survive the round trip. For intents, measure routing accuracy, including “none of these.”</p><p>Two production rules close the loop. First, new inputs are new attack surfaces. OWASP’s LLM01:2025 entry on prompt injection includes a multimodal scenario in which instructions hidden in an image change the model’s behavior. [15] A photo is data, like a retrieved passage, and nothing written in it can grant a tool or a permission. Second, photos and recordings are personal data. Keep them only as long as your retention policy allows, and log extracted fields rather than raw media where you can.</p><blockquote><strong><em>Principal’s note:</em></strong><em> I treat each new modality as a new parser in front of the same system. The model’s reading of a photo or a call is input to validate, like a typed message. The facts still come from the desk log, the permissions still live in the executor, and every turn still leaves a trace, now with the transcript or the extracted fields beside it.</em></blockquote><h3>What to take away</h3><ol><li><strong>Images become tokens too.</strong> Patches turn a photo into hundreds or thousands of tokens, so crop and resize on purpose and test that text stays legible.</li><li><strong>A reading is a claim, not a fact.</strong> Extract identifiers from photos and transcripts, then look up the current state in the system of record.</li><li><strong>Choose the parser to fit the page.</strong> Text-only OCR for simple pages, layout-aware parsing for tables and columns, a vision model for the messy rest.</li><li><strong>Prefer a chained voice pipeline when you need control.</strong> The transcript in the middle can be logged, checked and tested, and the existing rules still apply to a caller.</li><li><strong>Test every door separately.</strong> Word error rate, field accuracy and listener ratings sit next to the answer test set, with the critical words scored on their own.</li></ol><h4>Next in the series</h4><p>The assistant can now read a photo and answer a phone call. Next: does every decision need an LLM? We look at small, fast decision models for routing, triage and gating risky tool calls, and how to tell whether their confidence can be trusted. For the full reading order, see <a href="https://medium.com/p/3fb1cf707a00">The AI Engineering Series: Start Here</a>. Read <a href="https://medium.com/p/eb1158c4d7fe">Part 16</a>.</p><p><strong>Enjoyed this?</strong> <a href="https://medium.com/@manulovesu22">Follow me on Medium</a> for more hands-on guides. If you work with enterprise data, the <a href="https://medium.com/p/d1655daedfbd">AI-Ready Data Series</a> shows how to get your tables and documents ready for AI assistants. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://arxiv.org/abs/2010.11929">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a> — Dosovitskiy et al., 2020</li><li><a href="https://arxiv.org/abs/2304.08485">Visual Instruction Tuning</a> — Liu et al., 2023</li><li><a href="https://platform.claude.com/docs/en/build-with-claude/vision">Vision</a> — Anthropic, Claude Platform documentation</li><li><a href="https://arxiv.org/abs/2111.15664">OCR-free Document Understanding Transformer</a> — Kim et al., 2021</li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/ai_parse_document">AI_PARSE_DOCUMENT</a> — Snowflake documentation</li><li><a href="https://arxiv.org/abs/2212.04356">Robust Speech Recognition via Large-Scale Weak Supervision</a> — Radford et al., 2022</li><li><a href="https://arxiv.org/abs/2402.08021">Careless Whisper: Speech-to-Text Hallucination Harms</a> — Koenecke et al., ACM FAccT 2024</li><li><a href="https://developers.openai.com/api/docs/guides/voice-agents">Voice agents</a> — OpenAI API documentation</li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/ai_transcribe">AI_TRANSCRIBE</a> — Snowflake documentation</li><li><a href="https://docs.snowflake.com/en/release-notes/2025/other/2025-11-04-cortex-ai-transcribe-ga">Cortex AI_TRANSCRIBE function (General availability)</a> — Snowflake release notes, 2025</li><li><a href="https://www.rasa.com/docs/reference/primitives/intents-and-entities">Intents and entities</a> — Rasa documentation</li><li><a href="https://rasa.com/docs/learn/concepts/calm/">CALM</a> — Rasa documentation</li><li><a href="https://github.com/huggingface/evaluate/blob/main/metrics/wer/README.md">Word error rate (WER) metric card</a> — Hugging Face Evaluate</li><li><a href="https://www.itu.int/rec/T-REC-P.800.1-201607-I/en">P.800.1: Mean opinion score (MOS) terminology</a> — ITU-T, 2016</li><li><a href="https://genai.owasp.org/llmrisk/llm01-prompt-injection/">LLM01:2025 Prompt Injection</a> — OWASP Gen AI Security Project, 2025</li><li><a href="https://docs.snowflake.com/en/release-notes/feature-releases-2026">Feature updates in 2026</a> — Snowflake release notes, 2026</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35448cb10f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Make an LLM Application Faster and Cheaper Without Making It Worse?]]></title>
            <link>https://medium.com/@manulovesu22/how-do-you-make-an-llm-application-faster-and-cheaper-without-making-it-worse-a9411faef24f?source=rss-b0741b1dd457------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9411faef24f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Manoj Kumar Thirumalareddy]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 18:24:15 GMT</pubDate>
            <atom:updated>2026-12-02T18:37:25.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Do You Make an LLM Application Faster and Cheaper Without Making It Worse? (AI Engineering Series, Part 14)</h3><h4>Prompt caching, semantic caching, routing, distillation and batching, and the test set that tells you what each saving really cost.</h4><figure><img alt="Flat illustration of a glowing core in a control desk, a shelf of stored cards each with a small clock tag, a path forking towards a small and a large glowing core, a funnel pouring light from a large vessel into a small one, coins, a stopwatch and a green locker." src="https://cdn-images-1.medium.com/max/1024/1*B2gIlxAhKTpE7kRjRKlJTQ.png" /></figure><figure><img alt="Card: THE BUDGET REVIEW “Half our questions are ‘where are my tickets?’ Why does the biggest model read the whole handbook every time?”" src="https://cdn-images-1.medium.com/max/1024/1*8o3a8SY0GGds12CbT_n5JQ.png" /></figure><p>The monthly bill for the East Hall assistant arrived, and someone finally read the traces. Half the visitors ask the same thing in slightly different words: where are my tickets? Every one of those questions sent the full system prompt, the tool definitions and the handbook passages to the largest model on the menu, and every visitor waited for the whole answer to be written before seeing a word.</p><p>Two fixes were proposed: cache the answers, so a repeated question never reaches the model, and switch everything to the cheapest model, because “where are my tickets” is not a hard question.</p><p>Both would have saved money. Both would also, at 12:20 on a busy afternoon, have sent visitors to a jammed red locker, or told a parent that their son could collect passes without the written authorization the handbook requires. Cheaper and faster are easy. Cheaper and faster without getting worse takes some engineering.</p><p>In Part 13 we made the assistant safe and visible in production, with guardrails against the OWASP risks, OpenTelemetry GenAI traces that record tokens and cost, drift checks and an incident plan. Those traces now show where the money and the seconds go. This part is about spending less of both, and proving the answers didn’t suffer.</p><figure><img alt="A semantic cache serves a 12:10 hit for the red locker, refuses a stale match at 12:25 because record B closed at 12:20, then a router sends lookups to SQL and rule or action questions to the large model, with one under-routed question shown." src="https://cdn-images-1.medium.com/max/840/1*duoI4xwpUqO3Tw19FR25oA.gif" /></figure><p><strong>Level:</strong> Practitioner to senior · <strong>Best for:</strong> engineers and architects running LLM applications at scale · <strong>Read first:</strong> <a href="https://medium.com/p/653e3e2b1883">Part 7 on evaluation</a></p><blockquote><strong><em>Plain English:</em></strong><em> A cache keeps a result so you don’t have to compute it again. Routing sends each request to the cheapest component that can handle it. Distillation trains a small model to copy a large one on your kind of work. Latency is how long the visitor waits.</em></blockquote><h4>In this article</h4><ol><li><a href="#0300">Find out where the cost and the time go</a></li><li><a href="#ceef">Prompt caching reuses work, not answers</a></li><li><a href="#9939">Semantic caching reuses answers, and answers expire</a></li><li><a href="#a54e">Route by difficulty, then check the routes</a></li><li><a href="#63db">Distillation: a smaller model trained on your traffic</a></li><li><a href="#6ec4">Batch what can wait, stream what can’t</a></li><li><a href="#adf2">Every saving goes through the release gate</a></li><li><a href="#4058">What to take away</a></li></ol><h3>Find out where the cost and the time go</h3><p>A hosted model bills you for tokens: the tokens you send and the tokens it writes. For a help desk, the input side is mostly repetition. The system prompt, the tool schemas and the standing handbook rules are identical on every request; only the desk-log evidence and the question change. The output side is small, but as <a href="https://medium.com/p/15c68daac4b7">Part 1</a> showed, the model writes it one token at a time, so a long answer is a slow answer.</p><p>Latency has the same two parts. There is the wait before the first token appears, which grows with how much input must be processed, and the time to write the rest, which grows with the length of the answer. Each technique in this article attacks one of those parts:</p><ul><li><strong>Repeated input:</strong> prompt caching.</li><li><strong>Repeated questions:</strong> semantic caching, carefully.</li><li><strong>Overqualified models:</strong> routing and distillation.</li><li><strong>Work nobody is waiting for:</strong> batching. <strong>Work somebody is waiting for:</strong> streaming.</li></ul><p>Start from the traces. If most of your tokens are a handbook dump returned on every turn, trimming it beats any model switch; that is the context budget from <a href="https://medium.com/p/af02015615fb">Part 9</a>.</p><p>Here is where each saving sits.</p><figure><img alt="Diagram: WHERE EACH SAVING SITS Visitor chat 1 question ↓ YOUR APPLICATION Semantic cache KEY CONTROL Hit only if the hall matches and the record is still open 2 miss ↓ Router Cheapest safe tier Desk log, SQL Locker lookups, no model 3 stable prefix first, evidence last ↓ MODEL PROVIDER Prompt cache Reuses the unchanged prefix Small model Hours, simple facts Large model Rules with conditions Batch API Nightly test runs, half" src="https://cdn-images-1.medium.com/max/1024/1*fHzIDflEVr00votuqT6DyQ.png" /></figure><h3>Prompt caching reuses work, not answers</h3><p>Prompt caching happens inside the model provider. When a new request begins with exactly the same prefix as a recent one, the provider reuses the processing it already did for that prefix instead of starting again.</p><p>Anthropic’s implementation caches the prefix in a fixed order: tools, then system, then messages, up to a point you mark. The default lifetime is five minutes, refreshed at no cost each time the entry is used, with a one-hour option at extra cost. Writing a five-minute cache entry costs 1.25 times the base input price (2 times for the one-hour option) and reading it costs 0.1 times, lower on some newer models. Prompts below a model-specific minimum length are processed without caching, and no error is returned. [1]</p><p>OpenAI enables prompt caching by default on supported models and gives the same layout advice: put stable instructions and shared reference material first, because reuse needs the entire prefix to match, and put dynamic content such as timestamps and user details at the end. [2]</p><figure><img alt="Card: TWO CACHES, TWO DIFFERENT RISKS PROMPT CACHE Where: inside the provider Reuses: work on an unchanged prefix Model runs: yes, on fresh evidence Order: tools, system, handbook, then evidence and question Risk: cost only SEMANTIC CACHE Where: in your code Reuses: a whole answer to a similar question Model runs on a hit: no Keys: hall and access; record IDs and their validity windows Risk: a stale or wrong answer" src="https://cdn-images-1.medium.com/max/1024/1*7-s5RElTZnqHbr4VQKoI1Q.png" /></figure><p>For the desk, that means ordering the request deliberately: tool definitions, then the system prompt, then the standing handbook rules, and only then the desk-log record and the visitor’s question. A clock in the first line of the system prompt (“It is now 12:05”) turns every request into a cache miss; move it down beside the evidence.</p><blockquote><strong><em>Key point:</em></strong><em> Prompt caching is safe for freshness because the model still reads the current evidence and writes a new answer every time. Only the processing of the unchanged prefix is reused. The risk is cost, not correctness: one changed character near the top and you pay full price again.</em></blockquote><h3>Semantic caching reuses answers, and answers expire</h3><p>A semantic cache sits in front of the model, in your own code. It embeds each incoming question, looks for a stored question that is close enough, and if it finds one, returns the stored answer without calling the model at all. GPTCache, an open-source library, describes exactly that pipeline: an embedding, a vector store and a similarity evaluator.</p><p>Its own documentation warns that you may see false positives on cache hits, and notes that the project no longer adds support for new APIs or models. [3] Research on semantic caching makes the same point more formally: a single fixed similarity threshold gives no correctness guarantee and can produce unexpected error rates. [4]</p><p>The desk adds a second problem that similarity can’t see. An answer is a claim derived from a record, and that record has a validity window. “The red locker” was true from 12:00, when record B opened, until 12:20, when the locker jammed and record C opened. A cached answer that doesn’t know which record it came from will keep saying “red” long after 12:20, the stale-answer failure from <a href="https://medium.com/p/033aa4b6f4a4">Part 2</a>, now caused by the cache rather than the search index.</p><p>So the cache below stores, with each answer, the hall it applies to and the ID of the record it depends on. Before serving a hit, it checks that record against the desk log at the time the question is asked. The word-count similarity stands in for a real embedding model from <a href="https://medium.com/p/b1f020887e99">Part 3</a>.</p><pre>import re<br>from collections import Counter<br>from math import sqrt<br><br>LOG = {&quot;B&quot;: [&quot;East Hall&quot;, &quot;red&quot;, &quot;12:00&quot;, None],     # hall, locker,<br>       &quot;W1&quot;: [&quot;West Hall&quot;, &quot;blue&quot;, &quot;09:00&quot;, None]}   # start, end<br>CACHE, model_calls = [], 0<br>def vec(text):<br>    return Counter(re.findall(r&quot;[a-z]+&quot;, text.lower()))<br>def sim(a, b):<br>    dot = sum(a[w] * b[w] for w in a)<br>    size = lambda v: sqrt(sum(n * n for n in v.values()))<br>    return dot / (size(a) * size(b))<br>def valid(rec, at):<br>    hall, locker, start, end = LOG[rec]<br>    return start &lt;= at and (end is None or at &lt; end)<br>def call_model(hall, at):  # stands in for retrieval plus an LLM call<br>    global model_calls<br>    model_calls += 1<br>    rec = next(k for k in LOG if LOG[k][0] == hall and valid(k, at))<br>    return f&quot;{LOG[rec][1]} locker (record {rec})&quot;, rec<br>def ask(question, hall, at, threshold=0.8):<br>    v, note = vec(question), &quot;MISS&quot;<br>    for e in CACHE:<br>        s = sim(v, e[&quot;vec&quot;])<br>        if e[&quot;hall&quot;] != hall or s &lt; threshold:<br>            continue<br>        if valid(e[&quot;rec&quot;], at):<br>            return f&quot;{at} HIT {s:.2f} -&gt; {e[&#39;answer&#39;]}&quot;<br>        CACHE.remove(e)<br>        note = f&quot;STALE {s:.2f}, record {e[&#39;rec&#39;]} closed&quot;<br>        break<br>    answer, rec = call_model(hall, at)<br>    CACHE.append({&quot;hall&quot;: hall, &quot;vec&quot;: v, &quot;answer&quot;: answer, &quot;rec&quot;: rec})<br>    return f&quot;{at} {note} -&gt; {answer}&quot;<br><br>print(ask(&quot;Where are my East Hall tickets?&quot;, &quot;East Hall&quot;, &quot;12:05&quot;))<br>print(ask(&quot;where are the East Hall tickets&quot;, &quot;East Hall&quot;, &quot;12:10&quot;))<br>print(ask(&quot;Where are my West Hall tickets?&quot;, &quot;West Hall&quot;, &quot;12:12&quot;))<br>LOG[&quot;B&quot;][3] = &quot;12:20&quot;                    # red locker jams at 12:20<br>LOG[&quot;C&quot;] = [&quot;East Hall&quot;, &quot;green&quot;, &quot;12:20&quot;, None]<br>print(ask(&quot;Where are my East Hall tickets?&quot;, &quot;East Hall&quot;, &quot;12:25&quot;))<br>print(ask(&quot;where are the East Hall tickets&quot;, &quot;East Hall&quot;, &quot;12:30&quot;))<br>print(f&quot;questions: 5, model calls: {model_calls}&quot;)</pre><p>I ran it with Python 3 and the standard library only. It prints:</p><ul><li>12:05 MISS -&gt; red locker (record B)</li><li>12:10 HIT 0.83 -&gt; red locker (record B)</li><li>12:12 MISS -&gt; blue locker (record W1)</li><li>12:25 STALE 1.00, record B closed -&gt; green locker (record C)</li><li>12:30 HIT 0.83 -&gt; green locker (record C)</li><li>questions: 5, model calls: 3</li></ul><p>The West Hall question scores 0.83 against the cached East Hall one, as close as the genuine paraphrase at 12:10; only the hall scope stops the cache from sending a West Hall visitor to the red locker. At 12:25 the similarity is a perfect 1.00, the same words as the 12:05 question, and the cache still refuses, because record B closed at 12:20. And five questions cost three model calls, with every answer correct for its time.</p><p>The demo purges lazily: a stale entry is removed only when a similar question finds it. In production, checking the record on every hit can be replaced or backed up by an event: when the desk log closes record B, purge every cached answer that cites it. Either way:</p><ul><li><strong>Scope before similarity.</strong> Venue, language and the reader’s access level are exact-match keys, not things for an embedding to weigh.</li><li><strong>Store what each answer depends on.</strong> Record IDs and rule IDs, so a change can find the answers it invalidates.</li><li><strong>Never cache actions or personal answers.</strong> A reassign_locker request or an answer about one visitor’s booking always goes to the live path.</li><li><strong>Measure the stale rate, not just the hit rate.</strong> A cache with a high hit rate and a few stale serves is a fast way to be wrong.</li></ul><h3>Route by difficulty, then check the routes</h3><p>Not every question needs the largest model. RouteLLM trains routers that choose between a stronger and a weaker model for each query, and its authors report cost reductions of over two times in certain cases without lowering response quality. [5] FrugalGPT takes the cascade approach: try cheaper models first and escalate when the answer isn’t reliable enough. On their benchmarks, the authors report matching the best individual model with up to 98 percent cost reduction. [6] Your saving depends on your traffic.</p><figure><img alt="Card: ROUTE EACH QUESTION TO THE CHEAPEST SAFE TIER 01 Semantic cache Serve only if hall matches and the source record is still open ↓ miss 02 SQL, no model “Where are my tickets?” is a validity-window lookup 03 Small model Opening hours, access, simple facts from the handbook 04 Large model Rules with conditions, refunds, and any tool call (still confirmed by staff) ! Count under-routes A rule question sent to a cheaper t" src="https://cdn-images-1.medium.com/max/1024/1*n3sek1aqWjhyNMTNgwU5RA.png" /></figure><p>The cheapest route of all uses no model. As <a href="https://medium.com/p/d4fe4b3d5c27">Part 8</a> showed, “where are my tickets” is a validity-window query in SQL. Here is a simple keyword router for the desk, scored against a small test set that records the cheapest tier that answers each question correctly. The costs are relative units for illustration, not real prices.</p><pre># Relative cost per request. Illustrative, not any vendor&#39;s prices.<br>COST = {&quot;sql&quot;: 0, &quot;small&quot;: 1, &quot;large&quot;: 12}<br>RANK = {&quot;sql&quot;: 0, &quot;small&quot;: 1, &quot;large&quot;: 2}<br>RULE_WORDS = (&quot;collect&quot;, &quot;authori&quot;, &quot;daughter&quot;, &quot;refund&quot;)<br>ACTION_WORDS = (&quot;move&quot;, &quot;reassign&quot;, &quot;release&quot;)<br><br>def route(question):<br>    q = question.lower()<br>    if any(w in q for w in ACTION_WORDS + RULE_WORDS):<br>        return &quot;large&quot;   # conditions or a tool call (still confirmed)<br>    if &quot;where&quot; in q and &quot;ticket&quot; in q:<br>        return &quot;sql&quot;     # validity-window lookup, no model at all<br>    return &quot;small&quot;<br><br>TESTS = [  # question, cheapest tier that answers it correctly<br>    (&quot;Where are my East Hall tickets?&quot;, &quot;sql&quot;),<br>    (&quot;Where are the tickets for booking 4411?&quot;, &quot;sql&quot;),<br>    (&quot;What time does the hall close today?&quot;, &quot;small&quot;),<br>    (&quot;Is there step-free access to East Hall?&quot;, &quot;small&quot;),<br>    (&quot;Can my daughter collect our passes?&quot;, &quot;large&quot;),<br>    (&quot;My son is picking up our passes. What does he need?&quot;, &quot;large&quot;),<br>    (&quot;Please move my tickets to the green locker.&quot;, &quot;large&quot;),<br>    (&quot;Can I get a refund if the show is cancelled?&quot;, &quot;large&quot;),<br>]<br>cost = under = 0<br>for question, need in TESTS:<br>    tier = route(question)<br>    cost += COST[tier]<br>    if RANK[tier] &lt; RANK[need]:<br>        under += 1<br>        print(f&quot;UNDER-ROUTED: {question!r} -&gt; {tier}, needs {need}&quot;)<br>baseline = COST[&quot;large&quot;] * len(TESTS)<br>print(f&quot;cost {cost} vs {baseline} all-large &quot;<br>      f&quot;({1 - cost / baseline:.0%} saved), under-routed: {under}&quot;)</pre><p>It prints UNDER-ROUTED: &#39;My son is picking up our passes. What does he need?&#39; -&gt; small, needs large and then cost 39 vs 96 all-large (59% saved), under-routed: 1. “Picking up” isn’t in the keyword list, so a question about the written-authorization rule went to the small model: the parent who gets turned away at the desk.</p><p>This is why the test set matters more than the router. Label each test question with the cheapest safe tier, count under-routes separately from the overall score, and treat any under-route in a high-risk category, such as permissions, refunds or tool calls, as a release blocker. A trained router can replace the keywords later, but it answers to the same test set.</p><blockquote><strong><em>Principal’s note:</em></strong><em> I report cost per correct answer, not cost per request. A route that saves 59 percent and gets one permission question wrong has moved cost from the API bill to the help desk queue, where nobody is measuring it. Every saving should arrive with its evaluation run attached, the same way a performance change arrives with its benchmark.</em></blockquote><h3>Distillation: a smaller model trained on your traffic</h3><p>Routing picks a cheaper model; distillation makes one. The idea is old. Hinton, Vinyals and Dean trained a small model on the class probabilities produced by a large one, which they called “soft targets,” raising the softmax temperature to make those targets softer. [7] With language models, the teacher’s outputs or reasoning become training data for the student. In one study, a 770-million-parameter T5 model trained this way outperformed the few-shot prompted 540-billion-parameter PaLM on a benchmark, using only 80 percent of the available data. [8]</p><p>For the desk, the recipe is to run the large model over real logged questions, keep only the answers that pass the evaluation checks, and fine-tune a small model on them, for example with the LoRA adapters from <a href="https://medium.com/p/a2388b266b81">Part 5</a>. Part 5’s lesson still applies: distill behavior, not facts. The student should learn to cite, to keep every condition and to say when the evidence is silent. It should not learn which locker holds the tickets, because that changes at 12:20 and lives in the desk log.</p><p>A student trained on the teacher’s mistakes learns them too, so filter its training data with your release checks, and read your provider’s terms before training on its outputs.</p><h3>Batch what can wait, stream what can’t</h3><p>Some model work has no visitor waiting: the nightly <a href="https://medium.com/p/653e3e2b1883">Part 7</a> test run, classifying the day’s messages, distillation data. Batch interfaces trade speed for price. Anthropic’s Message Batches API charges 50 percent of standard prices; Anthropic says most batches finish in under an hour, and a batch that isn’t done within 24 hours expires. [9] OpenAI’s Batch API also offers a 50 percent discount, completes within 24 hours and doesn’t count against the standard rate limits; it lists running evaluations and classifying large datasets among its uses. [10]</p><p>When somebody is waiting, streaming changes what they experience. With streaming, the response arrives as server-sent events (small messages the server pushes over one open connection) while it is being written, so the visitor reads the first words while the rest are still being generated. It doesn’t reduce the total time or the token bill, and Anthropic’s documentation notes it is also how SDKs avoid HTTP timeouts on long responses. [11]</p><p>The other lever on the output side is length: the short, structured answer from <a href="https://medium.com/p/6dc7fc8ad465">Part 4</a> is faster because it is shorter.</p><p>If you host your own models, batching happens inside the server. vLLM’s PagedAttention manages the memory of many concurrent requests more efficiently, and its authors report two to four times the throughput (requests served per second) of systems such as FasterTransformer and Orca at the same latency. [12]</p><h3>Every saving goes through the release gate</h3><p>Each technique here changes what the visitor sees, so each one is a release, gated on the same test set:</p><ul><li><strong>Run the test set on the cheap path.</strong> Compare against the baseline per category, not only overall.</li><li><strong>Replay real traffic through the cache.</strong> Count hits, false hits and stale serves across a shift that includes a locker change.</li><li><strong>Watch the traces after release.</strong> Hit rate, route mix, cost per correct answer and time to first token belong on the same dashboard as the error rate from Part 13.</li><li><strong>Keep a way back.</strong> Make every cache and routing rule switchable off without a deployment.</li></ul><h3>What to take away</h3><ol><li><strong>Measure first.</strong> Traces show whether the cost is repeated input, long output or an oversized model.</li><li><strong>Order prompts for prompt caching.</strong> Stable content first, dynamic content last; it reuses processing, never answers.</li><li><strong>A semantic cache must know what its answers depend on.</strong> Scope by exact keys, store record IDs, and refuse anything past its validity window.</li><li><strong>Route by difficulty and count the under-routes.</strong> The cheapest route is often SQL; the costliest mistake is a cheap wrong answer about a rule.</li><li><strong>Distill behavior, batch what can wait, stream what can’t.</strong> Then prove each saving on the test set before and after release.</li></ol><h4>Next in the series</h4><p>Next: what changes when a visitor sends a photo of a locker label or calls the desk instead of typing, and how images, documents and speech reach a model. For the full reading order, see <a href="https://medium.com/p/3fb1cf707a00">The AI Engineering Series: Start Here</a>. Read <a href="https://medium.com/p/35448cb10f8c">Part 15</a>.</p><p><strong>Enjoyed this?</strong> <a href="https://medium.com/@manulovesu22">Follow me on Medium</a> for more hands-on guides. If you work with enterprise data, the <a href="https://medium.com/p/d1655daedfbd">AI-Ready Data Series</a> shows how to get your tables and documents ready for AI assistants. <em>Views are my own. Not affiliated with or endorsed by any vendor named. Illustrations are AI-assisted.</em></p><h3>Sources and further reading</h3><ol><li><a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">Prompt caching</a> — Anthropic documentation</li><li><a href="https://developers.openai.com/api/docs/guides/prompt-caching">Prompt caching</a> — OpenAI API documentation</li><li><a href="https://github.com/zilliztech/GPTCache">GPTCache: a library for creating semantic cache for LLM queries</a> — Zilliz, GitHub</li><li><a href="https://arxiv.org/abs/2502.03771">vCache: Verified Semantic Prompt Caching</a> — Schroeder et al., ICLR 2026</li><li><a href="https://arxiv.org/abs/2406.18665">RouteLLM: Learning to Route LLMs with Preference Data</a> — Ong et al., ICLR 2025</li><li><a href="https://arxiv.org/abs/2305.05176">FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance</a> — Chen, Zaharia and Zou, 2023</li><li><a href="https://arxiv.org/abs/1503.02531">Distilling the Knowledge in a Neural Network</a> — Hinton, Vinyals and Dean, NIPS 2014 Deep Learning Workshop</li><li><a href="https://arxiv.org/abs/2305.02301">Distilling Step-by-Step! Outperforming Larger Language Models with Less Training Data and Smaller Model Sizes</a> — Hsieh et al., Findings of ACL 2023</li><li><a href="https://platform.claude.com/docs/en/build-with-claude/batch-processing">Batch processing</a> — Anthropic documentation</li><li><a href="https://developers.openai.com/api/docs/guides/batch">Batch API</a> — OpenAI API documentation</li><li><a href="https://platform.claude.com/docs/en/build-with-claude/streaming">Streaming messages</a> — Anthropic documentation</li><li><a href="https://arxiv.org/abs/2309.06180">Efficient Memory Management for Large Language Model Serving with PagedAttention</a> — Kwon et al., SOSP 2023</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9411faef24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>