<?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"><channel><title><![CDATA[AI Techbom]]></title><description><![CDATA[AI Techbom]]></description><link>https://aitechbom.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 19:58:42 GMT</lastBuildDate><atom:link href="https://aitechbom.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Designing an offline-first pharmacy POS]]></title><description><![CDATA[How Vevilo balances online reservations, expiring batches and offline counter sales when a pharmacy shares inventory across channels.]]></description><link>https://aitechbom.hashnode.dev/designing-an-offline-first-pharmacy-pos</link><guid isPermaLink="true">https://aitechbom.hashnode.dev/designing-an-offline-first-pharmacy-pos</guid><category><![CDATA[architecture]]></category><category><![CDATA[database]]></category><category><![CDATA[offline first]]></category><dc:creator><![CDATA[MUHAMMAD UMAID SIDDIQUI]]></dc:creator><pubDate>Fri, 04 Dec 2026 18:46:06 GMT</pubDate><content:encoded><![CDATA[<p>A pharmacy checkout should keep moving during a connection outage. The online store also needs to know how much stock it can promise. Vevilo was built around that tension. The counter and store share a stock record, while the desktop till can sell from its allocated stock when it goes offline.</p>
<h2>Draw the boundary between reserved and sellable</h2>
<p>Imagine three packs left on a shelf. An online customer adds one to a cart. The counter can sell another pack while that customer is still shopping. The decision point is checkout, where Vevilo reserves stock for the online order. Once reserved, those units are no longer available to promise on a second order. A till that cannot see live reservations can still sell from the stock already allocated to it.</p>
<p>Before building this kind of workflow, document when stock is reserved, when an allocation becomes usable, and when units go back into general stock. Include cancellations and refunds in the same exercise. Those rules matter on a normal day and become especially visible when several people are selling at once.</p>
<h2>Track the batch all the way through the sale</h2>
<p>Two packs with the same product name can have different expiry dates. Vevilo tracks stock by batch and makes expiry part of the order in which stock is used. Allocation needs to preserve that distinction. Keep the batch identifier with the sale record so that when a till reconnects, the movement can be reconciled against the right stock.</p>
<h2>Test the outage and the recovery</h2>
<p>An offline checkout test should cover the moment the network drops and the moment it comes back. Start from a known stock count, capture a real movement on the till, and compare the till, store and stock ledger after reconnecting.</p>
<ul>
<li>Disconnect a till with an existing allocation. Sell one unit and check the remaining allocation shown on the till.</li>
<li>While the till is offline, place an online order and check that checkout reserves only stock it can still promise.</li>
<li>Reconnect, interrupt the first sync, and retry it. Verify that the movement is recorded once against the right batch.</li>
<li>Repeat with multiple batches, a cancellation and an allocation that runs out before reconnection.</li>
</ul>
<p>The practical measure is whether staff can explain why a unit is available, reserved or allocated to the counter. Use those states in the UI and make stock differences visible after sync so the team can investigate them.</p>
<h2>What Vevilo does at each stage</h2>
<table>
<thead>
<tr>
<th>Stage</th>
<th>What happens</th>
</tr>
</thead>
<tbody><tr>
<td>Receiving</td>
<td>The batch and expiry date are recorded with the stock.</td>
</tr>
<tr>
<td>Online checkout</td>
<td>The order reserves stock, so the counter cannot sell the same units.</td>
</tr>
<tr>
<td>Counter sale</td>
<td>Barcode checkout allocates stock by earliest expiry and blocks expired batches.</td>
</tr>
<tr>
<td>Outage</td>
<td>The desktop till sells from the stock allocated to that device.</td>
</tr>
<tr>
<td>Reconnection</td>
<td>Sales sync to the shared stock record and conflicts are flagged for staff to review.</td>
</tr>
</tbody></table>
<h2>What a pharmacy POS costs</h2>
<p>A POS for a shop or pharmacy at AI Techbom is USD 500 to set up, then USD 100 a month, so the first year is USD 1,700. The monthly fee includes hosting, domain, support, bug fixes and 10 revisions. Hardware and card terminal fees are separate. See the <a href="https://www.aitechbom.site/pricing/pos-system-cost">POS cost guide</a>.</p>
<hr />
<p><em>First published on <a href="https://www.aitechbom.site/insights/designing-offline-first-pharmacy-pos">AI Techbom</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[RAG tutorial: retrieval-augmented generation in TypeScript]]></title><description><![CDATA[A tested RAG tutorial: chunk documents, embed them with a local model, retrieve the closest chunks, set a score threshold and build a grounded prompt.]]></description><link>https://aitechbom.hashnode.dev/rag-tutorial-retrieval-augmented-generation-in-typescript</link><guid isPermaLink="true">https://aitechbom.hashnode.dev/rag-tutorial-retrieval-augmented-generation-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[MUHAMMAD UMAID SIDDIQUI]]></dc:creator><pubDate>Fri, 04 Dec 2026 14:09:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b12c86828d7c63f325fd31f/d6d47bf6-f562-4228-9527-541ae6ddc1de.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Retrieval-augmented generation (RAG) makes a language model answer from your documents instead of from memory. Before the model is called, the question is used to find the most relevant passages, and those passages go into the prompt with an instruction to answer only from them. This tutorial builds the retrieval half end to end with a local embedding model, so it runs without an API key, and ends with the prompt you would send to any model.</p>
<p>Tested on 21 November 2026 with Node.js 26, @huggingface/transformers 4.3.2 and the Xenova/all-MiniLM-L6-v2 embedding model, run with tsx 4. The script type-checks with TypeScript 5 in strict mode. The measurement step in section 6 was run on 2 December 2026 with Node.js 26.13.1, tsx 4.23.15 and TypeScript 5.9.3 on a GitHub Actions runner; the pipeline output was unchanged.</p>
<h2>1. Set up the project</h2>
<pre><code class="language-bash">mkdir rag-demo &amp;&amp; cd rag-demo
npm init -y
npm pkg set type=module
npm install @huggingface/transformers@4.3.2
npm install -D tsx@4 typescript@5 @types/node@24
</code></pre>
<h2>2. The whole pipeline</h2>
<p>Five steps: chunk the documents, load an embedding model, embed every chunk once, embed the question and rank chunks by similarity, then build the prompt. The documents here are a small shop's delivery, returns and opening-hours notes.</p>
<pre><code class="language-ts">import { pipeline } from "@huggingface/transformers";

