<?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 H Swathi Shenoy on Medium]]></title>
        <description><![CDATA[Stories by H Swathi Shenoy on Medium]]></description>
        <link>https://medium.com/@hswathishenoy?source=rss-99a0754c64ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-sL5gYMBnULBZ6rxBiUemQ.png</url>
            <title>Stories by H Swathi Shenoy on Medium</title>
            <link>https://medium.com/@hswathishenoy?source=rss-99a0754c64ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hswathishenoy/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[Designing LLM Inference Pipelines for GxP-Regulated Environments: An Architecture Reference]]></title>
            <link>https://blog.devgenius.io/designing-llm-inference-pipelines-for-gxp-regulated-environments-an-architecture-reference-4e7cdf50d823?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e7cdf50d823</guid>
            <category><![CDATA[aws-fargate]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 09:26:01 GMT</pubDate>
            <atom:updated>2026-10-04T09:26:01.523Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A reference pipeline for LLM inference where correctness under failure matters more than raw speed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sJnhUAyy4ZVYLFnn" /></figure><h4>TL;DR:</h4><p>When an LLM pipeline handles clinical documents, “it worked” isn’t good enough, you need to know it’ll still be correct after a crash, a retry, or a duplicate message. This pipeline (SQS → Fargate → Amazon Bedrock, two dependent stages) is built around that one idea: nothing gets lost, nothing gets processed twice, and every result can be traced back to exactly what the model saw. Here’s how, with the code.</p><h4>Problem Statement</h4><p>Treat an LLM pipeline like a typical microservice and you optimize for the wrong thing. A synchronous API, parallel calls, aggressive retries all correct choices for a chatbot, <strong>all wrong for a clinical document pipeline.</strong></p><p>In a GxP regulated system, three failure modes matter more than response time:</p><ol><li>A message gets delivered twice, and the second delivery silently overwrites or duplicates a result that was already correct.</li></ol><p>2. A worker crashes between calling the model and writing the result, and the document is now neither pending nor processed, just gone.</p><p>3. Six months later, a QA reviewer asks what exactly the model saw and returned for a given document, and the answer depends on log lines that were never designed to survive that question.</p><p>None of these show up in a demo. They show up during validation, or during an incident review, when it is too late to redesign around them. The rest of this article is about the specific choices that close each of these gaps, not about making inference faster.</p><h4><strong>System Design</strong></h4><p>Two ECS Fargate workers, each consuming its own SQS queue, both calling Amazon Bedrock (Nova):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9d72Z2dbt85VU4RkqX5Eg.png" /><figcaption>Two ECS Fargate workers, each consuming its own SQS queue, both calling Amazon Bedrock (Nova Lite)</figcaption></figure><p>There is no REST API anywhere in this system. Documents enter only through a ‘SendMessage’ call to the extraction queue. Classification never touches a document until extraction has durably committed its result for that ‘doc_id’. The pipeline is intentionally two dependent stages, not two independent services that happen to share a database.</p><p>Both workers run on Fargate behind no load balancer and no public entry point, inside private isolated subnets reachable only through VPC endpoints. Scaling is driven by queue depth, since both workers spend most of their time waiting on a network call to Bedrock rather than consuming CPU.</p><h4><strong>Key Engineering Decisions</strong></h4><ol><li><strong>Delete after success, not delete on receive.</strong> Normally a queue consumer deletes a message as soon as it picks it up. Here the worker keeps the message until after it has written the result to DynamoDB and written the audit log( both extraction/classification). So if the worker crashes mid work, the message is still sitting in the queue and gets automatically retried instead of being lost forever.</li><li><strong>Visibility timeout sized to real inference latency</strong>. When a worker picks up a message, the queue hides it from other workers for a set time, five minutes here. That five minutes is chosen to be longer than the slowest Bedrock call could ever take. If it were too short, say thirty seconds, a second worker could grab the same message while the first is still waiting on the model, causing it to be processed twice by accident.</li><li><strong>Idempotency built into the data model</strong>, not the retry logic. Instead of writing complex code to detect and skip duplicate messages, the system relies on DynamoDB’s partition key, doc_id . Writing the same doc_id twice just overwrites the same row with the same final result. So even if a message does get processed twice, there is no duplicate or corrupted data, the simplest possible fix.</li><li><strong>Audit logs that prove traceability without storing sensitive data</strong>. Every processed document needs a record of what happened, for compliance. But you cannot log the actual patient text since that would create a second uncontrolled copy of sensitive data. So the log stores a SHA256 hash of the input, meaning a unique fingerprint that proves what input was used without revealing its contents, plus a short safe summary of the output.</li><li><strong>Model version pinned, never aliased</strong>. Bedrock lets you call a model by a floating alias like latest, which can silently change over time, or by an exact pinned version. This pipeline always uses the exact pinned version, so the model never changes underneath you without a deliberate, trackable configuration update.</li><li><strong>Least privilege IAM per stage. </strong>Each worker’s AWS permissions are scoped as tightly as possible. Extraction worker can only send to the next queue, classification worker cannot send anywhere, and neither can call any Bedrock model other than the one specific pinned model. This limits the blast radius if a worker is ever compromised or misconfigured.</li><li><strong>Queue depth autoscaling, not CPU</strong>. Since workers spend most of their time waiting for Bedrock to respond rather than doing heavy computation, CPU usage stays low even under load. So autoscaling is based on how many messages are waiting in the queue instead, which better reflects actual backlog.</li><li><strong>Failures escalate, they do not vanish</strong>. After three failed attempts a message is moved to a separate<em> </em><strong><em>dead letter queue</em> </strong>instead of being retried forever or silently dropped, so a human can investigate it directly.</li></ol><h4><strong>Trade-offs</strong></h4><p>Every decision above buys safety by spending time. A document is not considered done after one model call and one write. It goes through two separate stages, each with its own database write and its own audit log entry, plus a queue hop in between before classification even starts. A synchronous version of this same pipeline, one API call in, one answer out, would be noticeably faster for any single document.</p><p>That slowdown is accepted on purpose, for three concrete reasons.</p><p>First, speed was never the requirement here. The actual requirement is that a result can be trusted as its usually its behind a complex workflow, reproduced, and explained later, and that only comes from durable writes and audit logs, both of which take time.</p><p>Second, the time that is spent is deliberately sized, not wasted. The five minute visibility timeout and the autoscaling thresholds are set based on how long Bedrock actually takes, so the system is exactly as slow as it needs to be to avoid duplicate processing, and no slower.</p><p>Third, this is a one time cost per document, not a cost that grows. Each document pays for two writes and two audit logs regardless of load, so throughput scales by adding more workers against queue depth, latency per document stays roughly constant.</p><p>So the honest summary is this.</p><blockquote>A single document takes longer to finish here than it would in a simpler, faster pipeline. In exchange, you get a system where a crash never silently loses a document, a retry never silently duplicates one, and every finished result comes with proof of exactly what the model was given and what it returned.</blockquote><h4><strong>Lessons Learned</strong></h4><p>At this scale, a single shared queue per stage with per message idempotency is enough. At significantly higher volume, per document locking would need to move from an implicit property of the data model to an explicit mechanism, since concurrent overwrites of the same `doc_id` could reorder under load.</p><p>The audit log currently lives only in CloudWatch. For a system approaching real validation, that log needs a defined retention and export policy decided up front, not added later once compliance asks for it.</p><p>Pinning the model version solves reproducibility for a given deployment, but does not by itself solve the harder problem of proving the model’s behavior was validated against the version it is pinned to. That validation step lives outside this architecture and has to be tracked separately.</p><h4><strong>Conclusion</strong></h4><p>Before building something similar, answer three questions for your own pipeline.</p><p>What happens if this exact message gets processed twice?</p><p>What happens if the process dies between the model call and the write?</p><p>Can you prove what the model saw and returned, without that proof becoming a liability of its own?</p><p>Answer those first. The latency numbers that come after are the ones that will actually hold up under review.</p><p>Note: This project is a simplified version of a real production architecture I worked on. The scale, data, and infrastructure details below are rebuilt independently to be safe to share publicly, but the core design decisions are the same ones that mattered in the original system.</p><p>Full code and architecture: <a href="https://github.com/h-swathi-shenoy/clinical-doc-pipeline.git">https://github.com/h-swathi-shenoy/clinical-doc-pipeline.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7cdf50d823" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/designing-llm-inference-pipelines-for-gxp-regulated-environments-an-architecture-reference-4e7cdf50d823">Designing LLM Inference Pipelines for GxP-Regulated Environments: An Architecture Reference</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Flat RAG: Structure-Aware Graph Expansion for Multi-Hop Reasoning with GraphSAGE]]></title>
            <link>https://blog.devgenius.io/beyond-flat-rag-structure-aware-graph-expansion-for-multi-hop-reasoning-with-graphsage-4f780c1277d8?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f780c1277d8</guid>
            <category><![CDATA[graphdb]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-09-11T21:06:01.446Z</atom:updated>
            <content:encoded><![CDATA[<p>When one chunk isn’t enough GraphSAGE walks the chain that flat RAG can’t see!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E8Q6xvUcV3_qaBIe.png" /></figure><p><strong>GraphSAGE-GraphRAG</strong> is a working example of Structure-Aware Retrieval solving the multi-hop retrieval problem that flat vector RAG cannot. While traditional RAG treats document chunks as isolated units ranked purely by semantic similarity, this project builds a knowledge graph in Neo4j and trains a GraphSAGE GNN on it offline, so every node’s embedding absorbs its neighborhood before a single question is ever asked. This approach echoes the ideas behind the excellent SAGE (Structure Aware Graph Expansion) framework and the research paper it’s built on: <a href="https://www.arxiv.org/abs/2602.16964">https://www.arxiv.org/abs/2602.16964</a>.</p><p><a href="https://github.com/h-swathi-shenoy/graphsage-graphrag/tree/main">https://github.com/h-swathi-shenoy/graphsage-graphrag/tree/main</a></p><h3>1. The Problem : Why Flat RAG Fails</h3><p>Flat RAG works by embedding every chunk of text independently and retrieving whichever chunks are <em>semantically closest</em> to the question. That works fine when the answer lives inside one document. It breaks down the moment the answer is a <strong>chain of facts spread across multiple documents</strong>, none of which reference each other in a way that text embeddings can pick up.</p><p>The Dataset</p><p>This project ships with a small, self-contained example knowledge base 16 short documents describing the flight operations of a fictional airline, SkyLink Airlines.</p><p>It’s deliberately small so the multi-hop chain is easy to follow by hand, but it’s structured the way a real operations knowledge base is: a mix of entities (flights, aircraft, systems, teams, policies) and incidents that reference them indirectly.</p><blockquote>What’s in the corpus:</blockquote><p>• Flights &amp; aircraft: Flight 202 (ORD → LAX), flown by Aircraft N882AA , which is shared across two other routes on rotation<br>• Systems: ramp-scheduler (gate/ground scheduling, 8-slot-per-hour cap), crew-scheduler (pilot/crew assignment, FAA duty-time rules)<br>• Teams: Team Flight Operations , Team Ground Operations , Team Airport Operations , Team Crew Scheduling each owns a different piece of the puzzle<br>• Policies &amp; changes: SP-118 (a staffing-policy change), PL-FAA-7 (a safety policy it violated)<br>• Incidents: INC-2209 (the flight delay) and its root-cause analysis INC-2209-rca , plus an unrelated earlier incident INC-1187 for contrast<br>• Runbooks: capa-turnaround , capa-crewhold the “what to do” documents that operators actually consult</p><p>Each document is written the way real operational documentation is written: focused on its own system or event, with almost no cross-referencing. The ramp-scheduler doc never mentions Flight 202. The incident report never explains why the scheduler ran out of capacity. That’s the whole point the corpus is designed so that no single chunk answers a root-cause question, forcing retrieval to either get lucky on lexical overlap (flat RAG) or actually traverse relationships (GraphRAG).</p><blockquote>Lets look at the following concrete example:</blockquote><p><strong>Flight-delay incident INC-2209</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgCsr_kFw8AOf6mQQCsgBw.png" /><figcaption>Same question, same 16-document corpus, two very different answers.</figcaption></figure><p>When asked “Which team should be paged for INC-2209, and which team actually caused it?” and F<strong>lat vector RAG</strong> retrieves the four chunks that lexically resemble the question inc-2209 , inc-2209-rca , inc-1187 , team-groundops because they all contain words like “team,” “incident,” and “caused.” It never retrieves capa-turnaround , the runbook that actually names the correct team to page, because that document shares almost no vocabulary with the question. The result isn’t just incomplete it’s factually wrong: the LLM confidently names <em>Team Ground Operations</em> for both halves of the question, when in reality that team caused the incident but isn’t who gets paged.</p><p><strong>GraphRAG</strong> starts from the same question but asks a different kind of question of the data: not “what sounds similar?” but “what is this incident connected to?” By attaching the question as a virtual node and running it through GraphSAGE, it surfaces seed entities based on graph structure ( N882AA , INC-2209 , Flight 202 ), then walks two hops in Neo4j to reach ramp-scheduler → OWNED_BY → Team Airport Operations and, separately, SP-118 → TRIGGERED_BY → Team Ground Operations . Neither of those two facts lives in the same document, and neither is reachable by similarity search alone — only by following the relationship edges between them.</p><p>That’s the core failure mode this diagram illustrates: flat RAG is a similarity search, not a reasoning process. It fails silently with no low-confidence signal whenever the correct answer depends on a connection between two facts that don’t happen to use similar words.</p><h3>2. Implementation</h3><blockquote>Getting Started</blockquote><p>The full source is on GitHub, and you can reproduce every screenshot in this article on your own machine in about two minutes of actual runtime (plus setup):</p><pre>1. git clone &lt;repo-url&gt; &amp;&amp; cd graphsage-graphrag<br>2. docker compose up -d # Neo4j 5.26 on 7474 (browser) / 7687 (bolt). Starts Neo4j locally<br>3. python3 -m venv .venv .<br>4. /.venv/bin/pip install -r requirements.txt<br>5. ./.venv/bin/python 01_ingest.py # build the graph (~1 min, Bedrock calls)<br>6. ./.venv/bin/python 02_train_graphsage.py # train the GNN (~20 s, CPU)<br>7. ./.venv/bin/python 03_ask.py # answer the demo questions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qmiEbbdkRrdZuRrzhw-hw.png" /><figcaption>Stack, for context</figcaption></figure><p>There are three stages, and each one is a standalone script you can run and inspect independently: ingest the documents into a graph, train GraphSAGE on that graph, then retrieve using both the graph structure and the trained embeddings. The rest of this section walks through each stage in the order it runs, using the actual numbers and output from this project’s own pipeline — not simplified pseudocode.</p><h4>Stage 1 : Building the Graph (`01_ingest.py`)</h4><p>The first step turns the 16 flight-ops documents (present in corpus.py) into a graph instead of a flat list of chunks. For each document:</p><p>1. The raw text is stored and embedded as a `Chunk` (this is what flat vector RAG would use on its own).</p><p>2. An LLM (Nova Lite) reads the same text and extracts <em>entities</em> (`Flight 202`, `ramp-scheduler`, `Team Ground Operations`) and **relationships** between them (`DEPENDS_ON`, `OWNED_BY`, `TRIGGERED_BY`, …).</p><p>3. Those entities and relationships are merged into the graph, so the same entity mentioned in two different documents becomes *one* connected node — not two disconnected mentions.</p><blockquote><em>Why this matters: </em>This is the step that creates the connections flat RAG can never see. `ramp-scheduler` appears in one document and `Team Airport Operations` in another — a chunk-similarity search treats them as unrelated text. But here, once extracted into the graph, they’re one hop apart.</blockquote><p>One deliberate simplification worth knowing about: <em>entities</em> are matched by lowercasing their name (Flight 202 → flight 202). That’s enough for a 16-document demo, but it’s the first thing that breaks at real-world scale — two spellings of the same entity become two disconnected nodes. This is a known limitation, not an oversight.</p><p>The result, on this corpus: <strong>16 chunks → 33 entities, 54 relationships, 70 mentions.</strong> Small enough to inspect by hand in the Neo4j browser, large enough that no single chunk contains the full INC-2209 chain.</p><p>Each entity also gets its own embedding built from its name, type, description, and the text of chunks that mention it. That embedding is the <em>input feature</em> GraphSAGE trains on next(it’s separate from the chunk embeddings used for plain vector search)</p><blockquote>Under the hood: the Cypher</blockquote><pre>```cypher<br><br>CREATE CONSTRAINT chunk_id  IF NOT EXISTS FOR (c:Chunk)  REQUIRE c.id IS UNIQUE<br>CREATE CONSTRAINT entity_key IF NOT EXISTS FOR (e:Entity) REQUIRE e.key IS UNIQUE<br><br>CREATE VECTOR INDEX chunk_vec IF NOT EXISTS<br>FOR (c:Chunk) ON (c.embedding)<br>OPTIONS {indexConfig: {<br>  &#39;vector.dimensions&#39;: 1024,<br>  &#39;vector.similarity_function&#39;: &#39;cosine&#39;}}<br>```</pre><p>That vector index is what powers the <em>flat RAG baseline </em>in this project it’s the same Neo4j instance doing both jobs, which is what makes the<em> — compare</em> flag a fair, apples-to-apples test.</p><p>Every extracted entity is merged, not created this is what turns “Team Ground Operations” mentioned in three different documents into <strong>**one**</strong> node instead of three duplicates:</p><pre>```<br>cypher<br>MERGE (n:Entity {key: $key})<br>ON CREATE SET n.name = $name, n.type = $type, n.description = $desc<br>ON MATCH  SET n.description = CASE<br>WHEN size(coalesce(n.description,&#39;&#39;)) &lt; size($desc)<br>THEN $desc ELSE n.description END<br>WITH n MATCH (c:Chunk {id: $doc})<br>MERGE (c)-[:MENTIONS]-&gt;(n)<br><br>```</pre><p><em>key</em> is the entity&#39;s lowercased name this single line is the entity-resolution strategy for the whole project, and the reason it&#39;s flagged as the first thing to improve at scale.</p><p>Run the following query, right after ingestion, to see the exact chain the article is built around:</p><pre>```cypher<br><br>MATCH p = (:Entity {key:&#39;flight 202&#39;})-[:RELATES_TO*1..3]-(:Entity {key:&#39;ramp-scheduler&#39;})<br>RETURN p LIMIT 5<br>```</pre><p>That&#39;s the query that proves the connection exists in the graph <em>before</em> GraphSAGE ever runs GraphSAGE&#39;s job (next section) is to make that same connection discoverable <em>without</em> writing this exact Cypher by hand, i.e., from a natural-language question instead of a known entity pair.</p><h4><strong>Stage 2: Training GraphSAGE (`02_train_graphsage.py`)</strong></h4><p>At this point the graph exists in Neo4j, but it’s just structure no model has learned anything from it yet. This step trains <strong>GraphSAGE</strong> so that every node’s embedding absorbs information from its neighbors, not just its own text.</p><p><strong>Why not just use the entity embeddings from Stage 1 directly?<br></strong> Because those embeddings only capture what a document says about an entity they know nothing about what that entity is <em>connected to</em>. ‘ramp-scheduler’s’ embedding, on its own, has no idea it’s two hops from `Flight 202`. GraphSAGE’s whole job is to fix that: after training, an entity’s vector is a blend of its own features and its neighbors’ features, propagated across the graph.</p><p><strong>How it works?</strong> Each node repeatedly updates its embedding by combining its own vector with the <em>average</em> of its neighbors’ vectors, through a small learned transformation stack that a couple of times, and a node’s final embedding reflects everything within 2 hops of it.</p><p>Training is <strong>unsupervised</strong> there are no labels here, just the graph’s own structure. The signal comes from random walks: nodes that co-occur on a short walk are treated as should be similar, and the model is pushed to agree.</p><p><strong>Why GraphSAGE specifically?</strong> GraphSAGE learns <em>aggregator functions</em>. Given any nodes neighbors, even a node that didn’t exist at training time, it can produce a sensible embedding on the spot. That property is the entire reason the retrieval step (next section) works at all — a user’s question is exactly the kind of “new node” GraphSAGE was built to handle.</p><p>Once, the training is completed, the trained embeddings are written back as a ‘.sage’ property on each Chunk/Entity node in Neo4j itself, not a separate file, though <em>`graph_cache.pkl`/`sage_model.pt</em>` are also saved locally as a cache/checkpoint for retraining without re-hitting Neo4j.</p><h4>Stage 3: <strong>How Retrieval Actually Works (`retriever.py`)</strong></h4><p>By this point there are two separate things sitting in Neo4j: the original chunks with their text embeddings (Stage 1), and a graph where every entity’s embedding now reflects its neighbors (Stage 2). Retrieval is where both get used <em>together</em>.</p><p><strong>Think of it as three questions asked in sequence:</strong></p><p><strong>1. “Which text sounds like this question?” : </strong>The ordinary vector search. Titan embeds the question, Neo4j’s vector index returns the top few chunks whose <em>wording</em> is closest. This is flat RAG, and it’s still run here not thrown away, just no longer the only path.</p><p><strong>2. “Which entities is this question structurally close to?”</strong> : This is the part that makes GraphRAG different, and the trickiest idea in the whole project. The question doesn’t exist in the graph. So it’s temporarily <em>*inserted*</em> as a new node, connected to the handful of existing nodes it resembles most in raw text, and then run through the already-trained GraphSAGE model the same one from Stage 2, no retraining involved.</p><p>Why this works at all: GraphSAGE never memorized “the question” it learned a general rule for <em>how to combine a node with its neighbors</em>. Apply that same rule to a brand-new node, and it produces a sensible, structure-aware embedding on the spot(aggegrating feature of GraphSAGE). That’s the entire point of using GraphSAGE which only knows the exact nodes it was trained on.</p><p>The output of this step is a short list of <strong>seed entities</strong> not because they sound like the question, but because they sit in the right neighborhood of the graph. In practice, these often look nothing like a keyword match: on the flight-delay example, the top seed for “why was Flight 202 delayed” is the aircraft, `N882AA` not because the question mentions the tail number, but because that’s structurally where the answer lives.</p><p><strong>3. “What is each seed entity connected to?” </strong>starting from those seed entities, the graph is walked outward one or two relationship hops, collecting every entity and relationship along the way. This is the step that reaches `ramp-scheduler`, `Staffing Policy SP-118`, and `Team Ground Operations` none of which were retrieved by step 1, because none of them share vocabulary with the original question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRBKCOo6vc_c333vi4tCOg.png" /><figcaption>Virtual Node trick for creating a new structure aware graph</figcaption></figure><p><strong>Then everything is handed to the LLM together:</strong> The relationships found in step 3 (as a simple list “<em>ramp-scheduler owned by Team Airport Operations</em>”), plus the actual document text from steps 1 and 3, with an explicit instruction to use the relationships to connect facts across documents. The relationships are what let the model reason across chunks instead of just summarizing whichever one ranked highest.</p><p>Now I believe you have realized that flat RAG answers based on <br><em>what the question sounds like”</em>. But , this retriever answers based on “<em>what the question is connected to”</em> and those turn out to be very different sets of documents whenever the real answer requires more than one hop.</p><blockquote>TL; DR</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzQ0UoMWNCGC9Wpu79Yqsg.png" /></figure><p>The whole system is three scripts, run in order, each one handing something concrete to the next:</p><p>Stage 1 : Ingest (`01_ingest.py`) turns 16 plain-text documents into a graph. Nova Lite reads each document and extracts entities and relationships; those get merged into Neo4j. This runs **once**. Output: a graph of 33 entities, 54 relationships, 70 chunk-to-entity mentions sitting permanently in Neo4j.</p><p>Stage 2: Train (`02_train_graphsage.py`) reads that same graph back out, flattens it into 49 nodes and 113 edges, and trains GraphSAGE on it unsupervised. This also runs **once** (or periodically, if new documents are added later). The important thing it produces isn’t a file it’s two things: a trained model** (`sage_model.pt`, the reusable aggregator functions) and a 128-dimensional `.sage` embedding written onto every node in Neo4j itself**, so the graph now carries both its structure and its trained representation together.</p><p>Stage 3: Retrieve (`03_ask.py` / `retriever.py`) is the only stage that runs per question. It doesn’t touch the documents or retrain anything it reuses the trained model from Stage 2 and the graph from Stage 1 to (a) embed the question, (b) run it through GraphSAGE as a temporary “virtual node” to get structure-aware seed entities, and walk 2 hops from those seeds in Neo4j to pull in the connected facts.</p><h4>Demo</h4><p><a href="https://jumpshare.com/s/3H9Ii7iJ1zK3DviyKF1f">demo_compare_trace — View Image</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*nyFnH8_UoufPSxbJ" /></figure><h3>Conclusion</h3><p>This project is a small, concrete step toward retrieval systems that are both smarter and more trustworthy.</p><p>By moving structural reasoning offline extracting an entity graph and training GraphSAGE on it before any question is ever asked the expensive work of discovering relationships is separated from the latency-sensitive work of answering a query. What’s left at inference time is a single forward pass and a Cypher walk: fast enough to run per-question, deterministic enough to explain afterward.</p><p>Unlike a pure vector-similarity retriever, where all you can observe is what got retrieved, this pipeline is traceable end-to-end: which node the question attached to, which seed entities GraphSAGE ranked and why, which relationship edges were traversed, and which chunks backed the final answer. Every hop in the chain is <strong>inspectable</strong> including the one hop flat RAG silently drops.</p><p>That difference showed up concretely, not theoretically: asked the same question, flat RAG named the same team for two different roles paged and at-fault because both answers were anchored to the same top-ranked chunk. GraphRAG separated them, because it was reasoning over structure, not just wording.</p><p>As retrieval systems move into domains where a wrong answer isn’t just annoying but costly incident response, compliance, operational root-causing it retrieved something relevant stops being good enough. The question becomes <strong>why it retrieved</strong> that, and whether the chain of reasoning behind the answer can be checked.</p><p>This project doesn’t promise a bigger model or a cleverer prompt.</p><p>It promises a graph, an inductive embedding, and a traversal you can point to.</p><p>And in multi-hop retrieval, that’s the difference between a system that sounds right and one you can actually verify</p><p>Thank you for reading! 😊</p><p>Github Link: <a href="https://github.com/h-swathi-shenoy/graphsage-graphrag/tree/main">https://github.com/h-swathi-shenoy/graphsage-graphrag/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f780c1277d8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/beyond-flat-rag-structure-aware-graph-expansion-for-multi-hop-reasoning-with-graphsage-4f780c1277d8">Beyond Flat RAG: Structure-Aware Graph Expansion for Multi-Hop Reasoning with GraphSAGE</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Serverless MCP  : Your next power-up for Agentic AI]]></title>
            <link>https://blog.devgenius.io/build-serverless-mcp-your-next-power-up-for-agentic-ai-cf3d92f58716?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3d92f58716</guid>
            <category><![CDATA[strands-agents]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[end-to-end-solution]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 02:59:51 GMT</pubDate>
            <atom:updated>2025-07-30T18:18:06.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Serverless MCP 🧠📜 : Your next power-up for Agentic AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KsoXCgME5UO7dUHb.png" /></figure><p>Learn how to build Serverless MCP application powered by agentic rag , web search tools.</p><p>Since last few months, our team embarked on the journey to build agents at scale that can help us bring relevant answers from applications like Jira, Confluence using which personas like product owners, executives will be able to build Jira Stories/ Get Confluence content.</p><p>This journey was quite a fascinating one with great learning experience, thank you to my peers!</p><p>We utilized frameworks such as Phi data and AWS Strands to construct an Agentic Workflow. A streaming Lambda function was developed to address latency concerns. Finally, a serverless MCP (Model Context Protocol) server was implemented, hosting tools like Jira and Confluence, which allowed for the successful building of agents at scale.</p><p>In this article, I have made an effort to share the knowledge on how you can build serverless MCP servers on AWS.</p><blockquote><strong>Introduction</strong></blockquote><p>I’m sure you have already come across various definitions for MCP. One of them is mentioned below.</p><p>MCP, or Model Context Protocol, is an open standard that enables large language models (LLMs) to securely access and utilize external data, tools, and services.</p><p><strong>Key highlights:</strong></p><ul><li><em>Standardised Connection:</em> MCP offers a unified method for AI models to interact with external systems, independent of the model or underlying technology.</li><li><em>Secure Access</em>: MCP guarantees secure access to resources through defined boundaries and permissions for AI model interaction with external data and tools.</li><li><em>Two-Way Communication</em>: MCP enables both sending context to AI models and receiving results or actions, supporting dynamic and interactive AI applications.</li><li><em>Ecosystem of Tools</em>: MCP fosters an ecosystem of “MCP servers” (applications exposing functionality/data via MCP) and “MCP clients” (AI applications connecting to servers).</li></ul><blockquote><strong>Architecture Overview</strong></blockquote><p>Now, lets look at the architecture of building Serverless MCP with its tool such as AgenticRAG, WebSearch tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSgGyHp_nfeMBg7rLpTJhg.png" /><figcaption>1. High Level Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwAhKNeqpN_SBt7UFKdROA.png" /><figcaption>2. Serverless MCP Architecture</figcaption></figure><p>In the above architecture(1) we see the High Level Architecture of the Serverless MCP and its tool calling.</p><ol><li>At first <strong>Client</strong> sends the query to the MCP client.</li><li><strong>MCP Client</strong> being the user facing application is responsible for receiving the user query , communicating it to the backend server and finally forward the response back to user.</li><li><strong>MCP Server (</strong>Agent ): This is the core of our system — the “brain” of the operation. When the MCP Server receives a request, it doesn’t just try to answer from its own pre-trained knowledge. Instead, it acts as an <strong>agent</strong>, intelligently deciding if it needs more information to provide a high-quality answer.</li><li><strong>Tools:</strong> These are external resources the MCP Server can use to find information. Our architecture features two powerful tools:</li></ol><ul><li><strong>Vector DB search MCP tool:</strong> This tool connects to a specialised vector database(QDrant vector store). This database is ideal for storing and searching through your private documents, internal knowledge bases, or any custom text corpus. It excels at finding semantically similar information (the “Retrieval” in RAG).</li><li><strong>Web search MCP tool:</strong> When the answer isn’t in our private data, this tool allows the agent to search the live internet for the most current and relevant public information.</li></ul><blockquote><strong>Hands On</strong></blockquote><p>Now, that we have architecture mapped out..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*G4SPP69vkACDEXWP.png" /></figure><p><strong>Pre-requisites</strong></p><ol><li>Python &amp; pip</li><li>AWS Account ( primarily for Lambda, CodeBuild, ApiGateway services)</li><li>Docker( for building your application i.e lambda function)</li><li>QDrant Account for Vector Database</li></ol><p>The project structure mostly look like this</p><pre>/serverless-mcp<br> -server<br>   -- app.py # contains server logic i.e main application MCP Server<br>   -- Dockerfile<br>   -- requirements.txt<br>   -- env.txt <br> -client<br>   -- streamlit_app.py # contains mcp client logic to forward request to server/get responses.<br>   -- Dockerfile<br>   -- requirements.txt<br>   -- env.txt</pre><blockquote>Building MCP Server via Serverless Approach</blockquote><p>Now, lets have a look at how to build a MCP server logic, in a serverless way:)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/268e00d3cff194bd071b2370c3d5b7d3/href">https://medium.com/media/268e00d3cff194bd071b2370c3d5b7d3/href</a></iframe><p>Following are the crucial points to look at from above logic:</p><ol><li>In-order to build the serverless MCP server (the brain), we shall need a <strong>MCPLambdaHandler</strong> that will be our mcp server which will be responsible for handle the requests from the client and send back the responses.</li><li>Once we have the server defined, we add its respective tools. In our case tools are <strong>rag_retrieve_and_generate</strong> tool, <strong>firecrawl_web_search </strong>tool. The former one is responsible for handling queries related to deep learning concepts, and later one is for queries apart from deep learning.</li><li>The first tool is our <strong>rag_retrieve_and_generate </strong>which retrieves the context from <strong>QDrant vectorstore</strong> for querying LLM.</li><li>The second tool is the <strong>firecrawl_web_search </strong>tool using firecrawl api key for scraping data and provide relevant results.</li></ol><p>Once, we have the lambda code ready ready. We need to have the dependants i.e Dockerfile, requirements.txt files.</p><p>Later, we <strong>deploy our server logic as Lambda via CodeBuild</strong>, as this makes our life easier to deploy lambdas after every change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e2c1b09a4111e1e0fc1609aeee50d9e/href">https://medium.com/media/7e2c1b09a4111e1e0fc1609aeee50d9e/href</a></iframe><p>Once, the mcp server is deployed. We need to deploy Lambda as an endpoint using API Gateway.</p><p>As you deploy lambda as an endpoint , make sure to have the <strong>mount point or resource path</strong> to be ‘<strong>/mcp’.</strong></p><p>Now, that we have our backend deployed and ready, lets quickly hop on to the front end part.</p><blockquote>Building Client Side — Streamlit Frontend</blockquote><p>The deployed mcp server is now available as an endpoint which we shall use it as our api within our MCP Client</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1b9d12c18e46762e331ab279435bc85/href">https://medium.com/media/d1b9d12c18e46762e331ab279435bc85/href</a></iframe><p>Things to note from MCP Client:</p><ol><li>The MCP Client module of<strong> AWS Strands</strong> makes it easier to build the MCP client via which we can expose the tools available within MCP Server</li><li>Supports using <strong>Streamable HTTP from an MCP client</strong> way to connect to remote server( in our case deployed lambda as an endpoint at ‘/mcp’)</li></ol><p>I have deployed the simple frontend application via ECS Fargate.</p><p>Let me explain in gist how to deploy application into ECS Fargate</p><ul><li><strong>Build and Push Docker Image to Amazon ECR: </strong>In our case, the streamlit application including MCP Client logic.</li><li><strong>Create an Amazon ECS Cluster: </strong>Navigate to the Amazon ECS console. Create a new cluster, ensuring Fargate is chosen as the infrastructure type.</li><li><strong>Define an ECS Task Definition: </strong>Create a new task definition in the ECS console. Specify Fargate as the launch type compatibility. Configure the container details( streamlit application ecr), including the image URI from ECR, port mappings(8501 for streamlit), CPU, and memory requirements, task-execution role.</li><li><strong>Create an ECS Service: </strong>Create a new service within your ECS cluster. Select the Fargate launch type and choose the task definition created in the previous step. Configure the desired number of tasks, networking settings (VPC, subnets, security groups), and optionally set up an Application Load Balancer for traffic distribution.</li></ul><p>Once, the tasks are running within our cluster, you can see your deployed Streamlit application as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nU-DIsbBFgHWQhhGeFkcrQ.gif" /><figcaption>Streamlit Application for MCP Client</figcaption></figure><blockquote>Conclusion</blockquote><p>Kudos, for making this far.</p><p>We’ve seen how MCP allows us to define distinct tools and how the agent uses simple docstrings to intelligently decide which capability to use for a given query. This powerful pattern allows you to create applications that can reason about their own abilities and dynamically pull information from private knowledge bases (via RAG) and the public internet, leading to far more accurate and helpful responses.</p><p>Additionally you have also understood how to deploy backend pipeline i.e our MCP Servers in a serverless way using Lambda + API-Gateway Services. And also, deployed the frontend pipeline containing MCP Client using ECS Fargate Service.</p><p>Also, AWS Strands:))</p><p>This approach of building Serverless MCP Servers at scale gives us more freedom to expand the system by adding more tools (e.g., a calculator, a database query tool), ingesting more complex documents into your RAG pipeline, or connecting it to a real user interface. Henceforth we can claim that <strong>MCP is the next power-up for Agentic AI!</strong></p><p>You can find the Code for above implementation <a href="https://github.com/h-swathi-shenoy/strand-agents/tree/main/serverless-mcp">here</a>.</p><p>Thats all for now, folks! Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3d92f58716" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/build-serverless-mcp-your-next-power-up-for-agentic-ai-cf3d92f58716">Build Serverless MCP 🧠📜 : Your next power-up for Agentic AI</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Powered Invoice Analyser and Validator — PART 1]]></title>
            <link>https://blog.devgenius.io/building-ai-powered-invoice-analyser-and-validator-part-1-9c85259d73b9?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c85259d73b9</guid>
            <category><![CDATA[aws-nova]]></category>
            <category><![CDATA[mistral-ocr]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 17:22:13 GMT</pubDate>
            <atom:updated>2025-04-07T14:04:35.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building AI Powered Invoice Analyser and Validator — PART 1</h3><p>Using LangGraph + Mistral OCR + Amazon Nova Models+ Streamlit = AI Invoice Analyser Application 🤖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzdRuqJIMxmUHU7zQuIMCw.png" /></figure><h4><strong><em>Introduction</em></strong></h4><p>Invoice validation is a crucial process that ensures the accuracy and integrity of invoices by verifying details like vendor information, purchase orders, and invoice amounts before payment.Let’s explore our innovative solution! 🚀</p><h4><strong>🎯 <em>The Challenge</em></strong></h4><p>While invoice validation people face several challenges when dealing in large scale:</p><ul><li>⏰ Time-consuming manual review processes</li><li>❌ Potential for human error in invoice analysis</li><li>✅ Need for consistent validation of invoice i.e. eyeballing can be exhausting</li><li>🔍 Difficulty in quickly extracting key information</li></ul><h4><em>💡</em><strong><em>Solution: The Invoice Analyser and Validator</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKLcS9DUNftNMyMatjShZw.png" /><figcaption>Solution Architecture</figcaption></figure><p>We shall be developing a streamlit application(in PART 2) that uses advanced AI models to analyse and validate invoices. The application focuses on:</p><ul><li>🎨 User-friendly interface</li><li>⚡ Fast processing</li><li>🎯 Accurate analysis</li><li>✨ Comprehensive validation</li><li>📊 Clear presentation of results</li></ul><h4><strong><em>🏗️ Solution Architecture</em></strong></h4><ol><li><em>FrontEnd</em> : Streamlit Application( more details in part 2)</li><li><em>Backend AI Models</em>: We will be using Amazon Nova Pro Models for Analysis and Validation, Mistral OCR capabilities for PDF processing</li><li><em>LangGraph</em> as Workflow Orchestrator</li></ol><h4><em>🔄 </em><strong><em>The Analysis Pipeline</em></strong></h4><p>The application processes documents through four key stages:</p><ol><li><strong>📄 Document Extraction (using Mistral OCR)</strong></li></ol><ul><li>OCR processing for PDFs</li><li>Text extraction and cleaning</li><li>Format standardisation</li></ul><p><strong>2. 🔍 Invoice Analysis</strong></p><ul><li>Key Invoice Details like ID, GST Number, PAN Number</li><li>Seller Name/Address</li><li>Buyer Name/Address</li><li>Item Details with Price including GST/CGST</li><li>Signature Details</li><li>Payment Details</li></ul><p><strong>3. ✅ Invoice Validation</strong></p><ul><li>Check if key details from above analysis are present.</li><li>If all fields are present mention its a valid report and if not give reasoning.</li></ul><p>Now, that we have understood the workflow, lets get to work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3OEDMlPZX_ngsr_.png" /></figure><h4><em>🚀 Code Implementation</em></h4><p>At first, we shall use a sample invoice in a pdf format. It contains crucial details as follows:</p><ul><li><em>Seller Details</em><br> — Seller Name<br> — Seller Address</li><li><em>Buyer Details</em><br> — Name of the buyer<br> — Buyer Address<br> — GST Number<br> — PAN Number<br> — State/UT Code</li><li><em>Order Details</em><br> — Order Number<br> — Order Date</li><li><em>Invoice Details</em><br> — Invoice Number <br> — Invoice Details<br> — Invoice Date</li><li><em>Item Details</em><br> — List of Items with Description and Price without and with tax<br> — Total Amount</li><li><em>Signature Details( Provide Yes if signed, else No)</em><br> — Is it signed ?</li><li><em>Payment Details</em><br> — List of Transaction Ids<br> — List of Timestamp for transactio<br> — Mode of Payment<br> — Invoice Value</li></ul><p><strong>Steps</strong>:</p><ol><li>Document Extraction : We use Mistral OCR for this purpose.</li></ol><p><em>Why Mistral OCR?</em></p><ul><li>Efficient Document Understanding at Scale(Multimodal Recognition, Context Understanding)</li><li>Unmatched Speed for High-Volume Tasks(Mistral OCR processes up to 2,000 pages per minute on a single node)</li><li>Superb Accuracy Across All Document Types</li></ul><p>2. Invoice Analysis: We extract key fields that necessary for the invoice analysis. We shall use Amazon Nova Models for this purpose. More details about this, you can refer to my previous <a href="https://medium.com/dev-genius/intro-to-tool-use-function-calling-with-aws-nova-models-0d55b0c440cc">article.</a></p><p>3. Invoice Validation: Based on the above analysis, we shall validate if the given invoice is valid or no. We use Amazon Nova Models or this purpose.</p><p>Using <em>LangGraph</em> we will orchestrate the above workflow.</p><p>Lets see some Code now!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2fb0125d3499121a953c3b0d30399d1/href">https://medium.com/media/f2fb0125d3499121a953c3b0d30399d1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb997bfe2bced4804220232cf2542677/href">https://medium.com/media/fb997bfe2bced4804220232cf2542677/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4babd469aa2316167effd25c2fbba1d5/href">https://medium.com/media/4babd469aa2316167effd25c2fbba1d5/href</a></iframe><p>Graph of the above workflow is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*D3f4bKXbQLN07sSALO6H0w.png" /><figcaption>Graph of the invoice analysis/validator</figcaption></figure><p>Now, lets test the workflow by passing the sample invoice in pdf format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCdq9bFdUBZU83jinJw6Lw.png" /><figcaption>invoke analysis chain</figcaption></figure><p>Results from the above workflow are as follows. It has concluded that given invoice as valid , as it contains all the key details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6hmZ9YuvsAcbUvIMBm9sw.png" /></figure><h4><strong><em>🚀 Feasible Enhancements</em></strong></h4><p>The logic of the invoice was rather straightforward since it was a fairly brief document. We can develop significantly more intricate logic that incorporates additional financial and business logic.</p><p>The backend AI models, such as <em>Amazon Nova Models </em>and<em> Mistral’s OCR</em> functionalities, are designed to support this.</p><h4>🎉<strong><em> Conclusion</em></strong></h4><p>In this article, we explored how to create an AI-driven Invoice Analyzer and Validator that demonstrates how to enhance the accuracy and reliability of complex tasks like <em>Invoice Processing</em>.</p><p>In the next sequel, we will work on the following elements.</p><p>Server-Side Workflow: Encapsulating the backend functionality into Lambda Code via container image and deploying it.</p><p>Client-side workflow: A Streamlit application for users, will be deployed utilising AWS Fargate.</p><p>Thats all for now, folks! Stay tuned <a href="https://emojipedia.org/loudspeaker">📢</a></p><p>Code : <a href="https://github.com/h-swathi-shenoy/invoice-analyser-validator/tree/main">Github Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c85259d73b9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-ai-powered-invoice-analyser-and-validator-part-1-9c85259d73b9">Building AI Powered Invoice Analyser and Validator — PART 1</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Tool Use(function calling) with AWS Nova Models]]></title>
            <link>https://blog.devgenius.io/intro-to-tool-use-function-calling-with-aws-nova-models-0d55b0c440cc?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d55b0c440cc</guid>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[aws-nova]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 09:14:32 GMT</pubDate>
            <atom:updated>2025-02-19T15:52:37.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Explore the multimodal/tool functionalities of Nova Models with Amazon Bedrock Converse API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O3HtXQ0u_oNLsTO3.jpg" /><figcaption>AWS re:Invent 2024</figcaption></figure><blockquote>Introduction</blockquote><p>Amazon recently released ‘<strong>Nova Models</strong>’ , a State-of-the-art foundation models that delivers frontier intelligence and industry leading performance. These family of understanding models that can handle multiple input types such as text, images, and videos.</p><p>With its proprietary Trainium and Inferentia chips, Nova stands as a scalable and efficient solution, aiming to outpace competitors like OpenAI’s GPT-4o, Google’s Gemini, and Meta’s LLaMa.</p><p>Moreover, Nova Models offers superior price performance, with lower pricing at equivalent or better latency.</p><p>There are around 2 kinds of Models i.e. <strong>‘Understanding Models</strong>’ and <strong>‘Creative Content Generation’.</strong></p><blockquote>Understanding Models(Text Generation Models)</blockquote><ul><li><strong>Amazon Nova Micro</strong> is a text-only model that delivers the lowest latency responses at very low cost. Supports <strong>128k</strong> context window length</li><li><strong>Amazon Nova Lite</strong> is a very low cost multimodal model(text/image/video) that is lightning fast for processing image, video, and text inputs. Supports <strong>300K</strong> context window length</li><li><strong>Amazon Nova Pro</strong> is a highly capable multimodal model(text/image/video) with the best combination of accuracy, speed, and cost for a wide range of tasks. Supports <strong>300K </strong>context window length</li></ul><p>*<em>Arranged in increasing order of intelligence/price and decreasing order of latency</em></p><blockquote>Creative Content Generation(Video/Image Models)</blockquote><ul><li><strong>Amazon Nova Canvas</strong> — is a state-of-the-art image generation model that creates professional grade images from text and image inputs. Amazon Nova Canvas is ideal for a wide range of applications such as advertising, marketing, and entertainment.</li><li><strong>Amazon Nova Reel</strong> — is a state-of-the-art video generation model that supports the generation of short videos from input text and images. Amazon Nova Reel provides camera motion controls using natural language inputs.</li></ul><blockquote><strong>Why Nova Models?</strong></blockquote><ol><li>Lower Latency at very Low Costs. For instance : Nova Micro delivers an output speed of <strong>210 tokens per second</strong>, making it ideal for real-time applications such as chatbots and dynamic content generation.</li><li>Multi-Lingual and High Context Window. For instance :Context lengths of up to <strong>300K input tokens</strong> (30 minutes of video) for Nova Lite and Pro, with future updates expanding this to <strong>2M tokens.</strong></li><li>Customisation via AWS Bedrock i.e. Deploy Nova Models with minimal Infrastructure Complexity.</li><li>MultiModal Functionality/Function Calling.</li><li>Support for fine-tuning to boost accuracy</li><li>Supports Distillation i.e. to train smaller and more efficient models which enables the transfer of specific knowledge from a larger, highly-capable “teacher model” to a smaller, more efficient model that is highly accurate, but also faster and cheaper to run.</li></ol><blockquote>Function Calling (Tool Use) with AWS Nova</blockquote><p><strong>Tool use</strong> is a capability that allows a large language model to tell the calling application to invoke a function with parameters supplied by the model. The available functions and supported parameters are passed to the model along with a prompt. It’s important to note that the large language model does not call a function itself — it just returns JSON and lets the calling application do the rest.</p><p>Tool Use with the Amazon Bedrock Converse API follows these steps:</p><ol><li>The calling application passes (A) tool definitions and (B) a triggering message to the large language model.</li><li>If the request matches a tool definition, the model generates a tool use request, including the parameters to pass to the tool.</li><li>The calling application extracts the parameters from the model’s tool use request and passes them to the corresponding local function for the tool.</li><li>The calling application can then either use the tool result directly, or pass the tool result back to the model to get a follow-on response.</li><li>The model either returns a final response, or requests another tool.</li></ol><p>After learning what we need to know about Nova Models function calling, let’s go hands-on.</p><blockquote><strong>Code walkthrough: using the Amazon Bedrock Converse API</strong></blockquote><p>Just want the code? Grab it <a href="https://github.com/h-swathi-shenoy/aws-genai/tree/main/AmazonNova">here</a>.</p><p><strong>Implement the Tool.</strong></p><p>Tools that I have crafted are as follows:</p><ol><li>Document Summarizer: Generates the summary for a given document</li><li>Image Summarizer: Generates the summary for a given image</li><li>Country Canvas : Generates an image of countries based on the country name</li></ol><p>Lets understand in detail for one of the tool</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/423064e657d8ad368444bba199b950f8/href">https://medium.com/media/423064e657d8ad368444bba199b950f8/href</a></iframe><p>In line 7, we define the specification for our document summarizer tool using the Converse API tool definition format.</p><p>We describe the document summarizer tool and define the inputs so that the model knows how to interact with it. In this case, the tool has an input i.e. location of the document in the query from the user.</p><p>Further, implement the above tool which gets called if the tool is chosen by the model. I have used ‘<em>nova-lite</em>’ model for this purpose which gives us a summary as instructed to the model.</p><p>Similarly, i have crafted other 2 tools i.e Image Summarizer which takes an image as an input and describes it for us .</p><p>Additionally, a Country Canvas tool which generates an artistic image for a given country.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e58d1715c828bf6fffb4a72c5fbf8595/href">https://medium.com/media/e58d1715c828bf6fffb4a72c5fbf8595/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc44987c4870dce6d6cb798092dbf58/href">https://medium.com/media/9fc44987c4870dce6d6cb798092dbf58/href</a></iframe><p>Now that we have all the tools implemented, lets put these into use.</p><h4>Send conversation to Amazon Bedrock</h4><p>First, we’ll set up the system prompt and the tool configuration for our tool. The system prompt tells the model that it should use a tool in a specific situation.</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an helpful AI assistant that provides for user-specified query using only<br>the Document_Summarzier_Tool or Architecture_Summazier_Tool or ,ImageGenerator_Tool which expects a query from the user. <br>To use the tool, you strictly apply the provided tool specification.<br><br>- Explain your step-by-step process, and give brief updates before each step.<br>- Use the Document_Summazier_Tool for any summarization queries, Image_Summazier_Tool for Architecture image related queries,Canvas_Tool for given country..<br>- If only country name is mentioned, use ImageGenerator_Tool for image generation.<br>- If .png present in the query use Image_Summazier_Tool for architecture description.<br>- If .pdf present in the query use Document_Summazier_Tool for summary generation<br>- Repeat the tool use for subsequent requests if necessary.<br>- If the tool errors, apologize, explain information is unavailable, and suggest other options.<br>- Only respond to generic queries. Remind off-topic users of your purpose. <br>- Complete the entire process until you have all required data before sending the complete response.<br>&quot;&quot;&quot;</pre><p>To send the conversation to Amazon Bedrock, we first create a conversation array with our initial user prompt.Here, query is to generate the summary for a document, present in a given location.</p><pre>conversation = []<br>initial_message = {<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>        { &quot;text&quot;: &quot;Generate summary for document at location aws-genai/AmazonNova/data/Intro_DVC_Tool.pdf&quot; }<br>    ],<br>}<br>conversation.append(initial_message)</pre><p>Then, we make the converse call, sending along the model, conversation, tool config, and our system prompt.</p><pre>SUMMARIZER_SPEC_TOOL = document_summarizer_toolspec()<br>IMAGE_SUMMARIZER_SPEC_TOOL = image_summarizer_toolspec()<br>COUNTRY_CANVAS_SPEC_TOOL = country_canvas_toolspec()<br>response = bedrock_runtime_client.converse(<br>    modelId=model_id_micro,<br>    messages=conversation,<br>    inferenceConfig={<br>        &quot;maxTokens&quot;: 2000,<br>        &quot;temperature&quot;: 0<br>    },<br>    toolConfig={<br>            &quot;tools&quot;: [SUMMARIZER_SPEC_TOOL, IMAGE_SUMMARIZER_SPEC_TOOL, COUNTRY_CANVAS_SPEC_TOOL]<br>    },<br>    system=[{&quot;text&quot;: SYSTEM_PROMPT}]<br>)</pre><h4>Process the response and call the tool</h4><p>Once we have a response from Amazon Bedrock, we have to process the response. We’ll check to see if a tool is being requested (toolUse is returned) and if so, we call the requested tool, in this case Document_Summarizer as shown in screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaU7Ld300KvrMcFII4MsRg.png" /><figcaption>Document_Summarizer_Tool is requested by tool.</figcaption></figure><p>With a result from the tool as show in the screenshot above i.e. the document_summarizer function, we then prepare a toolResult as shown further.</p><pre>response_message = response[&#39;output&#39;][&#39;message&#39;]<br>conversation.append(response_message)<br>response_content_blocks = response_message[&#39;content&#39;]<br><br>follow_up_content_blocks = []<br><br>for content_block in response_content_blocks:<br>    if &#39;text&#39; in content_block:<br>      print(content_block[&#39;text&#39;])<br>    elif &#39;toolUse&#39; in content_block:<br>      tool_use_block = content_block[&#39;toolUse&#39;]<br>      tool_use_name = tool_use_block[&#39;name&#39;]<br><br>      if tool_use_name == &#39;Document_Summazier_Tool&#39;:<br>        print(tool_use_block[&#39;input&#39;][&#39;query&#39;])<br>        tool_result_value = document_summarizer(tool_use_block[&#39;input&#39;][&#39;query&#39;])<br>        ## for follow up queries<br>        follow_up_content_blocks.append({<br>            &quot;toolResult&quot;: {<br>                &quot;toolUseId&quot;: tool_use_block[&#39;toolUseId&#39;],<br>                &quot;content&quot;: [<br>                    {<br>                        &quot;json&quot;: {<br>                            &quot;result&quot;: tool_result_value<br>                        }<br>                    }<br>                ]<br>            }<br>        })<br>      elif tool_use_name == &#39;Image_Summazier_Tool&#39;:<br>        image_summarizer(tool_use_block[&#39;input&#39;][&#39;query&#39;])<br>        <br>        ## for follow up queries<br>        follow_up_content_blocks.append({<br>            &quot;toolResult&quot;: {<br>                &quot;toolUseId&quot;: tool_use_block[&#39;toolUseId&#39;],<br>                &quot;content&quot;: [<br>                    {<br>                        &quot;json&quot;: {<br>                            &quot;result&quot;: tool_result_value<br>                        }<br>                    }<br>                ]<br>            }<br>        })<br>        <br>      elif tool_use_name == &#39;Canvas_Tool&#39;:<br>        country_canvas(tool_use_block[&#39;input&#39;])<br>        <br>        ## for follow up queries<br>        follow_up_content_blocks.append({<br>            &quot;toolResult&quot;: {<br>                &quot;toolUseId&quot;: tool_use_block[&#39;toolUseId&#39;],<br>                &quot;content&quot;: [<br>                    {<br>                        &quot;json&quot;: {<br>                            &quot;result&quot;: tool_result_value<br>                        }<br>                    }<br>                ]<br>            }<br>        })<br>     <br>      # Handle unknown tools<br>      else:<br>        follow_up_content_blocks.append({<br>          &quot;toolResult&quot;: {<br>            &quot;toolUseId&quot;: tool_use_block[&#39;toolUseId&#39;],<br>            &quot;content&quot;: [<br>                {<br>                    &quot;text&quot;: &quot;unknown tool&quot; + tool_use_name<br>              <br>                }<br>            ],<br>            &quot;status&quot;: &quot;error&quot;<br>          }<br>        })</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioARagmjnPBBNp-19Noa6w.png" /><figcaption>Screenshot of the result from document_summarizer (summary by <strong>Nova-Lite</strong> model)</figcaption></figure><h4>More Results from tools.</h4><ol><li>Image_Summarizer Tool</li></ol><pre>conversation = []<br>initial_message = {<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>        { &quot;text&quot;: &quot;/home/ec2-user/SageMaker/aws-genai/agentic-workflows/AmazonNova/data/Complex-AWS-Architecture.png&quot; }<br>    ],<br>}<br>conversation.append(initial_message)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uj8qeZy39p9jvKgmQ5IFow.png" /><figcaption>Image_Summarizer_Tool is requested by tool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZoGErDSDv5XepRAdzXOhQ.png" /><figcaption>Screenshot of the result from image_summarizer (summary by <strong>Nova-Lite</strong> multi-modal model)</figcaption></figure><p>2. Country_Canvas Tool</p><pre>conversation = []<br>initial_message = {<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: [<br>        { &quot;text&quot;: &quot;Generate image for country india&quot; }<br>    ],<br>}<br>conversation.append(initial_message)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KKSw9RCeWZ2zPG2_ZgBdA.png" /><figcaption>Country_Canvas_Tool is requested by tool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwwauNy6IBgave_KtduwlQ.png" /><figcaption>Screenshot of the result from country_canvas (image by <strong>Nova-Canvas</strong> model)</figcaption></figure><h4><strong>Wrapping Up</strong></h4><p>In this post, you learned how to use Tools(function call) with AWS Nova Models via trivial examples. I have also showed multi-modal capabilities of AWS Nova Models. Then, I showed how to implement this in Python with Amazon Bedrock’s Converse API.</p><p>Here’s the basic takeaway: Make sure to select the appropriate tools and a compatible LLM that enables function calls to tailor your application to your specific needs.</p><p>Thats all for now, folks! Stay tuned</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d55b0c440cc" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/intro-to-tool-use-function-calling-with-aws-nova-models-0d55b0c440cc">Intro to Tool Use(function calling) with AWS Nova Models</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CodeBuild/CodePipeline  Deploy Lambda Tutorial]]></title>
            <link>https://blog.devgenius.io/aws-codebuild-codepipeline-deploy-lambda-tutorial-cec299dff4df?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/cec299dff4df</guid>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-codebuild]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 12:25:27 GMT</pubDate>
            <atom:updated>2024-07-04T17:50:12.772Z</atom:updated>
            <content:encoded><![CDATA[<p>Automatic deployment of lambda code(based on docker image)via CodeBuild and CodePipeline Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Uuk-fq14P-nOOkz_" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Introduction</em></blockquote><p><strong>AWS LAMBDA</strong></p><p>Serverless computing is one of the most interesting developments in the constellation of cloud-based services. AWS Lambda, a serverless computing solution offered by Amazon Web Services (AWS), has come to be recognised as one of the more significant serverless products.</p><p>It offers a lot of important features in addition to the pay-as-you-go pricing mechanism, but I’ve just included just a few below that I think are applicable to this use case.</p><ul><li><strong>Extend with other services using custom logic </strong>i.e. trigger the custom lambda code as events occur in s3 ,event-bridge etc.</li><li><strong>Completely automated administration</strong> i.e. AWS Lambda manages all the infrastructure to run your code on highly available, fault tolerant infrastructure, freeing you to focus on building differentiated backend services</li><li><strong>Package the code and deploy functions as docker images </strong>thus making it easy for customers to build Lambda-based applications using familiar container image tooling, workflows, and dependencies.</li></ul><p><strong>AWS CodeBuild</strong></p><p>CodeBuild is the real building service, as the name suggests. Don’t get too worked up over that phrase, though, because CodeBuild allows you to build pretty much anything. It’s not limited to building and packaging applications alone.</p><p>In addition, you may use infrastructure as code tools like Terraform or CDK to perform infrastructure manipulations, modify routing destinations, initiate backup creation, trigger Lambda functions for batch operations, and carry out any other task that can be included in a script.</p><p><strong>AWS CodePipeline</strong></p><p>There is more to a well-planned and organised delivery process than just one build work. The implementation of deployment packages and infrastructure in a dependable and secure manner is made possible by the coordination of numerous activities, many of which are idempotent jobs.</p><p>And that’s precisely what CodeBuild orchestration tool i.e. AWS CodePipeline delivers for you. You may build pipelines with CodePipeline that divide tasks into phases so that you can have a multi-step rollout process that is simple to understand and duplicate.</p><p><strong>Symbiosis of both</strong></p><p>CodeBuild is essential if you want to continue using AWS for your delivery process. Although CodePipeline is optional, it provides a fantastic way to develop complex continuous integration and delivery processes by extending the capabilities of CodeBuild.</p><p>These services are quite simple to design and set up, and they function together pretty well which we are going to see in the upcoming section.</p><p>Apart from above advantages, not having to maintain any build servers is a huge benefit and saves a lot of effort and operational burdens that can be used more sensibly in other places.</p><blockquote>Implementation</blockquote><p>Here is the overview of the approach</p><ol><li>Create a <strong>CodeCommit</strong> repository in AWS which you can clone to your local.</li><li>Add the necessary source code for the lambda functions within the CodeCommit repository</li><li>Create and <strong>ECR</strong> repository which is like a privarte repository for your docker images.</li><li>Push initial Docker Image to <strong>ECR.</strong></li><li>Create a lambda function that points to the image URI of <strong>ECR.</strong></li><li>Write your buildspec.yml (necessary for CodeBuild)</li><li>Create a <strong>Code build</strong> project and configure role</li><li>Create a <strong>Code</strong>P<strong>ipeline</strong> connecting <strong>source</strong> and <strong>build</strong></li></ol><blockquote>Detailed Approach</blockquote><ol><li>CodeCommit Repository</li></ol><p>As with Github/Gitlab, create an initial, empty CodeCommit Repository. Click Create after giving it a name and a brief description, leaving everything else as it is in the example below. Clone this repository at last, then start working on lambda!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*7EOZQ5gINRrZEEBFhkUU1Q.png" /><figcaption>Create an empty CodeCommit Repository</figcaption></figure><p>2. Source Code for Lambda</p><p>The directory will have the following files: lambda_function.py, the actual lambda function; requirements.txt, a list of the dependencies for our function; buildspec.yml, a collection of YAML-formatted build commands and related settings that CodeBuild uses to perform builds; and an.env file, which contains environment variables. To push the initial Docker image to ECR, a notebook was added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*oyjB1HM5PTmdKvdMLOUZfw.png" /><figcaption>Project Structure</figcaption></figure><p>We are working on lambda logic that will simply sort the files in an S3 bucket into the relevant directories based on their extension. But when new files are added to or changed in a particular S3, this will happen.</p><pre>#sort-files-dir.py<br>import boto3<br>import warnings<br>from dotenv import load_dotenv<br>import os<br>warnings.filterwarnings(&quot;ignore&quot;)<br>load_dotenv()<br><br>DATA_BUCKET = os.getenv(&#39;DATA&#39;)<br>SOURCE_BUCKET = os.getenv(&#39;SOURCE&#39;)<br>DESTN_BUCKET = os.getenv(&#39;DESTN&#39;)<br>EXL_FOLDER = os.getenv(&#39;EXL_FOLDER&#39;)<br>CSV_FOLDER = os.getenv(&#39;CSV_FOLDER&#39;)<br><br><br>def copy_files_constraint(DATA_BUCKET:str,SOURCE:str, DESTN:str, <br>                          excel_key: str, csv_key:str):<br>    &#39;&#39;&#39;<br>    Sort and copy Files from a SOURCE BUCKET into DESTN folders based on its extension i.e csv/excel<br>    &#39;&#39;&#39;<br>    DATA_BUCKET = f&#39;{DATA_BUCKET}&#39;<br>    s3 = boto3.resource(&#39;s3&#39;)<br>    s3client = boto3.client(&#39;s3&#39;)<br>    bucket = s3.Bucket(DATA_BUCKET)<br>    print(bucket)<br>    s3objects = s3client.list_objects_v2(Bucket=DATA_BUCKET, Prefix = &#39;Excel&#39;)<br>    for object in s3objects[&#39;Contents&#39;]:<br>        if &#39;.csv&#39; in object[&#39;Key&#39;]:<br>            kit_count += 1<br>            copy_source = {&#39;Bucket&#39;: DATA_BUCKET,&#39;Key&#39;: object[&#39;Key&#39;]}<br>            file_name = object[&#39;Key&#39;].split(&#39;/&#39;)[1]<br>            path = f&#39;{DESTN}/{csv_key}/{file_name}&#39;<br>            bucket.copy(copy_source, path)<br>        elif &#39;.xlsx&#39; in object[&#39;Key&#39;]:<br>            copy_source = {&#39;Bucket&#39;: DATA_BUCKET,&#39;Key&#39;: object[&#39;Key&#39;]}<br>            print(copy_source)<br>            file_name = object[&#39;Key&#39;].split(&#39;/&#39;)[1]<br>            path = f&#39;{DESTN}/{excel_key}/{file_name}&#39;<br>            bucket.copy(copy_source, path)<br>        else:<br>            pass<br>    return<br><br><br>def handler(event, context):<br>    if event:<br>        copy_files_constraint(DATA_BUCKET, SOURCE_BUCKET, DESTN_BUCKET, EXL_FOLDER, CSV_FOLDER)</pre><p>The ‘dotenv’ external library is necessary for loading our environment variables. Requirements.txt will therefore have the same. You can also save environment variables in a ‘.env’ file; in this example, they are the names of the S3 buckets that are imported by load_dotenv() in the scripts.</p><pre>#requirements.txt<br>python-dotenv==1.0.1</pre><p>Here is the Dockerfile that I will be using.</p><pre># Use the aws python3.10 lambda image <br>FROM public.ecr.aws/lambda/python:3.10<br><br><br># Copy function code<br>COPY sort-files-dir.py ${LAMBDA_TASK_ROOT}<br><br><br># Install the function&#39;s dependencies using file requirements.txt<br># from your project folder.<br>COPY requirements.txt  .<br>COPY .env .<br># RUN env | grep -i proxy # proxies identified till this step<br>RUN pip3 install --upgrade pip<br>RUN pip3 install -r requirements.txt --target &quot;${LAMBDA_TASK_ROOT}&quot;<br><br># Set the CMD to your handler<br>CMD [ &quot;sort-files-dir.handler&quot; ]</pre><p>3. Create ECR</p><p>Follow these steps to create a new Elastic Container Repository. Leave everything else as it is and enter the name of your repository.</p><p>The <em>Repository Name</em> below, is the one that will be used in the <em>lambda function</em> and in various other places in <em>buildspec.yml.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*yjeJmU6ktNy7le-HYyWdGg.png" /><figcaption>Create ECR repository.</figcaption></figure><p>4. Push the initial image to ECR.</p><p>Refer to the <em>View Push Commands </em>tab as you create the ECR repository. Follow those steps to push the initial image to ECR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*_ABlvdipuRqzkoX5VJ5L8Q.png" /><figcaption>Commands to push docker image to ECR.</figcaption></figure><p>5. Create a lambda function that points to the image URI of <strong>ECR</strong></p><p>Create the function using the below-listed setup, as seen in the screenshot.<br>Note: We created services using the custom IAM role LAMBDA_ARN, which has policies granting access to Code Commit and S3 services. Set it up in accordance with your code’s requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*QOD6Yn3KXq19681HpT94yQ.png" /><figcaption>Create Lambda function</figcaption></figure><p>6. Write your buildspec.yml</p><p>The secret is in buildspec.yml!</p><p>There are three key phases to it: pre-build, build, and post-build.<br>Each of these instructions is derived from the ECR push commands that we have just seen.<br>It should be noted that pre_build entails logging into ECR, build entails building and tagging docker images, and post_build entails pushing the tagged image to ECR and updating the lambda function with the most recent image of the mapped ECR repository.</p><pre>#buildspec.yml<br>version: 0.2<br><br>phases:<br><br>  install:<br>    commands:<br>      - DATETIME=$(date +&quot;%Y-%m-%d-%H-%M-%S&quot;)<br>      <br>  pre_build:<br>    commands:<br>      - echo Logging in to Amazon ECR...<br>      - aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 505184942745.dkr.ecr.us-east-1.amazonaws.com<br>      <br>  build:<br>    commands:<br>      - echo Build started on $DATETIME<br>      - echo Building the Docker image...<br>      - ls -larth<br>      - docker build -t lambda-sortfiles-dir .<br>      - docker tag lambda-sortfiles-dir:latest 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest<br>      <br>  post_build:<br>    commands:<br>      - echo Build completed on $DATETIME<br>      - echo Pushing the Docker image...<br>      - docker push 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest<br>      - aws lambda update-function-code --function-name sort-files-dir --image-uri 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest</pre><p><em>Additional Information:</em> You must restart the docker service in your codebuild environment with proxies if you need to configure them in your account. This will involve setting up environment variables and running a few more docker reset commands during the pre_build phase, as illustrated below.</p><pre>version: 0.2<br><br>env:<br>    variables:<br>         HTTP_PROXY: $HTTP_PROXY<br>         HTTPS_PROXY: $HTTPS_PROXY<br>         NO_PROXY: $NO_PROXY<br><br>phases:<br><br>  install:<br>    commands:<br>      - DATETIME=$(date +&quot;%Y-%m-%d-%H-%M-%S&quot;)<br>      <br>  pre_build:<br>    commands:<br>      - docker system info<br>      - kill $(cat /var/run/docker.pid)<br>      - while kill -0 $(cat /var/run/docker.pid) ; do sleep 1 ; done<br>      - /usr/local/bin/dockerd-entrypoint.sh<br>      - docker system info<br>      - echo Logging in to Amazon ECR...<br>      - aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 505184942745.dkr.ecr.us-east-1.amazonaws.com<br>      <br>  build:<br>    commands:<br>      - echo Build started on $DATETIME<br>      - echo Building the Docker image...<br>      - ls -larth<br>      - docker build -t lambda-sortfiles-dir .<br>      - docker tag lambda-sortfiles-dir:latest 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest<br>      <br>  post_build:<br>    commands:<br>      - echo Build completed on $DATETIME<br>      - echo Pushing the Docker image...<br>      - docker push 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest<br>      - aws lambda update-function-code --function-name sort-files-dir --image-uri 505184942745.dkr.ecr.us-east-1.amazonaws.com/lambda-sortfiles-dir:latest</pre><p>7. Create a <strong>Code build</strong> project and configure role</p><p>As seen in the screenshot below, create a new CodeBuild project with the project name and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUQk88BES8tScaS8JNJaUQ.png" /><figcaption>Project Configuration</figcaption></figure><p>Then, as indicated in the screenshot below, configure the source, or the CodeCommit Repository, and its relevant branch.</p><p>Important note: for <strong><em>Git Clone Depth</em></strong> clone value needs to be <strong><em>Full</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yd_L65maWOTD_IlBbrj8bQ.png" /><figcaption>CodeCommit Source Configuration</figcaption></figure><p>Next, set up the environment where your code will be built. Then, in the buildspec section, make sure the builspec.yml option is used.<br><em>Note:</em> Make sure the<strong> Privileged</strong> option box is checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xn-Xb4zeutM0BmPdR4PURg.png" /><figcaption>CodeCommit Environment/BuildSpec Configuration</figcaption></figure><p>For Service role, you must give an IAM role for the project in my case I have used <em>CodeBuild_ARN</em> that has following policies attached to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TR4vzhHs0RjIrLmsZuquQ.png" /><figcaption>Policies for CodeBuild_ARN</figcaption></figure><p>8. Create a <strong>Code</strong>P<strong>ipeline</strong> connecting <strong>source</strong> and <strong>build.</strong></p><p>Create a new pipeline with the appropriate pipeline name and automatically service role is created for codepipeline execution unless you want to add any custom roles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPgwAk-CRS49MbKuF3B5GA.png" /><figcaption>CodePipeline Configuration</figcaption></figure><p>As a source add <em>CodeCommit </em>as the provider and respective repository/branch you want to attach to the pipeline source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxXw4ILAFqkED5h33scM4g.png" /><figcaption>CodePipeline Source Configuration</figcaption></figure><p>For the build stage add CodeBuild as the provider and select the respective pipeline you want to attach for this stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI3rBC52ZN-mujo5_hRwUw.png" /><figcaption>CodePipeline Build Configuration</figcaption></figure><p>You can skip the deploy step as we have already deployed the lambda code above, and the pipeline has now been created.</p><p>Finally, trigger the pipeline and check if our source to build pipelines are working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqOxImUsBT93cXqZ7FA5Mw.png" /><figcaption>Pipeline Executed.</figcaption></figure><blockquote>Conclusion.</blockquote><p>You should now be able to use CodeBuild/CodePipeline and other similar services for a basic CI/CD procedure, I think.<br>Even after the initial build, it is possible to have many phases run sequentially. For example, a lambda that uses the processed data from the first lambda execution to conduct more analysis, and so on.</p><p>I will provide more examples of this in future posts; for now, this is all I have. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec299dff4df" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/aws-codebuild-codepipeline-deploy-lambda-tutorial-cec299dff4df">AWS CodeBuild/CodePipeline 👉 Deploy Lambda Tutorial🔥</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLFlow Tutorial -ML Tracking and Serving]]></title>
            <link>https://blog.devgenius.io/mlflow-tutorial-ml-tracking-and-serving-49abd929c8d9?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/49abd929c8d9</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlflow-registry]]></category>
            <category><![CDATA[mlflow-tracking]]></category>
            <category><![CDATA[mlflow]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 05:43:12 GMT</pubDate>
            <atom:updated>2023-12-21T17:19:10.880Z</atom:updated>
            <content:encoded><![CDATA[<p>Detailed walkthrough of the process to log your ML experiments(using MLFlow wrappers), register models to model registry and finally serve the model for inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V6Wb-s_ZZw27quSh" /><figcaption><a href="https://www.edlitera.com/">https://www.edlitera.com/</a></figcaption></figure><blockquote>Introduction</blockquote><p>MLFlow is a framework developed my Databricks for assisting the end to end machine learning lifecycle. Meaning it can store the models, monitor your models during training/testing, load the respective model in production, create the pipeline. It can do all these tasks independently. Lets have a look what each means.</p><p><strong><em>MLFlow Tracking</em></strong> : As a data-scientist, it’s a routine that you thrive for a near perfect model and to get there it takes efforts, innit it? :`).</p><p>Therefore, in order to log each experiment, the MLFlow-tracking API records all of the parameters and metrics. This allows us to compare the results of a run to those of a prior run and determine which performed better.</p><p><strong><em>MLFlow Projects</em></strong>: I thought this was a really interesting and distinctive thing. It is simple to share your model’s setup and code with other teams when using MLFlow projects. A simple directory called project/mlruns holds your code, requirement files, conda environment files, and additional metadata such as project version, git commit, and parameters.</p><p><strong><em>MLFlow Models:</em> </strong>This is also interesting because it makes deployment simple by enabling the packaging of models in a format that can be directly consumed by the REST API, SageMaker endpoint, etc.</p><p>The cherry on top is that these models’ packaging supports multiple flavors, including TensorFlow, sklearn, and Python functions (which includes a wrapper function that we will talk about in a moment).</p><p>Packaging a model includes what environment your model requires, what is the signature of your model i.e. format of model’s input and output. Once we have packaged the model, we can store it in a pickle file and deploy it using MLFlow models.</p><p><strong><em>MLFlow Registry: </em></strong>As we improve the models with new data, we will have multiple iterations with different metrics and parameters. Various models may be used, depending on staging, production level, etc. We can manage model stages with the aid of the MLFlow Model Registry, which is a centralized model store, collection of APIs, and user interface.</p><p>Before we get hands-on, one more thing!</p><p><strong><em>Wrapper : </em></strong>In order to comprehend wrapper, let’s look at a basic example. Preprocessing is the process of preparing our input so that the model can be fed into it before training. We cannot, however, rely on the user to carry out the same preprocessing steps during inference.</p><p>Let’s say we have a dataset of images that we are using to train an image classification model. Given that the images were transformed before being fed into the model, similar changes must be made to the test data as well. However, we don’t want users to take the same actions. In order to ensure that the image is automatically transformed to required form and then fed to the model when someone tries to access the API. Thus, we we will create a Wrapper around the model with preprocessing code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*qyuhUAZNcvmh3EjJ.png" /><figcaption><a href="https://statusneo.com/">https://statusneo.com/</a></figcaption></figure><p>Now, that we’ve learned everything there is to know about the intricacies of MLFlow let’s get to work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3322XG3k2ae-U03FfhblQ.png" /></figure><blockquote>Implementation</blockquote><p>For a change, I have implemented a simple Pytorch model for classifying images of Cats/Dogs using the amazing Pytorch-Lightning framework! It provides a high level interface for Pytorch, which makes data loading and training and many other things easier.</p><p>Therefore, for data preparation and loading into training and validation data loaders, I’ll use a Data Module from Pytorch Lightning.</p><p>The LightningDataModule is meant to be used in conjunction with the Lightning Module to isolate its data-related hooks, enabling you to develop models that are not dependent on datasets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/120c111adb1ab626877099b8a0415057/href">https://medium.com/media/120c111adb1ab626877099b8a0415057/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cccf871e68ad55e13085685441957ae/href">https://medium.com/media/6cccf871e68ad55e13085685441957ae/href</a></iframe><p>The snippets of code above are primarily used to prepare the data for loading into data-loaders, which we will see now.</p><p>The training script will involve logging of experiments and models using MLFlow.</p><p>i. PyTorch lightning support logs while training i.e. in our case we can use MLFlow loggers through which we can log experiments directly.</p><p>ii. But in our case, as we need to perform some transformations while inference, we need to write custom Pyfunc(wrapper) while saving/loading models.</p><p>iii. To track the experiments, we need to set the URI of the server. In our case, we are going to use localhost. Execute the following command for same</p><pre>mlflow ui</pre><p>iv. After defining the experiment’s name, you begin running it!</p><p>v. We log the corresponding model on the run;’) along with details like the wrapper code, source, and path of the artifacts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea5ccc9084c40199e13406d1f895879/href">https://medium.com/media/eea5ccc9084c40199e13406d1f895879/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf7e761beee385a9b8838e5557e70a65/href">https://medium.com/media/cf7e761beee385a9b8838e5557e70a65/href</a></iframe><p>Upon completion of the training script, the run id is displayed, assisting us in locating the MLFlow server.<br>All of the runs are stored under the folder 0/ in the locally generated mlruns/ folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*gppB1HYVOB8C9WI9WxhyGA.png" /><figcaption>Local directory structure for mlruns</figcaption></figure><p>Take note of the MLFlow Models, which include: code folder containing a custom wrapper that is called during inference; and artifacts folder containing the model stored. The information on the model flavors in the MLmodel file will be useful when serving the model across various platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P26XsoNFoSilFAOn8dEl7Q.png" /><figcaption>ML tracking in remote server of MLFlow.</figcaption></figure><p>Once, we have the near perfect model, we will register it to our MLFlow registry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8b340009c718ac354efdb19fa6971a/href">https://medium.com/media/2a8b340009c718ac354efdb19fa6971a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EtQjOZlaKECWgn70OYFqA.png" /><figcaption>Model Registered in MLFlow Registry</figcaption></figure><p>We can move the model to Production once it is in the registry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e8bfbd6aa4b0738e25aa2fd59763dfc/href">https://medium.com/media/5e8bfbd6aa4b0738e25aa2fd59763dfc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc2BYWxy8KUsQHQ5fU7a5w.png" /><figcaption>Model Transitioned for Production</figcaption></figure><blockquote><strong>Create the endpoint for model serve</strong></blockquote><ul><li>Set environment variable for MLFlow URI</li></ul><p>export MLFLOW_TRACKING_URI=http://localhost:5000</p><ul><li>Start MLFlow Server for the model</li></ul><p>mlflow models serve --model-uri models:/cat_vs_dog_classifier/production -p 7777 --no-conda</p><blockquote><strong>Invoke the model</strong></blockquote><p>Now, that model is made available at an endpoint lets get the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a941c0ac6563203d6115f618855112be/href">https://medium.com/media/a941c0ac6563203d6115f618855112be/href</a></iframe><p>Assuming the model is served at the endpoint, running the above script yields the following predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qTHOkEyeVMruBxmLi1x8w.png" /><figcaption>Given Cat image, predicted correctly as “Cat”</figcaption></figure><blockquote><strong>Conclusion:</strong></blockquote><ul><li>Basic Understanding of MLflow</li><li>Components of MLflow</li><li>Wrapper and how to integrate it with our code</li><li>Invoke the Model using MLFlow server</li></ul><p>The complete code repository is available <a href="https://github.com/h-swathi-shenoy/mlflow-track-serve">here</a></p><p>That’s all from my end. Until next time 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Va86sXYxI22YYKGz" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49abd929c8d9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mlflow-tutorial-ml-tracking-and-serving-49abd929c8d9">MLFlow Tutorial -ML Tracking and Serving</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop ML Projects with DVC]]></title>
            <link>https://medium.com/@hswathishenoy/develop-ml-projects-with-dvc-a54e4c660588?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54e4c660588</guid>
            <category><![CDATA[dvc]]></category>
            <category><![CDATA[data-versioning]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 19:39:38 GMT</pubDate>
            <atom:updated>2023-10-19T19:39:38.069Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to use DVC to version data, create models, and automate pipelines.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*SNbzpT7tQXWW8HpZCGOLJA.png" /><figcaption>Image generated with the help of Stable Diffusion, taken from <a href="https://iterative.ai/blog/november-2022-heartbeat/">Iterative</a>.</figcaption></figure><p>As a data scientist, you frequently work with large amounts of data. Data that has been processed, divided into train, validation, and test sets. Additionally, model files and configurations are also involved. Further, when multiple people are collaborating on the development, we must ensure that the correct data is being used for reproducibility. In this case, DVC is a lifesaver!</p><p>Before using any tool, we must understand what kind of problem it solves. I must admit that when I first started working, I wasn’t a “disciplined” data scientist. My supervisor made a frightfully funny statement later that day: “I’m going to delete your code repo, and disappear. Let me know what you’re going to do next”. Since then, versioning the code is now a must-do procedure.</p><blockquote>What is a DVC?</blockquote><p>DVC is a MLOps Swiss army knife. A version control system for machine learning projects that encourages structured development, collaboration, reproducibility and deployment.</p><p>Version Control Systems allows the developers to track the changes or developments in the project and gives them liberty to revert to previous state when there is flaw observed in the current state. Also, it gives some kind of happiness when there is an up to date backup of your work.</p><p>Unlike software projects, source code is not the only input to machine learning, but data. And data can get heavy. With Git versioning data and model wont be feasible as:</p><ol><li>Data and Models are way too big to upload to git</li><li>Use external storage, but it loses the idea of versioning.</li></ol><p>This is precisely what DVC Solves! It is built on top of Git and thus provides versioning capabilities for data, models, or images. Further, you even track experiments and reproduce them. Let’s look in detail at how we do that.</p><blockquote>Hands-On Tutorial for DVC</blockquote><p>At first, we need to install a few libraries before starting to use DVC. One of course is the <em>DVC</em> itself, and <em>DVC-s3</em> to configure the remote storage, here I have used AWS S3.</p><pre>pip install dvc dvc-s3</pre><p>For better understanding, I’m going to take -up an easy ML template that will involve FTI (Feature-Training-Inference) pipelines. The template will look like this. (Ignore the dvc folder/files for now)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*ibOOSSy_ta69_K1WYHFkSw.png" /><figcaption>ML Template</figcaption></figure><ol><li>data: Store all kinds of data i.e. raw/processed data which you can store as subfolders within this folder.</li><li>configs: Store all the model configurations.</li><li>models: Store the artifacts/feature-related objects here.</li><li>src: Your codebase i.e. scripts goes here.</li></ol><blockquote>The TL;DR; ( if you are in hurry)</blockquote><p>The main commands to start versioning your data are (<em>Considering you have already started versioning your code with git</em>):</p><ol><li>First, configure your remote storage i.e. s3 storage(prior to this, initialize your DVC)</li></ol><pre>dvc init<br>dvc remote add -d dvc-remote s3://&lt;bucket&gt;/&lt;key&gt;</pre><p>2. Now, add the folder/file i.e. the data you need to version with the following command</p><pre>dvc add &lt;folder/file-name&gt;</pre><p>3. Notice that dvc has automatically <em>created a file with a .dvc</em> extension. Now, DVC has started tracking your file/folder. It consists of the metadata describing what datasets, ML artifacts, etc. to track in remote storage. This metadata can be put in Git in lieu of large files</p><p>4. Now, finally push that .dvc file prior to committing and push it to git.</p><pre>dvc push</pre><p>5. So, as you switch between your features as in branches/commits; changes get reflected in the metadata of .dvc file and you do run dvc pull.</p><pre>dvc pull &lt;filename.dvc&gt;</pre><p>That’s how DVC does the data versioning.</p><blockquote>Data Pipelines.</blockquote><p>There are several pipelines involved when working on machine learning projects, including the training, inference, feature, and data preparation pipelines. It can be time-consuming to add inputs and outputs one by one for each pipeline because each are unique. What a way to automate that!</p><p>DVC pipelines can come in handy in this case. A <em>dvc.yaml </em>file must be defined, in which stages must be defined along with their corresponding inputs and outputs. and even monitor the graphs and metrics. How amazing is that!?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekaavOAPFPIGdB7CttcGcg.png" /><figcaption>The ML development pipeline with inputs and outputs specified.</figcaption></figure><p>It is very clear from the above figure how the pipelines and its corresponding Inputs/Outputs from each stage work.</p><p>So to make sure you can get a sense of it, let me demonstrate the dvc.yaml file template.<br>Note: I built a complete machine learning pipeline using a simple IRIS data as my dataset.</p><pre>stages:<br>  prepare:<br>    cmd: python src/load.py raw/IRIS.csv<br>    deps:<br>    - data/raw/IRIS.csv<br>    - src/load.py<br>    params:<br>    - load.split<br>    - load.random_state<br>    outs:<br>    - data/prepared</pre><ol><li>First, define the step “stages” under which each pipeline is defined.</li><li>Each stage is followed by a “cmd” is essentially a Python script with arguments, or inputs, for that particular script.</li><li>You specify the dependencies (Inputs) later on. The same arguments you passed in the last “cmd” command, basically. Keep in mind that the script itself is a dependent.</li><li>“Params” is for the configurations the scripts needs i.e. configs</li><li>Finally, “outs” refer to the results obtained from each stage’s execution.</li></ol><pre>stages:<br>  prepare:<br>    cmd: python src/load.py raw/IRIS.csv<br>    deps:<br>    - data/raw/IRIS.csv<br>    - src/load.py<br>    params:<br>    - load.split<br>    - load.random_state<br>    outs:<br>    - data/prepared<br>  features:<br>    cmd: python src/features.py data/prepared processed encoder features<br>    deps:<br>    - data/prepared/train.csv<br>    - src/features.py<br>    params:<br>    - features.max_features<br>    outs:<br>    - data/processed<br>    - models/encoder<br>    - models/features<br>  training:<br>    cmd: python src/model.py data/processed artifacts features<br>    deps:<br>    - data/processed/train-norm.csv<br>    - data/processed/encoded-labels.csv<br>    - models/features/features.yaml<br>    - src/model.py<br>    outs:<br>    - models/artifacts<br>  inference:<br>    cmd: python src/inference.py data/prepared features artifacts encoder<br>    deps:<br>      - data/prepared/test.csv<br>      - models/features/features.yaml<br>      - models/artifacts/model.pkl<br>      - models/encoder/scaler_encode.pkl<br>      - models/encoder/label_encode.pkl<br>    metrics:<br>        - data/evaluate/metrics.json<br><br></pre><p>Note the<em> metric</em>s stage at the final “inference” stage. To keep track of the metrics for every experiment, DVC offers dvc live .</p><p>The code snippet above contains all of the dvc.yaml needed for running an end-to-end FTI pipeline. To execute the yaml file, run following command.</p><pre>dvc repro</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*85QCKAJt2ZgHljMqLBHPLg.png" /><figcaption>Output for dvc repro</figcaption></figure><p>To track the experiments within each experiment , run</p><pre>dvc metrics show</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*aLjCtoNO5DnIYv8Jib0DGw.png" /><figcaption>Output for metrics tracker.</figcaption></figure><p>As the pipeline is run , <em>dvc.lock </em>file gets generated.</p><p>To record the state of your pipeline(s) and help track its outputs, DVC will maintain a <a href="https://dvc.org/doc/user-guide/project-structure/dvcyaml-files#dvclock-file">dvc.lock</a> file for each <a href="https://dvc.org/doc/user-guide/project-structure/dvcyaml-files">dvc.yaml</a>. Their purposes include:</p><ul><li>Allow DVC to detect when stage definitions, or their dependencies have changed. Such conditions invalidate stages, requiring their reproduction.</li><li>Tracking of intermediate and final outputs of a pipeline — similar to .dvc files.</li></ul><p>You only need to add the dvc.lockfile to your current commit once data -pipelines are updated. Consequently, the ongoing experiment is saved on git.</p><p><strong>Final thoughts</strong><em><br></em>Our projects can really go to the next level if we use DVC to manage Machine Learning pipelines and track experiments. Creating separate Python scripts for every stage and clearly defining the parameters, inputs, and outputs that each script uses are essential for machine learning projects reproducible. Thus, use dvc repro to execute the pipeline however you see fit.</p><p>You can find the entire code base in <a href="https://github.com/h-swathi-shenoy/dvc-exercise">here.</a></p><p>DVC provides pipeline management, experimentation, and version control in addition to collaboration and deployment features. I’ll try to include more about it in the upcoming article!</p><p>Thank you for reading, and that’s everything for now! 😁</p><p>References:</p><p><a href="https://www.ridgerun.ai/post/developing-ml-projects-with-dvc">Developing ML Projects with DVC</a></p><p><a href="https://dvc.org/doc">https://dvc.org/doc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54e4c660588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Scikit-learn Prediction Pipeline with Custom Transformers and Estimators]]></title>
            <link>https://medium.com/@hswathishenoy/build-scikit-learn-prediction-pipeline-with-custom-transformers-and-estimators-f426163f1a2d?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f426163f1a2d</guid>
            <category><![CDATA[scikit-learn-pipelines]]></category>
            <category><![CDATA[custom-transformer]]></category>
            <category><![CDATA[production-ready]]></category>
            <category><![CDATA[estimators]]></category>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 14:18:07 GMT</pubDate>
            <atom:updated>2023-07-12T12:24:42.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to build Custom Transformers/Estimators with TransformerMixin, ClassifierMixin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KKDzRtEvjty-ytThaYjEQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/fancycrave1-1115284/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=823622">fancycrave1</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=823622">Pixabay</a></figcaption></figure><p>Since last month, I have been working on building Production Ready Machine Learning Pipelines, and I must say the journey so far has been amazing ;’)</p><p>During this process, Scikit-learn Pipeline class was quite useful in streamlining the whole ML process. So, in this article I’m going to explain in-depth how we create custom transformers that can fit and transform your data and a custom estimator to fit and get the predictions.</p><blockquote>Introduction</blockquote><p>A Pipeline, in Scikit-learn consists of a chain of transformers with an estimator at the end. It is effectively a vertical stacking in which the output of one transformer provides an input for another. So you feed the raw data into the pipeline, which then runs through a number of transformers and eventually an estimator to provide the predictions.</p><blockquote>About Transformers</blockquote><p>Transformers, as the name implies, are used to transform data, such as scaling, normalising, and feature engineering. It implements four methods, namely</p><ol><li><em>__init__</em> : This is the constructor, called when we initialize a transformer class.</li><li><em>fit</em> : Learns the model params i.e. from the training set.</li></ol><p>3. <em>transform: </em>It applies transformations on the data.Morover, this is where all the magic on the data happens!</p><p>4. <em>fit_transform </em>— Used when you want to do modelling and transformation simultaneously.</p><blockquote>Estimator</blockquote><p>This can be any object which learns the patterns in the data. This could include classification,regression or clustering algorithms. It implements following methods,namely</p><p>1. __ini<em>t__</em> : This is the constructor, called when we initialize an estimator class.</p><p>2. <em>fit : </em>Learn the patterns in the data</p><p>3. <em>predict : </em>Predict on the unseen data based on the type of algorithm used(supervised/unsupervised)</p><p>Now, that we’ve learned everything there is to know about the Transformer and Estimator roles in Pipeline, let’s get to work!</p><p><strong>Python Implementation</strong></p><p>I’m going to generate some random data to demonstrate how we can create Custom Transformers/Estimators.</p><p>Let’s generate some synthetic data with 1000 rows and 5 columns i.e features for binary classifaction using sklearn <strong><em>make_classfication. </em></strong>We later split the data into 70:30 ratio for our train and test sets.</p><pre>from sklearn import datasets<br><br>X, y = datasets.make_classification(n_samples=1000, n_features=5, n_classes=2, n_redundant=0,<br>                                    random_state=42)<br>X_train = X[0:700]<br>y_train = y[0:700]<br>X_test = X[700:]<br>y_test = y[700:]</pre><p>Next, lets add the transformers. At first , I’m going to perform scaling of data and later add one more feature to our training data.</p><blockquote>Scaling Transformer</blockquote><p>In this transformer, we’ll use already-existing Scikit-learn <em>MinMaxScaler</em> to scale the values. All number columns will be affected by this. Because the values in separate columns differ, scaling will bring them all to a single consistent scale.</p><blockquote>Feature Generation Transformer</blockquote><p>In this transformer, we will use a custom transformer. I‘m going to update the data with one more feature. This feature is called a <em>cluster</em> since it was formed by utilising the Kmeans algorithm, which is a clustering algorithm (Yes, this is a fusion of estimator within a transformer, but because this is a feature generator, I used it as a transformer.)</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn import datasets<br>from omegaconf import DictConfig<br>from sklearn.cluster import KMeans<br>from sklearn.base import BaseEstimator, TransformerMixin<br>import typing as t<br><br>class Feature_Clustering(BaseEstimator, TransformerMixin):<br>    def __init__(self, clusters: int, random_state=42):<br>        self.clusters = clusters<br>        self.random_state = random_state<br>        self.clustering_ = None<br><br>    @classmethod<br>    def from_config(cls, config: DictConfig):<br>        &quot;&quot;&quot;<br>        Create instance of the class from OmegaConfig<br>        :param config: Configuration from Dictionary config<br>        :return:<br>        &quot;&quot;&quot;<br>        config = config.copy()<br>        return cls(**config)<br><br>    def fit(self, X: np.array, y:None):<br>        return self<br><br>    def transform_arr_df(self, input_arr: np.ndarray) -&gt; pd.DataFrame:<br>        &#39;&#39;&#39;<br>        Convert Array to a Dataframe<br>        :param input_arr: Array with feature values that to be converted into Dataframe with cols<br>        :return : Dataframe with 5 features.<br>        &#39;&#39;&#39;<br>        ref = range(1, 6, 1)<br>        feat_cols = [&quot;feature_&quot; + str(i) for i in list(ref)]<br>        model_input = pd.DataFrame(input_arr, columns=feat_cols)<br>        return model_input<br><br>    def transform(self, features: np.ndarray) -&gt; np.ndarray:<br>        &#39;&#39;&#39;<br>        Apply KMeans Clustering Algorithm to add Cluster Labels to data<br>        :param features: Scaled data<br>        :return : Array with additional entry for cluster feature<br>        &#39;&#39;&#39;<br>        if self.clustering_ and isinstance(features, np.ndarray):<br>            features_df = self.transform_arr_df(features)<br>            preds = self.clustering_.predict(features_df)<br>            features_df[&#39;cluster&#39;] = preds<br>            feature_arr = features_df.to_numpy()<br>        elif isinstance(features, np.ndarray):<br>            features_df = self.transform_arr_df(features)<br>            fit_obj = KMeans(n_clusters=self.clusters, random_state=42).fit(features_df)<br>            features_df[&#39;cluster&#39;] = fit_obj.labels_<br>            self.clustering_ = fit_obj<br>            feature_arr = features_df.to_numpy()<br>        else:<br>            raise ValueError(f&#39;Input features need to be of type Array, given{type(features)}&#39;)<br>        return feature_arr</pre><p>1. <em>__init__</em>: This consists of <em>clusters</em> and <em>random_state</em> variables which are basically KMeans algorithm hyperparams. In addition, we use one more variable i.e. <em>clustering_</em> which is essentially required for training and predicting scenarios.</p><p>2. <em>from_config</em>: This is a class method that reads the values required for our transformer from a configuration file (it is preferable to read variables from configuration rather than hardcoding them; I used OmegaConfig for this).</p><p>3. <em>fit</em>: This method is not required for our data transformation. As a result, we simply return the class itself from this method.</p><p>4. <em>transform</em>: As I previously stated, this is where magic happens! Here, we introduce a new feature to our data based on the Kmeans algorithm predictions.</p><p>Now, we create a pipeline using the above transformers. As a result, X_train will have a new column ‘cluster’.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.preprocessing import MinMaxScaler<br>from omegaconf import OmegaConf<br><br>CONFIG = OmegaConf.load(&quot;sample.yaml&quot;) #reading the Config file<br>CONFIG = CONFIG[&#39;feat_cluster&#39;] # Under key &#39;feat_cluster&#39; we have the keys defined <br><br>feat_cluster = Feature_Clustering.from_config(CONFIG) <br>pipe = Pipeline([(&#39;scaler&#39;,MinMaxScaler()),(&#39;feature_gen&#39;,feat_cluster)])<br>X_train = pipe.fit_transform(X_train)</pre><p>So, our transformers are ready. Let’s now write a Custom Estimator.</p><p>For the estimator, we will construct a <strong>MajorityVoteClassifier</strong> (a.k.a Voting Ensemble) which means that predictions are created by merging many classifiers and finally predicting the labels based on the vote(argmax).</p><p>This part is taken from the book<em> </em><strong><em>Python Machine Learning by Sebastian Raschka &amp; Vahid Mirjalili.</em></strong></p><p>And I have extended on this framework by adding a threshold for predictions and a StratifiedCV method fit , as mentioned in the code below.</p><pre>from sklearn.base import ClassifierMixin,clone<br><br>class MajorityVoteClassifier(BaseEstimator, ClassifierMixin):<br>    &quot;&quot;&quot;A majority vote ensemble classifier<br>    Parameters<br>    ----------<br>    classifiers : array-like, shape = [n_classifiers]<br>    Different classifiers for the ensemble<br>    vote : str, {&#39;classlabel&#39;, &#39;probability&#39;}<br>    Default: &#39;classlabel&#39;<br>    If &#39;classlabel&#39; the prediction is based on<br>    the argmax of class labels. Else if<br>    &#39;probability&#39;, the argmax of the sum of<br>    probabilities is used to predict the class label<br>    (recommended for calibrated classifiers).<br>    &quot;&quot;&quot;<br><br>    def __init__(self, classifiers, prob_cutoff=0.5, vote=&quot;classlabel&quot;):<br>        self.classifiers = classifiers<br>        self.vote = vote<br>        self.prob_cutoff = prob_cutoff<br><br>    def fit(self, X, y):<br>        &quot;&quot;&quot;Fit classifiers based on stratified folds of data.<br>        Parameters<br>        ----------<br>        X : {array-like, sparse matrix},<br>        shape = [n_examples, n_features]<br>        Matrix of training examples.<br>        y : array-like, shape = [n_examples]<br>        Vector of target class labels.<br><br>        Returns<br>        -------<br>        self : object<br>        &quot;&quot;&quot;<br>        if self.vote not in (&quot;probability&quot;, &quot;classlabel&quot;):<br>            raise ValueError(&quot;vote must be &#39;probability&#39;&quot; &quot;or &#39;classlabel&#39;; got (vote=%r)&quot; % self.vote)<br>        self.classes_ = np.unique(y)<br>        self.classifiers_ = []<br>        kfold = StratifiedKFold(len(self.classifiers)).split(X, y)<br>        for k, (train, test) in enumerate(kfold):<br>            fitted_clf = clone(self.classifiers[k]).fit(<br>                X[train],<br>                y[train],<br>                eval_set=[(X[test], y[test])],<br>                early_stopping_rounds=100,<br>                verbose=200,<br>            )<br>            self.classifiers_.append(fitted_clf)<br>        return self<br><br><br>    def predict(self, X):<br>        class_probs = self.predict_proba(X)<br>        class_probs = class_probs[:, 1]<br>        column_indexes = np.zeros(class_probs.shape)<br>        column_indexes[class_probs &gt; self.prob_cutoff] = 1<br>        return column_indexes.astype(int)<br><br>    def predict_proba(self, X) -&gt; t.List[int]:<br>        &quot;&quot;&quot;Predict class probabilities for X.<br>        Parameters<br>        ----------<br>        X : {array-like, sparse matrix},<br>        shape = [n_examples, n_features]<br>        Training vectors, where<br>        n_examples is the number of examples andf<br>        n_features is the number of features.<br>        Returns<br>        ----------<br>        avg_proba : array-like,<br>        shape = [n_examples, n_classes]<br>        Weighted average probability for<br>        each class per example.<br>        &quot;&quot;&quot;<br>        probas = np.asarray([clf.predict_proba(X) for clf in self.classifiers_])<br>        avg_proba = np.average(probas, axis=0)<br>        avg_proba = np.round(avg_proba, 2)<br>        return avg_proba<br>    <br>def generate_classifiers_from_config(config: DictConfig) -&gt; t.List[XGBClassifier]:<br>    &quot;&quot;&quot;Create a classifier from the given config<br>    Args:<br>        config (DictConfig): config containing the framework and params<br>    Raises:<br>        ValueError: If the framework is not supported<br><br>    Returns:<br>        t.List[XGBClassifier]: List of classifiers<br>    &quot;&quot;&quot;<br>    if config.framework == &quot;MajorityVoteXGBoost&quot;:<br>        clfs = []<br>        for i in range(config.num_classifiers):<br>            params = config.params.copy()<br>            classfier = XGBClassifier(**params)<br>            clfs.append(classfier)<br>    else:<br>        raise ValueError(f&quot;Wrong framework value provided {config.framework}.&quot;)<br>    return clfs</pre><p><em>Explanation:</em></p><p>1. <em>__init__</em>: This consists of classifiers or estimators, a vote type and a probability cutoff for predicting the labels.</p><p>2. <em>fit </em>: In this case, we use the fit technique to fit the training data to the set of estimators (classifiers) that we first pass. The estimator is fitted on several Stratified K folds of data before appending the fitted obj to the variable classifiers_, which is then used for prediction..</p><p>3. <em>predict_proba</em>: In this step, we take the predictions from the list of estimators returned by the above fit method and average them.</p><p>4. <em>predict</em> : Predicted probability obtained from the above method is later validated; if it is larger than the probability cutoff, it is marked as 1; otherwise, it is marked as 0</p><p>5. <em>generate_classifiers_from_config</em>: Here, we create list of estimators i.e. classifiers with necessary hyperparams(read from config) which will be used by our MajorityVoteClassifier.</p><p>Now that we have transformers and estimators ready, lets get to the meat of the matter!</p><pre>feat_cluster:<br>    clusters: 3<br>    random_state: 42<br>clf:<br>    num_classifiers : 5<br>    framework : &#39;MajorityVoteXGBoost&#39;<br>    params:<br>        random_state : 42<br>    prob_cutoff : 0.7<br><br></pre><pre>feat_cluster = Feature_Clustering.from_config(CONFIG.feat_cluster)<br>clfs = generate_classifiers_from_config(CONFIG.clf)<br>majorityvote_est = MajorityVoteClassifier(clfs, CONFIG.clf.prob_cutoff)<br>pipe = Pipeline([(&#39;scaler&#39;, MinMaxScaler()), (&#39;feature_gen&#39;, feat_cluster), (&#39;clf&#39;, majorityvote_est)])<br>pipe.fit(X_train, y_train)<br>y_preds = pipe.predict(X_test)</pre><p><strong>Wrap Up</strong></p><p>I believe you now understand how to create a chain of Custom Transformer/ Estimator and use them in a Scikit-learn Pipeline for streamlining your ML workflow. Also, the code looks neat and clean. It is also production-ready. You can just deploy this Pipeline inside your project code and start getting predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f426163f1a2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validate your Data with Pydantic]]></title>
            <link>https://medium.com/@hswathishenoy/validate-your-data-with-pydantic-6fda4cb095b5?source=rss-99a0754c64ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fda4cb095b5</guid>
            <dc:creator><![CDATA[H Swathi Shenoy]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 05:33:36 GMT</pubDate>
            <atom:updated>2023-02-10T05:33:36.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to use Pydantic’s custom validators to validate your data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*l-RFXh5mmpMOn773" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum">Claudio Schwarz</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Data Validation is a crucial step for any data-driven project. Having the right tools and techniques can help you improve the reliability of your model. One tool you could use for this is <strong><em>Pydantic</em></strong>.</p><p>I recently had to perform a model data refresh. Pydantic came in handy here, performing data checks prior to appending them to the previous version of data.</p><h4>About Pydantic</h4><p>Pydantic is a python library used to define your data models in a more efficient way. It is built on top of <em>data classes</em>, a popular library.</p><p>Key Features of Pydantic:</p><ol><li><strong>Type Annotations</strong>: Pydantic has a BaseModel that we can use to define the fields and data types for our model. This will help us understand our model and validate the inputs we provide.</li><li><strong>Constraints and Defaults</strong>: We can set up a constraint or default for a field in the model to ensure that the data is always valid and complete, saving you a lot of time and effort in validation and error handling.</li><li><strong>Serialization and deserialization:</strong> Pydantic provides built-in support for serializing and deserializing your data models to and from different formats, such as <strong>JSON, YAML, and XML</strong>. This can make it much easier to work with your data in different contexts and environments.</li></ol><h4><strong>Implementation</strong></h4><ul><li>Install pydantic using pip</li></ul><pre>pip install pydantic<br></pre><ul><li>Now that it’s installed, let’s create a data model. As input to our model, I will use data in JSON format.</li></ul><blockquote>If you have the data in CSV format you can convert them into dict or JSON format using the to_dict or to_json method of pandas and load them.</blockquote><pre>from pydantic import BaseModel<br>from typing import List, Optional<br><br>class PersonalIdentityInfo(BaseModel):<br>  &quot;&quot;&quot;<br>  Represents a Person Identity Info which you can read from JSON file<br>  &quot;&quot;&quot;<br>  name: str<br>  age: int<br>  address: str<br>  pan_no: Optional[str]<br>  aadhar_no: Optional[str]<br>  email: Optional[str]<br>  <br>def main() -&gt; None:<br>    &quot;&quot;&quot;Main function.&quot;&quot;&quot;<br>    <br>    # Read data from a JSON file<br>    with open(&quot;person-info.json&quot;) as file:<br>        data = json.load(file)<br>        people: List[Person] = [PersonalIdentityInfo(**item) for item in data]</pre><p>This simple model defines a PersonalIndentityInfo class with 6 fields: name, age, address,pan_no,aadhar_no,email. The field types are specified using <strong>type annotations</strong>, and Pydantic will validate the data automatically to ensure that it is always of the correct type. Note the <em>Optional</em> for pan_no,aadhar_no,emailmeans that those fields are optional, as in they are not required to be present in the inputs.</p><p>Let&#39;s give the JSON input i.e person-info.json which has the following entries.</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;Aradhya&quot;,<br>    &quot;age&quot;: 20,<br>    &quot;address&quot;: &quot;Kulur Ferry Rd, Kottara, Mangaluru&quot;,<br>  },<br>  <br>{<br>    &quot;name&quot;: &quot;Aashay&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;aadhar_no&quot;:&quot;3377 4432 1212&quot;<br>  },<br>  <br>]</pre><p>The above Input gives an error as shown below, as the address is missing from the input which is a mandatory field. Similarly, if the datatypes are different from the defined it raises the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZHCE9_u_F2Qy2Z_PHOTMA.png" /><figcaption>Validation error for the given JSON input as the address field is missing.</figcaption></figure><p>Let’s now add some constraints to our defined fields. For example, Aadhar or PAN IDs are required as identity proof for individuals, so let’s include that constraint.</p><pre>from pydantic import BaseModel,root_validator<br>from typing import List, Optional<br>import json<br><br>class IdentityProofMissingError(Exception):<br>    &quot;&quot;&quot;Custom error that is raised when both Aadhar and PAN nos are missing.&quot;&quot;&quot;<br><br>    def __init__(self, name: str, message: str) -&gt; None:<br>        self.title = name<br>        self.message = message<br>        super().__init__(message)<br><br><br>class PersonalIdentityInfo(BaseModel):<br>    &quot;&quot;&quot;<br>    Represents a Person Identity Info which you can read from JSON file<br>    &quot;&quot;&quot;<br>    name: str<br>    age: int<br>    address: str<br>    pan_no: Optional[str]<br>    aadhar_no: Optional[str]<br>    email: Optional[str]<br>    <br>    @root_validator(pre=True)<br>    @classmethod<br>    def check_aadhar_or_pan(cls, values):<br>        &quot;&quot;&quot;Make sure there is either an aadhar_no or pan_no value defined&quot;&quot;&quot;<br>        if &quot;aadhar_no&quot; not in values and &quot;pan_no&quot; not in values:<br>            raise IdentityProofMissingError(<br>                title=values[&quot;name&quot;],<br>                message=&quot;Entries should have either an Aadhar or PAN&quot;,<br>            )<br>        return <br><br>def main() -&gt; None:<br>    &quot;&quot;&quot;Main function.&quot;&quot;&quot;<br><br>    # Read data from a JSON file<br>    with open(&quot;person-info.json&quot;) as file:<br>        data = json.load(file)<br>        people: List[Person] = [PersonalIdentityInfo(**item) for item in data]<br>            <br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Notice the @root_validator(pre=True), in which case they’re called before field validation occurs (and are provided with the raw input data).</p><p>Let’s use the same JSON inputs as before and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SViQT0X9i90bkaPKEO4kUw.png" /><figcaption>Missing IdentityProof Error</figcaption></figure><p>IdentityProofMissing error is raised as the initial entry is not having either PAN or Aadhar ID.</p><p>Let us add another constraint to our data model where we check the format of the PAN number. PAN is a ten-digit alphanumeric number that is unique. So let us include that constraint.</p><p>Note: There are a few additional <a href="https://incometaxindia.gov.in/Forms/tps/1.Permanent%20Account%20Number%20(PAN).pdf">constraints</a> to check apart from the above for PAN number validation.</p><pre>class IdentityProofMissingError(Exception):<br>    &quot;&quot;&quot;Custom error that is raised when both Aadhar and PAN nos are missing.&quot;&quot;&quot;<br><br>    def __init__(self, title: str, message: str) -&gt; None:<br>        self.title = title<br>        self.message = message<br>        super().__init__(message)<br><br>class PANFormatError(Exception):<br>    &quot;&quot;&quot;Custom error that is raised when PAN no. doesn&#39;t have the right format.&quot;&quot;&quot;<br><br>    def __init__(self, value: str, message: str) -&gt; None:<br>        self.value = value<br>        self.message = message<br>        super().__init__(message)<br><br>class PersonalIdentityInfo(BaseModel):<br>    &quot;&quot;&quot;<br>    Represents a Person Identity Info which you can read from JSON file<br>    &quot;&quot;&quot;<br>    name: str<br>    age: int<br>    address: str<br>    pan_no: Optional[str]<br>    aadhar_no: Optional[str]<br>    email: Optional[str]<br>    <br>    @root_validator(pre=True)<br>    @classmethod<br>    def check_aadhar_or_pan(cls, values):<br>        &quot;&quot;&quot;Make sure there is either an aadhar_no or pan_no value defined&quot;&quot;&quot;<br>        if &quot;aadhar_no&quot; not in values and &quot;pan_no&quot; not in values:<br>            raise IdentityProofMissingError(<br>                title=values[&quot;name&quot;],<br>                message=&quot;Entries should have either an Aadhar or PAN&quot;,<br>            )<br>        return values<br>    <br>    @validator(&quot;pan_no&quot;)<br>    @classmethod<br>    def pan_no_valid(cls, value) -&gt; str:<br>        &quot;&quot;&quot;Validator to check whether PAN no. is valid&quot;&quot;&quot;<br>        chars = [c for c in value if c.isalnum()]<br>        if len(chars) != 10:<br>            raise PANFormatError(value=value, message=&quot;PAN No. should be 10 digits and alpha numeric.&quot;)<br>        return value<br><br>def main() -&gt; None:<br>    &quot;&quot;&quot;Main function.&quot;&quot;&quot;<br><br>    # Read data from a JSON file<br>    with open(&quot;person-info.json&quot;) as file:<br>        data = json.load(file)<br>        display(data)<br>        people: List[Person] = [PersonalIdentityInfo(**item) for item in data]<br>            <br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Note the @validator(&quot;pan_no&quot;) is similar to root_validator(pre=False) in which case they’re called after field validation.</p><p>Now, consider the JSON input file, which contains the following entries:</p><pre>[<br> { &quot;name&quot;: &quot;Aradhya&quot;,<br>  &quot;age&quot; : 20,<br>  &quot;address&quot; :  &quot;Kulur Ferry Rd, Kottara, Mangaluru&quot;,<br>  &quot;aadhar_no&quot;: &quot;3377 4432 1212&quot;<br><br> },<br> {<br>    &quot;name&quot;: &quot;Aashay&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;address&quot; :  &quot;Kulur Ferry Rd, Kottara, Mangaluru&quot;,<br>    &quot;aadhar_no&quot;: &quot;3377 4432 1212&quot;,<br>    &quot;pan_no&quot;:  &quot;AAAAA1234*&quot;<br>  }<br>  <br>]</pre><p>The above input raises the PANFormat error :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA2Zgfpox3bSeL0M9X6o7w.png" /><figcaption>PANFormat Error as it fails the alphanumeric check.</figcaption></figure><h4><strong>Wrap Up</strong></h4><p>I believe you are now convinced that Pydantic provides a simple and straightforward way to define and validate data models, saving you a significant amount of time and effort in coding and debugging. Furthermore, I believe you will appreciate its flexibility and compatibility because it can be easily integrated into your existing projects and workflow.</p><p>I hope you start using Pydantic from now on:)</p><p>Link to <a href="https://github.com/h-swathi-shenoy/pydantic_2023">GitHub Repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fda4cb095b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>