<?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[Emumba - Medium]]></title>
        <description><![CDATA[Bringing Startup Agility to Enterprises - Medium]]></description>
        <link>https://medium.com/emumba?source=rss----28784675a43c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Emumba - Medium</title>
            <link>https://medium.com/emumba?source=rss----28784675a43c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:29:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/emumba" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using AWS IPAM to Manage Public IPs in Auto Scaling Environments]]></title>
            <link>https://medium.com/emumba/using-aws-ipam-to-manage-public-ips-in-auto-scaling-environments-f17b455a64eb?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f17b455a64eb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[public-ip-address]]></category>
            <category><![CDATA[aws-ipam]]></category>
            <dc:creator><![CDATA[Faraz Ahmed]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 08:00:07 GMT</pubDate>
            <atom:updated>2026-01-13T08:00:06.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhOilu2SkDbCTmHRyq5RqA.png" /></figure><p>Auto Scaling Groups are designed for elasticity, not predictability. Instances come and go, and public IP addresses are assigned dynamically from AWS-managed pools. For many workloads, this behavior works well.</p><p>However, there are scenarios where <strong>static and predictable public IP addresses</strong> are not optional.</p><p>This article describes an AWS-native approach for assigning <strong>contiguous public IPv4 addresses</strong> to instances running in an Auto Scaling Group using <strong>Amazon VPC IP Address Manager (IPAM)</strong> and <strong>CloudFormation</strong>, with full lifecycle automation.</p><h3>Why Static Public IPs Are Sometimes Required</h3><p>Dynamic public IPs simplify infrastructure, but they introduce challenges in certain environments.</p><p>Static or fixed public IP addresses are commonly required when:</p><ul><li>External systems enforce strict IP allow-listing</li><li>Third-party partners only trust predefined IP ranges</li><li>Regulatory or compliance requirements mandate deterministic network paths</li><li>Network appliances, gateways, or relay nodes must advertise stable endpoints</li><li>Legacy systems cannot adapt to frequently changing source IPs</li></ul><p>In these cases, unpredictable IP assignment can cause service interruptions, failed integrations, or increased operational overhead. Contiguous IP blocks make this even easier by allowing a single CIDR range to be shared with external parties.</p><h3>The Core Idea</h3><p>Instead of relying on randomly assigned public IPs, this solution:</p><ol><li>Reserves a contiguous IPv4 CIDR using AWS IPAM</li><li>Allocates Elastic IPs from that CIDR during instance launch</li><li>Associates those IPs dynamically inside an Auto Scaling Group</li><li>Automatically releases them when instances terminate</li></ol><p>All steps are driven by CloudFormation, ensuring consistency and repeatability.</p><h3>Reserving a Public IP Block with IPAM</h3><p>Amazon VPC IP Address Manager provides centralized control over IP address space across accounts and regions.</p><p>To support this pattern:</p><ul><li>Create an IPAM instance using the Advanced tier</li><li>Enable region replication</li><li>Create a public-scope IPAM pool</li><li>Provision a CIDR block with the required netmask</li></ul><p>IPAM pools are region-specific, so each AWS region requires its own pool.</p><p>Once provisioned, the pool becomes the authoritative source for public IP allocation.</p><h3>CloudFormation Parameters for Flexibility</h3><p>The CloudFormation template introduces parameters that allow this behavior to be enabled or disabled per deployment.</p><pre>Parameters:<br>  UsePublicIPPool:<br>    Type: String<br>    AllowedValues:<br>      - &quot;true&quot;<br>      - &quot;false&quot;<br>    Default: &quot;true&quot;<br>    Description: Use contiguous public IPv4 pool for this subnet<br>  PublicIPv4PoolName:<br>    Type: String<br>    Default: &quot;public-ip-pool&quot;<br>    Description: Name or tag of the IPAM pool to lookup</pre><p>This keeps the template portable across environments with different networking requirements.</p><h3>Launching Instances with Explicit Network Interfaces</h3><p>Elastic IP association requires explicit control of networking, so the launch template defines a network interface directly.</p><pre>LaunchTemplate:<br>  Type: AWS::EC2::LaunchTemplate<br>  Properties:<br>    LaunchTemplateData:<br>      NetworkInterfaces:<br>        - DeviceIndex: 0<br>          AssociatePublicIpAddress: true<br>          DeleteOnTermination: true<br>          Groups:<br>            - !Ref InstanceSecurityGroup</pre><p>This configuration ensures the instance is ready for Elastic IP association immediately after startup.</p><h3>Allocating an IP from the IPAM Pool at Startup</h3><p>When the instance boots, a user data script performs the following actions:</p><ol><li>Looks up the IPAM pool by name</li><li>Allocates an Elastic IP from that pool</li><li>Associates the IP with the instance</li><li>Falls back to an auto-assigned public IP if allocation fails</li></ol><pre>#!/bin/bash<br>USE_POOL=&quot;${UsePublicIPPool}&quot;<br>POOL_NAME=&quot;${PublicIPv4PoolName}&quot;<br>REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region)<br>INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)<br><br>if [ &quot;$USE_POOL&quot; = &quot;true&quot; ] &amp;&amp; [ -n &quot;$POOL_NAME&quot; ]; then<br>  POOL_ID=$(aws ec2 describe-ipam-pools \<br>    --region &quot;$REGION&quot; \<br>    --filters &quot;Name=tag:Name,Values=$POOL_NAME&quot; \<br>    --query &#39;IpamPools[0].IpamPoolId&#39; \<br>    --output text)<br><br>  if [ -n &quot;$POOL_ID&quot; ] &amp;&amp; [ &quot;$POOL_ID&quot; != &quot;None&quot; ]; then<br>    ALLOC=$(aws ec2 allocate-address \<br>      --domain vpc \<br>      --ipam-pool-id &quot;$POOL_ID&quot; \<br>      --region &quot;$REGION&quot;)<br><br>    ALLOC_ID=$(echo &quot;$ALLOC&quot; | jq -r &#39;.AllocationId&#39;)<br><br>    aws ec2 associate-address \<br>      --instance-id &quot;$INSTANCE_ID&quot; \<br>      --allocation-id &quot;$ALLOC_ID&quot; \<br>      --region &quot;$REGION&quot;<br>  fi<br>fi</pre><p>This approach preserves availability even if the IPAM pool is temporarily unavailable.</p><h3>Auto Scaling Group Configuration</h3><p>The Auto Scaling Group references the launch template and declares dependencies on cleanup resources to ensure correct teardown order.</p><pre>AutoScalingGroup:<br>  Type: AWS::AutoScaling::AutoScalingGroup<br>  DependsOn:<br>    - EIPCleanupLambda<br>    - ASGLifecycleHook<br>  Properties:<br>    LaunchTemplate:<br>      LaunchTemplateId: !Ref LaunchTemplate<br>      Version: !GetAtt LaunchTemplate.LatestVersionNumber<br>    MinSize: 1<br>    MaxSize: 3<br>    DesiredCapacity: 1<br>    VPCZoneIdentifier:<br>      - !Ref SubnetId</pre><h3>IAM Permissions</h3><p>Instances need permission to interact with EC2 and IPAM APIs.</p><pre>InstanceRolePolicy:<br>  Type: AWS::IAM::Policy<br>  Properties:<br>    PolicyDocument:<br>      Version: &quot;2012-10-17&quot;<br>      Statement:<br>        - Effect: Allow<br>          Action:<br>            - ec2:DescribeInstances<br>            - ec2:DescribeAddresses<br>            - ec2:AllocateAddress<br>            - ec2:AssociateAddress<br>            - ec2:DisassociateAddress<br>          Resource: &quot;*&quot;<br>        - Effect: Allow<br>          Action:<br>            - ec2:DescribeIpamPools<br>            - ec2:AllocateIpamPoolCidr<br>          Resource: !Sub &quot;arn:aws:ec2:*:${AWS::AccountId}:ipam-pool/*&quot;</pre><h3>Preventing IP Leaks with Automated Cleanup</h3><p>Elastic IPs are a limited resource and must be released when no longer needed.</p><p>This solution uses:</p><ul><li>An Auto Scaling lifecycle hook</li><li>An EventBridge rule</li><li>A Lambda function to disassociate and release IPs</li></ul><h3>Lifecycle Hook</h3><pre>ASGLifecycleHook:<br>  Type: AWS::AutoScaling::LifecycleHook<br>  Properties:<br>    AutoScalingGroupName: !Ref AutoScalingGroup<br>    LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING<br>    DefaultResult: CONTINUE<br>    HeartbeatTimeout: 300</pre><h3>Cleanup Lambda</h3><pre>EIPCleanupLambda:<br>  Type: AWS::Lambda::Function<br>  Properties:<br>    Runtime: python3.9<br>    Handler: index.lambda_handler<br>    Timeout: 60<br>    Role: !GetAtt EIPCleanupLambdaRole.Arn<br>    Code:<br>      ZipFile: |<br>        import boto3<br><br>        ec2 = boto3.client(&#39;ec2&#39;)<br>        asg = boto3.client(&#39;autoscaling&#39;)<br><br>        def lambda_handler(event, context):<br>            instance_id = event[&#39;detail&#39;][&#39;EC2InstanceId&#39;]<br><br>            addresses = ec2.describe_addresses(<br>                Filters=[{&#39;Name&#39;: &#39;instance-id&#39;, &#39;Values&#39;: [instance_id]}]<br>            )[&#39;Addresses&#39;]<br><br>            for addr in addresses:<br>                if &#39;AssociationId&#39; in addr:<br>                    ec2.disassociate_address(<br>                        AssociationId=addr[&#39;AssociationId&#39;]<br>                    )<br>                ec2.release_address(<br>                    AllocationId=addr[&#39;AllocationId&#39;]<br>                )<br><br>            asg.complete_lifecycle_action(<br>                LifecycleHookName=event[&#39;detail&#39;][&#39;LifecycleHookName&#39;],<br>                AutoScalingGroupName=event[&#39;detail&#39;][&#39;AutoScalingGroupName&#39;],<br>                LifecycleActionToken=event[&#39;detail&#39;][&#39;LifecycleActionToken&#39;],<br>                LifecycleActionResult=&#39;CONTINUE&#39;<br>            )</pre><h3>EventBridge Trigger</h3><pre>EIPCleanupEventRule:<br>  Type: AWS::Events::Rule<br>  Properties:<br>    EventPattern:<br>      source:<br>        - aws.autoscaling<br>      detail-type:<br>        - EC2 Instance-terminate Lifecycle Action<br>    Targets:<br>      - Arn: !GetAtt EIPCleanupLambda.Arn<br>        Id: CleanupTarget</pre><h3>Why This Pattern Works</h3><ul><li>Predictable and contiguous public IP ranges</li><li>Fully automated allocation and cleanup</li><li>No orphaned Elastic IPs</li><li>CloudFormation-managed and repeatable</li><li>Preserves Auto Scaling elasticity</li></ul><h3>Final Thoughts</h3><p>Elastic infrastructure does not have to mean unpredictable networking.</p><p>By combining AWS IPAM, Auto Scaling lifecycle hooks, and CloudFormation, you can maintain strict control over public IP addressing while still benefiting from dynamic scaling. This pattern fits well in environments where security, compliance, and integration requirements demand consistent public endpoints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17b455a64eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/using-aws-ipam-to-manage-public-ips-in-auto-scaling-environments-f17b455a64eb">Using AWS IPAM to Manage Public IPs in Auto Scaling Environments</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding as Your High Functioning Intern and a Pair Programmer]]></title>
            <link>https://medium.com/emumba/vibe-coding-as-your-high-functioning-intern-and-a-pair-programmer-277ca5f297a8?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/277ca5f297a8</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[collaboration]]></category>
            <dc:creator><![CDATA[Sameer Khawaja]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 11:57:53 GMT</pubDate>
            <atom:updated>2025-11-14T11:57:52.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IbagepJJjYV3_eMXk0jjHQ.png" /></figure><p>Many of us already know what vibe coding is. The question is how to drive it so the outcome matches the intent. Treating the agent like a sharp intern who moves fast and never tires, then place it inside a deliberate collaboration loop. That’s where the results can start to look like a product, not just code.</p><p>Using vibe coding effectively isn’t about replacing engineers, it’s about <strong>reimagining collaboration</strong>.</p><p>After spending some time experimenting with tools like Replit, I’ve started to see a few key themes emerge. And I believe the following ideas can reshape how we think about vibe coding.</p><h3>Think of it as your new “High-Functioning Intern”</h3><p>Interns are capable, fast, and eager. But they can also miss context and fail to understand priorities. The same is true for today’s agents. The fix is not more keystrokes, it’s more leadership:</p><ul><li><strong>Scope ruthlessly.</strong> Define tasks as bounded modules with inputs, outputs, constraints, and a definition of done.</li><li><strong>Plan work.</strong> Ask for a plan, a rough sketch, then a refined version. Three or more distinct passes, not one long prompt.</li><li><strong>Review quickly and often.</strong> Give feedback early to prevent compounding errors.</li></ul><p>With this process, the agent can become the fastest junior on your team.</p><h3>Clarity of thought beats fluency in syntax</h3><p>Traditional coding warrants precision through syntax. Vibe coding asks you to bring that precision to language. Ambiguity can be very expensive.</p><p>“Build a task app” reads simple, but hides intent.</p><p>Replace unclear requests with intent rich commands:</p><ul><li><strong>Purpose:</strong> who uses it and what job it replaces.</li><li><strong>Behaviors:</strong> the default, the exception, and the error state for each feature.</li><li><strong>Non‑goals:</strong> what we are explicitly not building yet.</li></ul><p>The goal is not to write more words, but to clarify assumptions to the agent.</p><h3>Pair programming, upgraded</h3><p>Classic pair programming splits roles into driver and navigator, with one or more developers tied to each role.</p><p>With agents, the machine becomes the driver and the human a navigator.</p><p>The navigator role can be further split into two complementary sub roles:</p><ol><li><strong>An engineer navigator</strong> focuses on engineering aspects.</li><li><strong>A product manager navigator </strong>holds the customer narrative and the business outcomes.</li></ol><h4>Run the session like a tight feedback loop:</h4><ul><li>The product manager describes the next meaningful chunk of value, constraints, and acceptance criteria.</li><li>The engineer suggests the tech stack, architecture, and overall execution.</li><li>Agent proposes code. The engineer evaluates architecture and code. The product manager<strong> </strong>evaluates outcomes. Iterate.</li></ul><p>Traditionally, this feedback loop took what used to be a week of tickets and Slack threads into an hour of focused collaboration.</p><p>When decisions happen under the umbrella of context, rework can be reduced because misalignments surface immediately.</p><h4>An example working pattern you can adopt tomorrow</h4><ol><li><strong>Ask the agent for a plan, not code.</strong> Request a task list and a module structure. Iterate that list until both navigators agree it’s the right plan.</li><li><strong>Add acceptance checks early.</strong> Have the agent generate simple tests or scripts that express the product truth you care about. They don’t have to be perfect. They anchor reality.</li><li><strong>Keep a review cadence.</strong> Every review window, ask: What shipped? What broke? What’s next? Reset the agent’s context if drift appears.</li><li><strong>Document as you go.</strong> Ask the agent to produce a brief README after each review window.</li></ol><h3>Product management + vibe coding: the multiplier</h3><p>Agents right now are excellent at how, mediocre at why. Product managers are the inverse. Pair them and you get high value outcomes.</p><p>In a session, a PM should:</p><ul><li><strong>Name the value unit.</strong> What outcome will we be able to demo that a user would pay for or prefer?</li><li><strong>Describe what success looks like to the user, not how to build it.</strong><br> Example: “A user can upload a CSV with up to 500 tasks, we check it, and show which ones failed,” not “Add a CSV parser.”</li><li><strong>Price the trade‑offs.</strong> If the agent proposes a shortcut, PM decides whether speed beats capability or not.</li><li><strong>Guard the narrative.</strong> Make sure each chunk advances the product’s story, and does not turn it into a museum of features.</li></ul><p>The result is a trackable stream of value, not just code that compiles.</p><h3>Skills that now matter most</h3><p>The winners in vibe coding assisted teams are not the people who remember every API. They are the people who can:</p><ul><li>Take a vague goal and break it into small, clear, checkable tasks with simple rules.</li><li>Spot where the agent misunderstood the goal vs where the goal was not well explained</li><li>Give feedback that guides what it does next, not just comments on what it already did. Feedback that changes the next output.</li><li>Recognize when it’s good enough to deliver value and move on, instead of endlessly polishing.</li></ul><p>Technical intuition still matters. You don’t need to write every line yourself, but you should spot when something is poorly designed, risky by default, or quietly breaking</p><h3>Closing thoughts</h3><p>Vibe coding has the capability of replacing long hand‑offs and vague requirements, if employed well. The teams that win will install a clear operating model, treat the agent like a high‑functioning intern, pair it with a developer and a product manager, and run short, review‑heavy loops.</p><p>You will ship more, argue less, and spend your energy on decisions that move the product.</p><p>The point is not how elegantly the agent writes code. The point is how intentionally we guide it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277ca5f297a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/vibe-coding-as-your-high-functioning-intern-and-a-pair-programmer-277ca5f297a8">Vibe Coding as Your High Functioning Intern and a Pair Programmer</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Token Refresh in K6: A Step-by-Step Guide]]></title>
            <link>https://medium.com/emumba/dynamic-token-refresh-in-k6-a-step-by-step-guide-a8e3ff44d0ea?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/a8e3ff44d0ea</guid>
            <dc:creator><![CDATA[Aqsa Tahir]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 07:48:54 GMT</pubDate>
            <atom:updated>2025-10-30T07:48:53.787Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to managing authentication token expiry in K6 performance tests.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8yOm6NvVSU_7-cj12H4eA.png" /></figure><p><strong>Picture this:</strong> you’ve set up your new k6 performance tests, eager to see how your APIs hold up under load. The scripts fire up, requests start flowing, everything looks smooth… until suddenly, requests begin to fail. Not because your API broke, but because your <strong>authentication token quietly expired mid-test</strong>.</p><p>It’s one of those frustrating moments where your load test results are ruined by something that has nothing to do with the performance of the application being tested. If your tokens expire every few minutes, but your tests run for a longer duration, you’re guaranteed to hit this wall.</p><p>In this blog, I’ll show you how we combined <strong>Node.js, Puppeteer, and Express</strong> to automatically refresh tokens in the background and make sure our <strong>k6 tests always run with valid authentication</strong>.</p><h3>Problem Statement</h3><p>Our challenge:</p><ul><li>API tests take between <strong>1–15 minutes</strong>.</li><li>The <strong>auth token expires after 5 minutes</strong>.</li><li>K6 runs in its own <strong>Go-based JavaScript engine (Goja)</strong>, which means <strong>Node.js modules (like fs)</strong> don’t work.</li></ul><p>If we ignore this issue, our <strong>performance test results become unreliable</strong> because tests fail due to expired tokens instead of system performance.</p><h3>Solution: Step-by-Step Process</h3><p>Here’s the approach we took to keep tokens fresh during long-running K6 tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*0EAEXuWrX3aTEzVF6lXL8A.png" /></figure><p><strong>Step 1: Scheduled Token Refresh Using Node.js</strong></p><p>We already had a login method using <strong>Puppeteer</strong> to fetch tokens. We extended it to <strong>save tokens in a file</strong> and refresh them every 4.5 minutes using setInterval( duration should be close to token expiry).</p><pre>import fs from &#39;fs&#39;;<br><br><br>const tokenFilePath = &#39;./token.json&#39;;<br><br><br>export async function tokenRefresh() {<br>// Assume your login function returns the auth token<br>const authorization = await login();<br>fs.writeFileSync(tokenFilePath, JSON.stringify({<br>access_token: authorization,<br>expires_at: new Date(Date.now() + 4.5 * 60 * 1000).toISOString()<br>}, null, 2));<br>}<br><br><br>setInterval(async () =&gt; {<br>await tokenRefresh();<br>}, 4.5 * 60 * 1000);</pre><p>At this point, we have a <strong>token.json</strong> file that always contains a fresh token. But how do we access this from K6?</p><p><strong>Step 2 : Setting Up a Token Server with Express</strong></p><p>Since K6 does not support Node.js modules like fs, we couldn’t directly read the token from token.json during test execution. To address this, we introduced a lightweight <strong>Express server</strong> that exposes the token via an API endpoint, making it accessible to K6 whenever needed.</p><p>Additionally, we embedded the <strong>token refresh logic (</strong>setInterval<strong>)</strong> within the server itself. This way, the server automatically refreshes the token at regular intervals, eliminating the need to keep a separate login script running in parallel.</p><pre>// token-server.ts<br>import express from &#39;express&#39;;<br>import fs from &#39;fs&#39;;<br><br>const app = express();<br>const port= 4000;<br><br>app.get(&#39;/token&#39;, (req, res) =&gt; {<br>try {<br>const data = JSON.parse(fs.readFileSync(&#39;./token.json&#39;, &#39;utf8&#39;));<br>res.json({ access_token: data.access_token });<br>} catch (err) {<br>res.status(500).json({ error: &#39;Failed to read token&#39; });<br>}<br>});<br><br><br>app.listen(port, () =&gt; {<br> await refreshToken();<br>    setInterval(async () =&gt; {<br>        try {<br>            console.log(&#39; Auto-refreshing token...&#39;);<br>            await refreshToken();<br>        } catch (err) {<br>            console.error(&#39;Token refresh failed:&#39;, err);<br>        }<br>    }, 4.5 * 60 * 1000);<br>});</pre><p>This server:</p><ul><li>Reads the token from the file.</li><li>Exposes it at <a href="http://localhost:4000/token.">http://localhost:4000/token.</a></li><li>Keeps refreshing it in the background.</li></ul><p><strong>Note:</strong> You can either keep the <strong>login and refresh functions</strong> in one file and the <strong>server code</strong> in another, or combine them into a <strong>single file</strong> that handles login, token refresh, and serving the token. Combining everything into one file can simplify setup and reduce the overhead of managing multiple files.</p><p><strong>Step 3: Fetching Fresh Tokens Inside k6</strong></p><p>We created a <strong>separate helper script</strong> (fetchFreshToken.js) that k6 can use to fetch tokens from our local server. This avoids direct file reading (which k6 doesn’t support).</p><pre>// fetchFreshToken.js<br>import http from &#39;k6/http&#39;;<br><br>let authToken = &#39;&#39;;<br>let lastTokenReadTime = 0;<br>const tokenRefreshInterval = 4 * 60 * 1000;<br><br>export function getAuthToken() {<br>  const now = Date.now();<br>  if (!authToken || (now - lastTokenReadTime &gt; tokenRefreshInterval)) {<br>    const res = http.get(&#39;http://localhost:4000/token&#39;);<br>    authToken = JSON.parse(res.body).access_token;<br>    lastTokenReadTime = now;<br>  }<br>  return authToken;<br>}<br><br>export function getParams() {<br>  return {<br>    headers: { Authorization: `Bearer ${getAuthToken()}` }<br>  };<br>}</pre><p><strong>Notice the separation:</strong></p><ul><li>getAuthToken() talks to the local token server and caches the token.</li><li>getParams() updates request headers with the latest token.</li></ul><p>Then, in our actual k6 test scripts, it’s super simple. We are simply calling getParams().</p><pre>import http from &#39;k6/http&#39;;<br>import { getParams } from &#39;./fetchFreshToken.js&#39;;<br><br>export default function () {<br>  const res = http.get(`${__ENV.BASE_URL}/api/data`, getParams());<br>  console.log(`Response: ${res.status}`);<br>}</pre><p>Behind the scenes, getParams() makes sure the header always contains a valid token.</p><p><strong>Step 4: Running k6 &amp; Token Server in Parallel</strong></p><p>At first, we ran the <strong>token server</strong> and <strong>K6 script</strong> in separate terminals. But that was messy. To fix this, we automated both into a <strong>single command</strong> inside package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;run:k6&quot;: &quot;cross-env TOKEN_SCRIPT=$TOKEN_SCRIPT K6_SCRIPT=$K6_SCRIPT bash -c &#39;ts-node $TOKEN_SCRIPT &amp; PID=$!; trap \&quot;kill $PID 2&gt;/dev/null\&quot; EXIT INT TERM; sleep 20; k6 run --env $K6_SCRIPT; kill -0 $PID 2&gt;/dev/null &amp;&amp; kill $PID 2&gt;/dev/null; wait $PID 2&gt;/dev/null&#39;&quot;<br>}</pre><p>Run it like this:</p><pre>TOKEN_SCRIPT=&lt;path to login file&gt; K6_SCRIPT=&lt;path to k6 script&gt; npm run run:k6</pre><p>This starts the <strong>token server</strong>, waits a bit, runs the <strong>K6 test</strong>, and cleans up afterward.</p><h3>Key Takeaways</h3><ul><li>K6 doesn’t support Node.js modules, so you can’t directly refresh tokens inside K6.</li><li>A <strong>separate Node.js token server</strong> is a reliable workaround.</li><li>By fetching tokens via HTTP inside K6, you ensure your tests <strong>never fail due to expired tokens</strong>.</li><li>Running everything in parallel with an npm script makes the workflow seamless.</li></ul><h3>Final Thoughts</h3><p>Token expiry during performance tests is a <strong>common but solvable challenge</strong>. By combining Puppeteer, Express, and some scripting, we built a reliable pipeline that keeps k6 tests running <strong>without interruptions from expired tokens</strong>.</p><p>If you’re running performance tests on APIs with short-lived tokens, try this approach — it’ll save you a lot of headaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e3ff44d0ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/dynamic-token-refresh-in-k6-a-step-by-step-guide-a8e3ff44d0ea">Dynamic Token Refresh in K6: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Testing for Software Infrastructure 101]]></title>
            <link>https://medium.com/emumba/performance-testing-for-software-infrastructure-101-5752b71ecd65?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/5752b71ecd65</guid>
            <dc:creator><![CDATA[Hamza Ali]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 06:51:48 GMT</pubDate>
            <atom:updated>2025-10-28T06:51:46.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to evaluating autoscaling, resilience, and infrastructure performance in Kubernetes environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*lqppG9lREuAD0Dhi" /></figure><p>Imagine a scenario, where your e-commerce application just went into production. It works fine on the first day with an influx of 1000 users throughout the day. But what happens when 500 user access the app concurrently the next day? The application crashes and returns a 500 internal server error. Turns out the service pods could not withstand that much concurrent load and crashed.</p><p>Its important to understand that the above scenario is not an application bug, rather an infrastructure failure. It is the exact reason why executing performance testing for your software infrastructure is critical. It ensures that the software architecture is robust and resilient enough to handle all sorts of spikes in user traffic.</p><p>Before we dive deeper: Infrastructure testing is different from functional testing. While functional tests verify features (sign-up, login, payments), infrastructure performance tests validate whether the underlying system can handle spikes, failures, and scaling needs. This blog focuses on the latter.</p><p>This blog will be mainly focused on microservices infrastructure and cover how to test auto-scaling, high availability, DB resource consumption as well as load balancing from a performance point of view.</p><p><strong>Pre Requisites:</strong></p><p>Before we dive into the topic in depth, following are the pre requisites for testing an application’s infrastructure:</p><ul><li>A tool for cluster access i.e. Kubernetes lens</li><li>Access to DB</li><li>Access to monitoring tool, e.g. Grafana, Prometheus etc.</li><li>A basic level understanding of software infrastructure.</li></ul><h4>Software Infrastructure Overview</h4><p>While there are different types and forms of software architecture, this article will be mainly dealing with the microservices architecture. It is an architecture style where the application is comprised of loosely coupled independent modules known as services.</p><p>These services are running on lightweight environments know as <a href="https://www.docker.com/resources/what-container/"><strong>containers</strong></a>, which package an application and its dependencies. These containers are managed by deployment/orchestration tools such as Kubernetes etc.</p><p>Kubernetes organizes containers for each service into <a href="https://kubernetes.io/docs/concepts/workloads/pods/"><strong>pods</strong></a>- which are the smallest deployable unit. A pod can contain one or more tightly coupled containers that share:</p><ul><li>Network namespace (same IP address and ports)</li><li>Storage volumes</li><li>Lifecycle (they start, stop, and scale together)</li></ul><p>Pods run on physical servers called <a href="https://kubernetes.io/docs/concepts/architecture/nodes/"><strong>nodes</strong></a>, and multiple nodes join together to form a <a href="https://kubernetes.io/docs/concepts/architecture/">cluster</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*YJQccBCVKk_y0RUy8e2RTA.png" /><figcaption>An overview of Kubernetes architecture hierarchy</figcaption></figure><h4>Testing Autoscaling</h4><p><strong>What is autoscaling?</strong></p><p>Autoscaling is a process in cloud computing, that increases allocation of computational resources to a component, based on system requirement. In our context, if a service only has one pod and is under excessive load, auto scaling increases the number of pods to enable it to handle the load better. This is known as horizontal autoscaling.</p><p>Autoscaling in Kubernetes is usually managed through the <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaler</a> (HPA), which increases or decreases the number of pods based on CPU/memory thresholds. KEDA (Kubernetes Event-Driven Autoscaling) is an add-on that extends HPA by supporting event-driven metrics (like queue length, Kafka lag, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*F-Y0EzEp8O_vERkcORmjXg.png" /><figcaption>KEDA thresholds defined for a service</figcaption></figure><p>For example in the above image, once the specific service consumes more than 75% of its CPU or memory resources, the autoscaler will increase its number of pods.</p><p>The number of minimum or maximum pods for any service can be found using the following command:</p><pre>kubectl get hpa --all-namespaces<br>kubectl describe hpa &lt;deployment-name&gt; -n &lt;namespace&gt;</pre><p>The first command will return a list of the Horizontal Pod Autosclalers (HPA). The second command will display an output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*-Ut4xd056fPoNFHT78igUw.png" /><figcaption>KEDA HPA Metrics</figcaption></figure><p><strong>Testing Approaches:</strong></p><ol><li><strong>Load test execution:</strong></li></ol><p>One of the simplest yet most effective approaches for testing autoscaling is to execute load tests. This can be done through using tools such as JMeter, k6 etc. For example, a load test that simulates thousands of users signing up should put load on the authentication service leading it autoscaling and increasing its number of pods. Furthermore, once the test ends the number of pods should come back to normal.</p><p><strong>2. Using libraries for load generation:</strong></p><p>While performance test execution is an effective way to test autoscaling, some services are not directly part of end-user flows and would need to be tested in an isolated manner.</p><p>Using custom load generation tools like <a href="https://manpages.ubuntu.com/manpages/focal/man1/stress-ng.1.html">stress-ng</a> is the best choice in this case. These libraries generate the required CPU consumption on a pod for a specified time. You can monitor the resource consumption for the service in real time and verify that it auto scales and downscales accordingly.</p><pre>stress-ng --cpu 4 --cpu-load 90 --timeout 120s</pre><p>For example, the command above will generate 90% consumption on 4 CPU cores of an instance for 2 minutes. If the KEDA threshold for the service is ~70%, the service should auto scale and the number of pods should increase.</p><p>Similarly, once the tests end, the additional pods should get deleted and the service should come back to its original state.</p><p><strong>3. Custom shell scripts:</strong></p><p>A limitation in the above method is that for certain machines, the performance test engineer might not have the necessary privileges to install the library. The workaround for this limitation is to utilize custom shell scripts that generate excessive CPU load on the machine.</p><pre>#!/bin/bash<br><br># Number of parallel CPU-consuming processes<br>NUM_PROCESSES=4<br><br># Duration to run the CPU burn (in seconds)<br>TIMEOUT=120<br><br>echo &quot;Starting CPU burn with $NUM_PROCESSES processes for $TIMEOUT seconds...&quot;<br><br>for i in $(seq 1 $NUM_PROCESSES); do<br>  # Each process runs an infinite loop to consume CPU, wrapped in timeout<br>  timeout $TIMEOUT bash -c &quot;while :; do :; done&quot; &amp;<br>done<br><br># Wait for all background processes to finish<br>wait<br><br>echo &quot;CPU burn completed.&quot;</pre><p>A script like the one above can be executed inside a pod to generate load on the CPU. Commands such as while, do and done are CPU intensive commands that do not require I/O. Setting the value of NUM_PROCESSES to 4 and timeout to 120 means that the loop is executed for two minutes and starts 4 processes in parallel, which impact 4 CPU cores.</p><p>If the user does not have enough privileges to create a shell file, a similar command can be executed directly on the pod through ssh</p><pre>kubectl exec &lt;pod-name&gt; --namespace &lt;namespace&gt; -c &lt;container-name&gt; -- \<br>/bin/sh -c &quot;timeout 120 sh -c &#39;while :; do :; done&#39; &amp; timeout 120 sh -c &#39;while :; do :; done&#39;; wait&quot;</pre><h4>Testing High Availability</h4><p>High availability is a system’s ability to remain operational and accessible even when parts of it fail. In large enterprise applications, high availability means ensuring <strong>minimal to zero downtime</strong>, so users can continue interacting with the application without interruption — even during infrastructure failures or maintenance events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*aEWMEVake1vjVvJR.jpg" /><figcaption>A basic architecture with high availability</figcaption></figure><p><strong>Testing approach</strong></p><p>In our context, the approach to test self-healing is to delete multiple pods against a service and ensure that they new pods are created in their place in the shortest possible duration. This is critical to minimize downtime.</p><p>The following command can be used to simultaneously delete all the pods against a service</p><pre>kubectl delete pods -l &lt;label&gt; -n &lt;workspace name&gt;</pre><p>A similar command can be used to delete all the pods in a namespace, this ensures multiple services are impacted at once</p><pre>kubectl delete pods --all -n &lt;workspace name&gt;</pre><p>Once the command is executed, the tester should note down the time taken for the new pods to spin up and become active. It is also important to keep in mind that while the pods spin up almost instantly, the containers can take some time to stabilize. This time should be included in the duration being monitored. All these metrics including pod health can be observed in the pods section on Lens GUI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fyvQDM4LGzifI5GiZ_Vzw.png" /><figcaption>Pods listed in K8 Lens</figcaption></figure><p>A deeper HA test is to simulate node failure using the following command</p><pre>kubectl drain &lt;node&gt;</pre><p>This command evicts all the pods from a node and renders it unschedulable. After executing this command, verify that the pods are scheduled onto other existing nodes and the application downtime is minimal.</p><h4>Testing Database Resource Consumption</h4><p>Just as we execute load performance test scripts to put load on services, the same approach can be utilized to test databases. Executing load tests with concurrent read/write operations allows us to generate load on the DB and benchmark metrics such as:</p><ul><li>CPU consumption of DB</li><li>I/O network traffic</li><li>Query performance</li></ul><p>These metrics can be observed for databases against cloud monitoring dashboards (GCP, AWS etc). The objective of putting stress on the DB is to ensure that it is able to handle the required user traffic and does not choke during periods of high load.</p><h4><strong>Testing Load Balancing</strong></h4><p>Load balancing is a critical infrastructure component that ensures traffic is evenly distributed across different modules. To test load balancing effectively:</p><ul><li>Generate load and monitor key metrics such as network throughput, request latency, and backend utilization.</li><li>Review runtime load-balancing diagrams to visualize traffic distribution among modules.</li></ul><p>Proper load balancing guarantees that the system can handle traffic spikes and reroute requests to prevent any module from being overwhelmed.</p><h4>Environment Monitoring</h4><p>Another aspect of software infrastructure testing is to routinely scan and observe environment monitoring dashboards and raise the alarm for anomalies such as</p><ul><li><strong>CPU consumption spikes: </strong>Sudden spike in CPU consumption, apart from spikes observed during performance tests</li><li><strong>Irregular memory consumption patterns: </strong>Sudden spikes in memory consumption and overall memory consumption increasing significantly could point to potential memory leaks.</li><li><strong>Excessive DB resource consumption: </strong>This points to some unintended background processes draining the DB resources, which can be backtracked through query listings.</li></ul><p>These anomalies, if left unchecked, can lead to degraded performance, service outages, or scalability issues; hence the need for regular monitoring.</p><h4>Conclusion</h4><p>In today’s age of rapidly evolving dynamics and ever increasing customer demands, testing software infrastructure is a necessity, not a luxury. Rigorous performance testing in this regard ensures that an application is resilient enough to handle unexpected situations as user traffic spike and disaster recovery.</p><p>This blog is written with the intention of familiarizing performance QA engineers with the basics of software infrastructure and basic testing techniques to verify autoscaling, high availability etc. Feel free to reach out in case of queries. Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5752b71ecd65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/performance-testing-for-software-infrastructure-101-5752b71ecd65">Performance Testing for Software Infrastructure 101</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Wishing, Start Prompting]]></title>
            <link>https://medium.com/emumba/stop-wishing-start-prompting-134d32e2e603?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/134d32e2e603</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Usman Ghani]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 09:32:09 GMT</pubDate>
            <atom:updated>2025-09-22T09:31:49.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Practical Strategies to Get the Results You Want from AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9k3VPCSq2TVR7X3e" /></figure><p>We often type a sentence into an AI model and expect it to “just get it.” When the answer falls short, we assume the model is weak. In reality, most failures come from underspecified prompts. Language models are pattern machines; they respond best to clear roles, precise tasks, rich context, explicit constraints, and a target format.</p><p>Large language models don’t “understand” like humans. They predict the next token given your input. If the input is vague, the output will be plausible but unfocused. If the input is specific and structured, the model’s search space narrows and quality rises. Clear prompts reduce ambiguity, improve reproducibility, and make it easier to evaluate whether the response meets your goal.</p><p>This guide provides examples of prompts that consistently yield the desired outcomes. You’ll see concrete examples in plain text, Markdown, and JSON.</p><h3>Key building blocks</h3><p>Think of a good prompt as a compact spec:</p><ul><li><strong>Role</strong>: who the model should “be.”</li><li><strong>Task</strong>: exactly what to produce.</li><li><strong>Context</strong>: domain, audience, constraints, source material.</li><li><strong>Output format</strong>: Markdown, JSON, or simple text with headings.</li><li><strong>Examples</strong>: a few mini demos of desired inputs and outputs.</li><li><strong>Quality bar</strong>: acceptance criteria or a brief rubric.</li></ul><p>You don’t always need every piece, but each one reduces guesswork.</p><h3>Prompt Strategies</h3><h4>Add role + task + format</h4><ul><li>Weak prompt</li></ul><blockquote>Explain Kubernetes.</blockquote><ul><li>Better prompt</li></ul><pre>Role: You are a technical instructor for junior developers.<br>Task: Explain Kubernetes in simple terms with one analogy and one real-world example.<br>Audience: Developers new to containers (0–6 months experience).<br>Format: Markdown with H2 headings and a 5-item glossary.<br>Constraints: Keep it under 300 words; avoid marketing jargon.</pre><p><strong>Why it works</strong>: you’ve constrained scope, matched tone to audience, and set a verifiable format. The analogy and example anchor the explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YYfhLA6Lb03iuGpL" /></figure><h4>Use delimiters to isolate context</h4><p>Models can blur instructions with data. Delimiters keep them separate.</p><pre>Summarize the article inside &lt;&lt;&lt;CONTEXT&gt;&gt;&gt; in 5 bullet points for executives.<br>Return only the summary, no preface text.<br><br>&lt;&lt;&lt;CONTEXT&gt;&gt;&gt;<br>[Paste article here]<br>&lt;&lt;&lt;CONTEXT&gt;&gt;&gt;</pre><p><strong>Tip:</strong> triple backticks, XML tags, or custom tokens all work. The point is consistent boundaries.</p><h4>Request structured outputs</h4><p>If another tool needs to parse the answer, request JSON with a minimal schema. This turns prose into data.</p><p>Plain text request → JSON output</p><pre>Extract company insights from the review below. Return valid JSON only.<br><br>Schema:<br>{<br>  &quot;company&quot;: string,<br>  &quot;sentiment&quot;: &quot;positive&quot; | &quot;neutral&quot; | &quot;negative&quot;,<br>  &quot;aspects&quot;: string[],   // e.g., [&quot;support&quot;, &quot;pricing&quot;]<br>  &quot;summary&quot;: string<br>}<br><br>Review:<br>&quot;&quot;&quot;<br>Switching to Acme reduced our monthly bill, but their support replies were slow at first…<br>&quot;&quot;&quot;</pre><p><strong>Why it works:</strong> the schema narrows choices and reduces free-form rambling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*krYOmhaz3or5VcIW" /></figure><h4>Few-shot prompting (show, don’t just tell)</h4><p>Provide one to three miniature examples that demonstrate the pattern you expect.</p><pre>You are a resume editor. Improve concision and impact.<br><br>Examples:<br>Input: &quot;Responsible for managing CI/CD.&quot;<br>Output: &quot;Owned CI/CD pipelines, cutting build times 35%.&quot;<br><br>Input: &quot;Worked on frontend tasks.&quot;<br>Output: &quot;Built React components used by 120k MAU; reduced bundle size 18%.&quot;<br><br>Task:<br>Rewrite the following bullet in the same style, max 18 words:<br>&quot;Helped with API documentation for internal teams.&quot;</pre><p><strong>Why it works:</strong> examples anchor tone, length, and structure. The model imitates patterns more reliably than abstract instructions.</p><h4>Plan–Then–Produce (without exposing internal reasoning)</h4><p>Encourage the model to plan, but ask it to output only the final product and a brief rationale. A <strong>rationale</strong> is a brief “why” statement that follows an answer. It summarizes the key reason or trade-off behind the output, without showing step-by-step thinking.</p><p><strong>Template</strong></p><pre>Task: Draft a 2-paragraph risk assessment for migrating from MySQL to Postgres.<br><br>Process: First plan the outline internally. Then produce the final text.<br>Output: Provide only the final assessment plus a 2-sentence rationale explaining the main trade-off.</pre><p><strong>Output</strong></p><pre>[Two concise paragraphs with the assessment.]<br><br>Rationale: Prioritized data consistency over write latency because payment records must be correct; key risks are replication lag and type differences.</pre><p><strong>Why it works:</strong> nudges the model to think before writing, yet keeps the output tight and auditable.</p><h4>Add a lightweight rubric</h4><p>A <strong>rubric</strong> is a tiny scoring guide that turns “this looks good” into something you can test and repeat. Instead of relying on gut feel, you define 3–5 criteria (for example, accuracy, clarity, usefulness) and a simple scale (0–5).</p><p>The model then checks its own output against those criteria, or you can use the rubric to review results after generation.</p><p>Benefits:</p><ul><li>Quality is measurable</li><li>Helps you compare multiple drafts</li><li>Accelerates iteration</li></ul><p>Rubric design checklist (keep it light):</p><ul><li>Pick <strong>3–5 criteria</strong> aligned to your goal and audience.</li><li>Use a <strong>0–5 scale</strong> with short descriptions (0 = missing, 5 = excellent).</li><li>Make each criterion <strong>observable</strong> (avoid vague words like “nice”).</li><li>Set a <strong>pass threshold</strong> (e.g., average ≥4) so “good enough” is clear.</li></ul><p>Here’s the clean flow:</p><ol><li>Generate a draft</li></ol><pre>Task: Write a 2-paragraph intro to Kubernetes for beginners.<br>[MODEL OUTPUT = the draft we will evaluate]</pre><p><strong>2.</strong> Evaluate the draft using the rubric</p><pre>Act as a peer reviewer. Evaluate the response below against this rubric (0–5 each):<br>- Accuracy<br>- Clarity<br>- Usefulness<br><br>Return a JSON scorecard only (valid JSON, no comments) with:<br>{ &quot;scores&quot;: {...}, &quot;average&quot;: number, &quot;pass_threshold&quot;: 4, &quot;passed&quot;: boolean, &quot;improvement_tip&quot;: string }<br><br>If average &lt; pass_threshold, add one focused tip that would raise the lowest score on the next draft.<br><br>RESPONSE TO EVALUATE:<br>&lt;&lt;&lt;MODEL OUTPUT FROM STEP 1&gt;&gt;&gt;</pre><p><strong>3.</strong> Revise</p><pre>Revise the draft below. Keep structure; target the lowest-scoring criterion first.<br>Return only the improved draft.<br><br>DRAFT:<br>&lt;&lt;&lt;MODEL OUTPUT FROM STEP 1&gt;&gt;&gt;<br>TIP:<br>&lt;&lt;&lt;improvement_tip from scorecard&gt;&gt;&gt;</pre><h4>Iterative prompting: tighten with deltas, not rewrites</h4><p>When the model misses, don’t start over. Give a targeted correction. But…</p><p>Models are not mind readers. Your <strong>first prompt should contain ~80% of what you already know</strong> about the desired outcome: the goal, audience, scope, format, constraints, and success criteria. Leave only the final 20% for iteration. If you cannot articulate that first 80%, pause and define it; otherwise, you’ll get plausible fluff.</p><p><strong>Weak Start</strong></p><blockquote>Explain Kubernetes.</blockquote><p><strong>80% Start</strong></p><pre>Role: Senior instructor for junior developers (0–6 months with containers).<br>Task: Explain Kubernetes in plain language so a beginner can describe what it does and why it’s useful.<br>Audience: New developers; no prior K8s experience.<br>Scope: What it is, how it schedules/replicates containers, why teams use it.<br>Format: Markdown with an H2 “Overview” containing exactly two paragraphs, then an H2 “Glossary” with 3 items.<br>Constraints: 160–220 words total; define acronyms on first use; include ONE sports analogy and ONE real-world example (autoscaling a web app); avoid marketing language.<br>Acceptance Criteria: Mentions pods, nodes, scaling; the example shows traffic spikes; no unexplained jargon.</pre><p>This first prompt is already precise and testable. Now the model has a small search space and is more likely to hit your target on the first pass, but if you feel some points are missed, revise the request.</p><pre>Revision request (for the draft you just produced):<br>- Keep the existing structure and headings.<br>- Reduce Paragraph 2 in “Overview” by ~40% to remove repetition.<br>- Replace the sports analogy with a logistics metaphor (warehouses, shipments).<br>- Add a one-line TL;DR at the very top (≤ 20 words).<br>Return only the revised Markdown.</pre><p>This preserves the useful parts, speeds convergence, and keeps the model aligned with your original intent. The 80–20 approach sets the target; <strong>delta revisions</strong> walk the last mile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UtP6ghcPeMh7fKOC" /></figure><p>Before you hit Enter, decide how you’ll use the response. Format isn’t decoration; it sets boundaries for the model and influences what happens next, whether you’ll skim it with a teammate, paste it into a document, or pipe it into a script. Choose the right container up front to boost accuracy, enable reuse, and make review easier.</p><h3>Pick the Right Output Format</h3><h4>Simple text</h4><p>Best for quick tasks, brainstorming, or where human reading is primary. Keep instructions compact and explicit. Use delimiters to separate instructions and data.</p><h4>Markdown</h4><p>Ideal when structure matters to humans: headings, lists, code blocks, callouts. You can specify section counts, required headings, or tables.</p><pre>## Executive Summary<br>[80–120 words]<br><br>## Risks<br>- [3 bullets]<br><br>## Mitigations<br>- [3 bullets]</pre><h4>JSON</h4><p>Best for machine-readability, pipelines, and validations. Always define a mini schema, required fields, and value ranges. Ask for “valid JSON only, no comments.”</p><pre>{<br>  &quot;title&quot;: &quot;Weekly Incident Report&quot;,<br>  &quot;incidents&quot;: [<br>    {<br>      &quot;id&quot;: &quot;INC-2025-09-16-01&quot;,<br>      &quot;severity&quot;: &quot;high&quot;,<br>      &quot;systems&quot;: [&quot;billing-api&quot;, &quot;redis-cache&quot;],<br>      &quot;impact_summary&quot;: &quot;string&quot;,<br>      &quot;customer_visible&quot;: true<br>    }<br>  ],<br>  &quot;owner&quot;: &quot;SRE on-call&quot;<br>}</pre><h3>Conclusion</h3><p><strong>Good prompting is an applied specification.</strong> When you define role, task, context, constraints, and format, you remove ambiguity and give the model something concrete to optimize against. Start simple, add structure where it pays off, and evolve to include examples, rubrics, and iterative refinement as you progress.</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134d32e2e603" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/stop-wishing-start-prompting-134d32e2e603">Stop Wishing, Start Prompting</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playwright vs. WebdriverIO: How to Choose the Right Framework?]]></title>
            <link>https://medium.com/emumba/playwright-vs-webdriverio-how-to-choose-the-right-framework-512f428f7f86?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/512f428f7f86</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Usman Ghani]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 12:32:55 GMT</pubDate>
            <atom:updated>2025-09-15T12:31:39.554Z</atom:updated>
            <content:encoded><![CDATA[<h4>Guide for SDETS/QA to choose between the two frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UcM0HODBvOQGEL2x" /></figure><p>You’ve got a web app to ship and a mandate to “get UI automation running this sprint.” Two names dominate the conversation: <strong>Playwright</strong> and <strong>WebdriverIO (WDIO)</strong>. Both are powerful, both are popular — and both can pass your smoke suite tomorrow. So which one should you bet on?</p><p>This guide offers a practical, beginner-friendly comparison and a straightforward decision-making path, enabling you to choose confidently and start shipping tests.</p><p>Choosing a framework isn’t just a tooling preference — it shapes your <strong>developer experience</strong>, <strong>test stability</strong>, <strong>CI/CD setup</strong>, and even <strong>team onboarding</strong>. Make an incompatible choice and you’ll spend weeks fighting flaky waits, puzzling over integrations, or wrestling with a plugin ecosystem you didn’t need. Pick right and you’ll be writing reliable, maintainable tests by the end of the day.</p><h3>What “DX” Means</h3><p>Developer Experience (DX) is the overall quality of a developer’s journey with a tool. It spans installation, first run, day-to-day authoring, debugging, and scaling in CI. Good DX lowers cognitive load and removes busywork: it turns common failures into clear, actionable feedback so you spend time testing product risks, not wrestling the framework.</p><p>In this blog’s comparison, “great DX” means the framework helps you with:</p><ul><li><strong>Fast setup &amp; time‑to‑first‑test</strong> — minimal steps to install, scaffold, and see a passing test.</li><li><strong>Clear docs &amp; error messages</strong> — answers are easy to find; failures explain what to fix next.</li><li><strong>Good defaults</strong> — sensible APIs, resilient locators, and built‑in auto‑waiting so you write less glue code.</li><li><strong>Built‑in tooling</strong> — trace/screenshot/video artefacts, codegen, and helpful CLIs/UX for triage.</li><li><strong>Easy CI integration &amp; parallel runs</strong> — straightforward Docker/Actions examples and horizontal scale without extra plumbing.</li></ul><p><strong>How does this map in our Playwright vs. WebdriverIO context:</strong></p><ul><li>With Playwright, DX shows up in a batteries-included test runner, the Locator API’s auto-waiting, and the Trace Viewer, which ships by default.</li><li>With <strong>WebdriverIO</strong>, DX shows up as the interactive config wizard, a rich services ecosystem (cloud grids, reporters, image comparison), and first‑class BDD via Cucumber when teams prefer feature files.</li></ul><p>Throughout this comparison, we’ll use these DX criteria to help you map each framework’s strengths to your project’s needs.</p><h3>Hands‑on DX: getting your first test green</h3><h4><strong>Playwright quick start (TypeScript)</strong></h4><pre>// tests/example.spec.ts<br>import { test, expect } from &#39;@playwright/test&#39;;<br><br><br>test(&#39;homepage has docs link&#39;, async ({ page }) =&gt; {<br>await page.goto(&#39;https://example.com&#39;);<br>await expect(page.getByRole(&#39;link&#39;, { name: &#39;More information...&#39; })).toBeVisible();<br>});</pre><ul><li><strong>DX lens:</strong> npx playwright test gives you parallel runs, an HTML report, traces, screenshots, videos, and a powerful Locator API that re-queries the DOM and waits for actionability conditions automatically.</li><li>Result: excellent <strong>time-to-first-green</strong> with strong defaults for stability.</li></ul><h4>WebdriverIO quick start (Mocha style):</h4><pre>// test/specs/example.e2e.js<br>describe(&#39;homepage&#39;, () =&gt; {<br>   it(&#39;shows docs link&#39;, async () =&gt; {<br>       await browser.url(https://medium.com/&#39;https://example.com&#39;);<br>       const link = await $(&#39;=More information...&#39;);<br>       await expect(link).toBeDisplayed();<br>   });<br>});</pre><ul><li><strong>DX lens:</strong> npx wdio run wdio.conf.js (created via the interactive config wizard) plus, services and reporters give you great <strong>customizability</strong>, especially if your org standardizes on Selenium/WebDriver, cloud grids, or BDD.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSEIKyJ2kypbhXh2" /></figure><h3>Stability and flakiness (DX factor: good defaults)</h3><p>Flaky tests are usually timing problems disguised as bugs.</p><ul><li><strong>Playwright’s Locator + auto‑waiting</strong> reduces the need for explicit waits. It waits for the element to be visible, stable, and ready for interaction before clicking or asserting. <strong>Cause → effect → implication:</strong> fewer timing bugs → fewer retries → <strong>more trust</strong> in nightly runs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*tatJj9Et1A9Ps50e" /></figure><ul><li><strong>WebdriverIO</strong> offers implicit waits, e.g. waitUntil, and matcher helpers (e.g., toBeDisplayed). It’s powerful and flexible, but in practice, you may sprinkle more explicit waits or use helper utilities to achieve the same “always stable” feel that Playwright bakes in by default.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PGrF7BLKgnF4xR5W" /></figure><h3>Docs, errors, and onboarding (DX factor: clarity)</h3><ul><li><strong>Playwright</strong> has highly opinionated docs and examples that match the shipped defaults (runner, fixtures, locators). Error messages often point to actionability issues and suggest fixes.</li><li><strong>WebdriverIO</strong> has comprehensive docs across many stacks (Mocha/Jasmine/Cucumber), plus an interactive config wizard. Breadth is a strength; for beginners, the flexibility means a few more choices up front.</li></ul><h3>CI/CD and parallelism (DX factor: easy scaling)</h3><h4><strong>Playwright</strong>:</h4><ul><li>Parallelization is native; The Playwright <strong>test runner</strong> has built‑in scheduling and concurrency. It automatically splits your tests across multiple <strong>worker processes</strong> without extra plugins. You control it with a single setting or CLI flag.</li><li>GitHub Actions examples and Docker images are straightforward.</li><li>You get the reliable artefacts (traces, screenshots, videos, HTML report) by default.</li><li>Playwright’s concurrency is <strong>built in and simple to turn on.</strong></li></ul><p><strong>Config:</strong></p><pre>// playwright.config.ts<br>import { defineConfig } from &#39;@playwright/test&#39;;<br>export default defineConfig({<br>  workers: &#39;50%&#39;, // use half of available CPU cores<br>  fullyParallel: true, // allow tests to run in parallel<br>  reporter: [[&#39;html&#39;], [&#39;line&#39;]],<br>  use: { trace: &#39;on-first-retry&#39;, video: &#39;retain-on-failure&#39;, screenshot: &#39;only-on-failure&#39; }<br>});</pre><p><strong>CLI:</strong></p><pre>npx playwright test --workers=4</pre><h4><strong>WebdriverIO</strong></h4><ul><li>Scales via workers and integrates smoothly with <strong>cloud grids</strong>.</li><li>WDIO’s <strong>runner</strong> spawns one or more <strong>worker processes</strong> per spec/capability. You dial up concurrency with maxInstances (global or per capability) in the config file.</li><li>It’s flexible and plays well with <strong>cloud grids</strong> (BrowserStack, Sauce Labs) and enterprise <strong>Selenium Grid</strong> via services, but that also means a bit more configuration.</li><li>WDIO’s concurrency is <strong>highly configurable</strong> and excels when you’re orchestrating many remote sessions on cloud grids.</li></ul><pre>// wdio.conf.js<br>export const config = {<br>  maxInstances: 4, // number of parallel workers per capability<br>  services: [&#39;chromedriver&#39;], // or [&#39;sauce&#39;], [&#39;browserstack&#39;], [&#39;selenium-standalone&#39;]<br>  reporters: [&#39;spec&#39;],<br>  capabilities: [{<br>  browserName: &#39;chrome&#39;,<br>   &#39;goog:chromeOptions&#39;: { args: [&#39;--headless=new&#39;] }<br>  }]<br>};<br>// run: npx wdio run wdio.conf.js</pre><p>Before choosing based on DX alone, zoom out: your surrounding ecosystem, including your BDD workflow, cloud-grid alignment, and whether you need one runner for web and mobile, is often the deciding factor. The next section maps common scenarios to the tool that fits best.</p><h3>Ecosystem fit: when each shines</h3><h4>Choose <strong>Playwright</strong> if you want:</h4><ul><li>A <strong>single, integrated tool</strong> (runner, assertions, parallelization, trace viewer, codegen)</li><li>Fast, reliable <strong>cross‑browser</strong> (Chromium, Firefox, WebKit) with great debugging artefacts</li><li>A modern <strong>locator</strong> philosophy that minimizes explicit waits</li><li>A small‑to‑mid‑size <strong>web‑only</strong> project where speed and maintainability trump everything</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmDb-SzjULRD3e0chYlTwA.png" /></figure><h4>Choose <strong>WebdriverIO</strong> if you need:</h4><ul><li>Strong <strong>BDD (Cucumber)</strong> support, or your team prefers feature files and step definitions</li><li><strong>Cloud grid</strong> and Selenium ecosystem alignment (BrowserStack/ Saucelabs / enterprise Selenium Grid)</li><li>A single runner across <strong>web + mobile</strong> (via <strong>Appium</strong>) and multi‑project setups</li><li>Deep customization via <strong>services</strong> (DevTools, ChromeDriver, image comparison, cloud integrations)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQ2oRD-ZkM6cL-iolL4U_g.png" /></figure><h3>Conclusion / CTA</h3><p>There’s no universal winner. The better choice is the one that fits your first project’s constraints. If your immediate goal is to stand up a reliable web UI suite within a week with minimal decisions, start with <strong>Playwright</strong>. If your roadmap includes <strong>Cucumber</strong>, <strong>Appium</strong>, or deep <strong>cloud grid</strong> usage, consider <strong>WebdriverIO</strong> as your long-term anchor.</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512f428f7f86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/playwright-vs-webdriverio-how-to-choose-the-right-framework-512f428f7f86">Playwright vs. WebdriverIO: How to Choose the Right Framework?</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Solution to Automate S3-to-Tableau Data Pipelines]]></title>
            <link>https://medium.com/emumba/serverless-solution-to-automate-s3-to-tableau-data-pipelines-c44d3212eeaa?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/c44d3212eeaa</guid>
            <dc:creator><![CDATA[Mahak Urooj]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 12:35:10 GMT</pubDate>
            <atom:updated>2025-08-18T12:35:10.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg2YuRP8jceUGmSOSD55hA.png" /></figure><p>In today’s fast-paced digital landscape, building real-time dashboards for data-driven decision-making is more critical than ever. As data trends evolve rapidly, delays in updating dashboards can lead to missed opportunities and hinder timely insights. Tableau, a widely adopted analytics and dashboarding tool, offers native connectors to various cloud platforms, making it well-suited for real-time or near real-time data ingestion.</p><p>Today we’ll explore a problem statement where application data is received daily in the form of CSV files, which are stored in date-based subfolders within an Amazon S3 bucket. As days progress, additional CSV files continue to accumulate in new folders. However, Tableau supports connecting only to a <strong>single CSV file</strong> within an S3 bucket, which poses a challenge:</p><p><em>How can we ensure Tableau accesses up-to-date data without manual consolidation?</em></p><p>To address this, we need a solution that automatically merges daily CSV data into a single, continually updated file or provides a structured way for Tableau to access and query this data without manual intervention.</p><p>This article outlines <strong>two fully serverless AWS-based solutions</strong> to automate the S3-to-Tableau data pipeline — ensuring Tableau receives consistent data updates and dashboards remain synchronized with the latest information.</p><h3>Proposed Solutions:</h3><ol><li><strong>AWS Lambda + Master CSV<br></strong> A lightweight Lambda function merges incoming daily CSVs into a single rolling <strong>master.csv</strong> file that Tableau can directly import.</li><li><strong>AWS Glue Crawler + AWS Glue Data Catalog + Athena<br></strong> A managed AWS Glue Crawler automatically discovers new files and schemas, while Athena enables SQL-based querying that Tableau can leverage using its Athena connector.</li></ol><p><strong>Note</strong>: Throughout this article, replace placeholders with your actual S3 bucket name and prefixes such as:</p><ul><li>YOUR_BUCKET_NAME</li><li>raw-data-prefix/</li><li>master-data-prefix/</li></ul><h3>Solution 1: AWS Lambda + Master CSV</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtTzPSeECtDHlsbAiaoFQA.png" /></figure><h4>Architecture Overview</h4><p><strong>S3 Event Trigger</strong></p><ul><li>Fires AWS Lambda when new CSV files arrive within the specified folder of an S3 Bucket</li></ul><p><strong>Lambda Function</strong></p><ul><li>Reads a state marker (<em>last_processed.txt</em>) to determine which folders have been processed.</li><li>Downloads the existing <em>master.csv</em> from S3 <em>(if it exists)</em> to seed the merge.</li><li>Streams and concatenates only new CSV files from unprocessed date folders.</li><li>Uploads the updated <em>master.csv</em> directly to S3 and updates the <em>last_processed.txt</em> marker.</li></ul><p><strong>Tableau</strong>:</p><ul><li>Connects directly to the static <em>master.csv</em> in S3 using the native S3 connector or as an external file source.</li></ul><h4>Prerequisites</h4><ul><li>AWS account with S3 and Lambda permissions.</li><li>IAM user or role with rights to create and manage Lambda functions, IAM roles, and S3 resources.</li></ul><h4>Step 1: Create the S3 Bucket &amp; Folder Structure</h4><p>In the AWS Console, navigate to <strong>Amazon S3 </strong>service and click <strong>“Create bucket.” </strong>Name your bucket as YOUR_BUCKET_NAME.</p><p>Once the bucket is created, set up the folder<em> (prefix)</em> structure:</p><ol><li>Inside the bucket, create a folder for raw data/daily data dumps: <em>raw-data-prefix/.</em></li><li>Within this folder, upload at least one subfolder named in YYYY-MM-DD/ format <em>(e.g., 2025–07–10/)</em>, and place sample CSV files such as <em>regionA.csv</em> and <em>regionB.csv</em> inside it.</li></ol><p>Next, create another folder at the root level of the same bucket to store the consolidated output:</p><ul><li><em>master-data-prefix/</em> — this is where the merged <em>master.csv</em> will be stored.</li></ul><h4>Step 2: Create an IAM Role for Lambda</h4><p>In the <strong>AWS Console</strong>, navigate to <strong>IAM</strong> → <strong>Roles</strong>, and click <strong>“Create role.”<br></strong> This will guide you through a 3-step role creation process:</p><ol><li><strong>Select trusted entity</strong></li></ol><ul><li>Choose <strong>AWS service</strong> as the trusted entity type.</li><li>Select <strong>Lambda</strong> as the use case.</li><li>Click <strong>Next</strong>.</li></ul><p><strong>2. Add permissions</strong></p><ul><li>Attach the managed policy: <strong>AWSLambdaBasicExecutionRole</strong>.</li><li>Click <strong>Next</strong>.</li></ul><p><strong>3. Name, review and create</strong></p><ul><li>Enter a name for your role, e.g.: <em>lambda-s3-master-role.</em></li><li>Click <strong>Create role</strong>.</li></ul><p>Once the role is created:</p><ol><li>Navigate to the <strong>Permissions</strong> → “Add inline policy” of the newly created role.</li><li>In the policy editor, switch to the <strong>JSON</strong> tab and paste the following policy:</li></ol><pre>{<br> &quot;Version&quot;: &quot;2012–10–17&quot;,<br> &quot;Statement&quot;: [<br> {<br> &quot;Effect&quot;: &quot;Allow&quot;,<br> &quot;Action&quot;: [&quot;s3:ListBucket&quot;],<br> &quot;Resource&quot;: &quot;arn:aws:s3:::YOUR_BUCKET_NAME&quot;<br> },<br> {<br> &quot;Effect&quot;: &quot;Allow&quot;,<br> &quot;Action&quot;: [&quot;s3:GetObject&quot;,&quot;s3:PutObject&quot;],<br> &quot;Resource&quot;: &quot;arn:aws:s3:::YOUR_BUCKET_NAME/*&quot;<br> }<br> ]<br>}</pre><p>3. Click <strong>Next</strong> and name the policy LambdaS3AccessPolicy, and finally click on button <strong>Create policy</strong>.</p><p>You have now successfully created an IAM Role with the necessary permissions to access the S3 bucket and perform read and write operations.</p><h4>Step 3: Create the Lambda Function</h4><ol><li>Navigate to <strong>Lambda </strong>service<strong> → Create function</strong>.</li><li>Choose option “<strong>Author from scratch” to </strong>create the function.</li><li>Add the following settings for the Lambda function:</li></ol><ul><li>Function name: merge-daily-csvs <em>(our one of your choice)</em></li><li>Runtime: <strong>Python 3.9</strong> <em>(or higher).</em></li></ul><p>4. Under <strong>Permissions</strong>, select <strong>Use an existing role</strong> and choose IAM role we created earlier i.e. <em>lambda-s3-master-role</em>.</p><p>5. Click <strong>Create function</strong>.</p><h4>Step 4: Deploy the Lambda Code</h4><ol><li>In your lambda function’s <strong>Code</strong> tab, delete any default code.</li><li>Copy and paste the complete Python code below into <em>lambda_function.py</em>:</li></ol><pre>import os<br>import boto3<br>import csv<br>from io import StringIO<br>from datetime import datetime, timezone<br><br>s3 = boto3.client(&#39;s3&#39;)<br><br># ─── Configuration ──────────────────────────────────────────────<br>BUCKET        = os.environ.get(&#39;BUCKET&#39;, &#39;YOUR_BUCKET_NAME&#39;)<br>BASE_PREFIX   = os.environ.get(&#39;BASE_PREFIX&#39;, &#39;lambda/raw/&#39;)<br>MASTER_PREFIX = os.environ.get(&#39;MASTER_PREFIX&#39;, &#39;lambda/master/&#39;)<br>MASTER_KEY    = f&quot;{MASTER_PREFIX}master.csv&quot;<br>MARKER_KEY    = f&quot;{MASTER_PREFIX}last_processed.txt&quot;<br># ────────────────────────────────────────────────────────────────<br><br>def lambda_handler(event, context):<br>    print(&quot;Lambda triggered&quot;)<br><br>    # 1️⃣ Load last processed marker<br>    try:<br>        resp = s3.get_object(Bucket=BUCKET, Key=MARKER_KEY)<br>        last_processed = resp[&#39;Body&#39;].read().decode(&#39;utf-8&#39;).strip()<br>        print(&quot;Last processed date:&quot;, last_processed)<br>    except s3.exceptions.NoSuchKey:<br>        last_processed = &quot;0000-00-00&quot;<br>        print(&quot;No marker found; processing all folders&quot;)<br><br>    # 2️⃣ List all folders under raw/<br>    paginator = s3.get_paginator(&#39;list_objects_v2&#39;)<br>    all_folders = []<br>    for page in paginator.paginate(Bucket=BUCKET, Prefix=BASE_PREFIX, Delimiter=&#39;/&#39;):<br>        all_folders += [p[&#39;Prefix&#39;] for p in page.get(&#39;CommonPrefixes&#39;, [])]<br><br>    folders_to_proc = [<br>        p for p in all_folders<br>        if p.rstrip(&#39;/&#39;).split(&#39;/&#39;)[-1] &gt; last_processed<br>    ]<br>    if not folders_to_proc:<br>        print(&quot;✅ No new folders — nothing to do&quot;)<br>        return<br>    folders_to_proc.sort()<br>    print(&quot;Folders to process:&quot;, folders_to_proc)<br><br>    # 3️⃣ Start output buffer<br>    output = StringIO()<br>    writer = csv.writer(output)<br>    header_written = False<br><br>    try:<br>        resp = s3.get_object(Bucket=BUCKET, Key=MASTER_KEY)<br>        output.write(resp[&#39;Body&#39;].read().decode(&#39;utf-8&#39;))<br>        header_written = True<br>        print(&quot;✅ Seeded with existing master.csv&quot;)<br>    except s3.exceptions.NoSuchKey:<br>        print(&quot;ℹ️ No existing master.csv found — starting fresh&quot;)<br><br>    # 4️⃣ Process new files<br>    for prefix in folders_to_proc:<br>        print(&quot;→ Scanning folder:&quot;, prefix)<br>        result = s3.list_objects_v2(Bucket=BUCKET, Prefix=prefix)<br>        if &#39;Contents&#39; not in result:<br>            print(&quot;⚠️ No files found in&quot;, prefix)<br>            continue<br><br>        for obj in result[&#39;Contents&#39;]:<br>            key = obj[&#39;Key&#39;]<br>            if not key.lower().endswith(&#39;.csv&#39;):<br>                continue<br>            print(&quot;   Processing:&quot;, key)<br>            try:<br>                body = s3.get_object(Bucket=BUCKET, Key=key)[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>                reader = csv.reader(StringIO(body))<br>                header = next(reader)<br>                if not header_written:<br>                    writer.writerow(header)<br>                    header_written = True<br>                writer.writerows(reader)<br>            except Exception as e:<br>                print(&quot;❌ Error reading&quot;, key, &quot;:&quot;, str(e))<br><br>    # 5️⃣ Upload new master<br>    output.seek(0)  # 🔧 Required to reset pointer before reading buffer<br>    s3.put_object(<br>        Bucket=BUCKET,<br>        Key=MASTER_KEY,<br>        Body=output.getvalue().encode(&#39;utf-8&#39;)<br>    )<br>    print(f&quot;📄 Wrote up-to-date master to {MASTER_KEY}&quot;)<br><br>    # 6️⃣ Update marker<br>    newest_date = folders_to_proc[-1].rstrip(&#39;/&#39;).split(&#39;/&#39;)[-1]<br>    s3.put_object(<br>        Bucket=BUCKET,<br>        Key=MARKER_KEY,<br>        Body=newest_date.encode(&#39;utf-8&#39;)<br>    )<br>    print(f&quot;📝 Updated marker to {newest_date}&quot;)</pre><p>3. Click <strong>Deploy </strong>to deploy your code.</p><h4>Step 5: Configure S3 Trigger</h4><p>Next, configure a trigger for the Lambda function so that it runs automatically whenever the specified condition is met. This ensures the pipeline remains fully automated and eliminates the need for manual intervention.</p><ol><li>In Lambda function’s <strong>Configuration Tab → Triggers</strong>, click <strong>Add trigger</strong> and add following settings:</li></ol><ul><li>Select <strong>S3</strong>, choose YOUR_BUCKET_NAME.</li><li>Event type: <strong>PUT</strong>.</li><li>Prefix: raw-data-prefix/, Suffix: .csv.</li><li>Runtime: <strong>Python 3.9</strong> <em>(or higher).</em></li></ul><p>2. Click button <strong>Add</strong>.</p><p>You have now successfully set up an automated pipeline that automatically triggers the Lambda function whenever a new CSV file is uploaded to the S3 bucket, ensuring the data is seamlessly consolidated into a single master CSV file.</p><h4>Step 6: Test and Verify</h4><p>To test and verify your solution, follow these steps:</p><ol><li>Upload a new folder YYYY-MM-DD/ with CSV files under <em>raw-data-prefix/.</em></li><li>In <strong>CloudWatch Logs</strong>, check <em>/aws/lambda/merge-daily-csvs </em>for execution logs where you’ll be able to see that a new <em>master.csv</em> file is created in the same s3 bucket.</li><li>Confirm <em>master.csv</em> and <em>last_processed.txt</em> under <em>master-data-prefix/.</em></li></ol><p>With the first solution in place, it’s time to dive into the second serverless approach.</p><h3>Option 2: AWS Glue Crawler + Glue Data Catalog + Athena</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lVhysRd8GfFOjlhxROFVw.png" /></figure><h4>Architecture Overview</h4><ul><li><strong>AWS Glue Crawler</strong>: Scans S3 daily and catalogs CSV schema and partitions.</li><li><strong>AWS Glue Data Catalog</strong>: Stores metadata and table definitions.</li><li><strong>Amazon Athena</strong>: Executes SQL queries over the cataloged data.</li><li><strong>Tableau</strong>: Connects via Athena ODBC/JDBC driver for live queries.</li></ul><h4>Prerequisites</h4><ul><li>AWS account with Glue, Athena, and S3 Bucket permissions.</li><li>IAM role for Glue with AWSGlueServiceRole and S3 read access.</li><li>An Athena workgroup (optional).</li></ul><p>Here’s a step by step guide on how we can configure AWS Glue Crawler to scan our daily CSV files coming up in S3 Bucket</p><h3>Step 1: Create the Glue Crawler</h3><p>In the AWS Console, navigate to <strong>AWS Glue → Crawlers → Add crawler</strong>.</p><ol><li><strong>Name your crawler</strong>:</li></ol><ul><li>Enter a unique name, such as “<em>daily-s3-crawler</em>”. Optionally, you may add a description to clarify the crawler’s purpose. Click <strong>Next</strong>.</li></ul><p><strong>2. Configure the data source</strong>:</p><ul><li>Choose <strong>S3</strong> as the data store.</li><li>Set the path to point to your S3 bucket (e.g., <em>s3://YOUR_BUCKET_NAME/raw-data-prefix/)</em>.</li><li>For crawler behavior, select <strong>“Crawl new sub-folders only”</strong> to ensure only newly added folders are processed, avoiding redundancy.</li><li>Once configured, add the data source and click <strong>Next</strong>.</li></ul><p><strong>3. Set up security</strong>:</p><ul><li>Choose an existing IAM role or create a new one that includes both <strong>AWSGlueServiceRole</strong> and <strong>S3</strong> read permissions.</li></ul><p><strong>4. Define output and schedule</strong>:</p><ul><li>Choose to create a new Glue database (<em>e.g., daily_data_db</em>) or select an existing one.</li><li>Set the crawler schedule to either <strong>Run on demand</strong> or define a schedule (<em>e.g., daily at 00:15 UTC</em>).</li></ul><p><strong>5. Review and complete</strong>:</p><ul><li>Review all settings and click <strong>Finish</strong>.</li></ul><p>Congratulations! Your crawler is now configured and ready to scan your S3 data.</p><h4>Step 2: Run the Crawler &amp; Validate</h4><p>Select your crawler and click <strong>Run crawler</strong> if you have configured it to run on demand.</p><p>Once the crawler completes its run, navigate to <strong>AWS Glue → Tables</strong>. You should now see a table <em>(e.g., raw_data_prefix) </em>that includes partitions organized by date. The table is typically named after the folder path where the daily CSV files are stored.</p><p>You’ll observe that the table includes data from all the CSV files present in your S3 bucket. In AWS Glue, partitions act like virtual folders — each partition corresponds to a sub-folder within your S3 bucket, allowing for efficient querying and organization based on those subdirectories.</p><h4>Step 3: Query Data in Athena</h4><ol><li>Open <strong>Amazon Athena</strong>.</li><li>In <strong>Query Editor</strong>, select the database daily_data_db.</li><li>Run the following sample query, you’ll be able to view the data for the specified date.</li></ol><pre>SELECT *<br>FROM raw_data_prefix<br>WHERE date = current_date;</pre><h4>Step 4: Connect Tableau to Athena</h4><ol><li>In Tableau Desktop, click <strong>Connect → Amazon Athena</strong>.</li><li>Enter your AWS credentials or use <strong>IAM Role</strong> if on EC2.</li><li>Select your <strong>region</strong>, S3 staging directory (e.g., <em>s3://YOUR_BUCKET_NAME/query-results/)</em>.</li><li>Choose the database daily_data_db and your table.</li><li>Build and publish dashboards that automatically reflect daily updates.</li></ol><p>We’ve now walked through a detailed, step-by-step guide on how to consolidate daily data dumps — uploaded as CSV files into an Amazon S3 bucket — and make them accessible to Tableau without requiring any manual intervention. Both solutions presented offer a fully automated, serverless setup to keep your Tableau dashboards up-to-date in near real-time.</p><p>Next, let’s compare the two solutions in terms of their <strong>advantages, trade-offs, and associated costs</strong>.</p><h3>Comparison: Pros, Cons &amp; Costs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JyzKdJULQLZoHLltYRy1w.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fn2dRH%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fn2dRH%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fn2dRH%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="525" frameborder="0" scrolling="no"><a href="https://medium.com/media/085702f4d83ae3b195707bec7fede19d/href">https://medium.com/media/085702f4d83ae3b195707bec7fede19d/href</a></iframe><h3><strong>When to choose Lambda solution</strong></h3><ul><li>You have small-to-medium daily CSVs (&lt;100 MB/day).</li><li>You need immediate updates on file arrival.</li><li>You prefer minimal AWS services and nearly zero cost.</li></ul><h3><strong>When to choose Glue + Athena solution</strong></h3><ul><li>You expect schema evolution or large data volumes.</li><li>You prefer SQL querying and partition pruning.</li><li>You can tolerate slight delays based on crawler schedule.</li></ul><h3><strong>Conclusion</strong></h3><p>Both solutions deliver a serverless pipeline to make daily S3 CSV dumps available in Tableau:</p><ul><li><strong>Lambda + Master CSV</strong> is ideal for ultra-simple, near real-time merging.</li><li><strong>Glue Crawler + Athena</strong> offers robust schema management and SQL-based analytics at scale.</li></ul><p>Select the pattern that best fits your data volume, freshness requirements, and operational overhead.</p><p>Happy Learning!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyYQFZx1hITZxfbLuneyHA.png" /></figure><h3>References</h3><p>Here are some resources to learn more about the services used in these solutions:</p><ol><li><a href="https://aws.amazon.com/s3/?nc=sn&amp;loc=1&amp;refid=6f994a6a-dde0-4a5a-9b7d-16470c6f35bd">AWS S3</a></li><li><a href="https://aws.amazon.com/pm/lambda/?trk=bc544035-c62f-4265-a610-fe68e4271715&amp;sc_channel=ps&amp;ef_id=Cj0KCQjwnovFBhDnARIsAO4V7mCCByfsQVJMGwqnICXwr4FsGdy1C4ARy8b_yTDxpGu8ymxgwDxSmWYaAptsEALw_wcB:G:s&amp;s_kwcid=AL!4422!3!651510255294!e!!g!!aws%20lambda!19828212645!149982299751&amp;gad_campaignid=19828212645&amp;gbraid=0AAAAADjHtp_I5C-lRqgQfSepKdmaSdEem&amp;gclid=Cj0KCQjwnovFBhDnARIsAO4V7mCCByfsQVJMGwqnICXwr4FsGdy1C4ARy8b_yTDxpGu8ymxgwDxSmWYaAptsEALw_wcB">AWS Lambda</a></li><li><a href="https://aws.amazon.com/glue/">AWS Glue</a></li><li><a href="https://aws.amazon.com/athena/">AWS Athena</a></li><li><a href="https://www.tableau.com/">Tableau</a></li><li><a href="https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html">Using glue crawlers to populate the Data Catalog</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44d3212eeaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/serverless-solution-to-automate-s3-to-tableau-data-pipelines-c44d3212eeaa">Serverless Solution to Automate S3-to-Tableau Data Pipelines</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM as a Judge: Future of Evaluation? A Complete Guide for Software Engineers]]></title>
            <link>https://medium.com/emumba/why-use-llm-as-a-judge-a-complete-guide-for-software-engineers-e79c81cdbc64?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/e79c81cdbc64</guid>
            <dc:creator><![CDATA[Wisam ul Haque]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 06:11:25 GMT</pubDate>
            <atom:updated>2025-07-28T10:41:45.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJxncp1wA43y_fRMDiKULw.jpeg" /></figure><p><strong>Ever wondered if AI can judge AI?</strong> This article explores how and why we use large language models (LLMs) to evaluate the outputs of other LLMs or systems. It’s a practical guide for software professionals, engineers, QA specialists, and ML practitioners — regardless of whether you’re working with GPT, Claude, Mistral, or any other model.</p><p>We’ll walk through:</p><ul><li>What it means for an LLM to act as a judge</li><li>Why traditional evaluation methods fall short</li><li>Benefits, challenges, and real-world use cases</li><li>Best practices for safe, fair, and accurate evaluation</li></ul><h3>What is LLM-as-a-Judge?</h3><p>In simple terms, <strong>LLM-as-a-Judge</strong> is an evaluation technique where we use an LLM to <strong>evaluate</strong> the outputs of an LLM Application.</p><p>It answers questions like:</p><ul><li>Was the response factually correct?</li><li>Was it relevant to the question?</li><li>Was it helpful or complete?</li></ul><p>The judging LLM is prompted to <strong>give structured, Boolean judgments (✅ or ❌)</strong>, or even <strong>grade output on a scale</strong>, along with <strong>reasoning</strong> for its decision. Typically, the judgment prompt will include the original question, the expected answer or ground truth (if any), and the actual response generated. This is particularly helpful when aiming to improve our system through LLM-based evaluation. <strong>Reasoning</strong>, a key strength of LLMs, serves as a powerful tool — one that is uniquely available when using LLMs as judges.</p><p>This technique is especially useful in <strong>non-deterministic</strong> scenarios like open-ended answers where traditional unit tests or rule-based evaluation fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlzbWlsl6UR96RXiI6M7uA.png" /></figure><h3>Why Traditional Evaluation Techniques Fall Short?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1sEqpYWevrY7BGP" /></figure><p><strong>Manual Human Evaluation</strong></p><p>The most common evaluation approach today is assigning a human reviewer or subject matter expert (SME) to manually evaluate AI-generated responses. While this method brings human understanding and context into the process, it has significant limitations:</p><ol><li><strong>Bias</strong>: LLM outputs are often subjective. Similarly, human reviewers carry inherent subjectivity due to their individual preferences, backgrounds, and understanding. This introduces evaluation noise, leading to <strong>false positives </strong>or <strong>false negatives</strong> in judgments.</li><li><strong>Expensive</strong>: Human evaluation is costly hiring, training, and managing a large group of evaluators becomes financially impractical, especially when scaling the evaluation process across thousands of responses.</li><li><strong>Scalability</strong>: The human-based approach does not scale well. As your dataset grows, so do the costs, time, and risks of inconsistent evaluation results due to increased bias and fatigue.</li></ol><p><strong>Automated Rule-Based Evaluation</strong></p><p>So, if manual efforts aren’t enough, the natural next step is automation. One popular method is <strong>rule-based or similarity-based evaluation</strong>, such as:</p><ul><li><strong>Cosine Similarity</strong></li><li><strong>Embedding distance comparisons</strong></li><li><strong>String or token overlap</strong></li><li><strong>Threshold-based matching</strong></li></ul><p>These techniques involve comparing AI responses to a pre-defined ground truth and checking whether they cross a similarity threshold.</p><p>But here’s why this approach breaks down:</p><ol><li><strong>Threshold Variability</strong>: Due to the <strong>non-deterministic nature of LLMs</strong>, similar questions can yield slightly different but equally valid answers. Setting a fixed threshold becomes tricky.</li><li><strong>Lack of Reasoning</strong>: These methods only give a numeric score. If a response fails, you <strong>don’t know why</strong>. There’s no explanation or traceability of logic. Human reviewers still need to jump in and dig through the response manually.</li><li><strong>No Contextual Understanding</strong>: These techniques treat the text as tokens not meaning. They fail to assess <strong>tone, creativity, coherence, helpfulness</strong>, or the nuanced structure of the answer. That’s a dealbreaker for LLM-based apps like <strong>chatbots</strong>, <strong>educational assistants</strong>, or <strong>creative generators</strong>, where human-like context and tone matter just as much as factual correctness.</li><li><strong>No Ground Truth: </strong>There can be cases where you don’t have a ground truth. In such cases these techniques do not provide much help at all.</li></ol><h3>When to Use What?</h3><p><strong>LLM-as-a-Judge</strong> is best suited for <strong>non-deterministic applications</strong> where outputs may vary in form but still be valid (e.g., chatbots, search, summarization).<br>Use LLM-based evaluation when:</p><ul><li>Responses are open-ended and not easily matched word-for-word</li><li>Manual evaluation is too costly or slow</li><li>You want to iterate rapidly on model quality</li><li>Traditional metrics like BLEU or ROUGE are misleading</li><li>You’re evaluating reasoning, helpfulness, or domain-specific accuracy</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqjA5obrknWIQ1YQYCz16w.png" /></figure><p>Do not use LLM As a Judge when we know our application will have objective response and we know the response. In such cases traditional techniques works the best. Traditional API testing, UI testing do not require using LLM As a Judge.</p><h3>A Checklist for selecting LLM As a Judge</h3><p>Use this <strong>checklist</strong> to determine if LLM-as-a-Judge is appropriate for your evaluation:</p><ul><li>🔘 Is the output <strong>subjective</strong>?</li><li>🔘 Do traditional techniques <strong>miss key quality signals</strong>?</li><li>🔘 Would an LLM-based approach be <strong>more cost-effective than humans</strong>?</li><li>🔘 Do you need to <strong>iterate frequently</strong> on evaluations?</li><li>🔘 Is <strong>manual evaluation impractical</strong> due to volume?</li><li>🔘 Do you need to <strong>scale evaluations</strong> automatically?</li><li>🔘 Is the evaluation task <strong>complex or multi-dimensional</strong>?</li></ul><p>If most of these answers are <strong>yes</strong>, LLM-as-a-Judge might be the right fit.</p><h3>Advantages of Using LLM as a Judge</h3><p>Here’s why teams across the industry are moving toward LLM-as-a-Judge:</p><ol><li><strong>Scalable Evaluation</strong><br>Run thousands of tests programmatically across datasets or API responses.</li><li><strong>Handles Subjectivity</strong><br>Especially useful for evaluating tone, relevance, completeness, or insightfulness.</li><li><strong>Iterative Feedback</strong><br>Use judgments to improve both the LLM responses and the evaluation prompt itself.</li><li><strong>Customizable Criteria</strong><br>Define your own rubric — factuality, helpfulness, clarity, domain knowledge, etc.</li></ol><h3>Risks &amp; Challenges of LLM-as-a-Judge</h3><p>LLMs aren’t perfect judges. Common issues include:</p><p><strong>Model Bias</strong><br>If you use GPT-4 as both generator and evaluator, it may favor its own responses over others like Claude.</p><p><strong>Long Responses</strong><br>In long, multi-topic responses, the LLM might miss key incorrect details, leading to false positives.</p><p><strong>Authority Bias</strong><br>Citing a famous source followed by an incorrect statement may be incorrectly marked as accurate.</p><p><strong>Positional Bias</strong><br>LLMs can overlook incorrect information if it’s embedded in the middle of an otherwise correct response.</p><p><strong>Aesthetic Bias</strong><br>LLMs might favor well-written or pleasing text, even if factually incorrect.</p><h3>How to Mitigate Risks</h3><p>Here’s what you can do to improve accuracy and fairness in LLM-as-a-Judge setups:</p><p><strong>1. Prompt Engineering</strong></p><ul><li>Be explicit about what you’re evaluating.</li><li>Ask for a <strong>binary answer + reasoning</strong> (Is this correct? Yes/No. Explain.).</li><li>Set up a <strong>persona or system instruction</strong> clearly (e.g., “You are an impartial judge”).</li><li>Give the required details to your prompt. Think of it like onboarding a human to the task.</li></ul><p><strong>2. Chain-of-Thought Reasoning</strong></p><ul><li>Break down the problem statement in steps instead of prompting it to do everything in one go.</li><li>Ask the model to first <strong>explain its judgment</strong>, then <strong>output the final score</strong>.</li><li>This reduces hallucinated scores and improves transparency.</li></ul><p><strong>3. Use Multiple Judges</strong></p><ul><li>Try evaluation from <strong>two different LLMs</strong> and check for consistency.</li></ul><p><strong>4. Add Human Oversight</strong></p><ul><li>Especially important for high-stakes domains like healthcare or finance.</li></ul><p><strong>5. Standard Tooling</strong></p><p>Consider using open-source tools like:</p><ul><li><a href="https://github.com/openai/evals">OpenAI Evals</a> — built-in test framework</li><li><a href="https://github.com/explodinggradients/ragas">Ragas</a> — for RAG evaluation pipelines</li><li><a href="https://v2docs.galileo.ai/what-is-galileo">Galileo</a> — for end 2 end evaluation pipelines</li></ul><h3>Example LLM Evaluator Prompt:</h3><pre>You are an AI assistant designed to evaluate the correctness of RAG system responses by comparing them against a known ground truth.<br>Your goal is to determine if the RAG response accurately answers the user&#39;s question, is relevant to the question, and does not contain any hallucinated information.<br>QUESTION: {question}<br>GROUND_TRUTH: {ground_truth}<br>RAG_RESPONSE: {rag_response}<br>EVALUATION_RULES:<br>Correctness: The RAG_RESPONSE must directly answer the QUESTION and align with the facts presented in the GROUND_TRUTH. It should not contradict or misrepresent the GROUND_TRUTH.<br>Relevance: The RAG_RESPONSE must be directly relevant to the QUESTION asked. It should not include extraneous information that is not requested or implied by the question.<br>Completeness: The RAG_RESPONSE should cover all key aspects of the answer implied by the QUESTION, as found in the GROUND_TRUTH. It should not be a partial answer if a more complete one is available in the GROUND_TRUTH.<br>Conciseness: While complete, the RAG_RESPONSE should be concise and to the point, avoiding unnecessary verbosity.<br>No Hallucination: The RAG_RESPONSE must only contain information derived from the GROUND_TRUTH. Any information not supported by the GROUND_TRUTH will be considered a hallucination.<br>EXAMPLES:<br>Positive Example 1:<br>QUESTION: What is the capital of France?<br>GROUND_TRUTH: The capital of France is Paris.<br>RAG_RESPONSE: Paris is the capital city of France.<br>EVALUATION:<br>{<br>&quot;is_correct&quot;: true,<br>&quot;reasoning&quot;: &quot;The RAG response correctly identifies Paris as the capital of France, which directly aligns with the ground truth and answers the question accurately.&quot;<br>}<br>Negative Example 1: QUESTION: What is the largest ocean on Earth? GROUND_TRUTH: The Pacific Ocean is the largest and deepest of Earth&#39;s five oceans. RAG_RESPONSE: The Atlantic Ocean is the largest.<br>EVALUATION:<br>{<br>&quot;is_correct&quot;: false,<br>&quot;reasoning&quot;: &quot;The RAG response incorrectly states the Atlantic Ocean is the largest. The ground truth clearly indicates the Pacific Ocean is the largest. This is a factual error.&quot;<br>}<br>RESULT_FORMAT: Provide your evaluation in a JSON object with the following keys: is_corr</pre><h3>Final Questions You May Have</h3><h3>1. What’s the role of humans in this evaluation?</h3><p>LLM-as-a-Judge does <strong>not</strong> mean we eliminate human input. Instead, humans — especially Subject Matter Experts (SMEs) — should:</p><ul><li>Review edge cases</li><li>Provide feedback on misjudgments</li><li>Adjust prompts or criteria</li><li>Supervise and <strong>continually improve</strong> the judge LLM</li></ul><p>Think of the LLM as your <strong>evaluation assistant</strong>, not your only reviewer.</p><h3>2. Isn’t it wrong to use the same LLM for generating and evaluating responses?</h3><p>Good question — but <strong>not necessarily</strong>.</p><p>LLMs behave based on their <strong>task instruction or persona</strong>. The same model can act as a helpful assistant in one prompt and as a critical evaluator in another.</p><p>That said, it’s still a good idea to:</p><ul><li>Experiment with <strong>different models for judging and responding</strong></li><li>Use structured prompts and chain-of-thought</li><li>Validate against human-labeled datasets occasionally</li></ul><h3>3. Where can I learn more and try this out?</h3><p>No worries, I’ve got you covered.</p><p><strong>Blog on RAG Evaluation</strong>:<br> 👉 <a href="https://blog.emumba.com/rag-evaluation-simplified-cbbc7151a89a">RAG Evaluation Simplified</a></p><p><strong>Hands-on Evaluation Pipeline Code</strong>:<br> 👉 <a href="https://github.com/wisamulhaq/RAG_Automation">GitHub — RAG_Automation</a></p><p>You’ll find sample use cases, prompts, and a working setup you can fork or extend.</p><h3>Summary</h3><p>LLM-as-a-Judge is one of the most promising approaches to <strong>automated, scalable, and nuanced evaluation</strong> in the LLM ecosystem.</p><p>When used responsibly — with good prompting, human oversight, and cross-validation — it can drastically speed up your QA, model fine-tuning, or research workflows.</p><p>Got more questions? Curious about how to integrate this into your pipeline?</p><p>Drop a comment, or reach out!</p><p>Happy Building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79c81cdbc64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/why-use-llm-as-a-judge-a-complete-guide-for-software-engineers-e79c81cdbc64">LLM as a Judge: Future of Evaluation? A Complete Guide for Software Engineers</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Designer’s Guide to AI Prompting]]></title>
            <link>https://medium.com/emumba/the-designers-guide-to-ai-prompting-478da5cb3de1?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/478da5cb3de1</guid>
            <category><![CDATA[prompt-design]]></category>
            <category><![CDATA[ai-designer]]></category>
            <category><![CDATA[promptings]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ai-design]]></category>
            <dc:creator><![CDATA[Kiran Sajjad]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 11:57:22 GMT</pubDate>
            <atom:updated>2025-07-07T09:11:21.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYspDJPYdb_0j_vo6L3nxQ.png" /></figure><p>Every designer knows that moment when a tool promises to revolutionize your workflow, then leaves you staring at a blank screen, wondering how to make it actually useful. That’s exactly what’s happening with AI right now. Artificial Intelligence is no longer a distant sci-fi promise — it’s already in our Figjam boards and Figma files. And while tools like ChatGPT or Claude can feel magical at first, they quickly expose a frustrating truth: <strong><em>If you don’t know how to talk to AI, it won’t know how to help you.</em></strong></p><p>As a designer, I know the excitement and tension that comes with this. Suddenly, we’re expected to be writers, strategists, and prompt engineers — on top of everything else.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F118p3q768COZhu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZzZsMGh4bGI2aWlsdzR3bjdtMG10M2hwYjd5eWJxbG8yZHlvaGR1ayZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2F118p3q768COZhu%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMXJoOTk4bW1mN253ZnFvZmtmMTJ1dnp1cjNrZjZqaDM0M3d2czNzNyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F118p3q768COZhu%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3d3b0c849ed096d8759001fff00dea6/href">https://medium.com/media/a3d3b0c849ed096d8759001fff00dea6/href</a></iframe><p>But here’s the good news: <strong><em>prompting is design</em>.</strong> And design is communication. It’s something we already do every day. For example, think back to the last time you gave design feedback:</p><ul><li>“Make the color of the UI more accessible for older users.”</li><li>“The button size is too small for the thumb interaction.”</li><li>“Give the user contextual error messages.”</li></ul><p>These are prompts — they work for AI too. That realization changed everything for me, but it took a real project to truly understand what “prompting” actually means in practice.</p><h3>My First Prompt Design Project</h3><p>As a designer, I was handed a new kind of brief: Design prompts for a product being built entirely on Pythagora, a no-code AI platform that helps teams build applications without traditional coding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9dJbol-NY_OWv1waBUzQg.png" /><figcaption>Pythagora.ai</figcaption></figure><p>I’ll be honest — I had no idea what I was doing. Prompting? Sure, I’d used ChatGPT for quick ideas. But designing prompts for actual product behavior? That was new territory. Exciting, yes. But also… nerve-wracking.</p><p>In traditional design, we start with low-stakes wireframes. We expect to revise. There’s always ⌘ + Z. But in prompt design? Every word counts. In production environments where API calls cost tokens, there’s pressure to optimize prompts efficiently.</p><p>That fear was real. What if I wrote the wrong thing? What if the AI misunderstood me? What if the developers set everything up, and I break it?</p><p>That’s when I started exploring standard AI prompt types to see how they might apply to my design challenge:</p><h4>1. Zero-Shot Prompting</h4><p>You give the AI a task with no example — just the instruction. <em>“Summarize this usability report in three bullet points.”</em></p><p>Great for tasks like rewriting or summarizing, but results can feel generic or misaligned with brand tone.</p><h4>2. One-Shot Prompting</h4><p>You give one example to guide the AI. <em>“Here’s our marketing tagline: ‘Bringing startup agility to Enterprises.’ Now write one tagline for our sub-brand.”</em></p><p>Better control over tone and format, but still not enough context for complex tasks like journey mapping.</p><h4>3. Few-Shot Prompting</h4><p>You give multiple examples to ‘train’ the AI in the prompt. You share 2–3 copy examples from previous projects and then ask the AI to generate more in the same style.</p><p>Good for replicating content patterns, but can become bloated and doesn’t adapt well to UX complexity.</p><h4>4. Instructional Prompting</h4><p>You give the AI very clear instructions, almost like micro-copy for a form. <em>“Write five onboarding screen messages, each under 12 words, written in a friendly and reassuring tone.”</em></p><p>Great when tasks are specific and constraints are clear, but struggles with open-ended design problems that require empathy or context.</p><h4>5. Chain-of-Thought Prompting</h4><p>You show the AI how to think through a problem step-by-step. <em>“First review the designs. Then list all the UI improvements. Then give 3 suggestions.”</em></p><p>Powerful for reasoning-based tasks, but not intuitive for visual thinking or design systems logic.</p><h3>The Gap Between Standard Methods and Design Thinking</h3><p>Having knowledge of these prompt types was just the beginning. The real question was: Which one would work for designing actual product behavior?</p><p>As I tried applying each type to my Pythagora project, I hit a wall. Here’s why: These prompt techniques work well for specific design tasks like copywriting, but when applied to holistic design challenges — the kind I was facing — they miss the mark. The tools are strong, but the framing doesn’t account for how designers actually think and work.</p><p>So what now? I went back to my design roots. What if I treated prompt design like any other design challenge? In product design, we create design systems — foundations, components, patterns. So we tried the same approach for our Pythagora prompts.</p><h4>Attempt # 1</h4><p>We created:</p><ul><li><strong>Foundations</strong>: Defined brand tone, product principles, design language</li><li><strong>User flows</strong>: Mapped out journey-based prompts (e.g., “Create a new OKR”, “Set progress”)</li><li><strong>Variants</strong>: Tried modular prompts for different screen states</li></ul><p>But it didn’t work. The AI lost track with too much context, didn’t read the Foundation guidelines well, and missed most of the variants.</p><h4>Attempt # 2</h4><p>We pivoted to:</p><ul><li><strong>Focused context</strong>: We gave it minimal, relevant context instead of comprehensive documentation</li><li><strong>Clear hierarchy</strong>: We used Markdown to organize sections and highlight priorities</li><li><strong>Frequent refresh</strong>: We refreshed the thread often instead of overloading it with information</li></ul><p>The result? Much better. The AI stayed on track, maintained tone consistency, and delivered more relevant outputs. Our revision cycles dropped from 5–7 iterations to 2–3, and consistency scores improved noticeably. Learn more about the project <a href="https://drive.google.com/file/d/1Uab5s5R1GoVAl--g3u0YFkowz8rILrNX/view?usp=drive_link">here.</a></p><p>This experience taught me something fundamental: AI doesn’t fit into traditional design processes — you have to adapt the process for AI. The role of a designer is shifting — not away from creativity, but toward orchestration.</p><h3>Design-Native Prompting Frameworks</h3><p>Most prompting advice comes from developers and writers. It doesn’t account for how designers actually think and work. That’s why we need frameworks that acknowledge ambiguity, embrace iteration, blend visuals and language, and work with creative constraints.</p><p>This led me to explore frameworks like CARE and Perfect formula, adapting them specifically for design challenges.</p><h4>The CARE Method</h4><p>CARE is a structure that works especially well for research, writing, and generating UX-focused ideas. Unlike developer-focused frameworks, CARE accounts for the contextual thinking designers use daily.</p><ul><li><strong>Context</strong> — Provides the background or scenario. Who is this for? What’s the situation?</li><li><strong>Action</strong> — Specifies the task. What do you want AI to do?</li><li><strong>Results </strong>— Articulates the desired outcome. What should the output look like?</li><li><strong>Examples</strong> — Shows the desired response format.</li></ul><p><strong>Example: </strong>“You’re designing an onboarding screen for a mental wellness app targeted at Gen Z <strong>(Context)</strong>. Create a 3-step onboarding flow <strong>(Action)</strong> with microcopy in a calming, friendly tone. Output in bullet format (<strong>Results)</strong>. For example: <strong>(Examples)</strong></p><ul><li>Step 1 — Welcome message</li><li>Step 2 — Set your intention</li><li>Step 3 — Daily reminder setup”</li></ul><p><strong>CARE </strong>worked well for straightforward design tasks, but I found it wasn’t robust enough for complex, multi-layered design challenges. That’s when <strong>Perfect formula</strong> became valuable.</p><h4>The Perfect Formula</h4><p>Some tasks in design are layered and contextual — like writing onboarding flows or outlining product strategy. Perfect formula is a more comprehensive structure for complex design thinking.</p><ul><li><strong>Task</strong> — Your instruction to the AI, what you want it to do</li><li><strong>Context </strong>— The situation, background, or constraints</li><li><strong>Exemplars</strong> — Examples that illustrate the expected structure, format, or tone</li><li><strong>Persona </strong>— Who you want the AI to “become” while generating the response</li><li><strong>Format</strong>—How you want the information structured</li><li><strong>Tone </strong>— The emotional style or attitude of the output</li></ul><p><strong>Simple Example First:</strong> “Write three button labels for a checkout flow (<strong>Task</strong>). This is for an e-commerce app where users often abandon cart at payment (<strong>Context</strong>). Use action-oriented, confidence-building language like ‘Secure Checkout’ instead of ‘Pay Now’ (<strong>Exemplars</strong>). Act as a UX writer specializing in conversion optimization (<strong>Persona</strong>). Provide them as a bulleted list with brief rationale for each (<strong>Format</strong>). Professional but reassuring tone (<strong>Tone</strong>).”</p><p><strong>Complex Example:</strong> “Create user research interview questions for usability testing (<strong>Task</strong>). We’re testing a new expense tracking app for freelancers. The app launched 2 weeks ago and we’re seeing 60% drop-off after signup. We need to understand why users aren’t completing their first expense entry (<strong>Context</strong>). Follow this structure: ‘When you first opened the app, what was your initial impression?’ (open-ended observation) → ‘Can you walk me through how you would add your first expense?’ (task-based) (<strong>Exemplars</strong>). Act as a senior UX researcher with 5+ years of experience in fintech user testing (<strong>Persona</strong>). Provide 8 questions in a numbered list, with 2–3 follow-up probes for each main question (<strong>Format</strong>). Professional but conversational, avoiding jargon, designed to make interviewees feel comfortable sharing honest feedback (<strong>Tone</strong>).”</p><h3>Your Next Steps</h3><p>Ready to try this approach? Here’s how to begin:</p><ol><li><strong>Start small</strong>: Pick one routine design task (like writing error messages or button labels) and try the CARE method</li><li><strong>Document what works</strong>: Keep a running note of prompts that produce good results</li><li><strong>Build your template library</strong>: Create reusable PERFECT templates for common design challenges</li><li><strong>Share with your team</strong>: Test these frameworks with colleagues and refine based on feedback</li><li><strong>Iterate regularly</strong>: Like any design process, prompt design improves with practice and feedback</li></ol><h3>The Future of Prompt Design</h3><p>The truth is, we’re still in the early days of prompt design. With every passing week, AI tools are getting faster, more intuitive, and more embedded in our design workflows.</p><p>Just like design systems evolved from style guides… Prompt design will evolve too.</p><p>The methods we use today — CARE, Perfect formula, zero-shot, chain-of-thought — will transform. We’ll co-create with AI, not just command it. We’ll build prompt libraries that are as flexible and nuanced as our Figma components. We’ll develop team-wide prompting practices, design principles for AI interaction, and brand voice guidelines for AI outputs.</p><p>And most importantly, designers will lead this evolution, not just adapt to it.</p><p>Because design isn’t just about how something looks or works — it’s about how it understands and responds to people. And that’s exactly what prompt engineering is becoming: a conversation, a collaboration, a craft.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT9IgG50Fb7Mi0prBC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeHd3ejd0NnpzNDYxZHE4ODRsZ3JkbjBhdHJueWN2OWZ0aWVlcWEwbiZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2FxT9IgG50Fb7Mi0prBC%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcHk4Zmp1aXdjbm8zdDNtbTNkZmdvcXVzMWJpb3I5c2JnNTJ1aGYxZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FxT9IgG50Fb7Mi0prBC%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="218" frameborder="0" scrolling="no"><a href="https://medium.com/media/19cb0b626d1810cd1625f2182db2538b/href">https://medium.com/media/19cb0b626d1810cd1625f2182db2538b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478da5cb3de1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/the-designers-guide-to-ai-prompting-478da5cb3de1">The Designer’s Guide to AI Prompting</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Hallucination Detection for Reliable RAG Pipelines]]></title>
            <link>https://medium.com/emumba/benchmarking-hallucination-detection-for-reliable-rag-pipelines-2541d9240e3a?source=rss----28784675a43c---4</link>
            <guid isPermaLink="false">https://medium.com/p/2541d9240e3a</guid>
            <dc:creator><![CDATA[Zainab Abaid]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 07:52:20 GMT</pubDate>
            <atom:updated>2025-07-21T08:01:07.309Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This benchmarking study was conducted within the Genie R&amp;D group at Emumba. Genie (GENaI@Emumba) is Emumba’s dedicated Generative AI research and prototyping team, working across recent advances in large language models and applied GenAI domains — including retrieval-augmented generation (RAG), multi-agent applications, and LLM fine-tuning. Our goal is to validate practical methods that help build safer, more reliable, and production-ready AI systems for enterprise use.</em></p><h3>LLMs Hallucinate — What Should We Do?</h3><p>Hallucinated answers — confident but incorrect outputs — remain a leading cause of user distrust in AI-powered RAG systems. These incorrect answers become a critical failure point in real-world applications.</p><p>To address this, we systematically evaluated <strong>six</strong> hallucination detection techniques: built-in metrics from three LLM evaluation frameworks (<strong>UpTrain</strong>, <strong>Ragas</strong>, and <strong>DeepEval)</strong>; <strong>Vectara HHEM</strong>, an open-source LLM-based classifier; the <strong>LettuceDetect</strong> library; and <strong>Trustworthy Language Model (TLM)</strong>, a SaaS solution for hallucination detection. Except for TLM, all methods are open source and free to use, with the only cost being the underlying LLM API calls where applicable.</p><p>Our goal was to identify which frameworks are most effective for practical use cases, using criteria that go beyond simple accuracy:</p><ul><li><strong>Granularity</strong>: Can the method pinpoint exactly which parts of an answer are hallucinated?</li><li><strong>Precision</strong>: Does it avoid false positives (flagging correct content) and false negatives (missing hallucinations)?</li></ul><p>We conducted a <strong>three-phase experiment:</strong></p><ol><li>Benchmarking on a labeled, hallucination-rich dataset</li><li>Stress-testing top performers with adversarial examples</li><li>Evaluating the top performing method (UpTrain) for fine-grained detection.</li></ol><p>This post shares our methodology, findings, and practical recommendations for choosing the right hallucination detection tool.</p><blockquote><strong>TL; DR: We tested six hallucination detectors for RAG. UpTrain stood out with pinpoint accuracy and clear explanations. Read on to see which tools failed, which ones surprised us, and how to pick the best fit for safer AI.</strong></blockquote><h3>Hallucination Detection Frameworks</h3><p>We evaluated six hallucination detection tools, each using a distinct method to assess whether an LLM-generated answer is grounded in its supporting context. The table below summarizes the core technique behind each tool, the required inputs, and the format of its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29LpkGyYXy06tW2B2iyYtA.png" /><figcaption>Hallucination detection tools benchmarked in our study.</figcaption></figure><h3>Phase 1: Benchmarking on a Hallucination-Rich Dataset</h3><p>To evaluate how well each framework detects hallucinated outputs, we curated a small but high-quality benchmark dataset deliberately designed to include a wide variety of hallucination types. Starting from a base dataset of question and answer pairs over our internal Wiki data, we injected synthetic hallucinations generated by an LLM, and refined them manually.</p><p>Our goal was to test detection performance across <strong>diverse hallucination patterns</strong> often encountered in RAG pipelines, including:</p><ul><li>Context overrides (ignoring retrieved documents),</li><li>Fabricated details,</li><li>Misinterpretations of source content,</li><li>Over-generalizations,</li><li>Contradictions,</li><li>Conflicts across sources, and</li><li>Incorrect selection from context.</li></ul><p>The hallucinated answers included a balanced mix of the types listed above. Each generated hallucination was manually reviewed and labeled to ensure clean ground-truth annotations. We maintained a high hallucination ratio (~80%) to test the detection frameworks under challenging conditions. The remaining examples were factual, grounded answers for contrast.</p><p>To simulate a realistic retrieval setting, we built a standard RAG pipeline using LangChain over the document set (internal Wiki documents) used for creating the benchmark dataset.</p><h3>A Note on Threshold Calibration</h3><p>Some frameworks return a continuous score instead of a binary label, so in production this score must be thresholded to decide whether to flag a response. We experimented with both F1 score maximization and Youden’s J statistic on the ROC curve to determine optimal thresholds. While not the focus of this study, these calibration methods can significantly affect precision and recall.</p><h3>Phase 1 Results</h3><p>Below, we report accuracy results based on the best-performing thresholds for each tool, sorted from most to least accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QsPNGh0aPyjOrTgboOCWQ.png" /><figcaption>Accuracy results for six hallucination detection tools.</figcaption></figure><p>These results provided an initial view of accuracy, but real-world robustness needed more rigorous testing — addressed in Phase 2.</p><h3>Phase 2: Stress-Testing Fine-Grained Detection on Subtle Hallucinations</h3><p>In Phase 1, we evaluated the overall accuracy of different frameworks at detecting whether an answer contained hallucinated content. But benchmark accuracy alone isn’t enough — real-world RAG systems often produce answers that blend fact with subtle hallucinations. Phase 2 tested whether top frameworks can still detect hallucinations embedded within otherwise factual responses.</p><p>This experiment further tested the three top-performing frameworks from Phase 1 — UpTrain, Vectara HHEM, and Ragas — on a larger dataset of 181 queries, each containing adversarially-injected hallucinations. The goal was to see whether these systems would still flag the responses correctly, even when the hallucinations were subtle and contextually embedded.</p><p>Note we evaluated only <strong>overall detection robustness</strong>, not granularity — frameworks needed only to detect that a hallucination was present, not locate it precisely. This is because Vectara HHEM and Ragas do not provide a statement or span level breakdown.</p><h3>Dataset: Hallucination-Augmented Subset from RAGBench</h3><p>For both Phase 2 and Phase 3, we used a new dataset derived from <strong>RAGBench</strong>, a public benchmark available on Hugging Face. We sampled <strong>181 question–answer–context triples</strong>, all originally generated by GPT-4 and grounded in supporting documents.</p><p>To construct a clean factual baseline, we passed each answer through UpTrain and retained only those for which it returned a perfect factuality score of 1.0, manually spot-checking to ensure reliability of the ground truth data. This ensured we began with fully grounded answers with no hallucinations.</p><p>From this verified subset, we created a new test set by injecting hallucinations into selected factual statements using controlled LLM prompts. This produced answers that contained a <strong>mix of grounded and hallucinated statements</strong>, simulating real-world LLM behavior in RAG pipelines where hallucinations often appear subtly within otherwise factual text.</p><h3>Phase 2 Results</h3><p>Each hallucination-augmented sample was passed through the three frameworks. Since all responses now contained some hallucinated content, we expected that:</p><ul><li><strong>None of the frameworks should return a perfect score</strong> (i.e. indicating zero hallucination)</li><li>Any perfect score would indicate a <strong>missed hallucination</strong></li></ul><p>This allowed us to evaluate <strong>real-world robustness</strong> without relying on threshold tuning.</p><p>As the table below shows, UpTrain ended up missing 10.5% of the injected hallucinations, while Ragas captured all but 5.5% of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8t6EFwoCjMS9vMnGmOs6LQ.png" /><figcaption>Missed hallucinations by the top 3 hallucination detection tools.</figcaption></figure><p>While Vectara HHEM appears to have caught all hallucinations, this result is misleading. In our tests, Vectara HHEM never returns a perfect 1.0 score — even for fully factual answers. As a result, if we treat only a perfect score as proof of factuality, every response would be flagged as partially hallucinated by default. This means proper threshold calibration is essential for meaningful results with Vectara HHEM, and its raw output cannot be fairly compared in this phase without that step.</p><h3>Phase 3: Fine-Grained Evaluation of UpTrain</h3><p>While Phase 2 tested whether frameworks can detect that hallucination occurred, it still treated the answer as a whole. But in actual RAG applications, that’s not good enough. For safe and meaningful use, we need frameworks that not only raise a flag, but can also <strong>tell us exactly which parts of an answer are unsupported</strong>.</p><p>UpTrain is the only framework in our study that outputs a <strong>statement-level breakdown</strong>. In Phase 3, we evaluated how reliable this breakdown actually is.</p><ul><li>Does UpTrain correctly flag the hallucinated statements?</li><li>Equally important, does it avoid falsely flagging factual statements?</li></ul><p>We reused the hallucination-augmented dataset from Phase 2, but this time focused on <strong>per-statement performance</strong>. Specifically, we measured:</p><ul><li><strong>True Detections</strong>: Hallucinated statements correctly identified</li><li><strong>False Positives</strong>: Grounded statements incorrectly flagged</li></ul><p>This deeper evaluation allowed us to assess how usable UpTrain’s output would be in a pipeline that aims to remove or revise only the hallucinated parts, rather than discard the whole answer.</p><h3>Phase 3 Results</h3><p><strong>True detections: </strong>UpTrain correctly flagged 232 out of 303 hallucinated statements, achieving a 76.6% detection rate.</p><p><strong>False positives:</strong> UpTrain correctly identified 278 out of 322 factual statements, mislabeling 13.7% as hallucinations.</p><p>While UpTrain’s fine-grained detection is not flawless, its ability to pinpoint hallucinated statements makes it uniquely valuable for production RAG pipelines. Unlike frameworks that only flag the entire answer, UpTrain’s span-level verdicts enable targeted corrections, content pruning, or automated re-queries, all while preserving valid information. As the only open-source tool in our study that provides this granularity, UpTrain stands out as the most practical choice for teams that want to move beyond binary hallucination checks and towards real-time factuality refinement. With further prompt tuning, dataset-specific examples, and potential integration with custom retrieval signals, its accuracy can be further improved, unlocking safer, trustable LLM outputs in high-stakes deployments.</p><h3>Conclusion</h3><p>In summary, hallucination detection is essential for any robust RAG deployment — yet not all frameworks are equal in practicality or depth of insights. Our multi-phase evaluation shows that while general-purpose tools like Ragas and Vectara HHEM offer strong baseline detection with minimal integration effort, UpTrain delivers the best combination of high accuracy and actionable granularity. For organizations building production-grade, trust-sensitive AI systems, investing in a fine-grained, tunable detection workflow like UpTrain can dramatically reduce the risk of misleading outputs and build user confidence in LLM-powered products.</p><p>We hope this benchmarking and fine-grained testing effort helps teams make informed choices to safeguard their RAG pipelines against the persistent risk of hallucinations.</p><h3>Code</h3><p>The code for these experiments is available on <a href="https://github.com/Genie-Experiments/hallucination-detection-benchmark">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2541d9240e3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/benchmarking-hallucination-detection-for-reliable-rag-pipelines-2541d9240e3a">Benchmarking Hallucination Detection for Reliable RAG Pipelines</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>