// 1. Your documents, split into small chunks with a source for each.
const chunks = [
  { source: "delivery.md", text: "We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day." },
  { source: "delivery.md", text: "Delivery is free on orders over 3,000 rupees. Below that it costs 200 rupees." },
  { source: "returns.md", text: "Unopened items can be returned within 7 days with the receipt." },
  { source: "returns.md", text: "Medicines cannot be returned once they have left the pharmacy." },
  { source: "hours.md", text: "The shop is open 9 am to 11 pm every day, including public holidays." },
];

// 2. A local embedding model. It downloads once and then runs offline.
const embed = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2");

async function vector(text: string): Promise&lt;number[]&gt; {
  const output = await embed(text, { pooling: "mean", normalize: true });
  return Array.from(output.data as Float32Array);
}

// Vectors are normalised, so the dot product is the cosine similarity.
const similarity = (a: number[], b: number[]) =&gt; a.reduce((sum, value, i) =&gt; sum + value * b[i], 0);

// 3. Index: embed every chunk once and keep the vectors.
const index = await Promise.all(chunks.map(async (chunk) =&gt; ({ ...chunk, vector: await vector(chunk.text) })));

// 4. Retrieve: embed the question and take the closest chunks.
async function retrieve(question: string, k = 2) {
  const q = await vector(question);
  return index
    .map((chunk) =&gt; ({ source: chunk.source, text: chunk.text, score: similarity(q, chunk.vector) }))
    .sort((a, b) =&gt; b.score - a.score)
    .slice(0, k);
}

// 5. Build the prompt for any LLM: context first, then the rule, then the question.
function buildPrompt(question: string, context: { source: string; text: string }[]) {
  const sources = context.map((c, i) =&gt; `[${i + 1}] (${c.source}) ${c.text}`).join("\n");
  return `Answer using only the sources below. If they do not answer the question, say you don't know.\n\nSources:\n${sources}\n\nQuestion: ${question}`;
}

