<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abutalhaparkote on Medium]]></title>
        <description><![CDATA[Stories by Abutalhaparkote on Medium]]></description>
        <link>https://medium.com/@abutalhaparkote?source=rss-32ba97e75223------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_3A6E1rZ7dR-8aOI</url>
            <title>Stories by Abutalhaparkote on Medium</title>
            <link>https://medium.com/@abutalhaparkote?source=rss-32ba97e75223------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:47:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abutalhaparkote/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Three-Tier AWS Architecture: What Broke and How I Fixed It]]></title>
            <link>https://medium.com/@abutalhaparkote/building-a-three-tier-aws-architecture-what-broke-and-how-i-fixed-it-adb3414fda8c?source=rss-32ba97e75223------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb3414fda8c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-3-tier-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Abutalhaparkote]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 19:01:38 GMT</pubDate>
            <atom:updated>2026-10-29T19:01:38.254Z</atom:updated>
            <content:encoded><![CDATA[<p>30 Oct 2026 · @Abutalha parkote</p><h3>The resources existed. The application still didn’t work.</h3><p>Creating resources in the AWS Console is the easy part. The hard part starts when everything shows as created, the configuration looks right, and requests still fail somewhere between the user and the database.</p><p>I reached that point while building a three-tier web application on AWS in ap-southeast-2. This post walks through five real problems I debugged, the evidence that pointed to each root cause, and the habits I now apply to every deployment.</p><p>If you are hiring for a junior cloud or DevOps role, it shows how I troubleshoot. If you are a senior engineer, I would value your feedback on what I could do better.</p><h3>Architecture at a glance</h3><p>A request crosses six layers on its way to the data, and each layer accepts traffic only from the one in front of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*NvGzdF6ISuI86SYA_Cy6nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OEzV61WnOKUO487wBxDtQ.png" /><figcaption>Each Tier accepts traffic only from the tier in front of it.</figcaption></figure><p>The two shaded tiers run in Auto Scaling Groups spread across two Availability Zones. Around this path, IAM roles control access to S3, NAT Gateways give private subnets outbound internet access, and route tables and security groups control the traffic between components.</p><p>Both Auto Scaling Groups use the same sizing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*zF3Hher-nFNhPbUCAq1w5Q.png" /></figure><h3>Incident 1: S3 AccessDenied when pulling application code</h3><p><strong>Symptom.</strong> From the app server, I tried to download the application code from a private S3 bucket:</p><pre>aws s3 cp s3://threetier-project-bucket03/application-code/app-tier/ app-tier/ --recursive</pre><p>The CLI returned AccessDenied on ListObjectsV2, stating that no identity-based policy allowed s3:ListBucket.</p><p><strong>Root cause.</strong> The instance was running under the IAM role ThreeTier-Project-Role, which had no permission to list the bucket. A recursive copy must list objects under the prefix before it can download them. Being able to reach the instance through Session Manager says nothing about what that instance may do in other AWS services.</p><p><strong>Fix.</strong> I added an inline policy to the role with two grants:</p><ul><li>s3:ListBucket on the bucket, restricted to the relevant prefix</li><li>s3:GetObject on the application files</li></ul><p>The bucket stayed private, and the instance did not get administrator access.</p><p><strong>Takeaway.</strong> Read the denied action in the error, find the identity making the call, and grant exactly that. Making the bucket public would have made the error disappear and created a worse problem.</p><h3>Incident 2: Nginx would not start because port 80 was taken</h3><p><strong>Symptom.</strong> After configuring the server, systemctl status nginx showed a failed service. The log said:</p><pre>nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)</pre><p>It looked like an Nginx installation problem. Reinstalling would have been the reflex.</p><p><strong>Investigation.</strong> Error 98 means another process already owns the port. I checked sudo systemctl status httpd and found Apache running and listening on port 80. Two web servers were competing for the same port on the same instance.</p><p><strong>Fix.</strong> The project was designed around Nginx, so I stopped Apache, disabled it, and removed it:</p><pre>sudo systemctl stop httpd<br>sudo systemctl disable httpd<br>sudo yum remove -y httpd<br>sudo systemctl start nginx<br>sudo systemctl enable nginx</pre><p><strong>Verification.</strong> I confirmed the result in three ways: the service reported active (running), sudo ss -lntp | grep &#39;:80&#39; showed what was listening, and curl -I http://localhost/ returned HTTP/1.1 200 OK from Nginx.</p><p><strong>Takeaway.</strong> A package being installed does not mean the service can run. systemctl, ss, and curl found the cause directly, which reinstalling never would have.</p><h3>Incident 3: Healthy web server, unhealthy load balancer targets</h3><p><strong>Symptom.</strong> Nginx answered 200 OK on the instance, yet the Application Load Balancer target group still marked my EC2 targets unhealthy.</p><p><strong>Why a local 200 proves little.</strong> A local curl shows the web server can respond to a request that starts on the same machine. The ALB sends its health check over the network, so it also depends on the path between the two. That leaves several suspects:</p><ul><li>the health-check protocol, port, or path</li><li>a security group blocking traffic from the ALB to the instance</li><li>a response code that does not match the configured success codes</li><li>a routing or target group configuration problem</li></ul><p><strong>Approach.</strong> I opened the <strong>Targets</strong> tab, read the exact health status reason, and then reviewed the health-check settings and the instance security group, which must allow the ALB security group on the target port.</p><p>The status reason decides the next move. Target.Timeout means no response arrived in time, which points at reachability. Target.ResponseCodeMismatch means the target did respond, but with a code outside the success range, which points at the application or the matcher. Treating a timeout as an HTTP error sends you to the wrong layer.</p><p><strong>Takeaway.</strong> A load balancer health check is an end-to-end test: web server, security groups, routing, and health-check configuration all have to agree.</p><h3>Incident 4: A service that runs but cannot be reached</h3><p><strong>Symptom.</strong> The service was running on the instance, but requests from outside it did not arrive. In a VPC with public and private subnets, load balancers, and security groups, that is a common failure shape.</p><p><strong>Approach.</strong> I stopped guessing at the web server and checked one connection at a time:</p><ol><li><strong>Locally:</strong> curl -I http://localhost/ Confirms the service answers on the instance.</li><li><strong>Listener:</strong> sudo ss -lntp shows which process listens on which port.</li><li><strong>Security groups:</strong> each tier should accept traffic only from the tier in front of it.</li><li><strong>Routing and registration:</strong> a security group rule cannot fix a missing route, a wrong target port, or an unregistered target.</li></ol><p>The security group chain I designed for the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*pbYLq426fE2BJsPXkVmsSA.png" /></figure><p><strong>Takeaway.</strong> Referencing security groups instead of open CIDR ranges keeps each tier reachable only from its neighbour, and it makes the failing hop easy to find. If the local request works but the health check times out, investigate the path between the ALB and the target, not the web server install.</p><h3>Incident 5: CloudFormation rejected the template</h3><p><strong>Symptom.</strong> Validation failed with:</p><pre>Unsupported property [AssociatePublicIpAddress] in template</pre><p><strong>Root cause.</strong> Infrastructure as code is strict about structure. A property that is valid in one place can be invalid when it sits at the wrong level or under a different resource. For launch templates, the network interface and public IP settings must follow the schema CloudFormation supports, and they must match the subnet and route table design.</p><p><strong>Approach.</strong></p><ol><li>Read the resource and property path named in the error.</li><li>Compare the template against the supported schema for that resource type.</li><li>Move or remove the property to match the intended launch configuration.</li><li>Validate the template before deploying again.</li><li>Confirm the launched instance received the intended network configuration.</li></ol><p><strong>Takeaway.</strong> Validate infrastructure definitions before deploying them, and confirm the result on the running resource rather than trusting the template.</p><h3>Auto Scaling: capacity settings are not scaling behaviour</h3><p>Both Auto Scaling Groups, web-asg and app-asg, run with a minimum of 2, a desired capacity of 2, and a maximum of 4. The console showed two healthy instances in each group, spread across two Availability Zones.</p><p>That setup keeps capacity steady and can replace instances that the configured health checks mark unhealthy. It does not mean the groups will scale out under load. A maximum of 4 only sets the ceiling; actual scale-out depends on scaling policies, metrics, and thresholds.</p><p>So I treat “capacity is configured” and “scaling behaves correctly” as two separate things to verify. Adding and load-testing a scaling policy is the next item on my list.</p><h3>My troubleshooting playbook</h3><p>An error message is evidence, not an obstacle. These are the habits the five incidents taught me:</p><ol><li><strong>Read the whole error.</strong> The S3 error named the denied action. The Nginx log named the port conflict.</li><li><strong>Test one layer at a time.</strong> A local request, a listener check, a target health reason, and an IAM policy each answer a different question.</li><li><strong>Separate instance health from application health.</strong> An instance can pass its EC2 status checks while the ALB still cannot get the response it expects.</li><li><strong>Grant least privilege.</strong> Fix a permission error with the specific actions needed, never a public bucket or an administrator policy.</li><li><strong>Do not reinstall without evidence.</strong> Apache already held port 80, so reinstalling Nginx would have changed nothing.</li><li><strong>Document the final state.</strong> Launch templates, Auto Scaling settings, target groups, security groups, and IAM permissions are what the next person, or the next incident, will need.</li></ol><h3>Where it ended up, and what I would do next</h3><p>The project reached a working state, and it gave me hands-on practice with:</p><ul><li>designing a three-tier architecture and configuring VPC networking and security groups</li><li>running EC2 with Nginx, and using IAM instance roles for S3 access</li><li>configuring and troubleshooting Application Load Balancers</li><li>building Auto Scaling Groups from launch templates</li><li>diagnosing CloudFormation validation errors</li></ul><p>Three things I would tighten next: add and test scaling policies so scale-out is proven rather than assumed, validate every template before each deployment, and keep the final configuration documented alongside the code.</p><p>The biggest change is in how I work. I no longer assume a resource is correct because it exists in the console. I follow the request path hop by hop and let each service’s own evidence tell me where it breaks.</p><p>If you are learning AWS or preparing for a junior cloud or DevOps role, build something like this and write down what goes wrong. The troubleshooting is often worth more than the finished diagram.</p><p><strong>Project:</strong> AWS three-tier web application · <strong>Region:</strong> ap-southeast-2</p><p><strong>Services:</strong> CloudFront, VPC, EC2, Application Load Balancer, Auto Scaling, S3, IAM, RDS, NAT Gateway, CloudFormation</p><p><strong>Author:</strong> Abutalha Parkote · <strong>GitHub:</strong> <a href="https://github.com/">https://github.com/</a>Abutalha2132/AWS-Three-Tier-Web-Application-Architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb3414fda8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Employee Manager on AWS: What CORS Taught Me About Debugging]]></title>
            <link>https://medium.com/@abutalhaparkote/building-a-serverless-employee-manager-on-aws-what-cors-taught-me-about-debugging-f85a6adc8797?source=rss-32ba97e75223------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85a6adc8797</guid>
            <dc:creator><![CDATA[Abutalhaparkote]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 08:19:55 GMT</pubDate>
            <atom:updated>2026-10-26T08:19:55.840Z</atom:updated>
            <content:encoded><![CDATA[<p>26 Oct 2026 · @Abutalha parkote</p><p>Creating AWS resources in the console is the easy part. The hard part is the moment your browser says “Failed to fetch,” and every service looks healthy on its own.</p><h3>TL;DR</h3><p>I built a serverless Employee Manager on AWS, and the biggest lesson was that a vague browser error is a symptom, not a diagnosis. Testing the request flow one layer at a time found the problem faster than guessing.</p><ul><li><strong>What I built:</strong> a web app to add and retrieve employee records</li><li><strong>Stack:</strong> S3 + CloudFront (with Origin Access Control), API Gateway (REST), two Python Lambda functions, DynamoDB, IAM, and CloudWatch</li><li><strong>Region:</strong> ap-southeast-2 (Sydney)</li><li><strong>Hardest problem:</strong> CORS and the OPTIONS preflight request between a CloudFront frontend and an API Gateway backend</li><li><strong>Key takeaway:</strong> separate what you observed, what you suspect, and what you have verified</li></ul><p>The full project is on <a href="https://github.com/Abutalha2132/AWS-Serverless-Project">GitHub</a>: <a href="https://github.com/Abutalha2132/AWS-Serverless-Project">Abutalha2132/AWS-Serverless-Project: AWS Serverless Project</a>.</p><h3>1. The architecture: two separate request flows</h3><p>The application is two independent paths that happen to share a browser. Understanding that split is what made the CORS problem make sense later.</p><p><strong>Frontend delivery.</strong> The user opens a CloudFront URL. CloudFront fetches the HTML, CSS and JavaScript from a private S3 bucket using Origin Access Control (OAC). The bucket is never public.</p><p><strong>Backend communication.</strong> When the user loads or submits employee data, JavaScript calls API Gateway. API Gateway invokes the right Lambda function, which reads from or writes to DynamoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*qEvqeWWfQx9UAbjQ-6CZgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*7qOpSPLCdOLHsB0zA-LDSg.png" /></figure><p>The top flow never touches the API. Only the bottom flow crosses origins, which is why CORS appeared on the second flow and not the first.</p><p>Services used:</p><ul><li><strong>Amazon S3:</strong> stores the frontend files (private)</li><li><strong>Amazon CloudFront + OAC:</strong> serves the frontend securely</li><li><strong>Amazon API Gateway:</strong> exposes the REST endpoints</li><li><strong>AWS Lambda:</strong> runs the Python backend code</li><li><strong>Amazon DynamoDB:</strong> stores employee records</li><li><strong>AWS IAM:</strong> controls permissions</li><li><strong>Amazon CloudWatch:</strong> logs for troubleshooting</li></ul><h3>2. The backend: DynamoDB, two Lambdas and IAM</h3><p>I split the backend into two small Lambda functions so each one has a single job and is easy to debug.</p><ul><li><strong>GetFunction</strong> reads employee records from DynamoDB and returns them as JSON.</li><li><strong>InsertFunction</strong> validates the incoming fields and writes the record to DynamoDB.</li></ul><p>The table is called employeeData, with employeeid (String) as the partition key. Each record stores the employee ID, name, email, department and salary.</p><p>Here is a simplified version of the insert logic. Two details are worth copying. The condition expression rejects duplicate IDs, and salary is converted to Decimal because the DynamoDB resource API does not accept Python floats.</p><pre>import json<br>import boto3<br>from decimal import Decimal<br>from botocore.exceptions import ClientError</pre><pre>table = boto3.resource(&quot;dynamodb&quot;).Table(&quot;employeeData&quot;)</pre><pre>def lambda_handler(event, context):<br>    required = [&quot;employeeid&quot;, &quot;name&quot;, &quot;email&quot;, &quot;department&quot;, &quot;salary&quot;]<br>    missing = [f for f in required if not event.get(f)]<br>    if missing:<br>        return {&quot;statusCode&quot;: 400,<br>                &quot;body&quot;: json.dumps({&quot;error&quot;: f&quot;Missing: {&#39;, &#39;.join(missing)}&quot;})}</pre><pre>    item = {<br>        &quot;employeeid&quot;: str(event[&quot;employeeid&quot;]),<br>        &quot;name&quot;: event[&quot;name&quot;],<br>        &quot;email&quot;: event[&quot;email&quot;],<br>        &quot;department&quot;: event[&quot;department&quot;],<br>        &quot;salary&quot;: Decimal(str(event[&quot;salary&quot;])),<br>    }</pre><pre>    try:<br>        table.put_item(<br>            Item=item,<br>            ConditionExpression=&quot;attribute_not_exists(employeeid)&quot;,<br>        )<br>    except ClientError as e:<br>        if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;ConditionalCheckFailedException&quot;:<br>            return {&quot;statusCode&quot;: 409,<br>                    &quot;body&quot;: json.dumps({&quot;error&quot;: &quot;Employee ID already exists&quot;})}<br>        raise</pre><pre>    return {&quot;statusCode&quot;: 201,<br>            &quot;body&quot;: json.dumps({&quot;message&quot;: &quot;Employee added&quot;})}</pre><p>Creating a table and writing code is only half of the integration. The Lambda execution role must also be allowed to touch the table, or you will get an AccessDeniedException in CloudWatch. A least-privilege policy for the insert function looks like this (replace the account ID with your own):</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [{<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: [&quot;dynamodb:PutItem&quot;],<br>    &quot;Resource&quot;: &quot;arn:aws:dynamodb:ap-southeast-2:123456789012:table/employeeData&quot;<br>  }]<br>}</pre><p>The read function only needs dynamodb:GetItem and dynamodb:Scan (or Query) on the same table. In my current setup the two functions share one role, which is convenient but broader than necessary. I list separate roles under future improvements.</p><h3>3. Connecting the frontend to API Gateway</h3><p>The frontend is plain HTML, CSS and JavaScript. It calls the API with fetch(): GET to load records and POST to add one. The URL points at the deployed stage, which in my case is ApiDeploy.</p><pre>const API_URL =<br>  &quot;https://&lt;api-id&gt;.execute-api.ap-southeast-2.amazonaws.com/ApiDeploy/employees&quot;;</pre><pre>async function loadEmployees() {<br>  try {<br>    const response = await fetch(API_URL);<br>    if (!response.ok) throw new Error(`HTTP error: ${response.status}`);<br>    displayEmployees(await response.json());<br>  } catch (error) {<br>    console.error(&quot;Failed to load employees:&quot;, error);<br>  }<br>}</pre><pre>async function addEmployee(employee) {<br>  const response = await fetch(API_URL, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify(employee),<br>  });<br>  if (!response.ok) throw new Error(`HTTP error: ${response.status}`);<br>  return response.json();<br>}</pre><p>Notice the Content-Type: application/json header on the POST. It looks harmless, but it is exactly the kind of header that makes the browser send a preflight request, which leads to the next section.</p><h3>4. The biggest challenge: CORS and the OPTIONS preflight</h3><p>My page was served from a CloudFront domain, and my API lived on an execute-api domain. Those are different origins, so the browser applied cross-origin rules and blocked my requests until the API explicitly allowed them.</p><p>Because my POST sent a JSON Content-Type, the browser first sent an OPTIONS preflight request. If that request does not get an acceptable answer, the real POST is never sent. Configuring GET and POST on the API is not enough.</p><p>The preflight response needs three headers. The values below are examples, so match them to your own frontend:</p><pre>Access-Control-Allow-Origin: https://&lt;your-cloudfront-domain&gt;<br>Access-Control-Allow-Methods: GET,POST,OPTIONS<br>Access-Control-Allow-Headers: Content-Type,Authorization</pre><p><strong>What I got wrong.</strong> When I inspected the response headers, Access-Control-Allow-Origin and Access-Control-Allow-Headers were configured incorrectly. They do different jobs: the first says which frontend origin may call the API, and the second says which request headers the browser may send. I corrected both and retested.</p><p><strong>Three details that are easy to miss:</strong></p><ol><li><strong>The real response needs the header too.</strong> The OPTIONS response is not the only one that matters. The GET and POST responses must also include Access-Control-Allow-Origin. With a Lambda proxy integration, your function must return it. With a non-proxy integration, you set it in the method and integration responses.</li><li><strong>Origins must match exactly.</strong> https://d111.cloudfront.net and https://d222.cloudfront.net are different origins, even when they serve the same bucket. A trailing slash or a wrong scheme also breaks the match.</li><li><strong>Redeploy the stage.</strong> Changes to a REST API do not take effect until you deploy them to a stage. I tested against ApiDeploy and made sure I was testing the deployed configuration, not just the console edits.</li></ol><h3>5. Debugging “Failed to fetch”</h3><p>After the first CORS fixes, submitting an employee still showed Failed to fetch. That message does not name a cause. It can mean a CORS rejection, a wrong endpoint, or a network failure, and it does not prove that Lambda or DynamoDB is broken.</p><p>So I checked the request flow in order, from the browser inwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*oRkdCRRoYqfx5dSEnWEJMg.png" /><figcaption>Debugging “Failed to fetch”</figcaption></figure><p>The CloudFront domain turned out to matter. During development, I worked with more than one distribution, and each domain is its own origin. The POST failed on the newer distribution, and an origin mismatch fit that pattern. After correcting the CORS headers and retesting, the request went through.</p><p>This taught me to keep three things apart:</p><ul><li><strong>Observed:</strong> the browser shows Failed to fetch.</li><li><strong>Suspected:</strong> the allowed origin does not match the page’s origin.</li><li><strong>Verified:</strong> the OPTIONS and POST both succeed, the record is in DynamoDB, and GET returns it.</li></ul><h3>6. Verifying every layer, and the 200 vs 201 surprise</h3><p>Once the flow worked, I inserted an employee record, confirmed it in DynamoDB, and retrieved it through the GET endpoint.</p><p>One detail caught my attention. The API Gateway test console showed HTTP 200, while my Lambda payload contained statusCode: 201. This happens when the method uses a non-proxy Lambda integration. API Gateway treats the function&#39;s return value as the response body, so the statusCode inside it is just data unless you map it in the integration response. With a Lambda proxy integration, the statusCode becomes the real HTTP status.</p><p>The lesson is not to trust one status code. For each test, I now confirm five things:</p><ol><li>The frontend sends the request (Network tab).</li><li>API Gateway routes it to the right method and stage.</li><li>Lambda runs without errors (CloudWatch Logs).</li><li>DynamoDB holds the expected record.</li><li>The GET endpoint returns the saved data.</li></ol><h3>7. Security: what is protected and what is not</h3><p><strong>What is protected.</strong> The S3 bucket is private. CloudFront reads from it through Origin Access Control, and the bucket policy allows only that distribution. Users can reach the site through CloudFront but cannot browse the bucket directly.</p><p><strong>What is not.</strong> Private hosting protects the frontend origin only. My API Gateway endpoint has no authentication, so anyone who knows the URL can call it. For a demo, that is acceptable, but the data includes emails and salaries, so a real deployment would need:</p><ul><li>Authentication and authorization, for example, Amazon Cognito or IAM authorization</li><li>Input validation beyond checking for required fields</li><li>An API key and usage plan, or throttling, to limit abuse</li><li>AWS WAF in front of the API. A Web ACL on CloudFront does not protect direct calls to the API Gateway URL, so the API needs its own regional WAF association, or its traffic must be routed through CloudFront</li><li>Separate least-privilege execution roles for the two Lambda functions</li></ul><p>If you publish a project like this, use sample data only, and consider removing or rotating your live API URL once the demo is no longer needed.</p><h3>8. Cost and what I plan to build next</h3><p>Every service here is pay-per-use, so a low-traffic demo costs very little, and much of it may fall inside the AWS Free Tier. Check current pricing and your own usage before relying on that.</p><p>These are planned improvements, not features I have already implemented:</p><ul><li><strong>AWS CloudFormation:</strong> define the whole stack as code so it can be reproduced and torn down cleanly</li><li><strong>Route 53 and AWS Certificate Manager:</strong> a custom domain with a TLS certificate</li><li><strong>AWS WAF:</strong> protection for the public entry points, with the CloudFront and API Gateway caveat above</li><li><strong>CloudWatch alarms and SNS:</strong> alerts for Lambda errors and API failures</li><li><strong>Authentication and least-privilege roles:</strong> Cognito or IAM authorization, plus one execution role per Lambda function</li></ul><h3>9. Common mistakes to avoid</h3><ul><li>Configuring CORS on GET and POST but forgetting the OPTIONS method</li><li>Forgetting to redeploy the API Gateway stage after a change</li><li>Allowing the wrong origin, such as an old CloudFront domain or one with a trailing slash</li><li>Leaving Content-Type out of Access-Control-Allow-Headers</li><li>Passing a Python float to DynamoDB instead of a Decimal</li><li>Trusting the API Gateway test status without checking the Lambda payload, logs, and table</li><li>Assuming a private S3 bucket secures the API as well</li></ul><h3>What I learned</h3><p>Deploying resources is only one part of building an application. The more valuable skill is following a request across services and proving, layer by layer, where it fails. This project gave me hands-on practice with private S3 hosting through CloudFront OAC, REST API configuration, Python Lambda functions, DynamoDB, IAM execution permissions, CORS preflight requests, deployment stages, and CloudWatch troubleshooting.</p><h3>Conclusion</h3><p>Building the AWS Serverless Employee Manager moved me from configuring individual services to understanding how they work together. When something fails, investigate the whole request flow one layer at a time.</p><p>The code is on <a href="https://github.com/Abutalha2132/AWS-Serverless-Project">GitHub</a>. If you are learning AWS, I would love to hear how you debug CORS issues, so feel free to connect with me on LinkedIn and share your approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85a6adc8797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain: Building Modular LLM Applications from Scratch]]></title>
            <link>https://medium.com/@abutalhaparkote/langchain-building-modular-llm-applications-from-scratch-c66a18642ca2?source=rss-32ba97e75223------2</link>
            <guid isPermaLink="false">https://medium.com/p/c66a18642ca2</guid>
            <dc:creator><![CDATA[Abutalhaparkote]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 17:40:53 GMT</pubDate>
            <atom:updated>2026-04-12T17:40:53.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Large Language Models (LLMs) like GPT-4, Claude, and Gemini are extraordinarily capable — but raw capability doesn’t equal usable software. Calling an LLM API returns text. Real applications need <em>orchestration</em>: routing prompts, chaining outputs, connecting to databases, remembering past turns, invoking external tools, and making decisions autonomously. That gap between a model API and a functioning AI application is precisely what <strong>LangChain</strong> fills.</p><p>LangChain is an open-source framework for building applications <em>powered by</em> language models. Its core insight is deceptively simple: LLM-powered apps are composable pipelines. Break the application into standardised, swappable components — prompts, models, memory, tools, agents — and assemble them like LEGO blocks. The framework handles the plumbing so you focus on the application logic.</p><p><strong>Why does it matter right now?</strong> The LLM ecosystem in 2024–25 is exploding with models, embedding services, vector databases, and tool APIs. LangChain provides a unified abstraction layer across all of them. It also ships with battle-tested patterns for the hardest problems:</p><ul><li><strong>Prompt orchestration</strong> — keeping prompts structured, versioned, and reusable</li><li><strong>Chaining</strong> — passing model outputs as inputs to the next step without manual parsing</li><li><strong>Tool integration</strong> — letting the model call functions, query databases, or search the web</li><li><strong>Memory</strong> — giving a stateless API a notion of conversation history</li><li><strong>Agents</strong> — giving the model the ability to <em>reason and act</em> in a loop</li></ul><p>This blog is a deep technical walkthrough of all these components, with working Python code, architecture intuition, and real-world use cases.</p><h3>Core Components</h3><h3>1. LLMs and Chat Models</h3><p><strong>Conceptual explanation</strong><br>LangChain distinguishes between two model interfaces. An <em>LLM</em> takes a plain string and returns a string. A <em>Chat Model</em> takes a list of structured messages (system, human, AI) and returns a message object. In practice, all modern frontier models use the chat interface, but LangChain abstracts both under a common Runnable interface so your pipeline code doesn’t change when you swap providers.</p><p><strong>Why it exists</strong><br>Every provider — OpenAI, Anthropic, Google, Cohere, local Ollama — has its own SDK, authentication method, rate-limit logic, and response shape. LangChain provides a single .invoke() call regardless of the backend. Swapping ChatOpenAI for ChatAnthropic It is a one-line change.</p><p><strong>Internal intuition</strong><br>Under the hood, LangChain’s model wrappers are thin shims. They format your input into the provider’s expected schema, call the HTTP API, parse the response into a standard AIMessage object, and expose metadata (token usage, finish reason) on the result. The real power is that these wrappers implement the Runnable protocol — they can be composed with | (the pipe operator) into chains.</p><pre># 1_llm_chat_model.py<br>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import HumanMessage, SystemMessage</pre><pre># Initialise the model — temperature=0 for deterministic output<br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)</pre><pre>messages = [<br>    SystemMessage(content=&quot;You are a helpful Python tutor.&quot;),<br>    HumanMessage(content=&quot;Explain list comprehension in one sentence.&quot;)<br>]</pre><pre>response = llm.invoke(messages)<br>print(response.content)<br># Output: &quot;List comprehension is a concise way to create a new list by<br># applying an expression to each item in an iterable, optionally filtering<br># with a condition — all in a single readable line.&quot;</pre><h3>2. Prompt Templates</h3><p><strong>Conceptual explanation</strong><br>A PromptTemplate is a string with named placeholders. A ChatPromptTemplate is a list of message templates with placeholders. At runtime, you supply a dictionary of values, and the template fills the slots to produce the final prompt string or message list.</p><p><strong>Why it exists</strong><br>Hardcoding prompt strings into application code is a maintenance nightmare. When the prompt changes (and it will), you hunt through the codebase. Templates externalise prompts into reusable, testable units. They also enable type-safe input validation and dynamic few-shot injection.</p><p><strong>Internal intuition</strong><br>Templates are not just string formatting. They compile a <em>schema</em> of required variables, validate inputs at call time, and produce PromptValue objects that can be passed to either an LLM or a Chat Model without modification. This is what makes them composable: template | llm is a valid chain.</p><pre># 2_prompt_templates.py<br>from langchain_core.prompts import ChatPromptTemplate</pre><pre># Define a reusable template with named variables<br>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are an expert in {domain}. Answer concisely.&quot;),<br>    (&quot;human&quot;, &quot;Question: {question}&quot;)<br>])</pre><pre># Fill the template with runtime values<br>prompt = template.invoke({<br>    &quot;domain&quot;: &quot;machine learning&quot;,<br>    &quot;question&quot;: &quot;What is the vanishing gradient problem?&quot;<br>})</pre><pre>print(prompt.to_messages())<br># Produces a list of SystemMessage and HumanMessage ready to send</pre><h3>3. Chains</h3><p><strong>Conceptual explanation</strong><br>A Chain is a sequence of operations where the output of one step feeds into the next. LangChain v0.3+ uses <strong>LCEL</strong> (LangChain Expression Language) — the | operator — to compose Runnables into chains. This replaces the older verbose LLMChain class.</p><p><strong>Why it exists</strong><br>Most real LLM workflows are multi-step: format prompt → call model → parse output → transform result. Without chains, you write repetitive glue code for every pipeline. LCEL gives you a declarative, readable syntax and automatic streaming, batching, and async support at every step.</p><p><strong>Internal intuition</strong><br>| is syntactic sugar for RunnableSequence. When you call .invoke() On the chain, LangChain walks the sequence left to right, passing each step’s output as the next step’s input. The key insight: <em>every step must accept what the previous step returns</em>. StrOutputParser bridges the gap between an AIMessage (what a chat model returns) and a plain string (what downstream text processing expects).</p><pre># 3_simple_chain.py<br>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>parser = StrOutputParser()  # Converts AIMessage → plain string</pre><pre># LCEL chain: template | model | parser<br>chain = (<br>    ChatPromptTemplate.from_messages([<br>        (&quot;system&quot;, &quot;Summarise the following text in exactly one sentence.&quot;),<br>        (&quot;human&quot;, &quot;{text}&quot;)<br>    ])<br>    | llm<br>    | parser<br>)</pre><pre>result = chain.invoke({&quot;text&quot;: &quot;LangChain is a framework that enables developers to build applications powered by large language models through composable components.&quot;})<br>print(result)<br># Output: &quot;LangChain is a developer framework for building LLM-powered<br># applications using composable components.&quot;</pre><h3>4. Memory</h3><p><strong>Conceptual explanation</strong><br>LLMs are stateless — each API call is independent. Memory components inject <em>conversation history</em> into each prompt, creating the illusion of continuity. LangChain offers several strategies: ConversationBufferMemory (full history), ConversationSummaryMemory (LLM-compressed history), and ConversationBufferWindowMemory (sliding window of last N turns).</p><p><strong>Why it exists</strong><br>A chatbot that forgets what the user just said is useless. But naively appending all history bloats the context window and increases cost. Different memory strategies represent different tradeoffs between fidelity, token usage, and latency.</p><p><strong>Internal intuition</strong><br>Memory works by maintaining a store of past messages. Before each LLM call, the memory object serialises the store into a string or message list and injects it into the prompt. After the LLM responds, the memory updates its store with both the human input and the AI response. The chain never sees raw turn data — only the formatted history string.</p><pre># 4_memory_system.py<br>from langchain_openai import ChatOpenAI<br>from langchain.memory import ConversationBufferMemory<br>from langchain.chains import ConversationChain</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0.5)</pre><pre># Buffer memory stores the full conversation history<br>memory = ConversationBufferMemory(return_messages=True)</pre><pre># ConversationChain automatically manages history injection<br>conversation = ConversationChain(llm=llm, memory=memory, verbose=False)</pre><pre># Turn 1: introduce context<br>r1 = conversation.predict(input=&quot;My name is Arjun and I&#39;m learning about neural networks.&quot;)<br>print(&quot;Turn 1:&quot;, r1[:80])</pre><pre># Turn 2: the model should recall the name<br>r2 = conversation.predict(input=&quot;What should I learn after backpropagation?&quot;)<br>print(&quot;Turn 2:&quot;, r2[:120])</pre><pre># Inspect raw memory contents<br>print(&quot;\nMemory:&quot;, memory.load_memory_variables({}))</pre><h3>5. Agents</h3><p><strong>Conceptual explanation</strong><br>An Agent is an LLM that can <em>decide which action to take</em> at each step, execute it, observe the result, and iterate until it reaches a final answer. Instead of a fixed pipeline, the model drives the control flow. LangChain supports ReAct (Reason + Act) agents, which alternate between generating a <em>thought</em>, choosing a <em>tool</em>, observing the <em>result</em>, and eventually producing a final answer.</p><p><strong>Why it exists</strong><br>Static chains cannot handle tasks where the number of steps is unknown in advance, or where the right action depends on intermediate results. Agents enable dynamic, multi-step reasoning. This is what makes them qualitatively different from chains: the LLM is not just a component in the pipeline — it <em>is</em> the orchestrator.</p><p><strong>Internal intuition</strong><br>In a ReAct agent loop, the LLM receives the user query plus the list of available tools as part of the system prompt. It generates a “Thought: …, Action: …, Action Input: …” block. The agent executor parses the action name, calls the corresponding tool with the input, appends the tool result as an “Observation:”, and feeds everything back to the LLM. This continues until the LLM generates a “Final Answer:” block.</p><pre># 5_agent_with_tools.py<br>from langchain_openai import ChatOpenAI<br>from langchain.agents import create_react_agent, AgentExecutor<br>from langchain_community.tools import DuckDuckGoSearchRun<br>from langchain_core.prompts import PromptTemplate</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>search_tool = DuckDuckGoSearchRun()<br>tools = [search_tool]</pre><pre># ReAct prompt template (standard format)<br>react_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>Answer the following questions as best you can. You have access to these tools:</pre><pre>{tools}</pre><pre>Use the following format:<br>Thought: consider what to do<br>Action: the action to take — must be one of [{tool_names}]<br>Action Input: the input to the action<br>Observation: the result of the action<br>... (repeat Thought/Action/Observation as needed)<br>Thought: I now know the final answer<br>Final Answer: the final answer</pre><pre>Question: {input}<br>{agent_scratchpad}<br>&quot;&quot;&quot;)</pre><pre>agent = create_react_agent(llm, tools, react_prompt)<br>executor = AgentExecutor(agent=agent, tools=tools, verbose=True)</pre><pre>result = executor.invoke({&quot;input&quot;: &quot;What is the latest stable version of Python?&quot;})<br>print(result[&quot;output&quot;])</pre><h3>6. Tools</h3><p><strong>Conceptual explanation</strong><br>A Tool is any function wrapped in a standard interface the agent can call. LangChain ships with built-in tools (web search, calculator, Python REPL, Wikipedia, file I/O) and makes it trivial to define custom tools using the @tool decorator or StructuredTool.</p><p><strong>Why it exists</strong><br>LLMs cannot browse the internet, run code, or query databases by themselves. Tools bridge the gap between language and action. By giving the model a palette of tools with clear descriptions, you essentially extend its capabilities without retraining.</p><p><strong>Internal intuition</strong><br>Each tool has a name, description, and _run(input) method. The description is what the LLM reads to decide when to use the tool. Writing a clear, accurate description is arguably the most important part of tool design — a vague description leads to misuse.</p><pre># 6_custom_tool.py<br>from langchain_core.tools import tool</pre><pre>@tool<br>def celsius_to_fahrenheit(celsius: float) -&gt; str:<br>    &quot;&quot;&quot;Converts a temperature from Celsius to Fahrenheit.<br>    Use this tool when the user provides a temperature in Celsius<br>    and wants the Fahrenheit equivalent.&quot;&quot;&quot;<br>    f = (celsius * 9 / 5) + 32<br>    return f&quot;{celsius}°C = {f:.1f}°F&quot;</pre><pre># Test the tool directly<br>print(celsius_to_fahrenheit.invoke({&quot;celsius&quot;: 100}))<br># Output: &quot;100°C = 212.0°F&quot;</pre><pre># Tool metadata the agent will see:<br>print(celsius_to_fahrenheit.name)        # &quot;celsius_to_fahrenheit&quot;<br>print(celsius_to_fahrenheit.description) # Full docstring</pre><h3>7. Document Loaders</h3><p><strong>Conceptual explanation</strong><br>A Document Loader reads data from a source (PDF, URL, CSV, Notion, S3 bucket, etc.) and returns a list of Document objects, each containing page_content (text) and metadata (source, page number, etc.).</p><p><strong>Why it exists</strong><br>Before you can do RAG (Retrieval-Augmented Generation), you need to ingest your data. LangChain has over 100 loaders that normalise every possible data source into the same format Document format, decoupling ingestion from downstream processing.</p><pre># 7_document_loader.py<br>from langchain_community.document_loaders import PyPDFLoader, WebBaseLoader</pre><pre># Load a PDF (each page becomes one Document)<br>pdf_loader = PyPDFLoader(&quot;research_paper.pdf&quot;)<br>pdf_docs = pdf_loader.load()<br>print(f&quot;Loaded {len(pdf_docs)} pages from PDF&quot;)<br>print(pdf_docs[0].page_content[:200])   # First 200 chars of page 1<br>print(pdf_docs[0].metadata)             # {&quot;source&quot;: &quot;...&quot;, &quot;page&quot;: 0}</pre><pre># Load a web page<br>web_loader = WebBaseLoader(&quot;https://python.org/about&quot;)<br>web_docs = web_loader.load()<br>print(f&quot;\nLoaded {len(web_docs)} document(s) from URL&quot;)</pre><h3>8. Indexes / Vector Stores</h3><p><strong>Conceptual explanation</strong><br>A Vector Store is a database that stores text chunks alongside their dense vector embeddings, and supports approximate nearest-neighbour (ANN) search. Given a query, it returns the top-k most semantically similar chunks. This is the heart of Retrieval-Augmented Generation (RAG).</p><p><strong>Why it exists</strong><br>LLMs have a fixed context window. You cannot stuff an entire 500-page document into a prompt. Vector stores solve this by pre-indexing the document, then retrieving only the relevant chunks at query time — making it possible to “talk to your documents” without exceeding context limits.</p><p><strong>Internal intuition</strong><br>The pipeline is: split documents into chunks → embed each chunk via an embedding model → store (chunk_text, embedding_vector) in the vector DB. At query time: embed the query → run ANN search against stored embeddings → retrieve top-k chunks → inject them into the prompt as context.</p><pre># 8_vector_store_rag.py<br>from langchain_openai import OpenAIEmbeddings, ChatOpenAI<br>from langchain_community.vectorstores import FAISS<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough</pre><pre># Sample knowledge base<br>texts = [<br>    &quot;LangChain was created by Harrison Chase and released in October 2022.&quot;,<br>    &quot;LCEL stands for LangChain Expression Language, introduced in 2023.&quot;,<br>    &quot;LangGraph is a library for building stateful, multi-actor applications with LLMs.&quot;,<br>    &quot;LangSmith is LangChain&#39;s observability and debugging platform.&quot;,<br>]</pre><pre># Create embeddings and index<br>embedder = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>vectorstore = FAISS.from_texts(texts, embedding=embedder)<br>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 2})</pre><pre># RAG chain<br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>rag_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;Answer using only the context below.\nContext:\n{context}&quot;),<br>    (&quot;human&quot;, &quot;{question}&quot;)<br>])</pre><pre>rag_chain = (<br>    {&quot;context&quot;: retriever, &quot;question&quot;: RunnablePassthrough()}<br>    | rag_prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><pre>answer = rag_chain.invoke(&quot;Who created LangChain?&quot;)<br>print(answer)<br># Output: &quot;LangChain was created by Harrison Chase.&quot;</pre><h3>Architecture Explanation</h3><p>The complete LangChain pipeline for a production RAG + Agent system flows like this:</p><pre>┌─────────────────────────────────────────────────────────────────────┐<br>│                         USER INPUT                                  │<br>│                    &quot;What did Einstein say about time?&quot;              │<br>└───────────────────────────────┬─────────────────────────────────────┘<br>                                │<br>                                ▼<br>┌─────────────────────────────────────────────────────────────────────┐<br>│                       PROMPT TEMPLATE                               │<br>│  Injects: {system_prompt} + {memory_history} + {retrieved_context} │<br>│           + {user_question}                                         │<br>└───────────────────────────────┬─────────────────────────────────────┘<br>                                │<br>                    ┌───────────┴────────────┐<br>                    ▼                        ▼<br>         ┌──────────────────┐    ┌───────────────────────┐<br>         │  MEMORY MODULE   │    │   VECTOR STORE        │<br>         │  (past turns)    │    │   (retrieved chunks)  │<br>         └──────────────────┘    └───────────────────────┘<br>                                │<br>                                ▼<br>┌─────────────────────────────────────────────────────────────────────┐<br>│                          LLM / CHAT MODEL                           │<br>│            (reasoning, generation, tool-call decisions)             │<br>└───────────────────────────────┬─────────────────────────────────────┘<br>                                │<br>                    ┌───────────┴──────────┐<br>                    ▼ (if agent)           ▼ (if chain)<br>         ┌──────────────────┐    ┌──────────────────────┐<br>         │  AGENT EXECUTOR  │    │   OUTPUT PARSER      │<br>         │  ┌────────────┐  │    │   (str / pydantic /  │<br>         │  │ Tool Call  │  │    │    custom schema)     │<br>         │  │ Observe    │  │    └──────────────────────┘<br>         │  │ Loop back  │  │<br>         │  └────────────┘  │<br>         └──────────────────┘<br>                    │<br>                    ▼<br>┌─────────────────────────────────────────────────────────────────────┐<br>│                       FINAL OUTPUT                                  │<br>│              (string, structured object, or stream)                 │<br>└─────────────────────────────────────────────────────────────────────┘</pre><p><strong>Data flow, step by step:</strong></p><ol><li><strong>User input arrives</strong> as a plain string or dict with named keys.</li><li><strong>Memory</strong> loads the conversation history and formats it as prior messages.</li><li><strong>Retriever</strong> embeds the query and fetches the top-k relevant document chunks from the vector store.</li><li><strong>Prompt Template</strong> assembles the final prompt: system instructions + history + context + user question.</li><li><strong>LLM</strong> receives the formatted prompt and generates a response (or a tool-call decision if agent mode).</li><li><strong>If the agent</strong>: the executor parses the tool call, invokes the tool, feeds the observation back to the LLM, and loops until a final answer is produced.</li><li><strong>Output Parser</strong> transforms the raw LLM response into the application’s expected format.</li><li><strong>Memory</strong> saves the new turn (human + AI) for the next invocation.</li></ol><h3>Hands-On Code Examples</h3><h3>Example A: Basic LLM Call</h3><pre># example_a_basic_llm.py<br>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import HumanMessage</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>response = llm.invoke([HumanMessage(content=&quot;What is 2+2?&quot;)])<br>print(response.content)  # &quot;4&quot;</pre><h3>Example B: PromptTemplate with Multiple Variables</h3><pre># example_b_prompt_template.py<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser</pre><pre>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a code reviewer. Review {language} code for {issue_type}.&quot;),<br>    (&quot;human&quot;, &quot;```{language}\n{code}\n```&quot;)<br>])</pre><pre>chain = prompt | ChatOpenAI(model=&quot;gpt-4o-mini&quot;) | StrOutputParser()</pre><pre>review = chain.invoke({<br>    &quot;language&quot;: &quot;Python&quot;,<br>    &quot;issue_type&quot;: &quot;security vulnerabilities&quot;,<br>    &quot;code&quot;: &quot;password = input(&#39;Enter password: &#39;)\nprint(f&#39;Password: {password}&#39;)&quot;<br>})<br>print(review)</pre><h3>Example C: Sequential Chain with Intermediate Parsing</h3><pre># example_c_sequential_chain.py<br>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0.7)<br>parser = StrOutputParser()</pre><pre># Step 1: Generate a blog title<br>title_chain = (<br>    ChatPromptTemplate.from_template(&quot;Generate one compelling blog title about: {topic}&quot;)<br>    | llm | parser<br>)</pre><pre># Step 2: Write an intro paragraph for that title<br>intro_chain = (<br>    ChatPromptTemplate.from_template(&quot;Write a 2-sentence intro paragraph for the blog titled: {title}&quot;)<br>    | llm | parser<br>)</pre><pre># Compose into a full pipeline<br>full_chain = title_chain | (lambda title: {&quot;title&quot;: title}) | intro_chain</pre><pre>result = full_chain.invoke({&quot;topic&quot;: &quot;quantum computing for beginners&quot;})<br>print(result)</pre><h3>Example D: Agent with Calculator and Search</h3><pre># example_d_agent_tools.py<br>from langchain_openai import ChatOpenAI<br>from langchain.agents import AgentType, initialize_agent<br>from langchain_community.tools import DuckDuckGoSearchRun<br>from langchain.tools import tool</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)</pre><pre>@tool<br>def calculate(expression: str) -&gt; str:<br>    &quot;&quot;&quot;Evaluate a Python math expression. Input must be a valid Python expression like &#39;2 ** 10&#39; or &#39;(3.14 * 5**2)&#39;.&quot;&quot;&quot;<br>    try:<br>        return str(eval(expression, {&quot;__builtins__&quot;: {}}, {}))<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;</pre><pre>tools = [DuckDuckGoSearchRun(), calculate]</pre><pre>agent = initialize_agent(<br>    tools=tools,<br>    llm=llm,<br>    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,<br>    verbose=True<br>)</pre><pre>result = agent.run(&quot;What is 2 raised to the power of the number of planets in the solar system?&quot;)<br>print(result)</pre><h3>Example E: Conversation with Buffer Memory</h3><pre># example_e_memory.py<br>from langchain_openai import ChatOpenAI<br>from langchain.memory import ConversationBufferWindowMemory<br>from langchain.chains import ConversationChain</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0.6)</pre><pre># Window memory: only keeps the last 3 turns to control token cost<br>memory = ConversationBufferWindowMemory(k=3, return_messages=True)<br>chat = ConversationChain(llm=llm, memory=memory)</pre><pre>responses = [<br>    chat.predict(input=&quot;I&#39;m building a REST API in FastAPI.&quot;),<br>    chat.predict(input=&quot;Should I use Pydantic v1 or v2?&quot;),<br>    chat.predict(input=&quot;What about dependency injection?&quot;),<br>]</pre><pre>for i, r in enumerate(responses, 1):<br>    print(f&quot;Turn {i}: {r[:100]}\n&quot;)</pre><h3>Real-World Use Cases</h3><h3>Use Case 1: Customer Support Chatbot</h3><p><strong>Problem:</strong> A SaaS company wants an AI support agent that answers questions from their 200-page documentation, remembers the ongoing conversation, and escalates to a human when it cannot answer confidently.</p><p><strong>LangChain Solution:</strong></p><ul><li><strong>Document Loaders</strong> ingest the documentation PDFs into chunks.</li><li><strong>FAISS Vector Store</strong> indexes the chunks for semantic search.</li><li><strong>ConversationBufferWindowMemory</strong> retains the last 5 turns per session.</li><li><strong>RAG Chain</strong> retrieves relevant doc sections before every response.</li><li><strong>Output structured with Pydantic</strong>: the model returns {&quot;answer&quot;: &quot;...&quot;, &quot;confidence&quot;: 0.8, &quot;escalate&quot;: false} — when confidence falls below a threshold, the app triggers a human handoff.</li></ul><p><strong>Why LangChain?</strong> The combination of retriever + memory + structured output is available out of the box. What would take weeks to build from scratch takes days.</p><h3>Use Case 2: Automated Code Review Pipeline</h3><p><strong>Problem:</strong> An engineering team wants an AI system that takes a GitHub Pull Request diff, identifies bugs and security issues, suggests improvements, and posts a structured review comment.</p><p><strong>LangChain Solution:</strong></p><ul><li>A <strong>custom Tool</strong> calls the GitHub API to fetch the PR diff.</li><li>A <strong>ChatPromptTemplate</strong> structures the review prompt with severity levels.</li><li>A <strong>PydanticOutputParser</strong> forces the model to return {&quot;issues&quot;: [{&quot;severity&quot;: &quot;high&quot;, &quot;line&quot;: 42, &quot;description&quot;: &quot;...&quot;}]}.</li><li>An <strong>Agent</strong> decides whether to fetch additional context (related files) before giving its final review.</li><li>LangSmith traces every chain run for debugging and quality monitoring.</li></ul><p><strong>Why LangChain?</strong> The structured output parser eliminates fragile regex parsing of LLM responses. The agent’s ability to dynamically fetch related files makes the review context-aware.</p><h3>Use Case 3: Research Paper Summarisation and Q&amp;A System</h3><p><strong>Problem:</strong> A graduate student needs to quickly extract key findings from a corpus of 50+ research papers and ask questions across the entire collection.</p><p><strong>LangChain Solution:</strong></p><ul><li><strong>PyPDFLoader</strong> ingests all papers.</li><li><strong>RecursiveCharacterTextSplitter</strong> chunks them at 1000 tokens with 200-token overlap (to preserve cross-sentence context).</li><li><strong>OpenAI Embeddings</strong> + <strong>Chroma vector store</strong> index the full corpus.</li><li>A <strong>Multi-Query Retriever</strong> generates 3 alternative phrasings of each question before retrieval, improving recall.</li><li>A <strong>Map-Reduce Chain</strong> summarises each retrieved chunk independently before synthesising a final answer — preventing the model from being overwhelmed by context.</li></ul><p><strong>Why LangChain?</strong> The multi-query retriever and map-reduce chain are non-trivial to implement correctly. LangChain ships them as tested, configurable abstractions.</p><h3>Advantages and Limitations</h3><h3>Advantages</h3><p><strong>Modularity</strong> is LangChain’s defining strength. Every component — model, prompt, memory, retriever, parser — adheres to the Runnable protocol. You can swap OpenAI for Claude, FAISS for Chroma, or Buffer memory for Summary memory with a single line change. This makes experimentation fast and production migrations manageable.</p><p><strong>Rapid prototyping</strong> is genuinely accelerated. Patterns that once required days of custom engineering — RAG pipelines, ReAct agents, multi-step chains — are available as high-level abstractions with sensible defaults.</p><p><strong>The integration ecosystem</strong> is unmatched. LangChain integrates with over 100 vector stores, 50+ LLM providers, dozens of document loaders, and major cloud services (AWS, GCP, Azure). The langchain-community package contains community-contributed integrations that expand this further.</p><p><strong>LangSmith</strong> gives production-grade observability: trace every chain run, inspect intermediate steps, compare prompt variants, and set up evaluation datasets — all in a unified dashboard.</p><h3>Limitations</h3><p><strong>Latency</strong> is a real cost. Every abstraction layer adds overhead. A multi-step agent loop may make 5–10 LLM calls to answer one question, compounding both latency and API cost. For latency-sensitive applications, LCEL’s streaming support helps, but the fundamental multi-hop problem remains.</p><p><strong>Debugging difficulty</strong> increases with complexity. When a chain of 6 components produces wrong output, isolating which step failed requires methodical tracing. LangSmith helps, but adds setup overhead. Without it, verbose logging quickly becomes unmanageable.</p><p><strong>Cost</strong> scales non-linearly. Agents that loop, chains that parallelize, and memory that retains full history all accumulate token costs rapidly. Profiling and optimising token usage is a discipline in itself.</p><p><strong>Abstraction leaks</strong> occur when LangChain’s opinionated interfaces conflict with a provider’s unique capabilities. Anthropic’s extended thinking, OpenAI’s function-calling schemas, or provider-specific parameters sometimes require dropping down to raw API calls.</p><h3>When NOT to use LangChain</h3><ul><li><strong>Simple single-turn queries</strong>: If your app just calls an LLM and displays the result, you don’t need LangChain. Use the provider’s SDK directly.</li><li><strong>Ultra-low latency applications</strong>: Each abstraction layer adds milliseconds. For real-time audio/video AI, lean code without framework overhead is preferable.</li><li><strong>Fully custom architectures</strong>: If your pipeline doesn’t map to LangChain’s abstractions, you’ll spend more time fighting the framework than building. Write it from scratch.</li><li><strong>Teams unfamiliar with async Python</strong>: LangChain’s LCEL is heavily async-oriented. Teams without async experience will hit confusing behaviour around event loops.</li></ul><h3>Conclusion</h3><p>LangChain transforms LLM application development from an artisanal, bespoke craft into an engineering discipline. Its core contribution is not any single component — it’s the insight that LLM applications are <em>composable pipelines</em> and the tooling to back that up: a unified Runnable protocol, a rich component library, and an observability platform.</p><p>As an MCA student, working through LangChain forced me to think clearly about what each layer of an AI application actually does. Prompting is not “just wording” — it’s a typed interface to a probabilistic system. Memory is not “just history” — it’s a context management problem with real cost tradeoffs. Agents are not “just smart chatbots” — they’re programs where the LLM is the control flow.</p><p><strong>Key takeaways:</strong></p><ul><li>Use LCEL (the | operator) for all new chains — it’s declarative, streaming-ready, and composable.</li><li>Design tool descriptions as carefully as function signatures — the LLM reads them to decide when to act.</li><li>Profile token usage early; unoptimised agents can cost 10× more than chains.</li><li>LangSmith is not optional for production — instrument from day one.</li></ul><p><strong>Future scope</strong> is genuinely exciting. <strong>LangGraph</strong> extends LangChain’s model to <em>stateful, cyclic</em> multi-agent systems: instead of a linear chain or a single ReAct loop, you define a graph of nodes (agents, tools, conditionals) with edges that can loop back, branch, and run in parallel. This enables complex workflows like supervisor–worker agent hierarchies, self-correcting pipelines, and long-horizon planning tasks. The trajectory is clear: from single LLM calls, to chains, to agents, to multi-agent systems operating autonomously over extended time horizons. LangChain, and especially LangGraph, is the scaffolding for that future.<br>#LangChain #GenerativeAI #LLM #MachineLearning #Python #MCA #AIEngineering #RAG #LLMOps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c66a18642ca2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Token Classification in Natural Language Processing]]></title>
            <link>https://medium.com/@abutalhaparkote/understanding-token-classification-in-natural-language-processing-29a5ebd6af1d?source=rss-32ba97e75223------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a5ebd6af1d</guid>
            <dc:creator><![CDATA[Abutalhaparkote]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 09:15:56 GMT</pubDate>
            <atom:updated>2026-04-04T09:15:56.970Z</atom:updated>
            <content:encoded><![CDATA[<p>A beginner-friendly guide to NER, POS tagging, and chunking — the building blocks of language understanding in machines.</p><p>Table of Contents</p><ul><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#intro">01Introduction to NLP &amp; Token Classification</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#ner">02Named Entity Recognition (NER)</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#pos">03Part-of-Speech (POS) Tagging</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#chunk">04Chunking — Phrase Detection</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#compare">05Comparing the Three Techniques</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#code">06Code Implementation with spaCy</a></li><li><a href="https://c99fe88d62ebd232e49cae90f4d54309.claudemcpcontent.com/mcp_apps?connect-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com&amp;resource-src=https%3A%2F%2Fesm.sh+https%3A%2F%2Fcdnjs.cloudflare.com+https%3A%2F%2Fcdn.jsdelivr.net+https%3A%2F%2Funpkg.com+https%3A%2F%2Fassets.claude.ai&amp;dev=true#bert">07BERT &amp; the Transformer Approach</a></li></ul><p>01 — Introduction</p><h3>What Is NLP, and Why Do Tokens Matter?</h3><p>Natural Language Processing (NLP) is the branch of AI that teaches computers to read, understand, and generate human language. From autocomplete suggestions when you search on Google, to the assistant in your banking chatbot — NLP is quietly powering these experiences.</p><p>At the heart of most NLP systems is the concept of a <strong>token</strong> — the smallest meaningful unit of text. A token is usually a word, but can also be a punctuation mark, a number, or a subword. Before a model can “understand” a sentence, it must first break it into tokens and then analyze each one.</p><p>Think of tokenization like cutting a sentence into puzzle pieces. Token classification is the process of labeling each piece, telling the machine what role every word plays.</p><h3>Real-world examples where this matters</h3><p>Chatbots</p><p>Identify whether the user mentioned a date, a name, or a product to route the request correctly.</p><p>Search engines</p><p>Recognize “Apple” as a company — not a fruit — to surface relevant results.</p><p>Resume parsers</p><p>Extract names, skills, and job titles from unstructured text automatically.</p><p>Medical records</p><p>Pull drug names, dosages, and patient symptoms from clinical notes.</p><p>02 — Named Entity Recognition</p><h3>NER — Teaching Machines to Spot Names</h3><p>Named Entity Recognition (NER) is the task of finding and classifying named entities in text — things like people, organizations, locations, dates, and monetary values. It answers the question: <em>“What specific things are mentioned here?”</em></p><h3>The BIO Tagging Scheme</h3><p>NER uses a tagging system called BIO (Beginning, Inside, Outside) to handle multi-word entities. A tag of B-ORG marks the start of an organization name, I-ORG Mark&#39;s continuation, and O means the token is not part of any entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*NXIdG5Qi9Cl3i82uJESc2Q.png" /></figure><p>NER is used in information extraction pipelines, building knowledge graphs, news aggregation (grouping stories by the entities involved), and financial analysis systems that monitor company mentions.</p><p>03 — Part-of-Speech Tagging</p><h3>POS Tagging — The Grammar of Machines</h3><p>Part-of-Speech (POS) tagging assigns a grammatical category to every token in a sentence. Where NER asks “Is this a name?”, POS tagging asks <em>“What grammatical role does this word play?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*ls8x_RtJCMbgOOf7V6DOxw.png" /></figure><blockquote>POS tagging is essential for building parsers, grammar correction tools, and machine translation systems. It also provides the foundation for the next technique — chunking.</blockquote><p>04 — Chunking</p><h3>Chunking — From Words to Meaningful Phrases</h3><p>Chunking (also called shallow parsing) groups sequences of tokens into short, meaningful phrases called chunks. Rather than labeling individual words, it identifies higher-level units like noun phrases (NP), verb phrases (VP), and prepositional phrases (PP).</p><p>Unlike NER, chunking does not care about <em>what</em> a phrase represents — it only cares about <em>the grammatical structure</em>. It is a step above POS tagging in the NLP pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*F5NtqzCIKbZq-U0sX6evqQ.png" /></figure><p>Chunking is used in query parsing for search engines, information retrieval, and question-answering systems, where understanding phrase-level meaning matters more than individual word roles.</p><p>05 — Comparison</p><h3>NER vs POS Tagging vs Chunking</h3><p>These three techniques work at different levels of the text and serve different purposes. Here is a side-by-side breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*H3j_5hksyomXADDl27mR0g.png" /></figure><p>In practice, these tasks form a pipeline: POS tagging feeds into chunking, and chunking helps identify candidate entities for NER. They are not alternatives — they are layers.</p><p>06 — Code Implementation</p><h3>Putting It Into Practice with spaCy</h3><p>spaCy is one of the most popular Python libraries for NLP. A single pipeline call handles all three tasks at once. Here is a minimal example:</p><pre>import spacy</pre><pre># Load the English model<br>nlp = spacy.load(&quot;en_core_web_sm&quot;)</pre><pre>text = &quot;Elon Musk founded SpaceX in Hawthorne, California in 2002.&quot;<br>doc = nlp(text)</pre><pre># POS Tagging<br>print(&quot;POS Tags:&quot;)<br>for token in doc:<br>    print(token.text, &quot;→&quot;, token.pos_)</pre><pre># Named Entity Recognition<br>print(&quot;\nEntities:&quot;)<br>for ent in doc.ents:<br>    print(ent.text, &quot;→&quot;, ent.label_)</pre><pre># Chunking — noun phrases<br>print(&quot;\nNoun Chunks:&quot;)<br>for chunk in doc.noun_chunks:<br>    print(chunk.text)</pre><p>Running this outputs Elon Musk → PERSON, SpaceX → ORG, Hawthorne → GPE, and 2002 → DATE — all extracted automatically from a single sentence.</p><p>07 — Bonus: Transformers</p><h3>How BERT Handles Token Classification</h3><p>Traditional NER and POS taggers relied on hand-crafted rules or shallow statistical models. BERT (Bidirectional Encoder Representations from Transformers) changed everything by reading each token in <em>full sentence context</em> — both left and right simultaneously.</p><p>Input tokens<br>[“Apple”, “Inc”, “is”, …]</p><p>→Token embeddings<br>+ positional info</p><p>→12× Self-attention<br>bidirectional context</p><p>→Classifier head<br>label per token</p><p>A linear classification layer is placed on top of BERT’s output. For each token position, it predicts the most likely label (e.g., B-ORG, I-ORG, O). Because every token’s representation is enriched by attention to all other tokens, BERT resolves ambiguous cases like “Apple” (fruit vs. company) with remarkable accuracy.</p><pre>from transformers import pipeline</pre><pre>ner = pipeline(&quot;ner&quot;, model=&quot;dslim/bert-base-NER&quot;)<br>result = ner(&quot;Tim Cook visited New Delhi last Monday.&quot;)<br>print(result)<br># [{&#39;entity&#39;: &#39;B-PER&#39;, &#39;word&#39;: &#39;Tim&#39;, ...},<br>#  {&#39;entity&#39;: &#39;I-PER&#39;, &#39;word&#39;: &#39;Cook&#39;, ...},<br>#  {&#39;entity&#39;: &#39;B-LOC&#39;, &#39;word&#39;: &#39;New Delhi&#39;, ...}]</pre><p>With just a few lines using HuggingFace Transformers, you get a state-of-the-art NER model running on any text — no manual feature engineering required.</p><p>Conclusion</p><p>Token classification is the invisible backbone of modern NLP. Whether labeling a single word’s grammar role or identifying a multi-word organization name, these techniques turn raw text into structured, machine-readable knowledge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a5ebd6af1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists vs Tuples in Python: When Should You Use Which?]]></title>
            <link>https://medium.com/@abutalhaparkote/lists-vs-tuples-in-python-when-should-you-use-which-130a52b824d9?source=rss-32ba97e75223------2</link>
            <guid isPermaLink="false">https://medium.com/p/130a52b824d9</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[understanding]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[python-basic-questions]]></category>
            <dc:creator><![CDATA[Abutalhaparkote]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 18:05:11 GMT</pubDate>
            <atom:updated>2026-02-16T18:05:11.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In Python, <strong>lists</strong> and <strong>tuples</strong> are two of the most commonly used data structures.<br> Both store multiple values in a single variable, and beginners often get confused because they look very similar. However, choosing the wrong one can affect <strong>performance, memory usage, and even program safety</strong>.</p><p>This article explains <strong>when to use a list and when to use a tuple, and what real problems each one solves</strong>.</p><h3>What is a List?</h3><p>A <strong>list</strong> is a collection of items that can be changed after creation.<br> It is written using <strong>square brackets </strong><strong>[ ]</strong>.</p><h3>Example</h3><pre>fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;]<br>print(fruits)</pre><h3>Key Features</h3><ul><li>Ordered</li><li>Mutable (can be modified)</li><li>Allows duplicate values</li><li>Can store different data types</li></ul><h3>You can modify it</h3><pre>fruits.append(&quot;orange&quot;)<br>fruits[0] = &quot;grapes</pre><p>So lists are <strong>dynamic containers</strong>.</p><h3>What is a Tuple?</h3><p>A <strong>tuple</strong> is also a collection of items, but it <strong>cannot be changed after creation</strong>.<br> It is written using <strong>parentheses </strong><strong>( )</strong>.</p><h3>Example</h3><pre>coordinates = (10, 20)<br>print(coordinates)</pre><h3>Key Features</h3><ul><li>Ordered</li><li>Immutable (cannot be modified)</li><li>Allows duplicates</li><li>Faster than lists</li></ul><p>If you try:</p><pre>coordinates[0] = 15</pre><p>You will get an error because tuples are read-only.</p><h3>The Most Important Difference — Mutability</h3><p>FeatureListTupleCan add elementsYesNoCan delete elementsYesNoCan change valuesYesNoSafetyLowHigh</p><p><strong>Meaning:</strong></p><ul><li>Use a <strong>list</strong> when the data will change.</li><li>Use a <strong>tuple</strong> when data must not change.</li></ul><p>This is the primary rule developers follow.</p><h3>Performance Comparison</h3><p>Tuples are faster because Python does not need to track modifications.</p><p>OperationFaster StructureIterationTupleReading dataTupleInserting/DeletingList</p><p><strong>Reason:</strong> Lists allocate extra memory for resizing, tuples do not.</p><p>So if you only need to store fixed data → <strong>tuple is more efficient</strong>.</p><h3>Memory Usage</h3><p>Tuples consume <strong>less memory</strong> than lists.</p><p>Why?<br> Lists are resizable containers. Python keeps additional space to allow future insertions.<br> Tuples are fixed-size, so Python allocates only the required memory.</p><p>This becomes important in:</p><ul><li>large datasets</li><li>machine learning datasets</li><li>high-performance applications</li></ul><h3>Real-World Use Cases</h3><h3>When to Use a List</h3><p>Use a list when the data will change during program execution.</p><p><strong>Examples</strong></p><ul><li>Shopping cart items in an e-commerce app</li><li>Student attendance list</li><li>Messages in a chat application</li><li>To-do tasks</li><li>User input collection</li></ul><p><strong>Problem solved:</strong><br> You can <strong>add, remove, or update</strong> values at any time.</p><h3>When to Use a Tuple</h3><p>Use a tuple when the data must remain constant.</p><p><strong>Examples</strong></p><ul><li>GPS coordinates (latitude, longitude)</li><li>RGB color values (255, 0, 0)</li><li>Database records (ID should not change)</li><li>Days of the week</li><li>Configuration settings</li></ul><p><strong>Problem solved:</strong><br> Prevents accidental modification of important data.</p><h3>Practical Example (Why It Matters)</h3><p>Imagine a banking system.</p><p><strong>Account number</strong> should never change → Tuple<br> <strong>Transaction history</strong> changes daily → List</p><pre>account_info = (1234567890, &quot;Abutalha&quot;)   # fixed<br>transactions = [500, -200, 1000]          # changing</pre><p>Using a list for account numbers could allow accidental editing, causing serious errors.</p><h3>When Developers Prefer Tuples</h3><p>Professionals often choose tuples for:</p><ul><li>Returning multiple values from functions</li></ul><pre>def get_user():<br>    return (&quot;Abu&quot;, 21)</pre><ul><li>Dictionary keys</li></ul><pre>locations = {(19.07, 72.87): &quot;Mumbai&quot;}</pre><p>A list cannot be used as a dictionary key because it is mutable.</p><h3>Quick Decision Rule</h3><p>Use <strong>LIST</strong> if:</p><ul><li>Data changes</li><li>You add/remove items</li><li>User input is stored</li></ul><p>Use <strong>TUPLE</strong> if:</p><ul><li>Data is fixed</li><li>Safety is required</li><li>Better performance is needed</li></ul><h3><strong>Conclusion</strong></h3><p>Lists and tuples may look similar, but they solve different problems.<br> A <strong>list</strong> is best for dynamic data that changes over time, while a <strong>tuple</strong> is ideal for fixed and secure data. Understanding mutability helps you write faster, safer, and more memory-efficient Python programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130a52b824d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>