<?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 Daniel Jude on Medium]]></title>
        <description><![CDATA[Stories by Daniel Jude on Medium]]></description>
        <link>https://medium.com/@danieljude1992?source=rss-82c58c4b9b89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WzPt_lUXCuDlEvLPi2DzDQ.jpeg</url>
            <title>Stories by Daniel Jude on Medium</title>
            <link>https://medium.com/@danieljude1992?source=rss-82c58c4b9b89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:02:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danieljude1992/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[Git and GitHub for Cloud Engineering: Building a Workflow that Makes Changes Safer]]></title>
            <link>https://danieljude1992.medium.com/git-and-github-for-cloud-engineering-building-a-workflow-that-makes-changes-safer-e60696b4b1ee?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60696b4b1ee</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 13:08:47 GMT</pubDate>
            <atom:updated>2026-10-02T22:06:57.116Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloud engineering is not only about creating infrastructure. It is also about managing change.</p><p>Most cloud projects are controlled by files:</p><ul><li>Terraform files describe infrastructure.</li><li>YAML files define CI/CD pipelines.</li><li>Markdown files explain architecture and operations.</li><li>Shell scripts automate repeated tasks.</li><li>Kubernetes manifests define workloads.</li></ul><p>These files may look ordinary, but they can control real cloud environments. A small change can affect a network, a deployment, a permission policy, or an application workflow.</p><p>That is why Git and GitHub are important.</p><p>They give cloud engineers a way to track changes, review work before it is merged, protect sensitive files, and keep a clear history of how a project evolved.</p><p>This article explains Git and GitHub through a simple cloud engineering foundation project. The repository is intentionally small, but the workflow behind it is the real focus.</p><p>The project demonstrates a complete workflow:</p><ul><li>create a clean repository</li><li>make changes on branches</li><li>inspect changes before committing</li><li>open pull requests</li><li>track work with issues</li><li>protect the repository with .gitignore</li><li>keep the main branch understandable</li></ul><p>The same workflow becomes even more important as projects grow.</p><p>It applies later to AWS networking, Terraform modules, CI/CD pipelines, Kubernetes resources, and platform engineering automation.</p><h4><strong>Why Git Matters In Cloud Engineering</strong></h4><p>Cloud infrastructure needs a reliable history.</p><p>Without version control, project folders can quickly become confusing:</p><pre>terraform-final/<br>terraform-final-new/<br>terraform-final-fixed/<br>terraform-final-real-one/</pre><p>Folder names like these do not explain what changed, why it changed, or which version is safe to use. They also make rollback difficult.</p><p>Git solves this by recording meaningful checkpoints called commits. Each commit captures a set of changes and attaches a message that explains the purpose of those changes.</p><p>Useful commit messages look like this:</p><pre>Add initial project structure<br>Improve project README<br>Update repository security rules<br>Normalize Markdown file endings</pre><p>These messages help a future reader understand the project history. They are much clearer than messages such as update, fix, or done.</p><p>In cloud engineering, Git commonly tracks:</p><ul><li>infrastructure-as-code files</li><li>CI/CD workflow definitions</li><li>Kubernetes manifests</li><li>automation scripts</li><li>architecture notes</li><li>runbooks</li><li>troubleshooting guides</li><li>security and compliance documentation</li></ul><p>When these files are tracked properly, changes can be reviewed before they affect a real environment.</p><p>That review process is one of the reasons Git is a core cloud engineering skill.</p><h4><strong>Git And GitHub Are Not The Same Thing</strong></h4><p>Git and GitHub work together, but they are not the same.</p><p><strong>Git</strong> is the version control system. It runs locally and records changes in a project folder.</p><p><strong>GitHub</strong> is a hosting and collaboration platform. It stores a remote copy of a Git repository.</p><p>It also adds features such as pull requests, issues, reviews, automation, and project visibility.</p><p>A simple way to picture the relationship is:</p><pre>Local project files<br>        |<br>        | Git tracks changes<br>        v<br>Local repository and commits<br>        |<br>        | git push<br>        v<br>GitHub remote repository<br>        |<br>        | pull requests, issues, reviews, automation<br>        v<br>Shared project history</pre><p>Git can work without GitHub, but GitHub is built around Git repositories.</p><h4><strong>The Foundation Project</strong></h4><p>The example project is called:</p><pre>cloud-engineering-foundations</pre><p><a href="https://github.com/dajuctech/cloud-engineering-foundations">Project repository</a>:</p><pre>https://github.com/dajuctech/cloud-engineering-foundations</pre><p>The purpose of the project is to practice a clean Git and GitHub workflow before moving into larger cloud projects.</p><p>The repository does not need advanced automation to be useful. Its value is in the engineering habits it demonstrates.</p><p>The public project structure is simple:</p><pre>cloud-engineering-foundations/<br>+-- README.md<br>+-- .gitignore</pre><p>The README.md explains the project, workflow, terms, commands, security rules, and lessons in one place.</p><p>The .gitignore file prevents unsafe or unnecessary files from being tracked.</p><p>Keeping the public repository simple makes it easier for someone else to understand the project without jumping between many separate documents.</p><h4><strong>The Workflow From Start To Finish</strong></h4><p>A clean Git workflow usually follows this path:</p><pre>Create or clone repository<br>-&gt; create a branch<br>-&gt; edit files<br>-&gt; inspect changes<br>-&gt; stage selected files<br>-&gt; commit<br>-&gt; push<br>-&gt; open pull request<br>-&gt; review<br>-&gt; merge into main<br>-&gt; pull latest main locally<br>-&gt; clean up merged branch</pre><p>Each step has a purpose.</p><p>The branch keeps unfinished work away from the stable version.</p><p>The diff shows what changed.</p><p>The staging area lets related changes be grouped together. The commit records a checkpoint. The pull request creates a review space before the work reaches main.</p><p>At first, this may feel like more steps than necessary.</p><p>In practice, this structure prevents confusion. It is much safer than editing files directly on main and pushing everything without review.</p><h4><strong>Starting A Repository</strong></h4><p>There are two common ways to start a Git project.</p><p>If the repository already exists on GitHub, clone it:</p><pre>git clone https://github.com/&lt;username&gt;/&lt;repository-name&gt;.git<br>cd &lt;repository-name&gt;<br>git status</pre><p>If the folder already exists locally and needs Git tracking, initialise it:</p><pre>git init -b main<br>git status</pre><p>The -b main option creates the initial branch as main.</p><p>After initialising locally, connect the local repository to GitHub:</p><pre>git remote add origin &lt;repository-url&gt;<br>git remote -v</pre><p>origin is the common local name for the GitHub remote. It is not a branch. It is simply the name Git uses for the connected remote repository.</p><h4><strong>Core Git Concepts</strong></h4><p>Git becomes easier when the main terms are clear.</p><pre>| Concept      | Meaning                                                        |<br>|--------------|----------------------------------------------------------------|<br>| Repository   | A project folder tracked by Git                                |<br>| Working tree | The visible files in the project folder                        |<br>| Commit       | A saved checkpoint in the project history                      |<br>| Branch       | A separate line of work                                        |<br>| main         | The stable branch used as the source of truth                  |<br>| Remote       | A connected repository hosted somewhere else, such as GitHub   |<br>| origin       | The common local name for the GitHub remote                    |<br>| Stage        | Select file changes for the next commit                        |<br>| Push         | Send local commits to GitHub                                   |<br>| Pull         | Bring remote changes into the local branch                     |<br>| Pull request | Propose branch changes before merging                          |<br>| Merge        | Combine approved changes into another branch                   |<br>| Issue        | Track a task, bug, or improvement                               |</pre><p>These concepts work together in normal project flow.</p><p>For example, a README update can follow this sequence:</p><pre>git switch -c improve-readme<br>git status<br>git diff<br>git add README.md<br>git diff --cached<br>git commit -m &quot;Improve project README&quot;<br>git push -u origin improve-readme</pre><p>After pushing the branch, a pull request can be opened on GitHub. The pull request gives the change a place to be reviewed before it is merged into main.</p><h4><strong>Branches Keep Work Controlled</strong></h4><p>A branch is a safe workspace.</p><p>Instead of editing main directly, create a branch for one focused change:</p><pre>git switch -c improve-readme</pre><p>That branch can hold the work while main remains stable.</p><p>If the change is incomplete or wrong, the branch can be corrected or deleted without damaging the stable version of the project.</p><p>This habit becomes important in cloud work.</p><p>A branch might contain a Terraform networking change, an IAM policy update, a GitHub Actions workflow, or a Kubernetes deployment update.</p><p>Those changes should be reviewed before they become part of the main project.</p><h4><strong>Review Changes Before Committing</strong></h4><p>One of the most useful Git habits is reviewing changes before committing them.</p><p>Start with:</p><pre>git status<br>git diff</pre><p>git status Shows the current branch, changed files, staged files, and whether the working tree is clean.</p><p>git diff Shows the content changes that have not yet been staged.</p><p>After staging files, review the staged version:</p><pre>git diff --cached</pre><p>This shows what the next commit will contain.</p><p>For Markdown, Terraform, scripts, and configuration files, it is also useful to check for whitespace issues:</p><pre>git diff --check<br>git diff --cached --check</pre><p>These commands help catch small formatting problems before they become part of the project history.</p><h4><strong>Stage Files Intentionally</strong></h4><p>Staging means selecting changes for the next commit.</p><p>To stage one file:</p><pre>git add README.md</pre><p>To stage a few specific files:</p><pre>git add README.md .gitignore</pre><p>To stage everything under the current folder:</p><pre>git add .</pre><p>git add . is convenient, but it should be used carefully.</p><p>Cloud projects often contain sensitive or generated files. A private key, .env file, Terraform state file, or local credential file should not be committed.</p><p>When the change is small, staging specific files is often safer and easier to reason about.</p><h4><strong>Write Useful Commit Messages</strong></h4><p>A commit message should explain the purpose of the change.</p><p>Weak examples:</p><pre>update<br>fix<br>changes<br>done</pre><p>Better examples:</p><pre>Add initial project structure<br>Document Git and GitHub workflow<br>Improve project README<br>Normalize Markdown file endings</pre><p>The goal is not to write a long sentence. The goal is to make the project history understandable.</p><h4><strong>Pull Requests Create The Review Space</strong></h4><p>A pull request is a proposal to merge one branch into another.</p><p>The normal flow is:</p><pre>feature branch -&gt; pull request -&gt; review -&gt; merge into main</pre><p>A pull request gives the project a place to show:</p><ul><li>what changed</li><li>why it changed</li><li>which files were touched</li><li>whether checks passed</li><li>whether feedback is needed</li></ul><p>Even in a solo project, pull requests are useful because they show how the work was managed.</p><p>A portfolio repository with clean pull requests shows more than the final files. It shows the workflow behind the files.</p><h4><strong>Issues Give Work A Clear Reason</strong></h4><p>GitHub Issues help define work before changes are made.</p><p>An issue can describe:</p><ul><li>a bug</li><li>a documentation improvement</li><li>a cleanup task</li><li>a feature idea</li><li>a learning objective</li></ul><p>For example:</p><pre>Issue: Improve project README</pre><p>A branch can then be created for that issue:</p><pre>git switch -c improve-readme</pre><p>When opening the pull request, the description can reference the issue:</p><pre>Closes #2</pre><p>After the pull request is merged, GitHub automatically closes the issue. This creates a clear link between the planned work and the completed change.</p><h4><strong>Protect the Repository with.</strong><strong>gitignore</strong></h4><p>The .gitignore file tells Git which files should not be tracked.</p><p>For cloud engineering projects, this is especially important.</p><p>Local folders often contain sensitive files, generated files, or temporary files that do not belong in a public repository.</p><p>A useful starter .gitignorecan include:</p><pre>.env<br>.env.*<br>!.env.example<br>*.pem<br>*.key<br>.aws/<br>.terraform/<br>terraform.tfstate<br>terraform.tfstate.backup<br>.DS_Store<br>node_modules/<br>__pycache__/</pre><p>Each rule has a purpose:</p><pre>| Rule               | Why it matters                                      |<br>|--------------------|-----------------------------------------------------|<br>| .env and .env.*    | Environment files may contain secrets               |<br>| !.env.example      | Allows a safe template file to be committed         |<br>| *.pem and *.key    | Blocks private keys                                 |<br>| .aws/              | Blocks local AWS configuration and credentials      |<br>| .terraform/        | Blocks local Terraform provider and module files    |<br>| terraform.tfstate  | Blocks infrastructure state that may expose details |<br>| .DS_Store          | Blocks macOS generated files                        |<br>| node_modules/      | Blocks installed JavaScript dependencies            |<br>| __pycache__/       | Blocks generated Python cache files                 |</pre><p>Ignore rules can be tested with:</p><pre>git check-ignore -v .env</pre><p>To see what Git is actually tracking, use:</p><pre>git ls-files</pre><p>This is more reliable than looking at the folder visually. A file can exist locally without being tracked by Git.</p><h4><strong>Common Mistakes And What They Teach</strong></h4><p>Git mistakes are part of learning the tool. The important habit is to stop, inspect the state, and avoid guessing.</p><p><strong>Comparing The Wrong Branches</strong></p><p>A pull request can look confusing if the base branch and compare branch are wrong.</p><p>The base branch is where the change should go. The compare branch is where the change currently exists.</p><p>For normal work, the base is oftenmain, and the compare branch is the feature branch.</p><p><strong>Working From The Wrong Branch</strong></p><p>Before editing files, check the active branch:</p><pre>git branch --show-current<br>git status</pre><p>If the active branch is not correct, switch first:</p><pre>git switch main<br>git pull origin main<br>git switch -c new-task-branch</pre><p><strong>Trying To Commit Without Staging</strong></p><p>If Git says there are changes but nothing to commit, the files have probably not been staged.</p><p>Use:</p><pre>git status<br>git add &lt;file&gt;<br>git commit -m &quot;Message&quot;</pre><p>Editing a file does not automatically place it into the next commit.</p><p><strong>Copying The Wrong Text Into The Terminal</strong></p><p>When copying commands, copy only the command itself.</p><p>Do not copy terminal prompt text such as:</p><pre>user@machine project %</pre><p>It is also worth reviewing file changes before committing, because accidentally pasted text can end up inside a source file or README.</p><p><strong>Deleted Remote Branches Still Appear Locally</strong></p><p>After branches are merged and deleted on GitHub, local Git may still show old remote-tracking references.</p><p>Clean them with:</p><pre>git fetch --prune</pre><p>This updates the local view of remote branches.</p><p><strong>Merge Conflicts In Plain English</strong></p><p>A merge conflict happens when Git cannot automatically combine changes.</p><p>For example, two branches may edit the same line in the same file. Git does not know which version should win, so it asks for human judgment.</p><p>Conflict markers look like this:</p><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD<br>current branch version<br>=======<br>incoming branch version<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; feature-branch</pre><p>The fix is to edit the file manually, keep the correct final content, remove the conflict markers, then stage and commit the resolved file.</p><p>Merge conflicts are not a sign that Git is broken. They are Git refusing to guess.</p><h4><strong>GitHub Actions: The Next Layer</strong></h4><p>GitHub Actions adds automation to a repository.</p><p>It can run tasks when someone pushes code or opens a pull request. In cloud engineering, GitHub Actions is commonly used for:</p><ul><li>formatting checks</li><li>linting</li><li>tests</li><li>Terraform validation</li><li>Terraform plan</li><li>security scanning</li><li>documentation checks</li><li>deployment workflows</li></ul><p>A simple future workflow might look like this:</p><pre>Pull request opened<br>-&gt; check Markdown formatting<br>-&gt; validate Terraform files<br>-&gt; run security scan<br>-&gt; show result before merge</pre><p>This is how GitHub moves from repository hosting into CI/CD and DevOps workflows.</p><h4><strong>What This Kind Of Repository Demonstrates</strong></h4><p>A small repository can still demonstrate strong engineering habits.</p><p>It can show that the work was managed with care:</p><ul><li>the project has a clear README</li><li>sensitive files are ignored</li><li>branches are used for focused changes</li><li>diffs are reviewed before commits</li><li>commits have meaningful messages</li><li>pull requests are used for review</li><li>issues are used to track work</li><li>merged branches are cleaned up</li></ul><p>For a cloud engineering portfolio, the process matters. A reviewer should be able to understand the repository without needing extra explanation.</p><p><strong>Key Commands Reference</strong></p><pre>| Command                    | Purpose                                 |<br>|----------------------------|-----------------------------------------|<br>| git status                 | Show repository state                   |<br>| git branch --show-current  | Show active branch                      |<br>| git switch -c &lt;branch&gt;     | Create and switch to a new branch       |<br>| git switch &lt;branch&gt;        | Switch branches                         |<br>| git diff                   | Show unstaged changes                   |<br>| git add &lt;file&gt;             | Stage selected file                     |<br>| git diff --cached          | Show staged changes                     |<br>| git commit -m &quot;message&quot;    | Create a commit                         |<br>| git push -u origin &lt;branch&gt;| Push branch and set upstream            |<br>| git pull origin main       | Pull latest main                        |<br>| git fetch --prune          | Remove stale remote-tracking references |<br>| git ls-files               | Show tracked files                      |<br>| git check-ignore -v &lt;file&gt; | Show why a file is ignored              |</pre><h4><strong>Security Checklist</strong></h4><p>Before pushing to GitHub, check:</p><ul><li>No .envfiles are staged.</li><li>No .pem or private-key files are staged.</li><li>No AWS credentials are staged.</li><li>No Terraform state files are staged.</li><li>No internal-only notes are staged.</li><li>git status shows only intended files.</li><li>git diff — cached has been reviewed.</li><li>.gitignore includes common sensitive files.</li><li>The README does not expose secrets, account IDs, or internal details.</li></ul><p>Security in Git starts before the push.</p><h4><strong>Final Thoughts</strong></h4><p>Git and GitHub are not just commands to memorise. They are part of the discipline of managing technical change.</p><p>For cloud engineering, that discipline matters because infrastructure is often described in files.</p><p>When those files change, networks, permissions, deployments, and services may change too.</p><p>A simple foundation repository is a good place to practice the workflow before using the same habits on larger AWS, Terraform, CI/CD, or platform engineering projects.</p><p>The goal is to make every change traceable, reviewable, and explainable.</p><p>That is the real value of Git and GitHub in cloud engineering.</p><h4><strong>References</strong></h4><ul><li><a href="https://git-scm.com/doc">Git documentation</a></li><li><a href="https://docs.github.com/">GitHub Docs</a></li><li><a href="https://docs.github.com/en/actions">GitHub Actions Docs</a></li><li><a href="https://git-scm.com/book/en/v2">Pro Git book</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60696b4b1ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Networking: How the Pieces Fit Together]]></title>
            <link>https://danieljude1992.medium.com/aws-networking-how-the-pieces-fit-together-d8df39f3f4ab?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8df39f3f4ab</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-networking]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 14:09:18 GMT</pubDate>
            <atom:updated>2026-09-22T14:25:28.552Z</atom:updated>
            <content:encoded><![CDATA[<p>If AWS networking feels confusing, it is usually because the services are learned as separate names instead of one connected system. VPCs, subnets, route tables, Internet Gateways, NAT Gateways, Security Groups, Network ACLs, Route 53, load balancers, CloudFront, and VPC peering all sound like separate topics at first. In a real architecture, they work together to answer one simple question: how should traffic move safely from one place to another?</p><p>The goal here is not to memorise definitions. It is to understand the flow: where resources live, how traffic finds a path, what makes a subnet public or private, how security rules affect access, and how AWS connects networks across VPCs, Regions, and even on-premises environments.</p><p>The main networking question is always:</p><pre>Who needs to talk to what, from where, through which path, and under which security rules?</pre><p>Once that question becomes clear, each networking service has a job.</p><h4><strong>The Big Picture</strong></h4><p>AWS networking is built in layers. A simple mental model looks like this:</p><figure><img alt="aws-networking-layers-diagram" src="https://cdn-images-1.medium.com/max/1024/1*OvO7sGll01JB03Fh8OS0Qw.png" /></figure><p>Each layer answers a different question.</p><pre>| Layer                 | Question it answers                                                      |<br>| --------------------- | ------------------------------------------------------------------------ |<br>| Region                | Which geographic AWS area am I using?                                    |<br>| Availability Zone     | Which isolated data centre area inside the Region hosts this subnet?     |<br>| VPC                   | What private network boundary contains my resources?                     |<br>| Subnet                | Which smaller IP range and Availability Zone does this resource live in? |<br>| Route table           | Where should traffic go next?                                            |<br>| Gateway or connection | What path carries traffic outside the subnet or VPC?                     |<br>| Security Group        | Is this resource allowed to receive or send this traffic?                |<br>| Network ACL           | Is this subnet allowed to receive or send this traffic?                  |<br>| DNS                   | What IP address belongs to this name?                                    |                                |</pre><p>This is why a networking problem is rarely solved by checking only one setting. A public EC2 instance, for example, needs a public IP, a route to an Internet Gateway, an attached Internet Gateway, Security Group rules, Network ACL rules, and a running SSH or web service.</p><h4><strong>A Simple Network Story</strong></h4><p>Before learning each service one by one, imagine you want to build a small application in AWS.</p><p>You start by choosing a Region, such as us-east-1because every regional resource must live somewhere. Inside that Region, you create a VPC. The VPC is your private network boundary. It is the space where your servers, subnets, routes, and firewall rules will live.</p><p>Next, you divide the VPC into subnets. You might create one public subnet for resources that need a direct path to the internet, and one private subnet for resources that should stay protected from direct internet access. A public-facing load balancer or bastion host can live in the public subnet. Application servers and databases usually belong in private subnets.</p><p>Then you connect the public side of the network to the internet. To do that, you attach an Internet Gateway to the VPC and add a route in the public subnet’s route table:</p><pre>0.0.0.0/0 -&gt; Internet Gateway</pre><p>That route means “send traffic for anywhere on the internet to the Internet Gateway.” But this still does not make everything public. An EC2 instance also needs a public IP address, and its Security Group must allow the correct inbound traffic.</p><p>For the private subnet, you usually avoid a direct Internet Gateway route. If a private server needs to download updates from the internet, you give it an outbound-only path through a NAT Gateway. The private subnet route table sends internet-bound traffic to the NAT Gateway, and the NAT Gateway uses the public subnet’s internet path.</p><p>Security Groups and Network ACLs then decide what traffic is allowed. The route table answers “where should this traffic go?” The Security Group answers “is this instance allowed to receive or send this traffic?” The Network ACL answers a similar question at the subnet boundary.</p><p>As the architecture grows, you may need to connect networks together. VPC peering can privately connect two VPCs. Transit Gateway can act as a central hub for many VPCs. VPN and Direct Connect can connect AWS to an office or data centre. PrivateLink and VPC endpoints can keep service access private. Load balancers, CloudFront, Global Accelerator, and Route 53 help users reach applications in a reliable and efficient way.</p><p>That is the overall flow: choose where the network lives, create the private network boundary, divide it into subnets, attach the right gateways, add routes, apply security rules, then test the traffic path.</p><h4><strong>Regions and Availability Zones</strong></h4><p>An AWS Region is a geographic area, such as <strong>US East (N. Virginia) </strong>with the code us-east-1. Another example is <strong>US West (Oregon)</strong> with the code us-west-2.</p><p>An Availability Zone, or AZ, is an isolated location inside a Region. Examples include us-east-1a, us-east-1b, us-west-2aand us-west-2b.</p><p>One detail that is easy to miss is that AZ letters are mapped per AWS account. Your us-east-1a might not be the exact same physical AZ as another person’s us-east-1a. For personal practice, this is usually fine. Just choose the AZ shown in your own AWS console and keep related resources in the same AZ when the architecture requires it.</p><p>A common mistake is to mix up Regions and Availability Zones.</p><pre>| Concept             | Plain explanation                                                                                     |<br>| ------------------- | ----------------------------------------------------------------------------------------------------- |<br>| Region              | A large AWS location, such as `us-east-1`                                                             |<br>| Availability Zone   | A smaller isolated zone inside a Region, such as `us-east-1a`                                         |<br>| VPC                 | Created inside one Region                                                                             |<br>| Subnet              | Created inside one Availability Zone                                                                  |<br>| EC2 instance        | Runs in the Availability Zone of the subnet you choose                                                |<br>| AZ-scoped resources | Some resources, such as EBS volumes, must be in the same Availability Zone as the instance using them |</pre><p>This matters because resources can appear to disappear when the console is set to the wrong Region. If you create a VPC inus-east-1, you will not see it while looking at us-west-2.</p><h4><strong>Amazon VPC: Your Private Network Boundary</strong></h4><p>Amazon VPC stands for <strong>Virtual Private Cloud</strong>. A VPC is your private network space inside AWS. It is where you decide the IP address range, subnets, route tables, gateways, and security controls.</p><p>Think of a VPC like the boundary around a private building. The building may have different rooms, doors, hallways, and security checks, but the VPC is the main boundary.</p><p>AWS has two common VPC ideas:</p><pre>| Default VPC                                     | Custom VPC                                      |<br>| ----------------------------------------------- | ----------------------------------------------- |<br>| Created by AWS for quick use                    | Created by you for a planned design             |<br>| Usually has default subnets and internet access | Starts with only what you configure             |<br>| Useful for quick testing                        | Better for learning and real-world architecture |<br>| Less intentional                                | More controlled                                 |</pre><p>Creating a custom VPC is useful because it forces every decision to be visible. Nothing is assumed. You can see that a VPC by itself does not automatically give you public subnets, NAT access, or VPC peering. Those are separate pieces you add intentionally.</p><h4><strong>CIDR Blocks and IP Planning</strong></h4><p>A CIDR block defines an IP address range. In AWS, VPCs and subnets use CIDR blocks to decide which private IP addresses are available.</p><p>Example:</p><pre>10.16.0.0/16</pre><p>This can be used as a VPC range. A subnet inside it might use:</p><pre>10.16.1.0/24</pre><p>The /16 range is larger. The /24 range is smaller and fits inside it.</p><pre>| CIDR example      | Common use                  |<br>| ----------------- | --------------------------- |<br>| `10.0.0.0/16`     | VPC CIDR                    |<br>| `10.0.1.0/24`     | Subnet CIDR                 |<br>| `203.0.113.10/32` | One exact public IP address |</pre><p>The /32 format is important for SSH rules. It means “only this one IP address.” A safer SSH rule often uses your current public IP with `/32` so SSH access is limited to your own connection instead of being open to the whole internet.</p><p>AWS reserves five IPv4 addresses in every subnet, so a /24 subnet does not give you all 256 addresses for instances. You do not need to memorise every reserved address for day-to-day understanding, but you should remember that AWS keeps a few addresses for networking functions.</p><p>CIDR planning also matters for VPC peering. Two VPCs that need to peer should not have overlapping CIDR blocks. If both networks use the same range, AWS cannot clearly route traffic because the same destination could exist in both places.</p><h4><strong>Subnets: Dividing the VPC</strong></h4><p>A subnet is a smaller IP range inside a VPC. Every subnet belongs to exactly one Availability Zone.</p><p>If the VPC is the building, subnets are the rooms. Some rooms are designed for public-facing resources. Others are designed for private application or database resources.</p><p>Example subnet layout:</p><pre>| Subnet             | CIDR           | Availability Zone | Intended role        |<br>| ------------------ | -------------- | ----------------- | -------------------- |<br>| `public-subnet`    | `10.16.1.0/24` | `us-east-1a`      | Public entry point   |<br>| `private-subnet`   | `10.16.2.0/24` | `us-east-1a`      | Private workload     |<br>| `public-subnet-a`  | `10.0.1.0/24`  | `us-east-1a`      | Public tier in AZ A  |<br>| `private-subnet-a` | `10.0.2.0/24`  | `us-east-1a`      | Private tier in AZ A |<br>| `public-subnet-b`  | `10.0.3.0/24`  | `us-east-1b`      | Public tier in AZ B  |<br>| `private-subnet-b` | `10.0.4.0/24`  | `us-east-1b`      | Private tier in AZ B |</pre><p>The name of the subnet does not control how it behaves. A subnet called public-subnet is not really public until its route table sends internet-bound traffic to an Internet Gateway.</p><p>This is a common reason people get stuck. An EC2 instance can have a public IP and a correct Security Group rule, but SSH can still time out if the subnet’s route table is not correctly connected to an Internet Gateway.</p><h4><strong>Public Subnets and Private Subnets</strong></h4><p>A public subnet has a route to an Internet Gateway. A private subnet does not have a direct route to an Internet Gateway.</p><p>The difference is routing, not the name.</p><pre>| Subnet type     | Main route behaviour             | Common resources                                      |<br>| --------------- | -------------------------------- | ----------------------------------------------------- |<br>| Public subnet   | `0.0.0.0/0 -&gt; Internet Gateway`  | Public load balancers, bastion hosts, NAT Gateways    |<br>| Private subnet  | No direct Internet Gateway route | Application servers, databases, private EC2 instances |<br>| Isolated subnet | No outbound internet route       | Highly restricted databases or internal systems       |</pre><p>For direct public access to an EC2 instance, you usually need all of these:</p><ol><li>The instance is in a subnet whose route table sends `0.0.0.0/0` to an Internet Gateway.</li><li>The instance has a public IPv4 address or an Elastic IP.</li><li>The Security Group allows the required inbound port.</li><li>The Network ACL allows the request and response traffic.</li><li>The service is running on the instance.</li></ol><p>This is why a public IP alone is not enough.</p><h4><strong>Route Tables and Local Routes</strong></h4><p>A route table tells AWS where to send traffic leaving a subnet. Every subnet uses one route table. One route table can be used by many subnets, but a subnet cannot use two route tables at the same time.</p><p>Example route table:</p><pre>Destination       Target<br>10.16.0.0/16      local<br>0.0.0.0/0         igw-xxxxxxxx</pre><p>The local route is created automatically by AWS. It allows resources inside the VPC CIDR to talk to each other. You do not create it manually, and you should not delete it.</p><p>Route tables use longest-prefix matching. In plain language, AWS chooses the most specific matching route.</p><pre>| Route                       | Meaning                                                    |<br>| --------------------------- | ---------------------------------------------------------- |<br>| `10.0.0.0/16 -&gt; local`      | Keep traffic for the VPC inside the VPC                    |<br>| `0.0.0.0/0 -&gt; igw-...`      | Send general IPv4 internet traffic to the Internet Gateway |<br>| `0.0.0.0/0 -&gt; nat-...`      | Send general IPv4 internet traffic to the NAT Gateway      |<br>| `192.168.0.0/16 -&gt; pcx-...` | Send traffic for a peered VPC through VPC peering          |</pre><p>A key route-table lesson is this: a correct route in the wrong route table does not help. The subnet must actually be associated with the route table that contains the route.</p><h4><strong>Internet Gateway</strong></h4><p>An Internet Gateway, often called an IGW, connects a VPC to the internet. It attaches to the VPC, but subnets use it through route tables.</p><p>The public path looks like this:</p><pre>Local computer<br>-&gt; Internet<br>-&gt; Internet Gateway<br>-&gt; Public route table<br>-&gt; Public subnet<br>-&gt; EC2 instance</pre><p>An Internet Gateway does not automatically make everything public. It only provides the VPC-level internet doorway. A subnet still needs the route, and a resource still needs a public address and allowed security rules.</p><p>For a public subnet, add the route:</p><pre>0.0.0.0/0 -&gt; Internet Gateway</pre><p>to the public route table is what gives internet-bound traffic a path out through the Internet Gateway.</p><h4><strong>NAT Gateway</strong></h4><p>A NAT Gateway allows private resources to initiate outbound internet connections without becoming directly reachable from the internet.</p><p>This is useful when a private EC2 instance needs to download software updates or reach an external service, but you do not want internet users connecting directly to it.</p><p>The NAT path looks like this:</p><pre>Private EC2 instance<br>-&gt; Private route table<br>-&gt; NAT Gateway in a public subnet<br>-&gt; Internet Gateway<br>-&gt; Internet</pre><p>The response comes back through the NAT Gateway because the private instance started the connection. The NAT Gateway does not allow random internet clients to start new inbound connections to the private instance.</p><pre>| Internet Gateway                                           | NAT Gateway                                          |<br>| ---------------------------------------------------------- | ---------------------------------------------------- |<br>| Used by public subnets for internet access                 | Used by private subnets for outbound internet access |<br>| Can support inbound public traffic when security allows it | Does not provide unsolicited inbound access          |<br>| Attached to a VPC                                          | Created in a subnet and Availability Zone            |<br>| Route target for public subnet internet traffic            | Route target for private subnet outbound traffic     |</pre><p>A common VPC design uses the Zonal NAT Gateway pattern. That means the NAT Gateway sits in a public subnet and uses an Elastic IP. If your AWS console offers regional or zonal choices, the important idea is the same: private subnet traffic goes to the NAT Gateway, and the NAT Gateway uses a public path to reach the internet.</p><p>NAT Gateways can create costs, so cleanup is part of responsible AWS practice.</p><h4><strong>Public IP, Private IP, and Elastic IP</strong></h4><p>Every EC2 instance in a VPC receives a private IP address. This is used for communication inside the VPC and across private connections such as VPC peering.</p><p>A public IPv4 address is reachable from the internet when routing and security allow it.</p><p>An Elastic IP is a static public IPv4 address allocated to your AWS account. It stays allocated until you release it.</p><pre>| Address type              | Meaning                             | Example use                           |<br>| ------------------------- | ----------------------------------- | ------------------------------------- |<br>| Private IPv4              | Internal VPC address                | EC2-to-EC2 private traffic            |<br>| Auto-assigned public IPv4 | Temporary internet-routable address | Quick public EC2 testing              |<br>| Elastic IP                | Static public IPv4 address          | NAT Gateway or stable public endpoint |</pre><p>Auto-assigned public IPv4 addresses can change when an instance is stopped and started. Elastic IPs are more stable, but they can create costs if allocated and unused.</p><h4><strong>Security Groups</strong></h4><p>A Security Group is a stateful firewall for resources such as EC2 instances, load balancers, and network interfaces.</p><p>Stateful means return traffic for an allowed connection is automatically allowed. If you allow SSH inbound from your public IP, the response traffic is allowed back out without you adding a separate return rule.</p><p>Common Security Group examples:</p><pre>| Purpose                | Type       |     Port | Safer source                      |<br>| ---------------------- | ---------- | -------: | --------------------------------- |<br>| SSH from your computer | SSH        |     `22` | `&lt;YOUR-PUBLIC-IP&gt;/32`             |<br>| HTTP web traffic       | HTTP       |     `80` | Intended clients or load balancer |<br>| HTTPS web traffic      | HTTPS      |    `443` | Intended clients or load balancer |<br>| App traffic behind ALB | Custom TCP | App port | ALB Security Group                |</pre><p>Security Groups only have allow rules. They do not have explicit deny rules. If traffic is not allowed, it is denied by default.</p><p>In a simple VPC peering design, one useful Security Group pattern is:</p><pre>sec-vpc1: allow SSH from your public IP /32<br>sec-vpc2: allow SSH from the VPC 1 CIDR</pre><p>This allowed the public instance in VPC 1 to connect privately to the instance in VPC 2 after peering and routes were configured.</p><h4><strong>Network ACLs</strong></h4><p>A Network ACL, or NACL, is a subnet-level firewall. It is stateless, which means it does not automatically remember return traffic.</p><p>If a NACL is customised, both the request and the response path must be allowed. This is where ephemeral ports matter. A client may connect to SSH on port 22, but the response may use a temporary client-side port.</p><pre>| Feature        | Security Group                                | Network ACL                        |<br>| -------------- | --------------------------------------------- | ---------------------------------- |<br>| Scope          | Resource or network interface                 | Subnet                             |<br>| State          | Stateful                                      | Stateless                          |<br>| Rule type      | Allow only                                    | Allow and deny                     |<br>| Rule order     | All rules evaluated together                  | Lowest numbered matching rule wins |<br>| Return traffic | Automatically allowed for allowed connections | Must be explicitly allowed         |</pre><p>In a new VPC, the default NACL normally allows all inbound and outbound traffic. So when someone says “Network ACLs must allow requests and ephemeral responses,” it usually means you should inspect the NACL if you customised it or if traffic still fails after route tables and Security Groups look correct.</p><h4><strong>VPC DNS and Route 53</strong></h4><p>DNS translates names into IP addresses.</p><p>Inside a VPC, AWS provides DNS resolution. The Amazon-provided resolver is reachable at:</p><pre>169.254.169.253</pre><p>It is also reachable at the second IP address of the VPC. For example, if the VPC CIDR is10.0.0.0/16, the resolver is also available at 10.0.0.2.</p><p>Two VPC DNS settings matter:</p><pre>| Setting              | Meaning                                                            |<br>| -------------------- | ------------------------------------------------------------------ |<br>| `enableDnsSupport`   | Allows DNS resolution through the Amazon-provided DNS resolver     |<br>| `enableDnsHostnames` | Allows public DNS hostnames for resources with public IP addresses |</pre><p>Route 53 is different. Route 53 is AWS’s DNS and domain routing service. It manages hosted zones, DNS records, health checks, domain registration, and routing policies.</p><pre>| VPC DNS                                    | Route 53                               |<br>| ------------------------------------------ | -------------------------------------- |<br>| Helps resources inside a VPC resolve names | Manages DNS records and domain routing |<br>| VPC-level setting                          | Global DNS service                     |<br>| Uses the Amazon-provided resolver          | Uses hosted zones and DNS records      |</pre><p>DHCP options can also affect what DNS servers instances use. For most simple setups, the default DHCP options are fine, but if name resolution behaves strangely, DNS support, DNS hostnames, and DHCP options are worth checking.</p><p>Route 53 stores DNS records inside hosted zones:</p><pre>| Hosted zone type    | Meaning                                          |<br>| ------------------- | ------------------------------------------------ |<br>| Public hosted zone  | DNS records resolvable from the public internet  |<br>| Private hosted zone | DNS records resolvable only from associated VPCs |</pre><p>Route 53 record types include:</p><pre>| Record | Meaning                                                              |<br>| ------ | -------------------------------------------------------------------- |<br>| A      | Name to IPv4 address                                                 |<br>| AAAA   | Name to IPv6 address                                                 |<br>| CNAME  | Name to another DNS name                                             |<br>| Alias  | Route 53-specific record for AWS resources such as ALB or CloudFront |</pre><p>Route 53 routing policies help decide what answer DNS should return. Examples include simple, weighted, latency-based, failover, geolocation, geoproximity, and multivalue answer routing.</p><p>Name servers matter for public hosted zones. If a domain was bought outside Route 53, the registrar must delegate the domain to the Route 53 name servers before public DNS queries use the hosted zone.</p><p>Route 53 ARC, or Application Recovery Controller, supports readiness checks and controlled failover for recovery planning. Route 53 answers DNS questions. Route 53 ARC helps control recovery.</p><h4><strong>EC2 Networking and SSH</strong></h4><p>EC2 networking brings several concepts together at once. To SSH into an EC2 instance from your computer, you need the network path and the correct key.</p><p>Typical SSH command:</p><pre>ssh -i ec2-user.pem ec2-user@&lt;PUBLIC-IP&gt;</pre><p>The key file must normally be protected:</p><pre>chmod 400 ec2-user.pem</pre><p>The username for Amazon Linux is usually:</p><pre>ec2-user</pre><p>There are two common SSH failure types:</p><pre>| Symptom                         | Likely meaning                                                         |<br>| ------------------------------- | ---------------------------------------------------------------------- |<br>| `Connection timed out`          | Route, security rule, wrong IP address, service, or network path issue |<br>| `Permission denied (publickey)` | Network path reached SSH, but the key or username is incorrect         |</pre><p>This distinction is important. A timeout usually means the packet did not complete the path. A public key error means the packet reached SSH, but authentication failed.</p><h4><strong>Bastion Host or Jump Host Pattern</strong></h4><p>A bastion host, also called a jump host, is a controlled public instance used to reach private instances.</p><p>The pattern looks like this:</p><pre>Your computer<br>-&gt; public IP of bastion<br>-&gt; private IP of private instance</pre><p>For learning, people sometimes use a public EC2 instance as a temporary jump host. They connect to the public instance first, then SSH from there to the private instance using the private instance’s private IP address. If a private key is copied to the jump host for practice, it should be removed after testing.</p><p>That pattern is useful for understanding the traffic path, but in production you should be more careful. AWS Systems Manager Session Manager or a stronger access pattern is usually preferred because it avoids leaving private keys on a server.</p><h4><strong>VPC Peering</strong></h4><p>VPC peering privately connects two VPCs so resources can communicate using private IP addresses. Traffic stays on the AWS network.</p><p>VPC peering does not require an Internet Gateway, NAT Gateway, or VPN. But it still requires route tables and security rules.</p><p>The required sequence is:</p><ol><li>Make sure the VPC CIDRs do not overlap.</li><li>Create the peering request.</li><li>Accept the request.</li><li>Wait for the peering connection to become active.</li><li>Add routes in both VPC route tables.</li><li>Allow the traffic in Security Groups and NACLs.</li><li>Test with private IP addresses.</li></ol><p>Example:</p><pre>VPC 1 CIDR: 10.0.0.0/16<br>VPC 2 CIDR: 192.168.0.0/16<br><br>rt-1 route: 192.168.0.0/16 -&gt; peering connection<br>rt-2 route: 10.0.0.0/16    -&gt; peering connection</pre><p>Routes are needed in both directions. If only one side has a route, traffic may leave one VPC, but the response will not know how to return.</p><h4><strong>Same-Region and Cross-Region Peering</strong></h4><p>Same-Region peering connects VPCs in the same AWS Region. Cross-Region peering connects VPCs in different AWS Regions.</p><pre>| Same-Region peering                                   | Cross-Region peering                                     |<br>| ----------------------------------------------------- | -------------------------------------------------------- |<br>| Both VPCs are in the same Region                      | VPCs are in different Regions                            |<br>| Easier to inspect within one console Region           | Requires switching between Regions                       |<br>| Can reference peer Security Groups in supported cases | Cross-Region Security Group references are not supported |<br>| Requires routes in both directions                    | Requires routes in both directions                       |</pre><p>In a cross-Region peering example, one VPC might live in, us-east-1 and another might live in us-west-2. The peering request is created from one Region and accepted from the other. A good test uses the private IP address of the remote instance, because that proves the traffic is crossing the peering connection instead of using the public internet.</p><h4><strong>Peering Is Not Transitive</strong></h4><p>VPC peering is not transitive. This means one peering connection cannot be used as a middle path to reach a third VPC.</p><p>This does not work automatically:</p><pre>VPC A &lt;-&gt; VPC B &lt;-&gt; VPC C</pre><p>VPC A cannot reach VPC C through VPC B just because both are peered with VPC B.</p><p>For three VPCs to all communicate directly using peering, each pair needs its own peering connection and routes:</p><pre>VPC A &lt;-&gt; VPC B<br>VPC A &lt;-&gt; VPC C<br>VPC B &lt;-&gt; VPC C</pre><p>As the number of VPCs grows, this becomes hard to manage. That is why Transit Gateway exists.</p><h4><strong>Transit Gateway</strong></h4><p>AWS Transit Gateway is a managed hub for connecting many VPCs and networks.</p><p>Instead of creating many individual peering connections, you connect VPCs to the Transit Gateway and control routing through Transit Gateway route tables.</p><p>Simple model:</p><pre>VPC A ----+<br>VPC B ----+--&gt; Transit Gateway &lt;-- VPN or Direct Connect<br>VPC C ----+</pre><p>Use VPC peering for simple one-to-one private VPC communication. Think about Transit Gateway when many VPCs, shared services, hybrid networks, or transitive routing are required.</p><h4><strong>PrivateLink and VPC Endpoints</strong></h4><p>AWS PrivateLink allows private access to services without sending traffic over the public internet. It is often used when a VPC needs to consume a service privately.</p><p>There are two endpoint ideas to remember:</p><pre>| Endpoint type      | Plain meaning                                     | Common use                                     |<br>| ------------------ | ------------------------------------------------- | ---------------------------------------------- |<br>| Interface endpoint | Creates private network interfaces in your subnet | Private access to many AWS or partner services |<br>| Gateway endpoint   | Adds route table access for supported services    | Private access to S3 or DynamoDB               |</pre><p>PrivateLink and VPC endpoints are different from VPC peering. Peering connects VPC address spaces. PrivateLink gives private access to a service endpoint.</p><h4><strong>VPN and Direct Connect</strong></h4><p>AWS networking is not only about AWS-to-AWS traffic. Companies often need to connect AWS to their own data centres or office networks.</p><p>Site-to-Site VPN creates encrypted IPsec tunnels over the public internet.</p><p>Direct Connect provides a dedicated private connection into AWS through a Direct Connect location.</p><pre>| Site-to-Site VPN                                 | Direct Connect                             |<br>| ------------------------------------------------ | ------------------------------------------ |<br>| Uses the public internet                         | Uses dedicated private connectivity        |<br>| Encrypted with IPsec                             | Uses a private physical network connection |<br>| Faster to set up                                 | Requires more planning and setup           |<br>| Good for quick or lower-cost hybrid connectivity | Good for consistent bandwidth and latency  |</pre><p>Transit Gateway can also be used as a hub when many VPCs and hybrid connections need centralised routing.</p><p>The common hybrid connectivity pieces are:</p><pre>| Component                  | Plain meaning                                                           |<br>| -------------------------- | ----------------------------------------------------------------------- |<br>| Customer Gateway           | The customer-side router or device information                          |<br>| Virtual Private Gateway    | AWS-side gateway attached to one VPC                                    |<br>| Transit Gateway attachment | Connection from a VPC, VPN, or Direct Connect path into Transit Gateway |<br>| VPN tunnel                 | Encrypted path over the internet                                        |<br>| BGP                        | Dynamic routing protocol often used to exchange routes                  |</pre><h4><strong>Load Balancers</strong></h4><p>Elastic Load Balancing gives users one endpoint and distributes traffic across healthy targets.</p><p>The general flow is:</p><pre>Client<br>-&gt; Load balancer listener<br>-&gt; Listener rule<br>-&gt; Target group<br>-&gt; Healthy target</pre><p>Main load balancer types:</p><pre>| Load balancer             | Best for                                                    |<br>| ------------------------- | ----------------------------------------------------------- |<br>| Application Load Balancer | HTTP/HTTPS applications, path-based and host-based routing  |<br>| Network Load Balancer     | TCP, UDP, TLS, high performance, and static IP requirements |<br>| Gateway Load Balancer     | Traffic inspection appliances such as firewalls             |<br>| Classic Load Balancer     | Legacy workloads                                            |</pre><p>An internet-facing load balancer goes in public subnets. An internal load balancer is used for private application traffic.</p><p>The Security Group design matters. A common web pattern is:</p><pre>Internet -&gt; ALB Security Group -&gt; EC2 Security Group -&gt; application port</pre><p>The EC2 instances should usually allow web traffic from the load balancer Security Group, not from the entire internet.</p><p>Health checks are also part of load balancing. A load balancer can see an EC2 instance as unhealthy even when the EC2 status checks are passing. EC2 status checks tell you the virtual machine is running; load balancer health checks tell you whether the application endpoint is responding correctly.</p><h4><strong>CloudFront and Edge Networking</strong></h4><p>Amazon CloudFront is AWS’s content delivery network, or CDN. It caches content at edge locations closer to users.</p><p>The flow looks like this:</p><pre>Viewer<br>-&gt; CloudFront edge location<br>   -&gt; cache hit: return content immediately<br>   -&gt; cache miss: fetch from origin, then return and cache</pre><p>An origin is the original source of the content. It could be S3, an Application Load Balancer, EC2, or another HTTP server.</p><pre>| Concept               | Meaning                                               |<br>| --------------------- | ----------------------------------------------------- |<br>| Distribution          | CloudFront configuration that users access            |<br>| Origin                | Original backend source                               |<br>| Cache hit             | CloudFront already has the requested object           |<br>| Cache miss            | CloudFront must fetch the requested object            |<br>| TTL                   | How long content can remain cached                    |<br>| Origin Access Control | Safer way for CloudFront to access private S3 content |</pre><p>CloudFront improves latency and reduces load on the origin. It is useful for static websites, media, application assets, and global web delivery.</p><p>CloudFront Functions and Lambda@Edge allow logic to run closer to users. CloudFront Functions are lighter and run at viewer request/response events. Lambda@Edge is more powerful and supports more event points.</p><p>Global Accelerator is related to edge networking, but it is not a cache. It improves global routing for TCP and UDP applications using AWS’s global network.</p><pre>| CloudFront                           | Global Accelerator                                                |<br>| ------------------------------------ | ----------------------------------------------------------------- |<br>| Caches web content                   | Optimises the network path                                        |<br>| Best for HTTP/HTTPS content delivery | Best for global application traffic where caching is not the goal |<br>| Uses distributions and origins       | Uses static anycast IP addresses and endpoints                    |</pre><h4><strong>Common Traffic Paths</strong></h4><p>Here are the patterns that make AWS networking easier to understand.</p><p><strong>Public EC2 Access</strong></p><pre>Your computer<br>-&gt; Internet<br>-&gt; Internet Gateway<br>-&gt; Public route table<br>-&gt; Public subnet<br>-&gt; EC2 Security Group<br>-&gt; EC2 instance</pre><p>If SSH times out, check the public IP, route table association, Internet Gateway route, Security Group source, NACL, and instance status.</p><p><strong>Private EC2 Outbound Through NAT</strong></p><pre>Private EC2<br>-&gt; Private route table<br>-&gt; NAT Gateway<br>-&gt; Internet Gateway<br>-&gt; Internet</pre><p>This lets the private instance start outbound connections without receiving direct inbound internet connections.</p><p><strong>Private SSH Through a Jump Host</strong></p><pre>Your computer<br>-&gt; Public EC2<br>-&gt; Private IP of private EC2</pre><p>This pattern proves the difference between public management access and private internal access.</p><p><strong>VPC Peering Test</strong></p><p>Before peering:</p><pre>EC2 in VPC 1 -&gt; private IP in VPC 2 -&gt; timeout</pre><p>After active peering, routes in both directions, and correct security rules:</p><p>EC2 in VPC 1 -&gt; private IP in VPC 2 -&gt; success</p><p>The before-and-after test is valuable because it proves exactly what changed.</p><p><strong>Useful Testing Commands</strong></p><pre>| Command                        | What it helps prove                                 |<br>| ------------------------------ | --------------------------------------------------- |<br>| `ssh -i key.pem ec2-user@&lt;ip&gt;` | Port 22 network path and SSH authentication         |<br>| `ping -c 3 &lt;host&gt;`             | Basic ICMP reachability, if ICMP is allowed         |<br>| `curl -I https://example.com`  | HTTP/HTTPS outbound connectivity and DNS resolution |<br>| `ip -4 addr show`              | The private IPv4 address on a Linux instance        |<br>| `hostname`                     | Which instance you are currently connected to       |<br>| Route table inspection         | Whether the subnet has the expected route target    |</pre><p>Use the right tool for the question. For example, a successful ping does not prove SSH works, and successful SSH does not prove a web application health check works.</p><h4><strong>Troubleshooting Networking Problems</strong></h4><p>When traffic fails, avoid changing everything at once. Follow the packet.</p><p>Start with these questions:</p><ol><li>Am I in the correct Region?</li><li>Is the resource in the expected VPC and subnet?</li><li>Does the subnet use the route table I think it uses?</li><li>Does the route table have the correct destination and target?</li><li>Is the target active, such as an IGW, NAT Gateway, or peering connection?</li><li>Does the Security Group allow the traffic?</li><li>Does the Network ACL allow request and response traffic?</li><li>Is the destination instance running and listening?</li><li>Am I using the correct IP address, username, and key?</li></ol><p>Common symptoms:</p><pre>| Symptom                                    | What to check first                                                           |<br>| ------------------------------------------ | ----------------------------------------------------------------------------- |<br>| SSH timeout                                | Route table, public IP address, Security Group, Network ACL, wrong IP address |<br>| `Permission denied (publickey)`            | SSH key, username, instance key pair                                          |<br>| Peering route is `Blackhole`               | Peering connection is not active or has been deleted                          |<br>| Private instance cannot reach the internet | NAT Gateway, private route table, public NAT subnet route                     |<br>| DNS name fails but IP works                | VPC DNS settings, resolver, Route 53 records                                  |<br>| ALB target unhealthy                       | Target Security Group, health check path, application port                    |</pre><p>A good troubleshooting habit is to change one thing, retest, and record what happened. That is how you learn the architecture instead of just clicking until something works.</p><h4><strong>Cost and Cleanup Awareness</strong></h4><p>Networking services can create cost. NAT Gateways, Elastic IPs, public IPv4 addresses, load balancers, CloudFront requests, Route 53 hosted zones, VPN, Direct Connect, and data transfer can all affect billing.</p><p>For practice environments, cleanup is part of the work.</p><p>Common cleanup order:</p><ol><li>Remove temporary SSH keys from EC2 instances.</li><li>Terminate EC2 instances.</li><li>Delete or detach dependent resources such as NAT routes and peering routes.</li><li>Delete NAT Gateways and release Elastic IPs.</li><li>Delete load balancers and target groups if created.</li><li>Delete route tables after subnet associations are removed.</li><li>Detach and delete Internet Gateways.</li><li>Delete subnets.</li><li>Delete Security Groups.</li><li>Delete VPCs.</li><li>Check both Regions when the architecture uses cross-region resources.</li><li>Review billing and leftover resources.</li></ol><p>The important point is that AWS often blocks deletion when dependencies still exist. If something will not delete, look for what is still attached to it.</p><h4><strong>Quick Memory Tips</strong></h4><pre>| If you need this                                 | Think this                  |<br>| ------------------------------------------------ | --------------------------- |<br>| A private network boundary in AWS                | VPC                         |<br>| A smaller network range in one Availability Zone | Subnet                      |<br>| Public subnet behaviour                          | Route to Internet Gateway   |<br>| Private outbound internet access                 | NAT Gateway                 |<br>| Stable public IPv4 address                       | Elastic IP                  |<br>| Resource firewall                                | Security Group              |<br>| Subnet firewall                                  | Network ACL                 |<br>| Private connection between two VPCs              | VPC peering                 |<br>| Central hub for many VPCs                        | Transit Gateway             |<br>| Private service access                           | PrivateLink or VPC endpoint |<br>| Hybrid encrypted tunnel                          | Site-to-Site VPN            |<br>| Dedicated hybrid connection                      | Direct Connect              |<br>| One endpoint for many targets                    | Load balancer               |<br>| Global content caching                           | CloudFront                  |<br>| DNS and domain routing                           | Route 53                    |<br>| Application recovery control                     | Route 53 ARC                |</pre><h4><strong>Final Summary</strong></h4><p>AWS networking becomes easier when you stop memorising services in isolation and start following traffic paths.</p><p>A VPC gives you the private network boundary. Subnets divide that network across Availability Zones. Route tables decide where traffic goes. Internet Gateways provide public internet paths. NAT Gateways let private resources initiate outbound internet connections. Security Groups and Network ACLs decide what traffic is allowed. DNS services turn names into destinations. VPC peering, Transit Gateway, PrivateLink, VPN, and Direct Connect connect networks and services in different ways. Load balancers, CloudFront, Global Accelerator, and Route 53 help users reach applications reliably and efficiently.</p><p>The practical lesson is that every piece matters. A public IP without a route still fails. A peering connection without route-table updates still fails. A correct route with the wrong Security Group still fails. But when the path, route, security, and destination are all correct, the architecture starts to make sense.</p><p>That is the real networking lesson: AWS connectivity is not magic. It is a chain of clear decisions.</p><p>When you understand that chain, troubleshooting becomes less stressful. Instead of guessing, you can ask better questions: where is the source, where is the destination, what route is being used, what gateway or connection carries the traffic, and which security layer allows or blocks it?</p><p>That way of thinking is what turns AWS networking from a confusing list of services into a system you can reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8df39f3f4ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG Project Should Not Be One Giant Python File]]></title>
            <link>https://danieljude1992.medium.com/your-rag-project-should-not-be-one-giant-python-file-34fcf7ceacae?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/34fcf7ceacae</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 15:54:02 GMT</pubDate>
            <atom:updated>2026-09-12T16:01:07.160Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A simple folder structure for building RAG systems that can grow beyond the demo stage.</em></p><figure><img alt="rag-project-structure-vs-giant-python-file" src="https://cdn-images-1.medium.com/max/1024/1*GaOrtdJTTVOtmic-VoM0sg.png" /></figure><p>A working RAG demo is easy to build.</p><p>You load a PDF. You split it into chunks. You create embeddings. You store them in a vector database. You ask a question. The LLM gives an answer.</p><p>For a weekend project, that is enough.</p><p>For a real project, it breaks quickly.</p><p>The problem is not usually the model. It is not always the vector database either. The problem is structure.</p><p>Many beginner RAG projects start as one large app.py file. Everything goes inside it: file loading, chunking, embeddings, vector storage, retrieval, prompt templates, model calls, API routes, logging, and configuration.</p><p>At first, this feels simple. There is only one file to open.</p><p>Then the project grows.</p><p>You add another document source. You try a different chunking strategy. You switch from ChromaDB to Pinecone. You change the prompt. You add a FastAPI endpoint. You need to debug why retrieval is poor. You want to write tests. Suddenly that one file becomes painful.</p><p>A maintainable RAG system is a different story.</p><p>It separates responsibilities.</p><p>Each part of the system has a clear job. Ingestion loads data. Chunking splits documents. Embeddings convert text into vectors. The vector database stores those vectors. Retrieval finds useful context. Prompts shape the final request. The LLM layer handles model calls. The API layer exposes the system to users.</p><p>That separation is what turns a RAG demo into an engineering system.</p><h4><strong>The Main Idea: Separate the Pipeline From the Application</strong></h4><p>The most useful mental model is this:</p><p><strong>Your RAG pipeline prepares knowledge. Your application uses that knowledge.</strong></p><p>Those two things should not be mixed together.</p><p>The pipeline side handles tasks like:</p><ul><li>loading documents</li><li>cleaning text</li><li>splitting content into chunks</li><li>creating embeddings</li><li>storing embeddings in a vector database</li></ul><p>The application side handles tasks like:</p><ul><li>receiving user questions</li><li>retrieving relevant chunks</li><li>building prompts</li><li>calling the LLM</li><li>returning answers through an API</li><li>logging behaviour in production</li></ul><p>When these responsibilities are mixed together, every change becomes risky.</p><p>If you want to test a new chunk size, you should not need to touch your API route. If you want to change from GPT to Claude, you should not need to rewrite your retrieval logic. If you want to add website ingestion, you should not need to edit your prompt templates.</p><p>Good structure protects you from that kind of mess.</p><h4><strong>A Clean RAG Project Structure</strong></h4><p>Here is a practical structure you can use as a starting point:</p><pre>rag-project/<br>|-- README.md<br>|-- requirements.txt<br>|-- .env<br>|-- .gitignore<br>|-- config.yaml<br>|-- main.py<br>|-- src/<br>|   |-- ingestion/<br>|   |   |-- __init__.py<br>|   |   `-- loader.py<br>|   |-- chunking/<br>|   |   |-- __init__.py<br>|   |   `-- chunker.py<br>|   |-- embeddings/<br>|   |   |-- __init__.py<br>|   |   `-- embedder.py<br>|   |-- vectordb/<br>|   |   |-- __init__.py<br>|   |   `-- vector_store.py<br>|   |-- retrieval/<br>|   |   |-- __init__.py<br>|   |   `-- retriever.py<br>|   |-- prompts/<br>|   |   |-- __init__.py<br>|   |   `-- prompt_templates.py<br>|   |-- llm/<br>|   |   |-- __init__.py<br>|   |   `-- llm_client.py<br>|   |-- api/<br>|   |   |-- __init__.py<br>|   |   `-- routes.py<br>|   `-- utils/<br>|       |-- __init__.py<br>|       `-- helpers.py<br>|-- tests/<br>|   `-- test_app.py<br>`-- logs/<br>    `-- app.log</pre><p>This is not the only correct structure.</p><p>But it is a good beginner-friendly structure because every folder has a clear reason to exist.</p><p>Let us walk through each part.</p><h4><strong>README.md: Explain the Project Before People Ask</strong></h4><p>The README.md file is the front door of the project.</p><p>It should explain what the RAG system does, how to set it up, how to run it, and what each major folder is responsible for.</p><p>Beginners often skip the README because they think documentation is only needed after the project is finished. That is a mistake. A good README helps you understand your own project one month later.</p><p>At minimum, include:</p><ul><li>project purpose</li><li>setup instructions</li><li>environment variables needed</li><li>how to ingest documents</li><li>how to run the API</li><li>example questions</li><li>known limitations</li></ul><p>For a portfolio project, the README is especially important. A recruiter or engineer may not run your code immediately. They may scan your README first to decide whether the project looks serious.</p><h4><strong>requirements.txt: Keep Dependencies Visible</strong></h4><p>The requirements.txt file lists the Python packages your project needs.</p><p>For a simple RAG project, it may include tools like:</p><pre>fastapi<br>uvicorn<br>python-dotenv<br>pydantic<br>langchain<br>chromadb<br>sentence-transformers<br>openai<br>pypdf</pre><p>Your exact list depends on the stack you choose.</p><p>The main rule is simple:</p><p><strong>Do not leave dependencies hidden on your machine.</strong></p><p>If someone clones your project, they should be able to install everything with one command:</p><pre>pip install -r requirements.txt</pre><p>This makes your project easier to reproduce, deploy, and review.</p><h4><strong>.env: Store Secrets Locally</strong></h4><p>The .env file stores sensitive values such as API keys.</p><p>For example:</p><pre>OPENAI_API_KEY=your_key_here<br>VECTOR_DB_URL=your_vector_db_url</pre><p>This file should never be committed to GitHub.</p><p>That is why your .gitignore file should include:</p><pre>.env<br>logs/<br>__pycache__/<br>*.pyc</pre><p>A common beginner mistake is hardcoding API keys directly into Python files. It may work locally, but it is unsafe and unprofessional.</p><p>Keep secrets outside your code.</p><h4><strong>config.yaml: Keep Settings in One Place</strong></h4><p>The config.yaml file stores project settings that are not secret.</p><p>For example:</p><pre>chunking:<br>  chunk_size: 800<br>  chunk_overlap: 120<br><br>retrieval:<br>  top_k: 5<br><br>models:<br>  embedding_model: text-embedding-3-small<br>  llm_model: gpt-4.1-mini<br><br>vector_db:<br>  provider: chromadb<br>  collection_name: company_docs</pre><p>This is useful because RAG systems need tuning.</p><p>You may want to change chunk size, chunk overlap, retrieval count, model name, temperature, or vector database settings. If these values are buried inside random Python files, tuning becomes annoying.</p><p>Configuration should be easy to find and easy to change.</p><h4><strong>ingestion/: Load Data From Different Sources</strong></h4><p>The ingestion/ folder handles data loading.</p><p>This is where your project reads from PDFs, websites, CSV files, APIs, databases, Markdown files, Notion exports, Google Drive folders, or any other source.</p><p>The job of ingestion is not to answer questions.</p><p>Its job is to bring raw content into the system in a clean, predictable format.</p><p>For example, loader.py may contain functions such as:</p><ul><li>load_pdf(path)</li><li>load_website(url)</li><li>load_csv(path)</li><li>load_database_table(connection, table_name)</li></ul><p>Each function should return documents in a standard structure, usually with text and metadata.</p><p>Metadata matters more than beginners think.</p><p>A chunk of text is useful. A chunk of text with source name, page number, URL, document type, author, and timestamp is much more useful. Metadata helps with filtering, citations, debugging, and trust.</p><h4><strong>chunking/: Split Documents Into Useful Pieces</strong></h4><p>The chunking/ folder handles document splitting.</p><p>Chunking looks simple, but it has a huge effect on RAG quality.</p><p>If chunks are too large, the retriever may return broad sections with too much irrelevant text. If chunks are too small, the model may lose the context needed to answer properly.</p><p>Good chunking tries to preserve meaning.</p><p>Instead of blindly cutting every 500 characters, you may split by:</p><ul><li>headings</li><li>paragraphs</li><li>sections</li><li>pages</li><li>code blocks</li><li>tables</li><li>semantic meaning</li></ul><p>The chunker.py file should contain the logic for turning full documents into smaller pieces that are ready for embedding.</p><p>Keeping chunking separate is important because you will probably experiment with it. One of the fastest ways to improve a RAG system is to adjust how documents are split.</p><p>If chunking is isolated, you can test new strategies without touching the rest of the system.</p><h4><strong>embeddings/: Convert Text Into Vectors</strong></h4><p>The embeddings/ folder handles the embedding model.</p><p>Embeddings are numerical representations of text. They help the system compare meaning. When a user asks a question, the system embeds that question and compares it with embedded document chunks.</p><p>That is how semantic search works.</p><p>The embedder.py file should centralize this logic.</p><p>It may include:</p><ul><li>loading the embedding model</li><li>embedding one text input</li><li>embedding many chunks in batches</li><li>handling rate limits</li><li>retrying failed requests</li><li>tracking embedding model versions</li></ul><p>This separation is useful because embedding models can change.</p><p>You may start with a local sentence-transformer model. Later, you may move to OpenAI embeddings. Later again, you may switch to another provider for cost or performance reasons.</p><p>If embedding logic lives in one place, the change is manageable.</p><h4><strong>vectordb/: Store and Manage Embeddings</strong></h4><p>The vectordb/ folder handles the vector database.</p><p>This is where embeddings and metadata are stored.</p><p>Common options include:</p><ul><li>FAISS for local experiments</li><li>ChromaDB for simple local or small production systems</li><li>Pinecone for managed cloud vector search</li><li>Weaviate, Qdrant, or Milvus for larger or more specialized use cases</li></ul><p>The vector_store.py file should hide database-specific details from the rest of the project.</p><p>Your retrieval code should not need to know every detail of Pinecone or ChromaDB. It should call simple project-level methods like:</p><ul><li>add_documents(chunks)</li><li>similarity_search(query, top_k)</li><li>delete_collection(name)</li><li>get_document_by_id(id)</li></ul><p>This gives you flexibility.</p><p>If you ever replace the vector database, you update the vector store layer instead of rewriting the whole project.</p><h4><strong>retrieval/: Find the Right Context</strong></h4><p>The retrieval/ folder handles the search step.</p><p>This is where the system takes a user question and finds the most relevant chunks.</p><p>Basic retrieval may use similarity search. More advanced retrieval may include metadata filters, hybrid search, reranking, query rewriting, or multi-query retrieval.</p><p>The retriever is one of the most important parts of a RAG system because the LLM can only answer well if it receives the right context.</p><p>If retrieval is weak, the final answer will be weak too.</p><p>The retriever.py file might handle:</p><ul><li>embedding the user query</li><li>searching the vector database</li><li>applying metadata filters</li><li>reranking results</li><li>removing duplicate chunks</li><li>returning clean context for the prompt</li></ul><p>Keeping retrieval separate makes debugging much easier.</p><p>When an answer is wrong, you can ask:</p><p><strong>Did the model fail, or did retrieval send the wrong context?</strong></p><p>That question is impossible to answer cleanly if retrieval and generation are tangled together.</p><h4><strong>prompts/: Keep Prompt Templates Out of Application Logic</strong></h4><p>Prompts should not be scattered across your codebase.</p><p>The prompts/ folder gives them a proper home.</p><p>For example, prompt_templates.py may include a template like:</p><pre>You are a helpful assistant answering questions using the provided context.<br><br>Use only the context below. If the answer is not in the context, say you do not know.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br><br>Answer:</pre><p>This may look simple, but separating prompts is a big habit.</p><p>Prompts change often. You may test different instructions, output formats, citation styles, safety rules, or refusal behavior.</p><p>If prompts are mixed inside API routes or model calls, they become hard to version and hard to test.</p><p>Treat prompts like part of your application design.</p><p>They deserve their own file.</p><h4><strong>llm/: Centralize Model Calls</strong></h4><p>The llm/ folder handles calls to the language model.</p><p>This could be OpenAI, Claude, Gemini, a local Ollama model, or another provider.</p><p>The rest of your application should not care which provider is being used.</p><p>That is the job of llm_client.py.</p><p>It can handle:</p><ul><li>model initialization</li><li>API calls</li><li>retries</li><li>timeouts</li><li>temperature settings</li><li>response parsing</li><li>token usage logging</li><li>provider-specific errors</li></ul><p>This layer is important because models change.</p><p>Today you may use GPT. Tomorrow you may test Claude. Next month you may use a smaller model for cheaper queries and a stronger model for complex ones.</p><p>If your LLM calls are centralized, model switching becomes much easier.</p><h4><strong>api/: Expose the RAG System</strong></h4><p>The api/ folder is where your RAG system becomes usable by other people or applications.</p><p>For Python projects, this is often built with FastAPI or Flask.</p><p>The API layer should handle things like:</p><ul><li>receiving user questions</li><li>validating request bodies</li><li>calling the retrieval and generation pipeline</li><li>returning structured responses</li><li>handling errors cleanly</li></ul><p>It should not contain all the logic itself.</p><p>An API route should be thin. It should receive the request, call the right service, and return the response.</p><p>If your route file has ingestion, chunking, embedding, retrieval, prompt building, and LLM calls all inside one endpoint, the project is becoming hard to maintain.</p><p>Keep the API as the doorway, not the entire house.</p><h4><strong>utils/: Shared Helpers</strong></h4><p>The utils/ folder is for small shared functions used across the project.</p><p>This might include:</p><ul><li>loading config files</li><li>formatting logs</li><li>cleaning text</li><li>validating file paths</li><li>timing function execution</li><li>common error helpers</li></ul><p>Use this folder carefully.</p><p>utils can become a dumping ground if you are not disciplined. If a helper clearly belongs to ingestion, put it in ingestion. If it belongs to retrieval, put it in retrieval. Only place something in utils when it is genuinely shared.</p><h4><strong>tests/: Prove Each Part Works</strong></h4><p>The tests/ folder is what separates serious projects from fragile demos.</p><p>RAG systems are made of many small parts. That means you can test many small parts.</p><p>You can test:</p><ul><li>whether PDFs load correctly</li><li>whether chunking produces expected chunk sizes</li><li>whether metadata is preserved</li><li>whether embeddings are created successfully</li><li>whether retrieval returns relevant documents</li><li>whether prompts include context and question correctly</li><li>whether the API returns the expected response shape</li></ul><p>You do not need perfect test coverage on day one.</p><p>But you do need enough tests to know when you broke something.</p><p>For RAG projects, retrieval tests are especially useful. Keep a small set of sample documents and questions. For each question, define which source document should be retrieved. When you change chunking or embedding settings, run the tests again.</p><p>This gives you a basic quality signal before users find the problem.</p><h4><strong>logs/: Understand What Happened</strong></h4><p>The logs/ folder stores runtime logs.</p><p>In production, logs may go to a proper monitoring tool. But during development, a simple log file is still useful.</p><p>RAG logs should help answer questions like:</p><ul><li>What question did the user ask?</li><li>Which chunks were retrieved?</li><li>What sources were used?</li><li>How long did retrieval take?</li><li>Which model was called?</li><li>Did the LLM return an error?</li><li>How many tokens were used?</li><li>Was the final answer grounded in the retrieved context?</li></ul><p>Without logs, debugging a RAG system becomes guesswork.</p><p>If a user says, “The answer was wrong,” you need to see what the system actually retrieved and what prompt was sent to the model.</p><p>Logs give you that trail.</p><h4><strong>main.py: Keep the Entry Point Simple</strong></h4><p>The main.py file should be the entry point of the application.</p><p>It should not contain the entire system.</p><p>For example, it may start the API server, initialize configuration, or call a main pipeline function.</p><p>The goal is for main.py to stay boring.</p><p>That is a good thing.</p><p>When the entry point is simple, it means the real responsibilities are organized in the correct modules.</p><h4><strong>What This Structure Makes Easier</strong></h4><p>A clean RAG structure makes the project easier to work with in several ways.</p><p>It makes debugging easier because you can isolate the failure. If the answer is wrong, you can inspect retrieval. If retrieval is bad, you can inspect chunking and embeddings. If the API fails, you can inspect the route layer.</p><p>It makes testing easier because each component can be tested alone. You do not need to run the full application just to check whether your PDF loader works.</p><p>It makes scaling easier because you can improve one layer without rewriting everything. You can add batch ingestion, background jobs, caching, reranking, or a new vector database in a controlled way.</p><p>It makes collaboration easier because different people can work on different parts. One person can improve ingestion while another improves prompts or API routes.</p><p>It makes deployment easier because configuration, secrets, dependencies, and application entry points are clear.</p><p>Most importantly, it makes the project understandable.</p><p>A project that is easy to understand is easier to trust.</p><h4><strong>A Simple Rule for Beginners</strong></h4><p>If you are building your first RAG project, use this rule:</p><p><strong>One folder for each responsibility.</strong></p><p>Do not try to make the architecture perfect.</p><p>Just avoid putting everything into one file.</p><p>Start with these core pieces:</p><ul><li>ingestion</li><li>chunking</li><li>embeddings</li><li>vector database</li><li>retrieval</li><li>prompts</li><li>LLM calls</li><li>API</li><li>tests</li><li>logs</li></ul><p>That is already enough structure for most beginner and portfolio projects.</p><p>As the project grows, you can add more advanced layers such as reranking, evaluation, caching, auth, background jobs, document versioning, and monitoring dashboards.</p><p>But the foundation stays the same:</p><p>Separate the pipeline from the application.</p><h4><strong>Final Thoughts</strong></h4><p>A RAG demo proves that the idea can work.</p><p>A maintainable RAG project proves that the system can grow.</p><p>That is the difference.</p><p>Anyone can put document loading, embeddings, retrieval, prompts, and an LLM call into one script. It may even look impressive in a short demo. But the moment you need to debug it, test it, deploy it, or let another person work on it, structure starts to matter.</p><p>A clean project structure is not about making folders for the sake of folders. It is about giving every responsibility a clear home.</p><ul><li>Ingestion should load data.</li><li>Chunking should split text.</li><li>Embeddings should create vectors.</li><li>The vector database should store and search them.</li><li>Retrieval should bring back the right context.</li><li>Prompts should shape the model request.</li><li>The LLM layer should handle model calls.</li><li>The API should expose the system.</li><li>Tests and logs should help you trust what is happening.</li></ul><p>That is how a RAG project starts looking like a real engineering system, not just an AI demo.</p><p>If you are building a RAG project, save this structure and use it as your starting point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34fcf7ceacae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating LLM Systems: What I Built in Module 4 of LLM Zoomcamp]]></title>
            <link>https://danieljude1992.medium.com/evaluating-llm-systems-what-i-built-in-module-4-of-llm-zoomcamp-8c4320aebe18?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4320aebe18</guid>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 01:28:29 GMT</pubDate>
            <atom:updated>2026-07-14T01:28:29.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cb1YiBU4dHQYAKLoubbkFQ.png" /></figure><p>Project repository:</p><p><a href="https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/04-evaluation/evaluation-lab">https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/04-evaluation/evaluation-lab</a></p><p>When people build LLM applications, a lot of attention usually goes into the exciting part: getting the model to answer questions, connecting it to data, adding search, and maybe even giving it tools so it can behave more like an agent.</p><p>That part is important, but Module 4 of LLM Zoomcamp focused on something just as important:</p><p>How do we know the system is actually working?</p><p>It is easy to try a few questions manually and feel like the system is doing well. But that does not tell us enough. A RAG system might answer one question correctly and fail badly on another. A search system might retrieve the right document sometimes, but not often enough. An agent might give a good final answer, but use tools in a wasteful or confusing way.</p><p>This module was about turning those guesses into measurements.</p><p>By the end of the module, I built an evaluation lab for a course assistant. The project evaluates three parts of the system:</p><pre>search -&gt; RAG -&gt; agent</pre><p>The full project is notebook-based because the module is taught step by step. Each notebook handles one part of the evaluation process.</p><h3><strong>The Main Idea: A -&gt; Q -&gt; A’</strong></h3><p>The most important idea in this module is simple:</p><pre>A -&gt; Q -&gt; A&#39;</pre><p>Here is what that means:</p><pre>A  = the original answer from the FAQ<br>Q  = a question generated from that answer<br>A&#39; = the answer produced by the RAG system or agent</pre><p>This gives us a practical way to create ground truth data.</p><p>If we start with an FAQ answer and ask an LLM to generate a question from it, we know which original document should answer that question. That means we can test whether our search system retrieves the right document. Later, we can also compare the answer generated by RAG or an agent with the original FAQ answer.</p><p>That is the foundation of the whole project.</p><h3><strong>What the Project Evaluates</strong></h3><p>The project evaluates the system at three levels.</p><p>First, it evaluates search.</p><p>Search evaluation answers this question:</p><pre>Did the search system retrieve the correct document?</pre><p>Second, it evaluates RAG.</p><p>RAG evaluation answers this question:</p><pre>Did the full RAG pipeline produce a useful answer?</pre><p>Third, it evaluates the agent.</p><p>Agent evaluation answers two questions:</p><pre>Did the agent answer correctly?<br>Did the agent use tools in a reasonable way?</pre><p>This was a useful distinction for me. A final answer can look good, but the system behind it can still be weak. For example, search can be wrong, the prompt can be unclear, or the agent can call tools too many times. Evaluation helps separate these problems.</p><h3><strong>Project Structure</strong></h3><p>I built the project inside the Module 4 folder:</p><pre>04-evaluation/evaluation-lab/</pre><p>The project contains notebooks, reusable helper code, generated data, and report files.</p><pre>evaluation-lab/<br>├── README.md<br>├── code/<br>│   ├── ingest.py<br>│   ├── rag_helper.py<br>│   ├── evaluation_utils.py<br>│   └── test_setup.py<br>├── data/<br>│   ├── ground_truth-new.csv<br>│   ├── question-boost-results.csv<br>│   ├── search-tuning-results.csv<br>│   ├── rag-answers-new.csv<br>│   ├── rag-evaluations-new.csv<br>│   ├── agent-answers.csv<br>│   └── agent-evaluations.csv<br>├── notebooks/<br>│   ├── 01_generate_ground_truth.ipynb<br>│   ├── 02_search_evaluation.ipynb<br>│   ├── 03_search_tuning.ipynb<br>│   ├── 04_generate_rag_answers.ipynb<br>│   ├── 05_llm_as_judge.ipynb<br>│   └── 06_agent_evaluation.ipynb<br>└── reports/<br>    ├── search_metrics.md<br>    ├── rag_evaluation.md<br>    ├── rag_judge_metrics.md<br>    └── agent_evaluation.md</pre><p>The helper files keep repeated logic out of the notebooks. For example, <em>ingest.py</em> loads the FAQ data and builds the search index. <em>rag_helper.py</em> contains the base RAG class. <em>evaluation_utils.py</em> contains metric functions, structured LLM calls, cost helpers, and the RAG class that tracks usage.</p><h4><strong>Step 1: Generating Ground Truth Questions</strong></h4><p>The first notebook generates ground truth questions from the FAQ documents.</p><p>The process starts by loading FAQ data from the DataTalksClub FAQ source. Each FAQ record has fields like:</p><pre>question<br>section<br>answer<br>course<br>id</pre><p>For this project, I filtered the data to the <em>llm-zoomcamp</em> course.</p><p>Then, for each FAQ answer, I used an LLM to generate questions that could be answered by that document. Each generated question is saved together with the document ID it came from.</p><p>The output file is:</p><pre>data/ground_truth-new.csv</pre><p>This file became the test set for the rest of the project.</p><p>In my run, the ground truth file contained 565 generated questions.</p><h4><strong>Step 2: Evaluating Search</strong></h4><p>After creating the ground-truth data, the next step was to evaluate the search.</p><p>The project uses <em>minsearch</em>, the same lightweight search tool used in the course. The index uses these searchable text fields:</p><pre>text_fields=[&quot;question&quot;, &quot;section&quot;, &quot;answer&quot;]</pre><p>It also uses this keyword field:</p><pre>keyword_fields=[&quot;course&quot;]</pre><p>The reason for using <em>course</em> as a keyword field is that we want exact filtering by course. In this case, the search should only return documents from <em>llm-zoomcamp</em>.</p><p>The two search metrics used in the module are Hit Rate and MRR.</p><p>Hit Rate checks whether the correct document appears anywhere in the returned results.</p><p>MRR, or Mean Reciprocal Rank, gives more credit when the correct document appears near the top. If the correct document is first, that is better than if it appears fifth.</p><p>The baseline search result was:</p><pre>Hit Rate: 0.7734<br>MRR: 0.6204</pre><p>This means the correct document appeared in the search results for about 77 percent of the questions. But there was still room to improve.</p><h4><strong>Step 3: Tuning Search</strong></h4><p>The next notebook focused on search tuning.</p><p>Search tuning means trying different weights for fields like question, answer, and section. The idea is that not all fields are equally important. Sometimes matching the answer text is more useful. Other times, matching the question field gives better results.</p><p>The tuning notebook tested different boost values and saved the results.</p><p>The output files are:</p><pre>data/question-boost-results.csv<br>data/search-tuning-results.csv</pre><p>The best result from my run used:</p><pre>Question boost: 3.0<br>Answer boost: 10.0<br>Section boost: 0.5</pre><p>After tuning, the metrics improved to:</p><pre>Hit Rate: 0.9203<br>MRR: 0.7898</pre><p>That was a clear improvement.</p><p>The biggest lesson here was that search settings should not be based only on intuition. Before evaluation, I might assume one field should always have the highest weight. But the metrics show what actually works better on the test set.</p><h4><strong>Step 4: Generating RAG Answers</strong></h4><p>Once search was tuned, the next step was to test the full RAG pipeline.</p><p>RAG stands for Retrieval-Augmented Generation. The flow is:</p><pre>user question -&gt; search -&gt; context -&gt; prompt -&gt; LLM answer</pre><p>For every ground truth question, the notebook ran the RAG system and saved the generated answer. It also saved the original FAQ answer so that the next notebook could compare them.</p><p>The output file is:</p><pre>data/rag-answers-new.csv</pre><p>In my run:</p><pre>Questions processed: 565<br>Total cost: 0.1069</pre><p>This part was useful because it moved evaluation beyond retrieval. Search can retrieve the right document, but the final answer can still be incomplete, too vague, or wrong. To evaluate the system properly, we need to look at the final generated answer too.</p><h4><strong>Step 5: Using an LLM as a Judge</strong></h4><p>The next notebook used an LLM-as-a-judge approach.</p><p>The judge receives three things:</p><pre>the generated question<br>the original FAQ answer<br>the RAG answer</pre><p>Then it decides whether the RAG answer is good or bad.</p><p>This is better than exact text matching because good answers do not need to copy the original FAQ answer word for word. They just need to contain the same key information.</p><p>The judge returns:</p><pre>score: good or bad<br>reasoning: explanation for the score</pre><p>The output file is:</p><pre>data/rag-evaluations-new.csv</pre><p>The RAG judge results were:</p><pre>Total answers judged: 565<br>Good answers: 528<br>Bad answers: 37<br>Good rate: 93.45%<br>Judge cost: 0.0660</pre><p>This was one of the most important parts of the module for me. It showed that evaluation is not only about numbers. The reasoning from the judge helps identify why answers fail. Sometimes the system retrieves the wrong context. Sometimes the answer misses a key detail. Sometimes the model is too generic.</p><p>Those bad cases are where the learning happens.</p><h4><strong>Step 6: Evaluating the Agent</strong></h4><p>The final part of the project evaluated an agent.</p><p>In the earlier RAG pipeline, the flow is fixed:</p><pre>search once -&gt; build prompt -&gt; answer</pre><p>An agent is different. It can decide when to call a tool, what query to send to the search tool, and whether it needs to continue.</p><p>For this project, the agent used a search tool built on the same FAQ index. The agent was created with ToyAIKit, following the course pattern.</p><p>For each question, the project saved:</p><pre>the question<br>the original FAQ answer<br>the agent answer<br>the tool calls made by the agent<br>the cost<br>the source document ID</pre><p>The output file is:</p><pre>data/agent-answers.csv</pre><p>Then another LLM judge evaluated two things:</p><pre>answer quality<br>trajectory quality</pre><p>Answer quality asks whether the agent’s final answer matches the original answer.</p><p>Trajectory quality asks whether the tool calls made sense. For example, did the agent search for something relevant? Did it avoid duplicate calls? Did it call the tool too many times?</p><p>The final output file is:</p><pre>data/agent-evaluations.csv</pre><p>The agent evaluation results were:</p><pre>Agent answers generated: 50<br>Good answers: 43/50<br>Good trajectories: 48/50<br>Agent generation cost: 0.0648<br>Agent judge cost: 0.0088</pre><p>This made the agent evaluation more practical. Instead of only asking, “Was the final answer good?”, the project also asks, “Did the agent behave well while getting there?”</p><p>That second question matters a lot when building real applications.</p><h3><strong>What I Learned</strong></h3><p>The biggest lesson from this module is that evaluation should be part of the project, not something added later.</p><p>Before this module, it was easy to think of a RAG system as one thing. But after building the evaluation project, it becomes clearer that the system has several parts:</p><pre>data loading<br>search<br>prompt construction<br>LLM answer generation<br>answer judging<br>agent tool use<br>cost tracking</pre><p>Each part can fail in a different way.</p><p>Search evaluation tells us whether the right document is being retrieved.</p><p>RAG evaluation tells us whether the final answer is useful.</p><p>Agent evaluation tells us whether the system is using tools properly.</p><p>Cost tracking also matters. Evaluation can involve hundreds of LLM calls, so it is useful to know how much each experiment costs before scaling it up.</p><p>Another important lesson is that metrics help remove guesswork. Search tuning improved the Hit Rate from 0.7734 to 0.9203. Without evaluation, it would be hard to know whether the tuning actually helped.</p><h3><strong>Final Thoughts</strong></h3><p>This project helped me see LLM applications from a more practical angle.</p><p>Building a chatbot is one thing. Knowing whether it works is another.</p><p>Module 4 showed how to build a repeatable evaluation pipeline for search, RAG, and agents. The project now gives me a way to test changes, compare results, inspect failures, and understand cost.</p><p>That is what makes the system easier to improve.</p><p>The full project is available here:</p><p><a href="https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/04-evaluation/evaluation-lab">https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/04-evaluation/evaluation-lab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4320aebe18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Orchestration Workflows with Kestra: What I Learned in Module 3]]></title>
            <link>https://danieljude1992.medium.com/building-ai-orchestration-workflows-with-kestra-what-i-learned-in-module-3-d37af6a58044?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37af6a58044</guid>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai-orchestration]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[kestra]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 20:39:30 GMT</pubDate>
            <atom:updated>2026-07-02T20:39:30.668Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning about LLM applications, most examples felt quite simple: send a prompt to a model, get a response back, and maybe wrap it in a small script. That is a useful starting point, but it does not really reflect how AI systems need to work when they become part of a real workflow.</p><p>In Module 3 of the LLM Zoomcamp, the focus moved from basic LLM calls to <strong>AI orchestration with Kestra.</strong> This module helped me understand how to organise AI tasks into workflows that can be run, inspected, repeated, and improved.</p><p>The main thing I took away is this:</p><ul><li>Building with AI is not only about prompts. It is also about context, tools, execution, observability, cost, and control.</li></ul><p>Kestra was used as the orchestration platform throughout the module. The examples covered AI Copilot, RAG workflows, AI agents, multi-agent systems, and production best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBDn_x7Se2FmxMXLrzZ6zA.png" /></figure><h4><strong>Why orchestration matters</strong></h4><p>A single LLM call is easy to understand. You send a prompt, and the model responds.</p><p>But real AI workflows often need more than that. They may need to:</p><ul><li>load documents</li><li>retrieve context</li><li>call an LLM</li><li>search the web</li><li>use external tools</li><li>save outputs</li><li>log results</li><li>track token usage</li><li>handle secrets</li><li>run on a schedule</li><li>pause for human review</li></ul><p>Without orchestration, all these pieces can become messy. It becomes harder to know what ran, what failed, what the model saw, what tools were used, and how much the workflow cost.</p><p>Kestra gives structure to this process. A workflow is written as YAML, each step is a task, and the execution can be viewed in the UI. This makes the AI system easier to inspect and reason about.</p><h4><strong>Setting up Kestra locally</strong></h4><p>The module used Docker Compose to run Kestra locally.</p><p>The setup includes two main services:</p><ul><li>PostgreSQL</li><li>Kestra</li></ul><p>PostgreSQL stores Kestra’s internal data, such as workflow metadata, execution state, and queue information. Kestra runs the workflow engine and provides the UI.</p><p>The local UI runs at:</p><pre>http://localhost:8080</pre><p>The login used in the module is:</p><pre>Username: admin@****.io<br>Password: Admin****!</pre><p>The module also uses API keys for providers such as Gemini, OpenAI, and Tavily. One important lesson here was not to hardcode keys directly in flow YAML. Instead, secrets should be referenced like this:</p><pre>apiKey: &quot;{{ secret(&#39;GEMINI_API_KEY&#39;) }}&quot;</pre><p>That is cleaner and safer than putting a raw key directly into the workflow.</p><h4><strong>Context engineering</strong></h4><p>One of the first lessons in the module was about <strong>context engineering</strong>.</p><p>The idea is simple but important: an AI model needs the right context to produce useful output.</p><p>The module used a practical example. A generic AI assistant was asked to create a Kestra flow that loads NYC taxi data from a CSV file into BigQuery. The result may look convincing, but it can still contain old syntax, wrong plugin names, missing output handling, or invalid properties.</p><p>That does not mean the model is useless. It means the model does not automatically know the exact version of Kestra, the current plugin schema, or the right task properties.</p><p>This is where context engineering becomes important. Instead of only asking a better question, we need to give the AI the right information to work with.</p><p>That lesson prepared the ground for AI Copilot.</p><h4><strong>AI Copilot</strong></h4><p>Kestra’s AI Copilot was used to generate and refine workflow YAML.</p><p>The difference between AI Copilot and a generic AI assistant is that Copilot is grounded in Kestra-specific context. It has access to current plugin documentation, valid task types, property names, and the structure expected by the running version of Kestra.</p><p>The module reused the same kind of prompt:</p><pre>Create a Kestra flow that loads NYC taxi data from a CSV file to BigQuery.<br>The flow should extract data, upload to GCS, and load to BigQuery.</pre><p>With Copilot, the output is more likely to use valid Kestra syntax.</p><p>The lesson also introduced what I think of as a practical rule:</p><ul><li>Let Copilot generate most of the structure, then review and adjust the final details yourself.</li></ul><p>Copilot can create the first version of a flow, but it does not know every environment-specific value. It may still need project names, bucket names, dataset names, secrets, retries, or better error handling.</p><p>So the workflow is not “ask once and trust everything”. It is more like:</p><pre>describe the goal -&gt; generate the flow -&gt; review -&gt; adjust -&gt; run -&gt; inspect logs -&gt; improve</pre><p>That feels much closer to how real development works.</p><h4><strong>RAG workflows</strong></h4><p>The next major topic was <strong>RAG</strong>, which stands for Retrieval Augmented Generation.</p><p>RAG helps an LLM answer using retrieved information instead of relying only on its training data.</p><p>The module used three related flows:</p><pre>flows/1_chat_without_rag.yaml<br>flows/2_chat_with_rag.yaml<br>flows/3_rag_with_websearch.yaml</pre><p>The first flow asks the model about Kestra 1.1 features without giving it any retrieved context. The model may respond with vague or incorrect information because it is answering from memory.</p><p>The second flow improves this by ingesting the actual Kestra 1.1 release notes. It creates embeddings with Gemini, stores them in Kestra’s KV Store, and then asks the model the same question with RAG enabled.</p><p>The difference is clear:</p><pre>Without RAG:<br>The model guesses from training data.<br><br>With RAG:<br>The model answers using retrieved context.</pre><p>The third flow shows another version of RAG using web search. Instead of ingesting static documents first, it uses Tavily to retrieve live web results at query time.</p><p>That is useful for current information, but it also comes with a warning: web search results are only as good as the search results returned. Static RAG is usually better when the source material is controlled and trusted.</p><h4><strong>Static RAG vs web search RAG</strong></h4><p>This distinction was one of the most useful parts of the module.</p><p>Static RAG is best when the knowledge source is controlled:</p><ul><li>internal documentation</li><li>release notes</li><li>policies</li><li>course notes</li><li>product manuals</li></ul><p>Web search RAG is better when the information changes quickly:</p><ul><li>latest releases</li><li>recent news</li><li>current company research</li><li>market updates</li></ul><p>The module made it clear that RAG is not magic. The quality of the final answer depends on the quality of the retrieved context. If retrieval is poor, the final answer can still be poor.</p><h4><strong>AI agents</strong></h4><p>After RAG, the module moved into AI agents.</p><p>In Module 1, the agentic loop was built manually: call the model, check if it wants to use a tool, run the tool, send the tool result back, and continue until the model produces a final answer.</p><p>In Kestra, the <em>AIAgent</em> task handles that loop.</p><p>The module used:</p><pre>flows/4_simple_agent.yaml<br>flows/5_web_research_agent.yaml</pre><p>The simple agent flow summarises text. It has inputs for summary length, language, and text. It also chains two agent tasks:</p><ul><li>multilingual_agent</li><li>english_brevity</li></ul><p>The first agent produces a summary in the selected language and length. The second agent turns that output into a one-sentence English summary.</p><p>The flow also logs token usage, which is important because agents can use more tokens than a single model call.</p><p>The web research agent is more advanced. It receives a research topic, uses Tavily web search to gather current information, and writes a Markdown report using a filesystem MCP tool.</p><p>The key idea is:</p><ul><li>You specify the goal. The agent decides how to achieve it.</li></ul><p>This is useful when the exact steps are not known in advance.</p><h4><strong>Multi-agent systems</strong></h4><p>The module then introduced multi-agent systems.</p><p>The example flow is:</p><pre>flows/6_multi_agent_research.yaml</pre><p>This flow uses two agents:</p><ul><li>a main analyst agent</li><li>a research agent used as a tool</li></ul><p>The research agent gathers current company information using Tavily web search. The main analyst agent takes that information and returns a structured JSON report.</p><p>The pattern looks like this:</p><pre>user enters company name<br>    -&gt; main analyst agent receives the task<br>    -&gt; main agent calls research agent<br>    -&gt; research agent searches the web<br>    -&gt; research agent returns findings<br>    -&gt; main agent creates structured JSON<br>    -&gt; log task parses and displays the result</pre><p>This taught me why multi-agent systems can be useful. Each agent has a clearer role. The research agent focuses on gathering facts. The analyst agent focuses on structuring the final report.</p><p>But the module also made it clear that more agents are not always better. Multi-agent systems cost more, are harder to debug, and need clear responsibilities.</p><h4><strong>Best practices</strong></h4><p>The best-practices lesson tied everything together.</p><p>The module gave a simple decision guide:</p><pre>| Scenario                                     | Better Choice            |<br>|--------------------------------------------- |--------------------------|<br>| Creating or editing flows                    | AI Copilot               |<br>| Answering questions from your data           | RAG                      |<br>| Fixed ETL pipelines                          | Traditional Workflows    |<br>| Research and analysis tasks                  | AI Agents                |<br>| Complex objectives with specialist roles     | Multi-Agent Systems      |</pre><p>This was an important reminder that not every task needs an agent.</p><p>If the process is fixed and repeatable, a traditional workflow is usually better. It is easier to audit, easier to test, and more predictable.</p><p>For example, a financial reporting workflow in a regulated environment should not depend on an agent deciding what to do next. A deterministic task-based workflow is more appropriate.</p><h4><strong>Cost, observability, and security</strong></h4><p>The module also covered practical concerns.</p><p>AI workflows cost money because LLM APIs are usually priced by token usage. Agents can be more expensive because they may call the model multiple times, use tools, and pass tool outputs back into the prompt.</p><p>That is why the simple agent flow logs token usage:</p><pre>Input tokens<br>Output tokens<br>Total tokens</pre><p>Observability also matters. With agents, it is not enough to know that the task finished. We need to understand what the agent did, which tools it used, what it returned, and whether the output is reliable.</p><p>For debugging, Kestra supports detailed logging:</p><pre>configuration:<br>  logRequests: true<br>  logResponses: true</pre><p>Security was another repeated point. API keys should not be committed to Git or written directly in flow files. The flows use Kestra secrets instead.</p><h4><strong>Homework lessons</strong></h4><p>The homework reinforced the main ideas from the module.</p><p>It asked about:</p><ul><li>Why AI Copilot creates better Kestra flows</li><li>How RAG compares with no RAG</li><li>How token usage changes with short and long summaries</li><li>How modifying a prompt affects output tokens</li><li>Why traditional workflows are better for deterministic, compliant processes</li></ul><p>One useful lesson from the homework was that token counts can vary. The homework even says to choose the closest answer if the result does not match exactly.</p><p>That is realistic. LLM outputs are not always identical across runs.</p><h4><strong>What I would build from this module</strong></h4><p>The project idea that naturally comes out of this module is a <strong>Workflow Intelligence Assistant.</strong></p><p>A small version could include:</p><ul><li>A RAG workflow for answering questions from documentation</li><li>A web search RAG workflow for current information</li><li>A simple agent for summarising text</li><li>A web research agent for generating reports</li><li>A multi-agent workflow for company research</li></ul><p>The important part is not to add features for the sake of it. The point is to use each pattern where it makes sense.</p><p>For example:</p><ul><li>Use RAG when the answer must come from trusted documents</li><li>Use web search when the information changes often</li><li>Use an agent when the workflow needs to decide what to do</li><li>Use multiple agents only when the task benefits from separate roles</li></ul><h4><strong>Final thoughts</strong></h4><p>Module 3 helped me see AI applications less as isolated model calls and more as workflows.</p><p>That shift matters.</p><p>A useful AI system needs more than a prompt. It needs context, orchestration, safe secrets, logging, cost awareness, and a clear reason for each tool being used.</p><p>Kestra makes these ideas easier to practise because the workflows are visible. You can run them, inspect logs, check outputs, compare results, and see how each step connects to the next.</p><p>The biggest lesson for me was this:</p><ul><li>Use AI where it adds value, but keep the workflow understandable, observable, and controlled.</li></ul><p>That is the difference between a demo and something you can actually build on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37af6a58044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Vector Search Assistant: What I Learned from Module 2]]></title>
            <link>https://danieljude1992.medium.com/building-a-vector-search-assistant-what-i-learned-from-module-2-fbeff8d174b6?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbeff8d174b6</guid>
            <category><![CDATA[pgvector]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 08:44:15 GMT</pubDate>
            <atom:updated>2026-07-02T08:44:15.517Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning about Retrieval-Augmented Generation, search felt like the simple part. You ask a question, look up the closest matching documents, put those documents into a prompt, and send everything to the model.</p><p>But Module 2 changed how I think about that search step.</p><p>The module was focused on vector search, and the big idea was this: if we want an AI assistant to answer questions well, we need a better way to retrieve useful context. Keyword search can work, but it only sees words. Vector search helps the system search by meaning.</p><p>To make that idea practical, I built a small Vector Search Assistant. The assistant uses course FAQ data, turns questions and answers into embeddings, searches for the most relevant records, and uses the results inside a RAG pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6RJmHASNVNhigshRTVeHg.png" /></figure><p><a href="https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/02-vector-search/vector-search-assistant">Project code</a></p><h4><strong>The Problem: Keyword Search Is Useful, But Limited</strong></h4><p>In a basic search system, the user types a question, and the system looks for documents with matching words.</p><p>For example:</p><pre>Can I still join the course?</pre><p>A keyword search engine can match words like:</p><pre>join<br>course<br>still</pre><p>That is useful. But it has a weakness.</p><p>If a user asks:</p><pre>I just found out about the program, can I still sign up?</pre><p>The meaning is almost the same, but the words are different. A pure keyword system may not rank the best result high enough because it is looking for exact words, not meaning.</p><p>Vector search solves this by converting text into numbers that represent meaning.</p><h4><strong>What Embeddings Are</strong></h4><p>An embedding is a list of numbers that represents text.</p><p>In the project, I used:</p><pre>SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)</pre><p>This model turns a sentence into a vector with 384 numbers.</p><p>So a question like:</p><pre>I just discovered the course, can I still join?</pre><p>becomes something like:</p><pre>[0.02, -0.13, 0.44, ...]</pre><p>The exact numbers are not important to read by hand. What matters is that similar sentences produce similar vectors.</p><p>That means these two questions should be close in vector space:</p><pre>I just discovered the course, can I still join?<br>I just found out about the program, can I still enroll?</pre><p>The model does not only match words. It understands that “join” and “enroll” are close in meaning in this context.</p><h4><strong>Comparing Text with Dot Product</strong></h4><p>After text becomes vectors, we need a way to compare them.</p><p>The module used dot product:</p><pre>score = v1.dot(v2)</pre><p>Because the vectors are normalised, this behaves like cosine similarity.</p><p>The idea is simple:</p><ul><li>Higher score means the texts are more similar</li><li>Lower score means the texts are less similar</li></ul><p>In the first script, I embedded two similar course-registration questions and compared them. The output showed a positive similarity score, confirming that the model sees them as related.</p><p>That small test was important because it proved the embedding model was working before using it on the full dataset.</p><h4><strong>Embedding the FAQ Dataset</strong></h4><p>After testing embeddings on two questions, the next step was to embed the FAQ dataset.</p><p>Each FAQ record has fields like:</p><pre>course<br>section<br>question<br>answer</pre><p>For search, I combined the question and answer:</p><pre>text = doc[&quot;question&quot;] + &quot; &quot; + doc[&quot;answer&quot;]</pre><p>This gives the embedding model more context. If the user query is close to either the question or the answer, the document can still be retrieved.</p><p>The dataset was embedded in batches:</p><pre>batch_size = 50<br>vectors = []<br><br>for i in range(0, len(texts), batch_size):<br>    batch = texts[i:i + batch_size]<br>    batch_vectors = model.encode(batch)<br>    vectors.extend(batch_vectors)</pre><p>Batching matters because embedding documents one by one is slower. With batching, the model processes multiple texts at once.</p><p>After that, I converted the list of vectors into a NumPy matrix:</p><pre>X = np.array(vectors)</pre><p>Each row in `X` is one document embedding.</p><h4><strong>Manual Vector Search with NumPy</strong></h4><p>Before using a search library, the module showed how vector search works by hand.</p><p>The steps were:</p><pre>embed the user query<br>compare it with every document vector<br>sort by similarity score<br>return the top results</pre><p>In code, the core search line was:</p><pre>scores = X.dot(v_query)</pre><p>This compares the query vector with every document vector at once.</p><p>Then I selected the best results:</p><pre>top5 = np.argsort(-scores)[:5]</pre><p>This manual version helped me understand what vector databases are doing behind the scenes. A vector search engine is not magic. At the core, it compares a query vector against document vectors and ranks the closest matches.</p><p>One thing I noticed immediately was that the search found semantically similar answers from different courses, not only LLM Zoomcamp. That was useful, but not always what we want.</p><p>If a user is asking about LLM Zoomcamp, answers from Data Engineering or MLOps may be confusing.</p><p>That led to the next important idea: filtering.</p><h4><strong>Vector Search with minsearch</strong></h4><p>After the manual NumPy version, I used:</p><pre>from minsearch import VectorSearch</pre><p>The <em>minsearch.VectorSearch</em> class gives a cleaner interface:</p><pre>vindex = VectorSearch(keyword_fields=[&quot;course&quot;])<br>vindex.fit(X, documents)</pre><p>Then search looks like this:</p><pre>results = vindex.search(<br>    query_vector,<br>    filter_dict={&quot;course&quot;: &quot;llm-zoomcamp&quot;},<br>    num_results=5<br>)</pre><p>The important part is:</p><pre>filter_dict={&quot;course&quot;: &quot;llm-zoomcamp&quot;}</pre><p>This keeps the results inside the correct course.</p><p>That small change made the assistant more useful. Instead of giving answers from other courses, it focused on the LLM Zoomcamp FAQ.</p><h4><strong>Adding Vector Search to RAG</strong></h4><p>The next step was to use vector search inside a RAG pipeline.</p><p>The basic RAG flow is:</p><pre>user question<br>-&gt; search<br>-&gt; build prompt with retrieved context<br>-&gt; send prompt to LLM<br>-&gt; return answer</pre><p>The nice thing about RAG is that the search step can be replaced without changing the whole system.</p><p>In the project, I used a base RAG helper class and created a vector version:</p><pre>class RAGVector(RAGBase):<br><br>    def __init__(self, embedder, **kwargs):<br>        super().__init__(**kwargs)<br>        self.embedder = embedder<br><br>    def search(self, query, num_results=5):<br>        query_vector = self.embedder.encode(query)<br>        filter_dict = {&quot;course&quot;: self.course}<br><br>        return self.index.search(<br>            query_vector,<br>            num_results=num_results,<br>            filter_dict=filter_dict<br>        )</pre><p>The only real difference is that the query is embedded before search.</p><p>This helped me see why modular design matters. If retrieval, prompt building, and LLM calling are separated, I can improve one part without rewriting everything.</p><h4><strong>Persisting Vectors with SQLite</strong></h4><p>The <em>minsearch</em> version works well for experiments, but it rebuilds the index every time the script starts.</p><p>That is fine for a small dataset. But in a real application, we do not want to embed all documents every time a user asks a question.</p><p>So the next tool was:</p><pre>from sqlitesearch import VectorSearchIndex</pre><p>The SQLite version stores the vector index in a database file:</p><pre>vs_index = VectorSearchIndex(<br>    keyword_fields=[&quot;course&quot;],<br>    mode=&quot;ivf&quot;,<br>    db_path=&quot;faq_vectors2.db&quot;</pre><p>This introduced an important production idea:</p><pre>ingestion time: embed documents and save the index<br>query time: embed only the user question and search</pre><p>I also created a separate script to reopen the saved index without rebuilding it.</p><p>That helped me understand why real RAG systems usually have at least two phases:</p><ul><li>one process for preparing and indexing data</li><li>another process for answering user questions</li></ul><h4><strong>PostgreSQL and pgvector</strong></h4><p>SQLite is useful for small projects, but many production systems already use PostgreSQL.</p><p>Module 2 introduced <em>pgvector</em>, a PostgreSQL extension for storing and searching vectors.</p><p>With PGVector, embeddings are stored in a table:</p><pre>CREATE TABLE documents (<br>    id SERIAL PRIMARY KEY,<br>    course TEXT,<br>    section TEXT,<br>    question TEXT,<br>    answer TEXT,<br>    embedding vector(384)</pre><p>The <em>vector(384)</em> column matches the embedding size from <em>all-MiniLM-L6-v2.</em></p><p>To search, PostgreSQL uses the vector distance operator:</p><pre>ORDER BY embedding &lt;=&gt; %s::vector</pre><p>I also created an HNSW index:</p><pre>CREATE INDEX ON documents<br>USING hnsw (embedding vector_cosine_ops)</pre><p>This is where the project started to feel closer to a real application. PostgreSQL gives features like persistence, SQL filtering, transactions, and concurrent access.</p><p>The lesson for me was that vector search can live inside tools teams already use. It does not always require a separate vector database.</p><h4><strong>ONNX Runtime for Lighter Embeddings</strong></h4><p>The project first used <em>sentence-transformers</em>, which is convenient. But it brings in PyTorch and a large dependency stack.</p><p>Module 2 also showed a lighter option: ONNX Runtime.</p><p>The ONNX version used:</p><pre>from embedder import Embedder<br><br>embed = Embedder()</pre><p>Then encoding looked familiar:</p><pre>v = embed.encode(text)<br>vectors = embed.encode_batch(texts)</pre><p>This was useful because the rest of the search pipeline stayed almost the same.</p><p>The main difference was the runtime. ONNX makes deployment lighter because it avoids pulling in the full PyTorch stack.</p><p>That matters for small servers, serverless functions, and projects where startup time or package size matters.</p><h4><strong>Hybrid Search with RRF</strong></h4><p>The final search idea was hybrid search.</p><p>Vector search is good at meaning. Keyword search is good at exact terms.</p><p>For example, vector search may understand a paraphrased question, but keyword search may be better when the user asks about a specific function, file name, or tool name.</p><p>Hybrid search combines both.</p><p>The module used Reciprocal Rank Fusion:</p><pre>def rrf(result_lists, k=60, num_results=5):<br>    scores = {}<br>    docs = {}<br><br>    for results in result_lists:<br>        for rank, doc in enumerate(results):<br>            key = (doc[&quot;filename&quot;], doc[&quot;start&quot;])<br>            scores[key] = scores.get(key, 0) + 1 / (k + rank)<br>            docs[key] = doc<br><br>    ranked = sorted(scores, key=scores.get, reverse=True)<br>    return [docs[key] for key in ranked[:num_results]]</pre><p>The important idea is that RRF does not compare raw scores from different search engines. Instead, it looks at rank position.</p><p>If a document appears high in both vector search and keyword search, it receives a stronger final score.</p><p>In the project, the hybrid search result showed why this is useful. A document that was not necessarily first in either individual search could still become the best final result because both search methods agreed it was relevant.</p><h4><strong>What I Built</strong></h4><p>The project lives in the Module 2 folder of my LLM Zoomcamp repository:</p><p>GitHub link:</p><p><a href="https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/02-vector-search">zoomcamp-llm-2026/02-vector-search at main · dajuctech/zoomcamp-llm-2026</a></p><p>The final project includes these files:</p><pre>ingest.py<br>embeddings.py<br>manual_vector_search.py<br>minsearch_vector_search.py<br>vector_rag.py<br>sqlite_vector_search.py<br>sqlite_reopen_search.py<br>pgvector_search.py<br>onnx_embedder_demo.py<br>hybrid_search.py<br>project_notebook.ipynb<br>README.md</pre><p>Each file focuses on one part of the workflow.</p><p>The notebook ties everything together and makes it easier to run each step interactively.</p><h4><strong>The Code That Connects Everything</strong></h4><p>The project is split into small files because each file teaches one part of vector search.</p><p>The data starts in <em>ingest.py</em>, which loads the FAQ documents. Once the documents are loaded, I combine each question and answer before embedding:</p><pre>texts = []<br><br>for doc in documents:<br>    text = doc[&quot;question&quot;] + &quot; &quot; + doc[&quot;answer&quot;]<br>    texts.append(text)</pre><p>That small step matters because a user query might match the question, the answer, or both.</p><p>In <em>embeddings.py</em>, I first checked that the embedding model worked:</p><pre>from sentence_transformers import SentenceTransformer<br><br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br><br>q1 = &quot;I just discovered the course, can I still join?&quot;<br>q2 = &quot;I just found out about the program, can I still enroll?&quot;<br><br>v1 = model.encode(q1)<br>v2 = model.encode(q2)<br><br>print(v1.shape)<br>print(v1.dot(v2))</pre><p>The shape was:</p><pre>(384,)</pre><p>That confirmed the model was creating 384-dimensional vectors.</p><p>In <em>manual_vector_search.py</em>, I used NumPy to search without a vector database:</p><pre>X = np.array(vectors)<br><br>query = &quot;Can I still join the course after the start date?&quot;<br>v_query = model.encode(query)<br><br>scores = X.dot(v_query)<br><br>top5 = np.argsort(-scores)[:5]</pre><p>This is the simplest form of vector search. The query is embedded, compared with every document, and the highest-scoring documents are returned.</p><p>In <em>minsearch_vector_search.py</em>, I moved from manual search to <em>minsearch:</em></p><pre>from minsearch import VectorSearch<br><br>vindex = VectorSearch(keyword_fields=[&quot;course&quot;])<br>vindex.fit(X, documents)<br><br>results = vindex.search(<br>    query_vector,<br>    filter_dict={&quot;course&quot;: &quot;llm-zoomcamp&quot;},<br>    num_results=5,<br>)</pre><p>The important improvement is the course filter. Without it, the search can return similar answers from other courses. With the filter, the assistant stays focused on LLM Zoomcamp.</p><p>In <em>vector_rag.py</em>, I plugged vector search into the RAG flow:</p><pre>class RAGVector(RAGBase):<br><br>    def __init__(self, embedder, **kwargs):<br>        super().__init__(**kwargs)<br>        self.embedder = embedder<br><br>    def search(self, query, num_results=5):<br>        query_vector = self.embedder.encode(query)<br>        filter_dict = {&quot;course&quot;: self.course}<br><br>        return self.index.search(<br>            query_vector,<br>            num_results=num_results,<br>            filter_dict=filter_dict<br>        )</pre><p>That class keeps the rest of RAG unchanged. The only difference is that the search method now embeds the query before retrieving context.</p><pre>vs_index = VectorSearchIndex(<br>    keyword_fields=[&quot;course&quot;],<br>    mode=&quot;ivf&quot;,<br>    db_path=&quot;02-vector-search/vector-search-assistant/faq_vectors2.db&quot;<br>)<br><br>vs_index.clear()<br>vs_index.fit(vectors, documents)</pre><p>I added <em>clear()</em> so the script can be rerun without failing when the database already has documents.</p><p>Then <em>sqlite_reopen_search.py</em> reuses the same database:</p><pre>vs_index = VectorSearchIndex(<br>    keyword_fields=[&quot;course&quot;],<br>    mode=&quot;ivf&quot;,<br>    db_path=&quot;02-vector-search/vector-search-assistant/faq_vectors2.db&quot;<br>)</pre><p>That showed the difference between building an index and querying an existing index.</p><p>In <em>pgvector_search.py</em>, I stored embeddings in PostgreSQL:</p><pre>conn.execute(&quot;CREATE EXTENSION IF NOT EXISTS vector&quot;)<br><br>conn.execute(&quot;&quot;&quot;<br>    CREATE TABLE documents (<br>        id SERIAL PRIMARY KEY,<br>        course TEXT,<br>        section TEXT,<br>        question TEXT,<br>        answer TEXT,<br>        embedding vector(384)<br>    )<br>&quot;&quot;&quot;)</pre><p>Then I searched with cosine distance:</p><pre>results = conn.execute(<br>    &quot;&quot;&quot;<br>    SELECT course, question, answer,<br>           1 - (embedding &lt;=&gt; %s::vector) AS similarity<br>    FROM documents<br>    WHERE course = %s<br>    ORDER BY embedding &lt;=&gt; %s::vector<br>    LIMIT 5<br>    &quot;&quot;&quot;,<br>    (query_str, &quot;llm-zoomcamp&quot;, query_str)<br>).fetchall()</pre><p>This made vector search feel closer to a production database workflow.</p><p>In <em>onnx_embedder_demo.py</em>, I replaced <em>sentence-transformers</em> with the ONNX embedder:</p><pre>from embedder import Embedder<br><br>embed = Embedder()<br><br>v1 = embed.encode(q1)<br>batch_vectors = embed.encode_batch(batch)</pre><p>The search logic stayed almost the same, but the embedding runtime became lighter.</p><p>Finally, in <em>hybrid_search.py</em>, I combined vector search and keyword search:</p><pre>vector_results = vindex.search(<br>    query_vector,<br>    num_results=5<br>)<br><br>text_results = text_index.search(<br>    query,<br>    boost_dict={&quot;content&quot;: 1.0},<br>    num_results=5<br>)<br><br>results = rrf([vector_results, text_results])</pre><p>The <em>rrf</em> function merges the two ranked lists:</p><pre>def rrf(result_lists, k=60, num_results=5):<br>    scores = {}<br>    docs = {}<br><br>    for results in result_lists:<br>        for rank, doc in enumerate(results):<br>            key = (doc[&quot;filename&quot;], doc[&quot;start&quot;])<br>            scores[key] = scores.get(key, 0) + 1 / (k + rank)<br>            docs[key] = doc<br><br>    ranked = sorted(scores, key=scores.get, reverse=True)<br>    return [docs[key] for key in ranked[:num_results]]</pre><p>This final step helped me understand why many real search systems are hybrid. Vector search handles meaning. Keyword search handles exact words. RRF gives a practical way to use both.</p><h4><strong>Key Lessons</strong></h4><p>The biggest lesson from Module 2 is that retrieval quality matters.</p><p>An LLM can only answer well if it receives the right context. If search retrieves weak or unrelated documents, the final answer will suffer.</p><p>Here are the ideas that stood out most to me:</p><ul><li>Embeddings turn text into meaning-based vectors.</li><li>Dot product can rank documents by similarity when vectors are normalised.</li><li>Manual vector search is useful because it explains the basic math.</li><li>Filtering is important because the most similar document is not always from the right course or category.</li><li>RAG becomes easier to improve when search, prompt building, and LLM calls are separate.</li><li>Persistent indexes matter because document embeddings should not be rebuilt on every app start.</li><li>PGVector is useful when vector search needs to live inside a production database.</li><li>ONNX Runtime can make embedding systems lighter.</li><li>Hybrid search is often stronger than choosing only keyword search or only vector search.</li></ul><h4><strong>Final Thoughts</strong></h4><p>Before this module, I understood RAG mostly as a prompt-building pattern. Now I see retrieval as its own serious part of the system.</p><p>The assistant I built is small, but it touches the main pieces used in larger RAG applications:</p><pre>data loading<br>embedding<br>indexing<br>filtering<br>retrieval<br>prompt construction<br>LLM response generation<br>storage<br>hybrid ranking</pre><p>That makes vector search feel less abstract. It is not just a concept anymore. It is a pipeline I can build, test, swap, and improve.</p><p>And that is the real value of the module: it shows that better AI answers often start with better search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbeff8d174b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Agentic RAG Course Assistant]]></title>
            <link>https://danieljude1992.medium.com/building-a-simple-agentic-rag-course-assistant-e7a3592b0e3b?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a3592b0e3b</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 16:27:29 GMT</pubDate>
            <atom:updated>2026-07-01T16:27:29.135Z</atom:updated>
            <content:encoded><![CDATA[<p>RAG is one of those ideas that sounds simple at first: give an LLM some useful context before asking it to answer. The concept is straightforward, but the full workflow becomes much clearer when the pieces are built step by step.</p><p>This project is a course assistant. It answers questions using a FAQ dataset from DataTalksClub. At first, it works like a normal RAG pipeline. Later, it becomes agentic, meaning the model can decide when to search before answering.</p><p>The final project is not a big production app. It is a learning project. That is what made it useful. Each file has one job, and each step helped me understand one part of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RucDZcoT8fv53A8F1i7rUg.png" /></figure><p><a href="https://github.com/dajuctech/zoomcamp-llm-2026/tree/main/01-agentic-rag/course-assistant">Project GitHub</a></p><h4><strong>The Problem I Wanted To Solve</strong></h4><p>Course students ask many repeated questions:</p><ul><li>Can I still join the course?</li><li>How do I get a certificate?</li><li>How do I run something locally?</li><li>Where do I submit homework?</li><li>What should I do if I joined late?</li></ul><p>An LLM can answer general questions, but it does not automatically know the exact course rules. If I ask it a course-specific question without giving it course data, it may give a vague answer or guess.</p><p>That is the reason for RAG.</p><p>RAG means Retrieval-Augmented Generation. In simple words, the app searches trusted documents first, then gives the search results to the LLM, and then the LLM answers using that context.</p><p>The basic flow looks like this:</p><pre>question -&gt; search -&gt; context -&gt; prompt -&gt; LLM answer</pre><p>That simple flow was the first important thing I learned.</p><h4><strong>The Project Structure</strong></h4><p>I split the project into small files:</p><pre>course-assistant/<br>  config.py<br>  data_loader.py<br>  search_engine.py<br>  rag.py<br>  tools.py<br>  agent.py<br>  app.py<br>  project_notebook.ipynb<br>  README.md</pre><p>This structure helped me avoid putting everything into one large notebook or one large Python file.</p><p>Each file has a clear job:</p><ul><li><em>config.py</em> loads environment variables and creates the OpenAI client.</li><li><em>data_loader.py</em> downloads the FAQ dataset.</li><li><em>search_engine.py</em> builds the search index.</li><li><em>rag.py</em> runs the plain RAG pipeline.</li><li><em>tools.py</em> defines search as a tool the model can call.</li><li><em>agent.py</em> runs the agentic loop.</li><li><em>app.py</em> connects everything and runs the full project.</li><li><em>project_notebook.ipynb</em> is used for testing each step.</li></ul><p>This separation made the project easier to understand. If something broke, I knew where to look.</p><h4><strong>Step 1: Loading The Dataset</strong></h4><p>The first real step was loading the FAQ data.</p><p>The project uses the DataTalksClub FAQ endpoint:</p><pre>https://datatalks.club/faq/json/courses.json</pre><p>The loader downloads the list of courses, then downloads the FAQ entries for each course. Each FAQ entry is a document.</p><p>A document has fields like:</p><pre>course<br>section<br>question<br>answer</pre><p>For example, one document might contain a question about joining the course late and an answer explaining what the student should do.</p><p>This was my first mental model:</p><pre>The dataset is the assistant&#39;s knowledge base.</pre><p>Without the dataset, the model only has its general knowledge. With the dataset, the model can answer based on course information.</p><h4><strong>Step 2: Building Search With minsearch</strong></h4><p>After loading the data, the next step was search.</p><p>The project uses <em>minsearch</em>, a small in-memory search library. The idea is simple: put all FAQ documents into an index, then search that index when a user asks a question.</p><p>The index searches through these fields:</p><pre>question<br>section<br>answer</pre><p>It also uses the <em>course</em> field as a filter so the assistant can focus on the LLM Zoomcamp FAQ instead of mixing results from other courses.</p><p>This is important because we do not want to send every FAQ document to the LLM. That would be slow, expensive, and confusing. Search helps us pick only the most relevant documents.</p><p>At this point, the flow looked like this:</p><pre>load documents -&gt; build index -&gt; search for relevant results</pre><p>When I searched for:</p><pre>I just discovered the course. Can I join now?</pre><p>The search result returned a related FAQ question about whether a student can still join. That confirmed the retrieval part was working.</p><h4><strong>Step 3: Turning Search Results Into Context</strong></h4><p>Search results are still just Python dictionaries. The LLM cannot use them properly until we format them into a prompt.</p><p>So the next step was building context.</p><p>The context is a readable text block made from the search results. Each result includes:</p><pre>section<br>question<br>answer</pre><p>The context gives the LLM the information it should use when answering.</p><p>This step taught me that RAG is not only about search. The formatting matters too. If the context is messy, the answer may also be messy.</p><h4><strong>Step 4: Building The Prompt</strong></h4><p>The prompt has two parts:</p><pre>instructions<br>user prompt</pre><p>The instructions tell the model how to behave. In this project, the model is told to answer course questions using the provided context. If the answer is not in the context, it should say it does not know.</p><p>The user prompt contains the actual question and the retrieved context.</p><p>That gave me this flow:</p><pre>question -&gt; search results -&gt; context -&gt; prompt</pre><p>This was one of the most useful lessons for me. The LLM does not magically know what documents I searched. I have to pass the results into the prompt.</p><h4><strong>Step 5: Calling The LLM</strong></h4><p>After building the prompt, the next step was sending it to the model.</p><p>The project uses the OpenAI Responses API:</p><pre>client.responses.create(...)</pre><p>The message history includes:</p><pre>developer message -&gt; instructions<br>user message -&gt; question and context</pre><p>The response gives back the final answer with:</p><pre>response.output_text</pre><p>Now the plain RAG pipeline was complete:</p><pre>question -&gt; search -&gt; context -&gt; prompt -&gt; LLM answer</pre><p>When I asked whether I could still join the course, the assistant answered using the FAQ context instead of guessing from general knowledge.</p><h4><strong>Step 6: Plain RAG Worked, But It Had A Limit</strong></h4><p>Plain RAG is useful, but the developer controls the whole flow.</p><p>The code always does this:</p><pre>search once -&gt; build prompt -&gt; ask the model</pre><p>That means the model does not decide when to search. It does not get to retry the search if the first query is weak. It simply receives whatever context the code gives it.</p><p>This is fine for many questions, but it can struggle when:</p><ul><li>The question has a typo</li><li>The first search result is not good</li><li>The user asks something that needs more than one search</li><li>The model needs to reformulate the search query</li></ul><p>That is where function calling becomes useful.</p><h4><strong>Step 7: Giving The Model A Search Tool</strong></h4><p>Function calling changes the flow.</p><p>Instead of forcing search to happen before the model thinks, we describe a search tool and give it to the model.</p><p>The tool has:</p><pre>name<br>description<br>parameters</pre><p>The search tool accepts one argument:</p><pre>query</pre><p>The model does not run Python directly. It returns a function call request. Python reads that request, runs the search function, and sends the result back to the model.</p><p>The flow becomes:</p><pre>user question<br>-&gt; model asks to call search<br>-&gt; Python runs search<br>-&gt; search result goes back to model<br>-&gt; model answers</pre><p>This helped me understand an important point:</p><pre>The model chooses the action, but Python still executes the action.</pre><p>The model is not secretly running my code. My code is still in control of what actually happens.</p><h4><strong>Step 8: Building The Agentic Loop</strong></h4><p>Function calling once is useful, but an agent needs a loop.</p><p>The loop keeps running until the model stops asking for tools.</p><p>The agentic loop does this:</p><pre>send messages to model<br>check if model requested a function call<br>run the function call<br>append the tool result to the message history<br>send the updated history back to the model<br>repeat until there are no more function calls</pre><p>That message history is important. LLMs do not remember previous API calls by themselves. If I want the model to know what happened, I have to send the full conversation history again.</p><p>The agent has three main parts:</p><pre>instructions<br>tools<br>memory</pre><p>The instructions define the role of the assistant. The tools define what actions it can take. The memory is the message history that keeps track of the question, function calls, and tool results.</p><p>When I ran the agent, I could see the loop:</p><pre>iteration #1<br>function_call: search ...<br><br>iteration #2<br>assistant gives final answer</pre><p>That made the concept much clearer. An agent is not magic. It is a loop around model responses and tool calls.</p><h4><strong>Plain RAG vs Agentic RAG</strong></h4><p>The difference became clearer after building both.</p><p>Plain RAG:</p><pre>The developer controls the steps.<br>Search happens once before the model answers.</pre><p>Agentic RAG:</p><pre>The model can decide when to search.<br>The model can use search results and continue reasoning.</pre><p>Plain RAG is simpler and cheaper. Agentic RAG is more flexible, but it can use more API calls because the model may search multiple times.</p><p>That tradeoff matters. I would not use an agentic loop for every small question. But for questions that need exploration, correction, or multiple searches, it becomes useful.</p><h4><strong>What I Learned From The Project</strong></h4><p>The biggest lesson was that RAG is a system, not one function.</p><p>It has several moving parts:</p><ul><li>loading data</li><li>indexing documents</li><li>searching relevant content</li><li>building context</li><li>writing a good prompt</li><li>calling the model</li><li>checking the output</li><li>exposing tools</li><li>managing message history</li><li>stopping the loop at the right time</li></ul><p>Each part is small, but together they create a useful assistant.</p><p>I also learned why it is better to build the simple version first. If plain RAG does not work, the agentic version will be harder to debug. The right order is:</p><pre>load data<br>build search<br>build plain RAG<br>add function calling<br>build the agentic loop</pre><p>That order made the project easier to reason about.</p><h4><strong>The Final Project</strong></h4><p>The final app runs both versions.</p><p>It first answers with plain RAG. Then it answers with agentic RAG.</p><p>The main file loads the documents, builds the index, asks a sample question, and prints both answers.</p><p>The sample question is:</p><pre>I just discovered the course. Can I still join it?</pre><p>The plain RAG answer uses the retrieved FAQ context.</p><p>The agentic RAG answer shows the model calling the search tool first, then producing a final response.</p><p>That was a good checkpoint. It proved that the full flow worked from end to end.</p><h4><strong>Mistakes That Helped Me Understand More</strong></h4><p>I also ran into a few errors while building the project.</p><p>One error came from using the wrong <em>uv</em> command. I learned that <em>&quot;uv run python …</em>&quot; is the right way to run the file in the project environment.</p><p>Another error was missing <em>minsearch</em>, which reminded me to sync the project dependencies.</p><p>I also tried using the wrong data loading approach at first. For this project, the FAQ data comes from the course JSON endpoint using `requests`.</p><p>Another issue happened when <em>agent.py</em> could not import <em>search_tool</em>. That taught me an important Python lesson: if another file needs to import a variable, that variable must be defined at the top level, not hidden inside an <em>if __name__ == __main__</em> block.</p><p>These errors were useful. They made the project feel less like copying code and more like understanding how the pieces fit.</p><h4><strong>Final Thoughts</strong></h4><p>Before building this project, I understood RAG as a definition. After building it, I understood it as a workflow.</p><p>Plain RAG gave the model better information.</p><p>Function calling gave the model a way to ask for actions.</p><p>The agentic loop connected everything together.</p><p>The simplest way I can describe the project is this:</p><pre>RAG helps the model answer with knowledge.<br>Function calling lets the model ask for help.<br>The agentic loop lets the model keep working until it is ready to answer.</pre><p>That is the foundation I wanted from Module 1. The project is small, but it touches the main ideas needed to build more advanced LLM applications later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a3592b0e3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day My Credit Risk Model Scored 0.71 AUC, and I Still Thought It Was Broken]]></title>
            <link>https://danieljude1992.medium.com/the-day-my-credit-risk-model-scored-0-71-auc-and-i-still-thought-it-was-broken-7438cef5c8da?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/7438cef5c8da</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[bigquery-ml]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Sun, 17 May 2026 09:49:49 GMT</pubDate>
            <atom:updated>2026-05-17T09:49:49.350Z</atom:updated>
            <content:encoded><![CDATA[<p>For about three minutes, I thought the BigQuery ML model I had just trained was a disaster.</p><p>The metrics looked solid. AUC was 0.71, which is respectable for a baseline logistic regression on Lending Club data. Precision was 0.55. The model was trained in under a minute and a half. By every textbook measure, I had built a working credit-risk classifier without leaving SQL.</p><p>Then I ran one more query, broke it down by loan grade, and stared at the result for a long time.</p><p>That moment is what this post is about. But to explain how I got there, I need to back up a little.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WaNPNSBq_LhtL22c1wueA.png" /></figure><h3><strong>Where Module 03 Picks Up</strong></h3><p>Module 02 of the DataTalksClub Data Engineering Zoomcamp ended with 855,502 Lending Club loans landing in BigQuery on a monthly schedule, orchestrated by Kestra. The pipeline ran. The dataset was full. The infrastructure provisioned in Module 01 was finally earning its keep.</p><p>What I had not done was use any of it.</p><p>A credit risk team does not just need data in a warehouse. They need three more things on top:</p><p>1. Queries that come back fast and cheap, even when an analyst is running the same dashboard 50 times a day.</p><p>2. A score per loan that says, <em>“based on this borrower’s</em> profile, here is the probability they will default.”</p><p>3. An explanation for every score, because in regulated lending, you cannot just decline an application. You owe the applicant a reason.</p><p>Module 03 was about delivering all three on a single, serverless stack. Storage, queries, machine learning, model serving, all of it living inside BigQuery, with only the final REST API stepping outside.</p><p>This is the honest version of how that went, including the part where I almost convinced myself a perfectly working model was broken.</p><h3><strong>The Tool I Was Trying to Get Comfortable With</strong></h3><p><strong>BigQuery</strong> is Google Cloud’s data warehouse. The headline feature is that it is <strong>serverless</strong>. You do not provision machines, you do not tune indexes, you do not manage storage. You write SQL, BigQuery runs it on a fleet of workers you never see, and you pay by the byte you scan.</p><p>That last part is the bit most people get wrong.</p><p>BigQuery does not charge you for the rows in your table. It charges you for the <strong>bytes the query reads</strong>. Two queries against the same 800,000-row table can cost wildly different amounts depending on how many columns each one touches. This single rule shapes every storage decision you make.</p><p>Sitting on top of BigQuery is <strong>BigQuery ML,</strong> a feature that lets you train a machine-learning model in pure SQL. Logistic regression, boosted trees, K-means, and even neural networks. You write <em>`CREATE MODEL`</em>, you give it some features, you point at a label column, and BigQuery handles the gradient descent. No Python, no separate ML platform, no data leaving the warehouse.</p><p>That last part matters more than it sounds. Most production credit-risk pipelines move data between three or four systems just to score a loan. Doing the whole loop inside one engine is a real simplification.</p><h3><strong>Step One: Tear the Table Apart, Three Different Ways</strong></h3><p>The Lending Club data sat in one flat BigQuery table after Module 02. My first job was to rebuild it three times, in three different shapes, and prove to myself that storage layout actually matters.</p><p><strong>Table 1 — non-partitioned.</strong> A vanilla native table. All 840,000 rows in one bucket. This is the baseline.</p><p><strong>Table 2 — partitioned by month.</strong> Same data, but BigQuery groups the rows by <em>`DATE_TRUNC(issue_date, MONTH)`</em>. Internally, each of the 24 months becomes its own physical segment. When a query filters by date, BigQuery can skip the segments that do not match.</p><p><strong>Table 3 — partitioned by month AND clustered by grade.</strong> Same partitioning as Table 2, but inside each monthly segment, the rows are now sorted by loan grade (A through G). When a query filters by both date and grade, BigQuery can drop whole segments <em>and</em> skip the blocks within a segment that hold grades it does not care about.</p><p>So I ran the same <em>`COUNT(*) WHERE issue_date BETWEEN ‘2015–01–01’ AND ‘2016–12–31’ AND grade = ‘B’`</em> against all three.</p><p>All three scanned <strong>exactly 7.01 MB</strong>.</p><p>I stared at that for a while, too.</p><h3><strong>The First Trap: Bytes Are Counted by Column, Not by Row</strong></h3><p>The textbook says partitioning saves bytes. I had three different storage layouts. None of them made any difference. Something was clearly wrong with my setup.</p><p>Except nothing was wrong. My queries were touching only two <em>columns: &#39; issue_date` </em>and <em>`grade`</em>. BigQuery reads columns, not rows. Two tiny columns across 840k rows is a fixed cost of about 7 MB, no matter how the table is laid out underneath. There was no fat left to trim.</p><p>To see partitioning actually do its job, I had to do two things. Read more columns, so there was something for the optimiser to skip. And narrow the date filter, so partitions could be excluded.</p><p>The second run, with four columns and a single-month filter:</p><ul><li>Non-partitioned: <strong>27.42 MB</strong></li><li>Partitioned: <strong>870 KB</strong></li><li>Partitioned plus clustered: <strong>870 KB</strong></li></ul><p>That is a 32× reduction by just laying the data out the right way. At the scale of a small project, this is the difference between a fraction of a cent and a few cents. At production scale, with a hundred analysts running the same dashboards daily, this is the difference between a sane bill and an angry one.</p><p>The lesson I learned: <strong>partitioning pays off when you filter on the partition column, and only when there is enough data in the untouched partitions to make the skip worth it.</strong> Without both conditions, you are still paying full price.</p><h3><strong>Step Two: A Model in SQL</strong></h3><p>Once the warehouse was the right shape, training the model was almost anticlimactic. One <em>`CREATE MODEL`</em> statement, a logistic regression, eleven features, one label column called <em>`default_flag`</em>. I clicked Run, waited a minute and eighteen seconds, and the model was live.</p><p>BigQuery ML handles all the boring bits automatically. Numeric features get normalised. Categorical features get one-hot encoded. The dataset is split into train and test sets. You do not write any of this. You just declare what you want.</p><p>When the model finished training, I called <em>`ML.EVALUATE` </em>to see how it did. Here is what came back:</p><pre>## Model Performance Metrics<br><br>| Metric     | Score  |<br>|------------|---------|<br>| ROC-AUC    | 0.7094  |<br>| Precision  | 0.5452  |<br>| Recall     | 0.0739  |<br>| F1-Score   | 0.1300  |<br>| Accuracy   | 0.7872  |</pre><p>The AUC said the model had genuinely learned something — 0.5 means a coin flip, 1.0 means perfect, and 0.71 is a respectable starting point for tabular credit data. Precision was reasonable. Accuracy looked decent on the surface.</p><p>Recall, though. Recall was 7.4 percent.</p><p>That meant of every hundred actual defaults in the test set, the model was catching about seven of them. The other ninety-three were getting through the net unflagged.</p><p>This is the part where you start to suspect something is wrong with how the model is making decisions, but the headline numbers don’t show it. Accuracy looks great because most loans don’t default, a model that always shouts <em>“no default”</em> gets nearly 80% accuracy on this dataset and is completely useless. Accuracy on imbalanced data is a polite lie.</p><p>So I asked the model to actually score every loan, and then I broke the predictions down by grade.</p><h3><strong>The Moment That Stopped Me Cold</strong></h3><p>Here is the table that broke my afternoon.</p><pre>## Default Rate Comparison by Loan Grade<br><br>| Grade | Actual Default Rate | Predicted Default Rate |<br>|-------|----------------------|------------------------|<br>| A     | 6.23%                | 0.00%                  |<br>| B     | 14.43%               | 0.00%                  |<br>| C     | 24.07%               | 0.01%                  |<br>| D     | 33.83%               | 0.03%                  |<br>| E     | 42.86%               | 6.68%                  |<br>| F     | 52.12%               | 81.57%                 |<br>| G     | 55.88%               | 99.31%                 |</pre><p>Read that top to bottom slowly.</p><p>For grades A through D, which are the bulk of the loan book, the model is predicting essentially zero defaults. For grades F and G, it is predicting that <strong>almost every loan will default</strong>, when the real default rate is only about half.</p><p>The model has not learned a smooth probability of default. It has learned a near-binary rule: <em>if the grade is A through E, never call default; if the grade is F or G, almost always call default.</em> Every nuance, from interest rate, income, debt-to-income ratio, and employment length, is gone. The 0.71 AUC was the average of being well-calibrated in the middle and completely wrong at the ends.</p><p>This is what happens when L1 regularisation is too aggressive. L1, also called Lasso, actively zeros out feature weights it considers small. I had set <em>`l1_reg = 0.1`</em>, which I learned the hard way is quite high for this dataset. The model essentially threw away everything except <em>`grade` </em>and <em>`sub_grade`</em>, then went to lunch.</p><p>It did not feel like a failure. It felt like the model had given up.</p><h3><strong>What I Tried Next, and What Did Not Work</strong></h3><p>The obvious next move was hyperparameter tuning. BigQuery ML supports it natively. You give it a range of L1 and L2 to try, you tell it how many trials to run, and it goes off and trains six models in parallel and picks the best one.</p><p>So I ran the tuning. Six trials, 5 minutes 32 seconds of compute, 340 MB scanned.</p><p>The tuned model came back with:</p><ul><li>AUC 0.7113 (up by 0.002 — meaningless)</li><li>Precision 0.5843 (up by 4 points — better)</li><li>Recall <strong>0.0473</strong> (down by 3 points — <strong>worse</strong>)</li></ul><p>Tuning had made the model <em>more</em> conservative, not less. It traded recall for precision along the same AUC frontier. The bimodal collapse was worse, not better.</p><p>This is the second big lesson I locked in. <strong>L1 and L2 regularisation tuning moves you along a precision/recall curve. It does not move the curve itself.</strong> If your model has a recall problem on imbalanced data, you cannot solve it by searching over regularisation strengths. You have to either change the decision threshold (logistic regression outputs probabilities; the cutoff of 0.5 is what produces the bimodal labels) or change the model class entirely.</p><p>For tabular binary classification with strong feature interactions like credit risk, the real answer is boosted trees, XGBoost or LightGBM. BigQuery ML supports them as <em>`boosted_tree_classifier`</em>. That is the natural follow-up project; this module was about learning what logistic regression on this data can and cannot do.</p><h3><strong>Step Three: Get the Model Out</strong></h3><p>A model living in BigQuery is great for nightly batch scoring. It is not great when someone applies for a loan online, and you have five hundred milliseconds to score them.</p><p>For real-time serving, the model has to leave BigQuery. The route is:</p><ol><li><em>`bq extract`</em> pulls the model out of BigQuery and writes it to Google Cloud Storage as a TensorFlow SavedModel. This took 15 seconds.</li><li><em>`gcloud storage cp`</em> pulls those files down to my laptop into a specific directory layout<em>`default_model/1/…`</em>. TensorFlow Serving expects the model name first, then a version number folder. So that version <em>`1`</em> is meaningful; when I retrain and want to deploy <em>`default_model/2/`</em>, TF Serving hot-swaps to it automatically.</li><li><em>`docker pull tensorflow/serving`</em> then <em>`docker run`</em> with the local directory bind-mounted into the container. The container loads the model and exposes a REST API on port 8501. Total time from `docker run` to model loaded: about 5 seconds.</li><li><em>`curl`</em> sends a JSON payload describing one loan applicant. The container returns a JSON response with the default probability.</li></ol><p>To test it, I made up a mid-risk grade-C borrower: $65,000 income, $15,000 loan, 14.5% interest rate, debt-to-income of 22.3, renting, no recent delinquencies, asking for the money to consolidate other debt. I sent that profile to my own laptop, and got back:</p><pre>&quot;default_flag_probs&quot;: [0.2578, 0.7422]</pre><p>The model said 25.78% probability of default.</p><p>The actual default rate for grade-C loans in the calibration table I had built earlier was 24.07%.</p><p>That’s a 1.7 percentage point match between a model running in a Docker container on my laptop and the empirical default rate of about a hundred and ninety thousand real loans. The bimodal problem was still there, but for grade C, which sits in the middle of the bimodal trap, the calibration was holding up.</p><p>End to end, the loop closed. CSV files in Google Cloud Storage, native tables in BigQuery, a model trained in SQL, an export to GCS, a download to a container, a REST API serving live predictions. All of it portable, all of it reproducible, all of it driven by the same Lending Club data I had been working with since Module 01.</p><h3><strong>What I Took Away</strong></h3><p>A few things stuck after this build.</p><ul><li><strong>The cost model of a warehouse is not the cost model of a database. </strong>In Postgres, you optimise by indexing things. In BigQuery, you optimise by reading fewer columns. Once that clicks, every SQL habit you have shifts a little.</li><li><strong><em>`SELECT `</em> is the most expensive query you can run in BigQuery.</strong> It always reads every column. <em>`LIMIT 10`</em> does not save you a single byte; it truncates the results after BigQuery has already read them. The cheap preview is <em>`SELECT id, grade FROM table LIMIT 10`</em>. Naming the columns is the entire point.</li><li><strong>Accuracy is a polite lie on imbalanced data.</strong> The first thing I look at now is the per-segment calibration. A model with 0.79 accuracy and 0.07 recall is not a working model; it is a model that has learned to say <em>“no”</em> to everything and call it 79 percent right.</li><li><strong>Explainability is not a bolt-on.</strong> <em>`ML.EXPLAIN_PREDICT`</em> ships in BigQuery ML out of the box. For every loan, it returns the three features that pushed the prediction most, with attribution scores. That is what reason codes look like in production. If you cannot say <em>why</em> a model declined a loan, you cannot put it into a regulated workflow. BigQuery handles this for you, but only if you ask for it.</li><li><strong>The pipeline matters more than the model.</strong> Most of the work in this module was not building the model. It was building the warehouse around it, getting the storage layout right, moving the model out cleanly, and putting it behind a container. The model itself was twenty-five lines of SQL.</li></ul><h3><strong>What’s Next</strong></h3><p>Module 04 is analytics engineering with dbt. The three storage tables and the ML feature table I built here become the source models for staging and marts. The bimodal-prediction problem becomes a dbt data test something that can fail the build if the predicted default rate ever drifts more than a couple of points away from the actual rate in any grade.</p><p>The boosted-tree experiment is still on the to-do list. So is decision-threshold tuning, which is the proper way to fix the recall problem this logistic regression model has. I will pick those up in a separate post.</p><p>If you want to read the underlying code, the SQL files, the runbook, and the full set of screenshots, including the bimodal calibration table that triggered the long pause, they live in the <a href="https://github.com/dajuctech/credit-warehouse">credit-warehouse repo</a>.</p><p>Module 03 is the one that taught me to look past the headline metric. Sometimes the model is technically working and conceptually broken at the same time. That’s a useful kind of broken to know about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7438cef5c8da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned Building a Credit Risk Data Pipeline with Docker, PostgreSQL, and Terraform]]></title>
            <link>https://danieljude1992.medium.com/what-i-learned-building-a-credit-risk-data-pipeline-with-docker-postgresql-and-terraform-4300c54d438c?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/4300c54d438c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Sat, 16 May 2026 08:52:01 GMT</pubDate>
            <atom:updated>2026-05-16T08:58:52.502Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A walkthrough of Module 1 of the DataTalksClub Data Engineering Zoomcamp.</em></p><h3><strong>Why I built this</strong></h3><p>I work in credit risk, and the thing that frustrates me most is watching analysts spend a Monday morning copy-pasting CSVs into spreadsheets. The lending platforms send their files. Someone opens them in Excel. Someone else pastes the numbers into another Excel file. By Wednesday, an analyst is finally running a SQL query that should have been ready on Monday.</p><p>The fix is not new. You load the files into a real database the moment they arrive, and you let people query the database instead of fighting with spreadsheets. But knowing the fix and shipping the fix are different things. So when I started Module 1 of the DataTalksClub Data Engineering Zoomcamp, I decided to use it as an excuse to build the exact pipeline I wish my workplace had.</p><p>The dataset I picked was the Lending Club loans dataset on Kaggle, about 2.2 million real loan applications from a peer-to-peer lending platform. I filtered it down to loans issued in 2015 and 2016, which left me with about 855,000 rows. That is more than enough to feel “real” without melting your laptop.</p><p>What follows is what I actually learned. Not the polished version. The version that includes the mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BSy_XU4OHsA2KT83-Q0kg.png" /></figure><h3><strong>The shape of the project</strong></h3><p>Before the details, here is the whole thing in plain English:</p><p>1. A Python script reads the loan CSV and loads it into a PostgreSQL database, in chunks of 50,000 rows at a time.</p><p>2. PostgreSQL runs inside Docker, so I do not have to install it on my laptop.</p><p>3. pgAdmin (a visual database tool) also runs in Docker, alongside PostgreSQL, so analysts can query the data through a web page.</p><p>4. Both containers start with a single `<em>docker compose up -d`</em> command.</p><p>5. The same infrastructure, a storage bucket, and a data warehouse can be created in Google Cloud using Terraform, just by running <em>`terraform apply`</em>.</p><p>That is it. Five steps. The hard part is not the steps. The hard part is everything that goes wrong between them.</p><h4><strong>Lesson 1: Quote your file paths</strong></h4><p>The very first command in the Postgres step looks innocent:</p><pre>docker run -d \<br>  -e POSTGRES_USER=&quot;credit_admin&quot; \<br>  -v $(pwd)/credit_data:/var/lib/postgresql/data \<br>  -p 5432:5432 \<br>  postgres:15</pre><p>I copied and pasted it. Docker spat back:</p><pre>invalid reference format: repository name (library/Engineer) must be lowercase</pre><p>I sat there confused for a minute. My folder was called <em>`Data Engineer Tools`</em>. The space in <em>`Engineer Tools`</em> was the entire problem. When the shell expanded <em>`$(pwd)`</em>, the space split the path into multiple arguments. Docker thought <em>`Engineer`</em> was an image name, decided that was illegal, and gave up.</p><p>The fix is one character per side. Wrap <em>`$(pwd)`</em> in double quotes:</p><pre>-v &quot;$(pwd)/credit_data:/var/lib/postgresql/data&quot;</pre><p>I had to redo this in three or four places before I learned the lesson. Every time you write <em>`$(pwd)`</em> in a shell command, wrap it in double quotes. Always. Even if your folder has no space today, it might tomorrow.</p><h4><strong>Lesson 2: <em>`localhost`</em> is not what you think it is</strong></h4><p>This one cost me more time than I am proud of.</p><p>The course material had me connect to PostgreSQL from a second Docker container:</p><pre>docker run -it --network=host postgres:15 psql -h localhost ...</pre><p>On a Linux machine, this works. On a Mac, you get:</p><p>connection to server at “localhost”, port 5432 failed: Connection refused</p><p>Here is the part nobody tells you upfront. On a Mac, Docker does not run containers directly. It runs them inside a Linux virtual machine. So when a container says “localhost,” it means the virtual machine, not your Mac. The PostgreSQL container is also inside that virtual machine, but it is listening on its own network address, not the VM’s.</p><p>There are two clean ways out:</p><ul><li>Use <em>`docker exec -it &lt;container_id&gt; psql …`</em> to run <em>`psql`</em> inside the same container Postgres is in. No networking gymnastics.</li><li>Use <em>`host.docker.internal`</em> instead of <em>`localhost`</em> when you really do need one container to reach another via the host.</li></ul><p>I now reach for <em>`docker exec`</em> by default. It just works.</p><h4><strong>Lesson 3: Reproducible environments are not optional</strong></h4><p>Python is famous for “works on my machine.” I had this exact thing happen to me halfway through.</p><p>I was using <em>`uv`</em>, a fast modern Python package manager, to install pandas, sqlalchemy, and psycopg2 into the project. When I tried to build the Docker image, the build failed because <em>`uv.lock`</em> did not exist. The Dockerfile copied that file in and ran <em>`uv sync — locked`</em> against it. No lockfile, no build.</p><p>The fix was supposed to be one command:</p><pre>uv lock</pre><p>But here is what actually happened. The command ran. It printed <em>`Resolved 371 packages in 5ms`</em>. No lockfile appeared in my project folder. The build still failed.</p><p>What I did not know was that my home folder also had a `<em>pyproject.toml`</em> from an older project, and that file declared a <em>“uv workspace”, </em>a way for one root project to manage several sub-projects. Because my credit pipeline lived inside the workspace tree, <em>`uv`</em> decided the lockfile belonged at the home folder root, not in my project. So it wrote the lockfile somewhere I was not looking, and resolved 371 packages from the whole workspace, way more than my tiny project needed.</p><p>The fix was to open the home folder’s `pyproject.toml`, add my project path to the `exclude` list of the workspace section, and re-run `uv lock`. This time, the lockfile landed in my project, resolved about 10 packages, and the Docker build worked on the first try.</p><p>The lesson is bigger than <em>`uv`</em>. Tools that walk up the directory tree looking for config files <em>`uv`</em>, <em>`git`</em>, <em>`npm`</em>, and many others can silently inherit settings from somewhere you have forgotten about. If something behaves oddly, ask: “What is in my parent folders?”</p><h4><strong>Lesson 4: Layer caching is the real reason your Dockerfile order matters</strong></h4><p>In the Dockerfile, the order looks arbitrary at first:</p><pre>COPY pyproject.toml uv.lock .python-version ./<br>RUN uv sync --locked<br><br>COPY ingest_data.py .</pre><p>Why not just copy everything at once? Because of how Docker caches builds.</p><p>Docker builds each line of the Dockerfile into a layer. Layers get cached. If a layer’s inputs do not change, Docker reuses the cached result instead of running the step again.</p><p>By copying the dependency files first, the layer that installs packages depends only on `pyproject.toml` and `<em>uv.lock`</em>. If I edit my Python script but do not touch dependencies, Docker skips the slow <em>`uv sync`</em> step entirely and goes straight to copying the new script. A rebuild that would have taken two minutes now takes five seconds.</p><p>This is not just a Docker thing. The same principle applies anywhere you have a slow step and a fast step. Put the slow, stable thing first. Put the fast-changing thing last.</p><h4><strong>Lesson 5: The schema of “the same data” can change underneath you</strong></h4><p>Halfway through, my ingestion script broke on a single line:</p><pre>df[&quot;int_rate&quot;] = df[&quot;int_rate&quot;].str.replace(&quot;%&quot;, &quot;&quot;).astype(float)</pre><p>The error was:</p><pre>AttributeError: Can only use .str accessor with string values!</pre><p>The raw Lending Club CSV stores interest rates as strings, with a percent sign, like <em>`”13.56%”`</em>. The code strips the percent sign and casts to a float. Sensible.</p><p>The problem was that I had filtered the original CSV down to 2015–2016 rows by reading it in pandas, slicing it, and re-saving it. When pandas re-saves a CSV, it writes numbers as plain numbers. The percent sign was gone, and the column was already a float. My ingestion script tried to use a string method on a float column, and pandas refused.</p><p>The fix is two extra lines:</p><pre>if df[&quot;int_rate&quot;].dtype == &quot;object&quot;:<br>    df[&quot;int_rate&quot;] = df[&quot;int_rate&quot;].str.replace(&quot;%&quot;, &quot;&quot;).astype(float)<br>else:<br>    df[&quot;int_rate&quot;] = df[&quot;int_rate&quot;].astype(float)</pre><p>The bigger lesson: a CSV is not a stable contract. Two files with the same name can have subtly different column types if one of them passed through a tool that changed how the data is stored. Real ingestion pipelines need to defend against this by checking column types, by validating data before insert, or by storing the raw bytes alongside the parsed version.</p><h4><strong>Lesson 6: SQL is still the language of the warehouse</strong></h4><p>Once the data was loaded, I ran a few queries through pgAdmin. The most satisfying one was this:</p><pre>SELECT purpose,<br>       COUNT(*) AS total_loans,<br>       SUM(CASE WHEN loan_status = &#39;Charged Off&#39; THEN 1 ELSE 0 END) AS defaults,<br>       ROUND(SUM(CASE WHEN loan_status = &#39;Charged Off&#39; THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS default_rate<br>FROM loan_applications<br>GROUP BY purpose<br>ORDER BY default_rate DESC;</pre><p>This is the kind of query that, in a real credit-risk team, would inform pricing thresholds and approval policies. Small-business loans default at a materially higher rate than credit-card refinancing, and that single fact, calculated in three seconds against 855,000 rows, is the entire reason you build a pipeline in the first place. The pipeline is plumbing. SQL is the conversation.</p><p>The <em>`CASE WHEN … THEN 1 ELSE 0 END`</em> trick is worth memorising. You will use it constantly to count rows that match a condition without writing a separate sub-query.</p><h4><strong>Lesson 7: Terraform is the part that feels like magic</strong></h4><p>The last phase moved the same infrastructure into the cloud. Two resources: a Google Cloud Storage bucket and a BigQuery dataset. Both are defined in about 30 lines of HashiCorp Configuration Language:</p><pre>resource &quot;google_storage_bucket&quot; &quot;credit_data_lake&quot; {<br>  name          = &quot;${var.project_id}-credit-data-lake-${var.bucket_suffix}&quot;<br>  location      = var.region<br>  force_destroy = true<br><br>  lifecycle_rule {<br>    action { type = &quot;Delete&quot; }<br>    condition { age = 90 }<br>  }<br>}<br><br>resource &quot;google_bigquery_dataset&quot; &quot;credit_dataset&quot; {<br>  dataset_id = &quot;credit_risk_data&quot;<br>  project    = var.project_id<br>  location   = var.bq_location<br>}</pre><p>Three commands:</p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>About 30 seconds later, both resources existed in my GCP project. I could see them in the cloud console. The <em>`plan`</em> step is the safety net; it shows you exactly what Terraform is going to change, and refuses to do anything until you type <em>`yes`</em>.</p><p>When I was done, one more command tore everything down:</p><pre>terraform destroy</pre><p>That round-trip from <em>“nothing exists”</em> to <em>“real cloud resources exist” </em>to <em>“nothing exists”</em> again took less than a minute and cost less than a cent. The point is not the cost. The point is that the infrastructure is now code. I can throw it in git, share it, change it, review it, and recreate it on any laptop, any time. There is no clicking. There is no <em>“remember to turn on the lifecycle rule.” </em>There is just a file.</p><p>This is the moment a lot of people get hooked on infrastructure-as-code, and I understand why.</p><h3><strong>What I would do differently</strong></h3><p>A few things I would put on the to-do list if I were running this in a real team:</p><ul><li><strong>Use a real secrets manager.</strong> I started with hardcoded passwords in `docker-compose.yml`, then moved them to a `.env` file (gitignored). That is fine for a local dev stack. In production, the same values would come from something like AWS Secrets Manager, GCP Secret Manager, or HashiCorp Vault.</li><li><strong>Validate the data before insert.</strong> My ingestion script trusts the CSV. A real pipeline would check for NULLs in critical columns, validate ranges (no negative loan amounts), and quarantine bad rows for review.</li><li><strong>Add monitoring.</strong> Right now, I would not know if the ingestion silently dropped half its rows. A simple row-count check after each chunk, logged to somewhere visible, would catch that.</li><li><strong>Test the pipeline end-to-end.</strong> Even a five-row CSV fixture and a pytest that runs the ingestion against a throwaway Postgres container would be worth its weight in gold the first time someone changes the schema.</li></ul><p>None of these are hard. They are just the things you only realise you need after the first time you ship something to production, and it surprises you.</p><h3><strong>Conclusion</strong></h3><p>The course markets this as a Docker and Terraform module. What it really teaches is debugging. Every single phase of the project broke for me at least once, in ways the instructions did not predict. Every fix taught me something I will use again: how my shell handles spaces, how Docker networking works across different operating systems, and how my dependency manager makes silent decisions based on parent folders.</p><p>That is the actual value of building these things. You do not learn Docker by reading the documentation. You learn it by typing <em>`docker run`</em> and getting an error message you do not understand, and then understanding it.</p><p>The code lives in <a href="https://github.com/dajuctech/credit-risk-pipeline-docker-terraform">my GitHub repo</a>. The PostgreSQL container has been stopped. The Terraform resources have been destroyed. Clone it, follow the README, and you can have the same setup running on your laptop in about ten minutes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4300c54d438c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG System Might Sound Right and Still Be Wrong: How to Evaluate It Properly]]></title>
            <link>https://danieljude1992.medium.com/your-rag-system-might-sound-right-and-still-be-wrong-how-to-evaluate-it-properly-07fc3910d34b?source=rss-82c58c4b9b89------2</link>
            <guid isPermaLink="false">https://medium.com/p/07fc3910d34b</guid>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Daniel Jude]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 04:08:54 GMT</pubDate>
            <atom:updated>2026-04-30T04:08:54.717Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly guide to the retrieval and generation metrics that tell you whether your RAG pipeline is actually trustworthy.</em></p><p>One of the easiest mistakes to make in AI engineering is to confuse a confident answer with a correct answer.</p><p>A Retrieval-Augmented Generation system can return polished, fluent responses that feel convincing on first read. That does not mean the answer is accurate. It does not even mean the answer came from the retrieved documents.</p><p>This is why RAG evaluation matters so much.</p><p>Without evaluation, a RAG pipeline is often just well-formatted guessing. It may look impressive in a demo, but once real users start asking real questions, the weaknesses show up fast. The retriever may bring back irrelevant chunks. The model may ignore the context. Or worse, it may combine a few correct facts with a few invented ones and produce an answer that sounds credible enough to pass casual inspection.</p><p>If you are building RAG systems for production, or preparing for AI engineer interviews, this is one of the most important ideas to understand: <strong>a good RAG system is not the one that sounds best. It is the one you can measure clearly.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45WdF24x7AeufpNTapeyIA.png" /></figure><h3><strong>RAG Has Two Parts to Evaluate</strong></h3><p>At a high level, a RAG system has two moving parts.</p><p>The first is the <strong>retriever</strong>. Its job is to search your knowledge base and fetch the right chunks of information for a given question.</p><p>The second is the <strong>generator</strong>, usually the LLM. Its job is to read the retrieved context and produce an answer based on it.</p><p>That means RAG evaluation also happens at two levels:</p><ol><li><strong>Retrieval-level evaluation</strong></li><li><strong>Generation-level evaluation</strong></li></ol><p>If you only evaluate one side, you can easily misunderstand the system.</p><p>For example, your retriever may work well, but the model may still hallucinate. Or the model may be capable of giving solid answers, but the retriever may feed it weak or noisy context. In both cases, the final answer quality suffers, but the root cause is different.</p><p>That is why a strong RAG evaluation always separates search quality from answer quality.</p><h3><strong>Why RAG Evaluation Is Non-Negotiable</strong></h3><p>There are several practical reasons teams evaluate RAG systems instead of relying on intuition.</p><p>First, evaluation helps reduce hallucinations. If the model is adding unsupported claims, you need a way to detect that systematically, not just when a human notices it by chance.</p><p>Second, evaluation helps improve retrieval quality. If your top results contain too much noise, the model has to work harder to ignore irrelevant context, and sometimes it fails.</p><p>Third, evaluation lets you compare versions of the system honestly. If you change your chunking strategy, add reranking, switch vector databases, or move to a new model, you need evidence that the change helped rather than hurt.</p><p>Most importantly, evaluation moves you from this mindset:</p><ul><li>“The answer looks fine.” to this mindset:</li><li>“Recall improved after reranking, but faithfulness dropped after the model change.”</li></ul><p>That is the difference between a demo and a production system.</p><h3><strong>1. Retrieval-Level Metrics: Is the System Fetching the Right Context?</strong></h3><p>Retrieval metrics tell you whether the search part of the pipeline is doing its job.</p><p>Before the model can answer well, it needs useful context. If the retriever misses the key chunk or fills the prompt with loosely related text, the model starts from a weak position. Even a strong LLM cannot reliably recover from poor retrieval.</p><p>The three core retrieval metrics beginners should know are <strong>Recall@K</strong>, <strong>Precision@K</strong>, and <strong>Context Relevancy</strong>.</p><h4><strong>Recall@K</strong></h4><p>Recall@K measures whether the important information appears in the top `K` retrieved results.</p><p>A simple way to think about it is:</p><p><strong>Did the system at least bring back the right chunk somewhere in the top results?</strong></p><p>Imagine the user asks:</p><ul><li>“What is the capital of France?”</li></ul><p>Your knowledge base contains these chunks:</p><ul><li>`C1`: Paris is the capital of France.</li><li>`C2`: France has a population of around 68 million.</li><li>`C3`: Berlin is the capital of Germany.</li></ul><p>If the retriever returns the top 2 results as `C2` and `C1`, then the important chunk is present in the top 2. In that case, `Recall@2` is good.</p><p>If `C1` does not appear at all, recall is poor because the retriever missed the most important evidence.</p><p>High recall means your system is less likely to miss critical information. This matters a lot in domains like healthcare, legal search, finance, and support systems, where missing the right document can cause the answer to fail even before generation begins.</p><h4><strong>Precision@K</strong></h4><p>Precision@K looks at the quality of the retrieved set from the opposite angle.</p><p>Instead of asking whether the right chunk was included, it asks:</p><p><strong>How many of the retrieved chunks were actually useful?</strong></p><p>Using the same France example, suppose the top 3 retrieved chunks are:</p><ul><li>`C1`: Paris is the capital of France.</li><li>`C2`: France population data.</li><li>`C3`: Eiffel Tower tourism facts.</li></ul><p>Only one chunk directly answers the question. So even if recall is acceptable, precision is weaker because the retrieved set contains extra noise.</p><p>That matters because LLMs do not read context like a careful human editor. When you give them too much loosely relevant text, they can overfocus on side details, merge unrelated facts, or answer in a less direct way.</p><p>High precision means the prompt is filled with cleaner, more focused evidence. Low precision means the model is being asked to reason through clutter.</p><h4><strong>Context Relevancy</strong></h4><p>Context relevancy asks not just whether the correct chunk appears, but how closely the overall retrieved context matches the user’s question.</p><p>This is more nuanced than recall and precision. A chunk may be somewhat related to the topic without being useful for the exact question.</p><p>For example, if the user asks:</p><p>“What are the side effects of paracetamol?”</p><p>and the retriever returns:</p><ul><li>a chunk listing paracetamol side effects</li><li>a chunk explaining how medicines should be stored</li></ul><p>The second chunk is not completely unrelated, but it is not helping much with the actual question. That lowers context relevancy.</p><p>This metric is often scored with an LLM judge or a similarity model. It gives you a practical signal about whether the retriever is bringing back focused context or making the model sort through distractions.</p><h3><strong>Good Retrieval Still Does Not Guarantee a Good Answer</strong></h3><p>This is a point many builders miss at first.</p><p>You can have high recall and decent precision and still end up with a bad RAG system.</p><p>Why?</p><p>Because retrieval only tells you what the model was given. It does not tell you what the model did with that information.</p><p>The retriever can fetch the right chunks, but the LLM may still:</p><ul><li>ignore part of the context</li><li>mix supported facts with unsupported ones</li><li>answer a slightly different question</li><li>fall back on pretraining knowledge instead of the retrieved source</li></ul><p>That is why you also need generation-level metrics.</p><h3><strong>2. Generation-Level Metrics: Did the Model Use the Context Correctly?</strong></h3><p>Generation metrics tell you whether the answer itself is reliable.</p><p>These metrics become especially important once the retrieval side is already decent. At that stage, many failures come from the model’s behaviour rather than the search layer.</p><p>The three core generation metrics to understand are <strong>Faithfulness</strong>, <strong>Groundedness</strong>, and <strong>Answer Relevancy</strong>.</p><h4><strong>Faithfulness</strong></h4><p>Faithfulness checks whether the claims in the answer are actually supported by the retrieved context.</p><p>This is one of the most important RAG metrics because it acts like a hallucination detector.</p><p>Ask yourself:</p><p><strong>Is every factual statement in the answer backed by the provided documents?</strong></p><p>Suppose the retrieved context says:</p><ul><li>“Paris is the capital of France.”</li></ul><p>and the model answers:</p><ul><li>“Paris is the capital of France and has a population of 5 million.”</li></ul><p>The first part is supported. The second part is not in the retrieved context. Even if the population claim happens to be close to reality, it is still unfaithful in a RAG evaluation setting because the answer added information that was not grounded in the source.</p><p>That is the key idea: in RAG, an answer can be factually plausible and still fail evaluation if it is not supported by the evidence retrieved for that question.</p><p>High faithfulness means the model stays within the bounds of the context. Low faithfulness means the model is inventing, extending, or guessing.</p><h4><strong>Groundedness</strong></h4><p>Groundedness is closely related to faithfulness, but it emphasises something slightly different.</p><p>It measures how strongly the answer depends on the provided source material.</p><p>In plain English, groundedness asks:</p><p><strong>Did the answer really come from these documents, or could the model have said the same thing without them?</strong></p><p>For example, if the context contains detailed information about Indian tax rules but the model responds with generic tax advice that could have been written without reading those documents, the answer is not well grounded.</p><p>This matters because some answers sound correct simply because the model already knew something similar from pretraining. That may feel useful, but it defeats the purpose of RAG when you need answers tied to a specific knowledge base.</p><p>Grounded answers are anchored in the retrieved documents. Poorly grounded answers drift toward generic model knowledge.</p><h4><strong>Answer Relevancy</strong></h4><p>Answer relevancy checks whether the response actually answers the user’s question.</p><p>This sounds obvious, but it is a common failure mode.</p><p>The model may produce a factual answer that is broadly related to the topic while still missing the user’s intent.</p><p>For example, the user asks:</p><ul><li>“What are the symptoms of diabetes?”</li></ul><p>and the model answers:</p><ul><li>“Diabetes is a metabolic disorder that has existed for centuries.”</li></ul><p>That answer is related to diabetes, but it does not answer the question about symptoms. So answer relevancy is low.</p><p>This metric matters because users do not care whether the model is vaguely informed. They care whether it addresses what they asked.</p><h3><strong>How to Read These Metrics Together</strong></h3><p>The real value of evaluation comes from looking at the metrics as a system rather than as isolated numbers.</p><p>Here is how to interpret a few common patterns:</p><p><strong>High recall, low precision</strong></p><p>Your retriever is finding the right information, but it is also bringing back too much noise. The model has access to the answer, but the context window is less clean than it should be.</p><p><strong>High retrieval scores, low faithfulness</strong></p><p>Your search layer is probably doing fine. The problem is that the model is not staying grounded in the context. This usually points to prompt issues, weak answer constraints, or model behaviour.</p><p><strong>High faithfulness, low answer relevancy</strong></p><p>The model is sticking to the documents, but it is not addressing the actual question directly enough. The answer may be safe yet unhelpful.</p><p><strong>Low recall, low faithfulness</strong></p><p>This is often a compound failure. The retriever is not fetching the right evidence, and the model is filling the gap with guesses or generic knowledge.</p><p>This kind of interpretation is what turns raw metrics into engineering decisions.</p><h3><strong>Tools That Make RAG Evaluation Practical</strong></h3><p>The good news is that you do not have to evaluate everything manually.</p><p>Several tools now make RAG evaluation much easier:</p><h4><strong>Ragas</strong></h4><p>Ragas is one of the most popular frameworks built specifically for RAG evaluation. It supports metrics such as faithfulness, answer relevancy, and context relevancy. If you are building a RAG pipeline and want a focused evaluation toolkit, this is usually the first place to look.</p><h4><strong>TruLens</strong></h4><p>TruLens is useful when you want feedback functions, observability, and stronger visibility into how grounded your model outputs are. It is especially helpful when you care about tracing system behaviour rather than just producing a final score.</p><p><strong>DeepEval</strong></p><p>DeepEval provides LLM-based evaluation flows and is useful for teams that want flexible scoring pipelines for LLM applications, including RAG.</p><p><strong>LangChain and LlamaIndex</strong></p><p>Both ecosystems include built-in evaluation flows or integrations that help you test retrieval quality and answer quality inside the same framework you are already using to build the application.</p><p>The right tool depends on your stack, but the important point is this: <strong>evaluation should be part of the pipeline, not an afterthought.</strong></p><h3><strong>What Production-Grade RAG Teams Say Differently</strong></h3><p>Once a team starts evaluating RAG properly, the conversation changes.</p><p>Instead of saying:</p><ul><li>“The model feels better now.”</li><li>“The answers seem cleaner.”</li><li>“This version looks more accurate.”</li></ul><p>They start saying things like:</p><ul><li>“Precision@K improved after we added reranking.”</li><li>“Faithfulness dropped after we switched to a smaller model.”</li><li>“Context relevancy improved once we changed the chunk size.”</li><li>“Hallucinations fell after we tightened the answer prompt.”</li></ul><p>That is a much more mature way to build AI systems.</p><p>It means your decisions are based on evidence. It means regressions become visible. It means you can explain system quality to your team, your stakeholders, and your interviewers with something stronger than instinct.</p><h3><strong>A Simple Mental Model to Remember</strong></h3><p>If you want a quick way to remember all of this, use this rule:</p><p><strong>Retrieval metrics tell you whether the model got the right reading material. Generation metrics tell you whether it wrote the right answer from that material.</strong></p><p>Both matter.</p><p>If retrieval fails, the model starts with the wrong evidence.</p><p>If generation fails, the model misuses the evidence it was given.</p><p>A strong RAG system needs both.</p><h3><strong>Final Thought</strong></h3><p>RAG is often presented as if retrieval alone makes answers trustworthy. In practice, that is only half true.</p><p>Retrieval gives the model a chance to be grounded. Evaluation tells you whether it actually was.</p><p>If you are serious about building reliable AI systems, do not stop at prompting and vector search. Measure what your retriever brings back. Measure what your model does with it. Measure how often the system stays faithful, relevant, and grounded.</p><p>That is when RAG stops being a flashy demo and starts becoming a dependable system.</p><p>If you are preparing for AI engineer interviews, these are exactly the kinds of concepts that separate surface-level RAG knowledge from production-level understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07fc3910d34b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>