for (const question of ["Do you deliver on the same day?", "Can I return medicine?", "Do you sell laptops?"]) {
  const hits = await retrieve(question);
  console.log(`\nQ: ${question}`);
  for (const hit of hits) console.log(`  ${hit.score.toFixed(2)}  ${hit.source}  ${hit.text}`);
}

console.log("\n--- Prompt for the first question ---");
const question = "Do you deliver on the same day?";
console.log(buildPrompt(question, await retrieve(question)));
</code></pre>
<p>Run it with npx tsx rag.ts. The first run downloads the model; after that it runs offline. This is the output it produced:</p>
<pre><code class="language-text">Q: Do you deliver on the same day?
  0.61  delivery.md  We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day.
  0.35  hours.md  The shop is open 9 am to 11 pm every day, including public holidays.

Q: Can I return medicine?
  0.70  returns.md  Medicines cannot be returned once they have left the pharmacy.
  0.33  returns.md  Unopened items can be returned within 7 days with the receipt.

Q: Do you sell laptops?
  0.17  delivery.md  Delivery is free on orders over 3,000 rupees. Below that it costs 200 rupees.
  0.14  returns.md  Unopened items can be returned within 7 days with the receipt.

--- Prompt for the first question ---
Answer using only the sources below. If they do not answer the question, say you don't know.

Sources:
[1] (delivery.md) We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day.
[2] (hours.md) The shop is open 9 am to 11 pm every day, including public holidays.

Question: Do you deliver on the same day?
</code></pre>
<h2>3. Reading the scores</h2>
<p>The two questions the documents can answer found the right chunk first, with scores of 0.61 and 0.70. The question about laptops, which nothing in the documents covers, still returned two chunks, because retrieval always returns the closest matches, but its best score was only 0.17.</p>
<p>That is why a RAG system needs a minimum score. Below it, skip the model and say you don't know, or hand the question to a person. The right threshold depends on the embedding model and your documents, so measure it on real questions rather than copying a number: section 6 shows how. To check the whole bot, not just retrieval, use the <a href="https://www.aitechbom.site/insights/ai-chatbot-testing-checklist">AI chatbot testing checklist</a>.</p>
<h2>4. Chunking decides most of the quality</h2>
<ul>
<li>Keep one idea per chunk. A chunk that mixes delivery and returns will match both kinds of question weakly.</li>
<li>Keep the source with every chunk, so answers can cite it and staff can check it.</li>
<li>Re-embed a document whenever it changes. Stale chunks give confident, outdated answers.</li>
<li>Write the documents for retrieval: short sentences that state the fact plainly retrieve better than long marketing copy.</li>
</ul>
<h2>5. Generating the answer</h2>
<p>The last block prints the prompt: the retrieved sources, numbered, an instruction to answer only from them, and the question. Send that to the model you use through its API. Asking the model to cite source numbers makes its answers easy to check. To let the model act on the answer as well, see <a href="https://www.aitechbom.site/insights/how-to-build-an-ai-agent">how to build an AI agent</a>.</p>
<h2>6. Measure retrieval and choose the threshold</h2>
<p>Section 3 said to measure the threshold on real questions. To do that, write questions the way customers ask them, in words that differ from the documents, and name the document that should answer each one. Add a few questions the documents cannot answer, with no expected document. Then add this to the end of rag.ts:</p>
<pre><code class="language-ts">// 6. Measure retrieval on labelled questions, then choose the threshold.
// Each case names the document that should answer it, or null if none can.
const cases: { question: string; expected: string | null }[] = [
  { question: "How late can I order and still get it today?", expected: "delivery.md" },
  { question: "Is there a delivery charge?", expected: "delivery.md" },
  { question: "Can I bring back something I bought last week?", expected: "returns.md" },
  { question: "Can I return antibiotics I no longer need?", expected: "returns.md" },
  { question: "Are you open on Eid?", expected: "hours.md" },
  { question: "What time do you close?", expected: "hours.md" },
  { question: "Do you sell laptops?", expected: null },
  { question: "Can I pay in instalments?", expected: null },
  { question: "Do you offer home blood tests?", expected: null },
];

const results: { question: string; expected: string | null; found: string; score: number }[] = [];
for (const c of cases) {
  const [top] = await retrieve(c.question, 1);
  results.push({ ...c, found: top.source, score: top.score });
  console.log(`${top.score.toFixed(2)}  ${(c.expected ?? "none").padEnd(11)} ${top.source.padEnd(11)} ${c.question}`);
}

// At threshold t the bot answers when the top score is at least t, and refuses otherwise.
// A good decision is a right answer for an answerable question, or a refusal for one that is not.
function grade(t: number) {
  let right = 0, wrong = 0, refusedAnswerable = 0, refused = 0, answeredUnanswerable = 0;
  for (const r of results) {
    const answers = r.score &gt;= t;
    if (r.expected === null) {
      if (answers) answeredUnanswerable++;
      else refused++;
    } else if (!answers) refusedAnswerable++;
    else if (r.found === r.expected) right++;
    else wrong++;
  }
  return { t, right, wrong, refusedAnswerable, refused, answeredUnanswerable, good: right + refused };
}

// Try each observed top score as the threshold.
const candidates = results.map((r) =&gt; r.score).sort((a, b) =&gt; a - b);
const graded = candidates.map(grade);
// The highest threshold with the most good decisions: when scores tie, refusing is the safer side.
const best = graded.reduce((a, b) =&gt; (b.good &gt;= a.good ? b : a));
console.log(`\nTop chunk from the right document: ${results.filter((r) =&gt; r.expected &amp;&amp; r.found === r.expected).length} of ${results.filter((r) =&gt; r.expected).length}`);
console.log(`Best threshold: ${best.t.toFixed(3)} (${best.good} of ${results.length} good decisions: ${best.right} answered right, ${best.refused} refused correctly, ${best.wrong} answered wrong, ${best.refusedAnswerable} answerable refused, ${best.answeredUnanswerable} unanswerable answered)`);
</code></pre>
<p>Run npx tsx rag.ts again. After the earlier output, it printed one line per question (the top score, the expected document, the document found and the question) and a summary:</p>
<pre><code class="language-text">0.50  delivery.md delivery.md How late can I order and still get it today?
0.65  delivery.md delivery.md Is there a delivery charge?
0.57  returns.md  returns.md  Can I bring back something I bought last week?
0.55  returns.md  returns.md  Can I return antibiotics I no longer need?
0.33  hours.md    hours.md    Are you open on Eid?
0.50  hours.md    hours.md    What time do you close?
0.17  none        delivery.md Do you sell laptops?
0.24  none        delivery.md Can I pay in instalments?
0.19  none        returns.md  Do you offer home blood tests?

Top chunk from the right document: 6 of 6
Best threshold: 0.335 (9 of 9 good decisions: 6 answered right, 3 refused correctly, 0 answered wrong, 0 answerable refused, 0 unanswerable answered)
</code></pre>
<p>Every answerable question found the right document first, including "Can I bring back something I bought last week?", which never uses the word "return". The answerable questions scored from 0.33 to 0.65 and the unanswerable ones from 0.17 to 0.24, so any threshold between those two groups gets all nine decisions right.</p>
<p>The script tries each observed score as the threshold and reports 0.335, the score of "Are you open on Eid?". That question only just clears it, so a slightly different wording could be refused. Pick a value in the middle of the gap instead, about 0.29 here, to leave a margin on both sides.</p>
<p>Nine questions show the method; they are not enough to set a production threshold. Collect real questions from your chat logs or inbox, label them the same way and re-run the script whenever you change the chunks, the embedding model or the documents. If the scores of answerable and unanswerable questions overlap, no threshold separates them: fix the chunking or the documents first.</p>
<h2>7. From example to production</h2>
<ul>
<li>Store vectors in a database once you have more than a few thousand chunks; PostgreSQL with pgvector is a common choice.</li>
<li>Grow the test set from section 6 with real questions from your logs, and re-run it whenever you change the chunks, the embedding model or the documents.</li>
<li>Log the question, the chunks retrieved and their scores for every answer.</li>
<li>Send anything below the threshold, and anything sensitive, to a person.</li>
</ul>
<hr />
<p><em>First published on <a href="https://www.aitechbom.site/insights/rag-tutorial">AI Techbom</a>.</em></p>
]]></content:encoded></item></channel></rss>