<?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 Yash Babiya on Medium]]></title>
        <description><![CDATA[Stories by Yash Babiya on Medium]]></description>
        <link>https://medium.com/@yashbabiya?source=rss-891ffb54cf5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x8q6Vdskgfe8x6PS</url>
            <title>Stories by Yash Babiya on Medium</title>
            <link>https://medium.com/@yashbabiya?source=rss-891ffb54cf5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:55:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashbabiya/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[LangGraph Tutorial: Building AI Workflows with Python for Ordering Pizza]]></title>
            <link>https://yashbabiya.medium.com/langgraph-tutorial-building-ai-workflows-with-python-for-ordering-pizza-80128e47315a?source=rss-891ffb54cf5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/80128e47315a</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Yash Babiya]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 07:55:10 GMT</pubDate>
            <atom:updated>2025-11-23T07:55:10.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSHqkFO1_RiBAgVj-gykIg.png" /></figure><p><strong>Have you ever gotten bored of doing the same thing over and over again?</strong></p><p>No, I’m not talking about brushing your teeth, taking a shower, going to work, dealing with traffic, watching a movie, wondering why your life feels like this, scrolling through reels, or binge-watching useless videos before falling asleep.</p><p>I’m talking about the real struggle, <strong>ordering a pizza</strong> from your nearest outlet.</p><p>Here’s how it usually goes:</p><p>First, exit Instagram (after an hour of mindless scrolling) → open Swiggy → search for nearby pizza places → pick the right restaurant → find the pizza you like → add it to your cart → place the order → make the payment.</p><p>Phew…</p><p>All that effort, just to say: <em>“I’ll have one medium Peppy Paneer from Domino’s.”</em></p><p>It’s like following a workflow every time. But what if we could <strong>automate</strong> this entire thing?</p><p>Well, that’s where <strong>LangGraph</strong> comes in.</p><p>It gives you an intuitive way to build and automate workflows; and now with LLMs in the picture, it’s even more powerful.</p><p><em>So, what is it?</em></p><p>First of all, let’s try to understand what LangGraph is. It’s a tool that helps <strong>standardize the definition of your workflow</strong>. It uses a <strong>graph structure</strong> to represent the flow and maintains a <strong>shared state</strong> across all the nodes. When you run a workflow, you’re essentially <strong>traversing this graph</strong> with your state.</p><p>In this graph, <strong>each node is a function</strong> that takes the current state, <strong>mutates or updates it</strong>, and then passes it to the next node in the graph.</p><p><em>Hold on…</em></p><p>Now, you might say, <em>“I could implement this without using LangGraph,”</em> and you’re absolutely right. But in practice, your custom implementation might become <strong>messy or difficult to manage</strong> over time. LangGraph takes care of the structure and flow control, so <strong>you can focus entirely on your pizza-ordering logic</strong>.</p><h3>The Basics</h3><p>Let’s first determine what are the things we need to track,</p><p>Basically, it would be: my input, restaurant, food item and it’s options, also did i completed the payment or not. This will be the state of the graph</p><pre>from typing import TypedDict, Optional, List<br><br><br>class PizzaState(TypedDict, total=False):<br>    user_input: str                   <br>    restaurant: Optional[str]         <br>    food_item: Optional[str]         <br>    options: Optional[List[str]]    <br>    payment_done: bool</pre><p>So, let’s first determine how much function we’ll need</p><ol><li>Ask For My input ( Where I can say <em>“I’ll have one medium Peppy Paneer from Domino’s.” )</em></li><li>Search For Restaurant</li><li>Search For Food Item</li><li>Select the correct option</li><li>Take the payment confirmation from me ( No trust issues, but still I like to be in command )</li></ol><p>So these functions are basically Nodes in graph. <em>(Yeah, Cursor Could Write This, But Here It Is Anyway)</em></p><pre>graph = StateGraph(PizzaState)<br><br>graph.add_node(&quot;ask_order&quot;, ask_user_node)<br>graph.add_node(&quot;search_restraunt&quot;, search_restraunt_node)<br>graph.add_node(&quot;search_food_item&quot;, search_food_in_menu)<br>graph.add_node(&quot;select_option&quot;, select_option)<br>graph.add_node(&quot;pay&quot;, payment_node)<br>graph.add_node(&quot;complete&quot;, complete_node)</pre><p>Now at each step, I also have to make sure that if It cannot find the result it will stop the workflow, For example if there are no “Pineapple Pizza” in Domino’s It should stop the workflow.</p><p>Now, Just make a separate “git branch” in your head, First let me show you the manual way, then a cooler way to do this thing.</p><h3><em>“The Manual Way”</em></h3><p>We’ll need conditional edges - basically, checkpoints that decide whether to move forward or stop the workflow.</p><p>Think of it like this: at each step, we’re asking, “Did we get what we need? Cool, move on. Didn’t find it? Stop right there.”</p><p>Here’s how we define those conditions:</p><pre>def should_continue_after_restaurant(state: PizzaState) -&gt; str:<br>    &quot;&quot;&quot;Check if restaurant was found&quot;&quot;&quot;<br>    if state.get(&quot;restaurant&quot;):<br>        return &quot;search_food_item&quot;  *# Found it? Let&#39;s find the food*<br>    return &quot;complete&quot;  *# Nope? We&#39;re done here*<br><br>def should_continue_after_food(state: PizzaState) -&gt; str:<br>    &quot;&quot;&quot;Check if food item exists in menu&quot;&quot;&quot;<br>    if state.get(&quot;food_item&quot;):<br>        return &quot;select_option&quot;  *# Found it? Pick size and quantity*<br>    return &quot;complete&quot;  *# Not on the menu? Workflow ends*<br>def should_continue_after_options(state: PizzaState) -&gt; str:<br>    &quot;&quot;&quot;Check if options are selected&quot;&quot;&quot;<br>    if state.get(&quot;options&quot;):<br>        return &quot;pay&quot;  *# All set? Time to pay*<br>    return &quot;complete&quot;  *# Something&#39;s off? Stop*<br>def should_continue_after_payment(state: PizzaState) -&gt; str:<br>    &quot;&quot;&quot;Check if payment is done&quot;&quot;&quot;<br>    if state.get(&quot;payment_done&quot;):<br>        return &quot;complete&quot;  *# Paid? We&#39;re done!*<br>    return &quot;ask_order&quot;  *# Payment failed? Start over (sad, but true)*</pre><p>Now let’s wire these conditions into our graph:</p><pre>graph.set_entry_point(&quot;ask_order&quot;)<br><br>graph.add_conditional_edges(<br>    &quot;ask_order&quot;,<br>    lambda state: &quot;search_restraunt&quot;<br>)<br>graph.add_conditional_edges(<br>    &quot;search_restraunt&quot;,<br>    should_continue_after_restaurant<br>)<br>graph.add_conditional_edges(<br>    &quot;search_food_item&quot;,<br>    should_continue_after_food<br>)<br>graph.add_conditional_edges(<br>    &quot;select_option&quot;,<br>    should_continue_after_options<br>)<br>graph.add_conditional_edges(<br>    &quot;pay&quot;,<br>    should_continue_after_payment<br>)<br>graph.set_finish_point(&quot;complete&quot;)</pre><p>If Defining the exact route looks harcoded to you then there’s an “AI” way of doing this:</p><h3><em>“The Cooler Way”</em></h3><p>The idea is that instead of defining the path manually there should be a “guide/captain” that manages where the flow should go. Formally speaking you need an “orchestrator” (love that fancy word).</p><p>Instead of hardcoding logic inside each node or condition, we’ll use an LLM as an orchestrator, a smart decision-maker that looks at the current state and decides what should happen next.</p><p>Think of it like having a really smart manager at the pizza place who looks at your order and instantly knows: “Ah, they mentioned Domino’s but not the size; let me route this to the options selection.”</p><blockquote><strong>Caution:</strong></blockquote><blockquote><strong>This orchestrator will eat your tokens, so be careful where you use it, it’s money afterall.</strong></blockquote><pre>from langchain_openai import ChatOpenAI<br><br><br>llm = ChatOpenAI(model=&quot;gpt-4&quot;, temperature=0)<br>def orchestrator(state: PizzaState, current_node: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    The LLM orchestrator that decides what to do next.<br>    It&#39;s like the brain of the operation.<br>    &quot;&quot;&quot;<br>    <br>    prompt = f&quot;&quot;&quot;<br>    You are an order processing orchestrator. Based on the current state, decide the next action.<br>    <br>    Current Node: {current_node}<br>    Current State:<br>    - User Input: {state.get(&#39;user_input&#39;, &#39;None&#39;)}<br>    - Restaurant: {state.get(&#39;restaurant&#39;, &#39;Not set&#39;)}<br>    - Food Item: {state.get(&#39;food_item&#39;, &#39;Not set&#39;)}<br>    - Options: {state.get(&#39;options&#39;, &#39;Not set&#39;)}<br>    - Payment Done: {state.get(&#39;payment_done&#39;, False)}<br>    <br>    Possible next actions:<br>    - search_restraunt: If restaurant is not identified yet<br>    - search_food_item: If restaurant is set but food item is not<br>    - select_option: If food item is set but options (size/quantity) are not<br>    - pay: If everything is set but payment is not done<br>    - complete: If payment is done OR if something is missing and we can&#39;t proceed<br>    - ask_order: If we need more information from user<br>    <br>    Return ONLY the next action name, nothing else.<br>    &quot;&quot;&quot;<br>    <br>    response = llm.invoke(prompt)<br>    next_action = response.content.strip()<br>    <br>    return next_action</pre><p>Now our nodes become ridiculously simple — they just extract or update information, no complex decision-making:</p><pre>def search_restraunt_node(state: PizzaState) -&gt; PizzaState:<br>    &quot;&quot;&quot;Just extract the restaurant name, that&#39;s it&quot;&quot;&quot;<br>    user_input = state[&quot;user_input&quot;].lower()<br>    <br>    *# Simple keyword matching*<br>    if &quot;domino&quot; in user_input:<br>        state[&quot;restaurant&quot;] = &quot;Domino&#39;s&quot;<br>    elif &quot;pizza hut&quot; in user_input:<br>        state[&quot;restaurant&quot;] = &quot;Pizza Hut&quot;<br>    elif &quot;papa john&quot; in user_input:<br>        state[&quot;restaurant&quot;] = &quot;Papa John&#39;s&quot;<br>    <br>    return state<br><br><br><br>def search_food_in_menu(state: PizzaState) -&gt; PizzaState:<br>    &quot;&quot;&quot;Find the item in menu, don&#39;t overthink it&quot;&quot;&quot;<br>    user_input = state[&quot;user_input&quot;].lower()<br>    <br>    *# Mock menu (in reality, you&#39;d fetch this from a database)*<br>    menu_items = {<br>        &quot;Domino&#39;s&quot;: [<br>            &quot;Margherita Pizza&quot;,<br>            &quot;Peppy Paneer Pizza&quot;,<br>            &quot;Farmhouse Pizza&quot;,<br>            &quot;Chicken Dominator&quot;<br>        ],<br>        &quot;Pizza Hut&quot;: [<br>            &quot;Veggie Supreme&quot;,<br>            &quot;Chicken Tikka&quot;,<br>            &quot;Pepperoni&quot;<br>        ]<br>    }<br>    <br>    restaurant = state.get(&quot;restaurant&quot;)<br>    if not restaurant:<br>        return state<br>    <br>    available_items = menu_items.get(restaurant, [])<br>    <br>    for item in available_items:<br>        if item.lower() in user_input:<br>            state[&quot;food_item&quot;] = item<br>            break<br>    <br>    return state<br>def select_option_node(state: PizzaState) -&gt; PizzaState:<br>    &quot;&quot;&quot;Extract size and quantity, nothing fancy&quot;&quot;&quot;<br>    user_input = state[&quot;user_input&quot;].lower()<br>    <br>    options = {}<br>    <br>    *# Size detection*<br>    if &quot;medium&quot; in user_input:<br>        options[&quot;size&quot;] = &quot;Medium&quot;<br>    elif &quot;large&quot; in user_input:<br>        options[&quot;size&quot;] = &quot;Large&quot;<br>    elif &quot;small&quot; in user_input:<br>        options[&quot;size&quot;] = &quot;Small&quot;<br>    else:<br>        options[&quot;size&quot;] = &quot;Regular&quot;<br>    <br>    *# Quantity detection (defaults to 1)*<br>    options[&quot;quantity&quot;] = 1<br>    if &quot;two&quot; in user_input or &quot;2&quot; in user_input:<br>        options[&quot;quantity&quot;] = 2<br>    elif &quot;three&quot; in user_input or &quot;3&quot; in user_input:<br>        options[&quot;quantity&quot;] = 3<br>    <br>    state[&quot;options&quot;] = options<br>    return state<br>def payment_node(state: PizzaState) -&gt; PizzaState:<br>    &quot;&quot;&quot;Simulate payment (in reality, you&#39;d integrate with a payment gateway)&quot;&quot;&quot;<br>    print(f&quot;\\nProcessing payment for:&quot;)<br>    print(f&quot;  Restaurant: {state.get(&#39;restaurant&#39;)}&quot;)<br>    print(f&quot;  Item: {state.get(&#39;food_item&#39;)}&quot;)<br>    print(f&quot;  Options: {state.get(&#39;options&#39;)}&quot;)<br>    print(&quot;Payment successful! 🎉\\n&quot;)<br>    <br>    state[&quot;payment_done&quot;] = True<br>    return state</pre><h3>Wiring Everything with the Orchestrator</h3><p>Now here’s the magic — we replace all those manual conditional functions with our orchestrator:</p><pre>*# Set the entry point*<br>graph.set_entry_point(&quot;ask_order&quot;)<br><br>*# Let the orchestrator decide everything*<br>graph.add_conditional_edges(<br>    &quot;ask_order&quot;,<br>    lambda state: orchestrator(state, &quot;ask_order&quot;)<br>)<br>graph.add_conditional_edges(<br>    &quot;search_restraunt&quot;,<br>    lambda state: orchestrator(state, &quot;search_restraunt&quot;)<br>)<br>graph.add_conditional_edges(<br>    &quot;search_food_item&quot;,<br>    lambda state: orchestrator(state, &quot;search_food_item&quot;)<br>)<br>graph.add_conditional_edges(<br>    &quot;select_option&quot;,<br>    lambda state: orchestrator(state, &quot;select_option&quot;)<br>)<br>graph.add_conditional_edges(<br>    &quot;pay&quot;,<br>    lambda state: orchestrator(state, &quot;pay&quot;)<br>)<br>graph.set_finish_point(&quot;complete&quot;)</pre><h3>The Full Picture</h3><p>Let’s actually run this thing:</p><pre>from langgraph.graph import StateGraph, END<br><br>app = graph.compile()<br>initial_state = {<br>    &quot;user_input&quot;: &quot;I&#39;ll have one medium Peppy Paneer from Domino&#39;s&quot;,<br>    &quot;payment_done&quot;: False<br>}<br>result = app.invoke(initial_state)<br>print(&quot;Final State:&quot;)<br>print(f&quot;Restaurant: {result.get(&#39;restaurant&#39;)}&quot;)<br>print(f&quot;Food Item: {result.get(&#39;food_item&#39;)}&quot;)<br>print(f&quot;Options: {result.get(&#39;options&#39;)}&quot;)<br>print(f&quot;Payment Done: {result.get(&#39;payment_done&#39;)}&quot;)</pre><p>Each node is a specialist that does one thing well. The orchestrator is the manager who knows everyone’s job and assigns tasks accordingly.</p><p>Now sure, LLM deciding the Pizza workflow is an overkill, “Manual Way” is the better way, but think about complex workflows, where thinking which path to take is not that straight forward to put in manual way.</p><p>For Example:</p><p>Think about customer support. They get all kinds of different queries from users, and someone needs to figure out which team should handle each one. In our LangGraph terms, each specialized team is a node, and the support coordinator is our LLM orchestrator, the brain that decides ‘okay, this goes to billing, that goes to tech support.’</p><p>With LangGraph, your workflow stays clean, your logic stays separated, and your pizza order stays on track.</p><p>Now, if you’ll excuse me, I’m going to order that Peppy Paneer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80128e47315a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How 10-Minute Deliveries Are Made Possible: The Technology and Tools Behind Route Optimization with…]]></title>
            <link>https://yashbabiya.medium.com/how-10-minute-deliveries-are-made-possible-the-technology-and-tools-behind-route-optimization-with-65832b5ac1e0?source=rss-891ffb54cf5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/65832b5ac1e0</guid>
            <category><![CDATA[quick-commerce]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[or-tools]]></category>
            <category><![CDATA[blinkit]]></category>
            <dc:creator><![CDATA[Yash Babiya]]></dc:creator>
            <pubDate>Sun, 18 May 2025 08:20:49 GMT</pubDate>
            <atom:updated>2025-05-18T09:27:02.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>How 10-Minute Deliveries Are Made Possible: The Technology and Tools Behind Route Optimization with Google OR-Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*qkkwMYatnJXKWzVUSQc_8Q.png" /></figure><p>It’s Sunday morning. You’re relaxing at home when your mom asks you to join her for some grocery shopping. She outlines the whole plan:</p><p>“First, get some milk from the dairy, then buy fruits from the vendor, and finally pick up sugar and salt from the grocery store.”</p><p>You’re not exactly excited about it — but of course, saying “no” to mom isn’t really an option.</p><p>Then it hits you: <em>Blinkit</em> can do this for you. You quickly grab your phone, place the order, and within 10 minutes, everything is delivered to your doorstep.</p><p>Mom’s happy. You’re happy. And just like that, you’re back on the sofa, phone in hand, doing absolutely nothing.</p><p>But wait — have you ever wondered about the delivery guy? He probably had a few more stops before yours, and he’s likely heading out for a few more after.</p><p>Sounds familiar? Yep, it’s the good old <em>Travelling Salesman Problem</em> from college.</p><p>But take a step back, and things get more interesting. It’s not just about finding the best route for one person. Imagine hundreds of delivery drivers and thousands of orders. The real challenge? Assigning the right deliveries to the right people in the right order, all while minimizing time, cost, and effort.</p><p>This is what’s known as the <strong>Vehicle Routing Problem (VRP)</strong> — a classic in operations research.</p><p>Today, we’re going to explore how Blinkit tackles this challenge using Google’s powerful open-source optimization toolkit: <strong>OR-Tools</strong>.</p><h3>What is Google OR-Tools ?</h3><p><strong>Google OR-Tools</strong> (Operations Research Tools) is an <strong>open-source software suite</strong> developed by Google for solving <strong>combinatorial optimization problems</strong>, like:</p><ul><li><strong>Vehicle Routing Problems (VRP)</strong></li><li><strong>Traveling Salesman Problem (TSP)</strong></li><li><strong>Linear Programming (LP)</strong></li><li><strong>Integer Programming (MIP)</strong></li><li><strong>Constraint Programming (CP)</strong></li></ul><p>Basically, It gives a way in which you can define you existing problem and then with it’s provided solver algorithms it gives a solution to it.</p><h3>How Blinkit uses OR-Tools ?</h3><p>In Blinkit’s delivery system, each <strong>pickup</strong> and <strong>delivery location</strong> can be modeled as a <strong>node</strong> in a graph. The <strong>edges (or arcs)</strong> between these nodes represent the possible routes a driver can take between locations.</p><p><strong>Each node</strong> carries attributes like:</p><ul><li>order_value – the monetary worth of the order</li><li>order_weight or volume</li><li>Type: whether it’s a <strong>pickup</strong> or a <strong>delivery</strong></li><li>Optional: time_window, priority_level, etc.</li></ul><p><strong>Each edge</strong> (between two nodes) has an associated <strong>cost</strong>, which could be:</p><ul><li>Travel distance</li><li>Estimated time</li><li>Fuel or operational cost</li></ul><h3>Optimization Goal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*0X1t7FHp_PMGwfe15GOkxg.png" /></figure><p>The objective is to use the available fleet of delivery drivers to <strong>traverse this graph</strong> in a way that:</p><ul><li><strong>Minimizes total distance or time traveled</strong></li><li><strong>Minimizes the number of active vehicles used</strong></li><li><strong>Maximizes the total order value delivered</strong></li></ul><p>This forms a <strong>multi-objective routing problem</strong>, which is well-suited for tools like <strong>Google OR-Tools</strong>.</p><h3>Implementation</h3><h3>Initialize</h3><p>If we try to model our problem in python, it would look like this:</p><pre>locations = [<br>    {<br>	    &quot;id&quot;: 0, <br>	    &quot;type&quot;: &quot;depot&quot;, <br>	    &quot;visiting_time_from&quot;: &quot;12:00 AM&quot;,<br>	    &quot;visiting_time_to&quot;: &quot;10:00 PM&quot;,<br>	    &quot;lat&quot;: ..., <br>	    &quot;lng&quot;: ...<br>	  },<br>    {<br>	    &quot;id&quot;: 1, <br>	    &quot;type&quot;: &quot;pickup&quot;,<br>	    &quot;weight&quot;: 3.5,<br>	    &quot;visiting_time_from&quot;: &quot;06:00 AM&quot;,<br>	    &quot;visiting_time_to&quot;: &quot;09:00 PM&quot;,<br>	    &quot;lat&quot;: ..., <br>	    &quot;lng&quot;: ...<br>	  },<br>	  {<br>	    &quot;id&quot;: 2, <br>	    &quot;type&quot;: &quot;pickup&quot;,<br>	    &quot;weight&quot;: 4.5,<br>	    &quot;visiting_time_from&quot;: &quot;06:00 AM&quot;,<br>	    &quot;visiting_time_to&quot;: &quot;09:00 PM&quot;,<br>	    &quot;lat&quot;: ..., <br>	    &quot;lng&quot;: ...<br>	  },<br>    {<br>	    &quot;id&quot;: 3, <br>	    &quot;type&quot;: &quot;delivery&quot;, <br>	    &quot;order_value&quot;: 120, <br>	    &quot;weight&quot;: -3.5,<br>	    &quot;visiting_time_from&quot;: &quot;01:00 PM&quot;,<br>	    &quot;visiting_time_to&quot;: &quot;01:30 PM&quot;,<br>	    &quot;lat&quot;: ..., <br>	    &quot;lng&quot;: ...<br>	  },<br>	  {<br>	    &quot;id&quot;: 4, <br>	    &quot;type&quot;: &quot;delivery&quot;, <br>	    &quot;order_value&quot;: 300, <br>	    &quot;weight&quot;: -4.5,<br>	    &quot;visiting_time_from&quot;: &quot;03:00 PM&quot;,<br>	    &quot;visiting_time_to&quot;: &quot;03:30 PM&quot;,<br>	    &quot;lat&quot;: ..., <br>	    &quot;lng&quot;: ...<br>	  },<br>]<br><br># Distance Matrix (from each location to each other)<br>distance_matrix = [<br>    [0, 10, 15],<br>    [10, 0, 8],<br>    [15, 8, 0],<br>]<br># Pickup and Delivery pairs (node indices)<br>pickup_delivery_pairs = [<br>    (1, 3),<br>    (2, 4)<br>    # more pairs...<br>]</pre><p>As you have noticed there are three types of locations:</p><ul><li>Depot: Where a driver usually starts and end his journey.</li><li>Pickup: Where a driver will pickup a order.</li><li>Delivery: Where driver need to deliver the order. ( Ignore the negative weight for now, we’ll discuss this further )</li></ul><p>Here there are 2 things to keep in mind that</p><ul><li>Pickup has to be visited before Delivery ( Obvious )</li><li>You can only visit a specific location in a specific time window.</li></ul><p>There is distance_matrix, which shows you the distance between locations, also pickup_delivery_pairs which is basically where to pickup and where to deliver the goods.</p><p>Now you also have to define the Drivers, which are going to deliver this:</p><pre>drivers = [<br>		{<br>	    &quot;id&quot;: 1,<br>	    &quot;depot&quot;: 0,<br>	    &quot;max_weight_capacity&quot;: 5,<br>	    &quot;start_time&quot;: &quot;10:00 AM&quot;,<br>	    &quot;end_time&quot;: &quot;05:00 PM&quot;<br>	  },<br>	  {<br>	    &quot;id&quot;: 2,<br>	    &quot;depot&quot;: 0,<br>	    &quot;max_weight_capacity&quot;: 10,<br>	    &quot;start_time&quot;: &quot;09:00 AM&quot;,<br>	    &quot;end_time&quot;: &quot;01:00 PM&quot;<br>	  },<br>	  # ...<br> ]</pre><p>So, for the drivers these are the things:</p><ul><li>Depot: The default location from where each driver starts and end his journey. ( For the sack of simplicity we have kept it 0 for all drivers )</li><li>max_weight_capacity: the amount of “kgs” a driver can lift on his vehicle on his journey. ( keep in mind that once you deliver the package, you won’t have to carry it anymore ) ( Now you know why delivery locations have negative weights because you unload those weights there )</li><li>start_time — end_time: the time window in which driver can work.</li></ul><p>also we might need some type of helper function that can convert 05:00 PM → 1020 ( minute of day )</p><pre>from datetime import datetime<br><br>def time_to_minutes(time_str):<br>    dt = datetime.strptime(time_str.strip(), &quot;%I:%M %p&quot;)<br>    return dt.hour * 60 + dt.minute<br># Example usage<br>print(time_to_minutes(&quot;05:00 PM&quot;)) # Output 1020</pre><p>Now OR-tools comes into picture:</p><p>First we need to register these things into the RoutingModel ( provided by ortools )</p><pre>from ortools.constraint_solver import pywrapcp<br><br>manager = pywrapcp.RoutingIndexManager(<br>            len(locations),  # Number of locations<br>            len(drivers),    # Number of drivers available<br>            [d.get(&#39;depot&#39;) for d in drivers],  # list of start location for each driver<br>            [d.get(&#39;depot&#39;) for d in drivers]   # list of end location for each driver<br>        )<br>        <br>routing = pywrapcp.RoutingModel(manager)</pre><h3>Dimensions</h3><p>Now in routing we have defined our initial problem space but not completely, We yet need to define time window constraint and weight constraint.</p><p>If you deep down in our problem statement you’ll find out that these constraints are not depending upon one node itself however it is depending upon the “Cumulative” value which you’ll get from your path. For tracking the cumulative values, ortools provides a feature called “Dimension” which will track these things, along with your driver in his journey.</p><p>This is how you can keep track of time ( in minutes ) along with a driver’s journey.</p><pre>def travel_time(from_index, to_index):<br>  from_node = manager.IndexToNode(from_index)<br>  to_node = manager.IndexToNode(to_index)<br>  return distance_matrix[from_node][to_node] // 40 # assuming that driver&#39;s avg speed is 40<br><br><br>transit_callback_index = routing.RegisterTransitCallback(travel_time)<br>time_dimension_name = &#39;Time&#39;<br>routing.AddDimension(<br>    transit_callback_index,<br>    24 * 60,           # Can wait for 24 Hours before visiting the next node<br>    1440,              # Max time (whole day)<br>    False,             # Don&#39;t force start at zero<br>    time_dimension_name<br>)<br>time_dimension = routing.GetDimensionOrDie(time_dimension_name)</pre><p>Now as you can see to track the time we need all the arcs in the graph, but to track the weight we only need nodes in the journey. So for node we’ll use RegisterUnaryTransitCallback instead of RegisterTransitCallback</p><pre>def get_weight(node_index):<br>  node = manager.IndexToNode(node_index)<br>  return locations[node][&#39;weight&#39;]<br><br><br>callback = routing.RegisterUnaryTransitCallback(get_weight)<br>weight_dimension_name = &#39;Weight&#39;<br>routing.AddDimensionWithVehicleCapacity(<br>    callback,<br>    0,<br>    [d.get(&#39;max_weight_capacity&#39;) for d in drivers], # Max allowed weight<br>    True,<br>    weight_dimension_name<br>)<br>weight_dimension = routing.GetDimensionOrDie(weight_dimension_name)</pre><h3>Adding constraints</h3><p>So now as we have cumulative values for each let’s just add the constraints we have discussed earlier:</p><p>For Time dimension:</p><ul><li>Pickup and deliveries need to be visited in order and by same driver.</li><li>We need to make sure no driver will work beyond his schedule ( start and end time )</li><li>We cannot visit a location out side of it’s time window ( visiting_time_from, visiting_time_to )</li></ul><pre>for pickup, delivery in pickup_delivery_pairs:<br>    pickup_index = manager.NodeToIndex(pickup)<br>    delivery_index = manager.NodeToIndex(delivery)<br>    <br>    # Register pickup and delivery pairs<br>    routing.AddPickupAndDelivery(pickup_index, delivery_index)<br>    <br>    # Pickup and delivery by same drivers<br>    routing.solver().Add(routing.VehicleVar(pickup_index) == routing.VehicleVar(delivery_index))<br>		<br>		# Visit pickup before delivery<br>		routing.solver().Add(time_dimension.CumulVar(pickup_index) &lt;= time_dimension.CumulVar(delivery_index)) <br>		<br>		<br>for d_idx, driver in enumerate(drivers):<br>	start_index = self.routing.Start(d_idx)<br>  end_index = self.routing.End(d_idx)<br>  <br>  driver_working_window = [time_to_minutes(driver[&#39;start_time&#39;]), time_to_minutes(driver[&#39;end_time&#39;])]<br>  <br>  <br>  # First node driver visits should be between his time range<br>  time_dimension.CumulVar(start_index).SetRange(driver_working_window[0], driver_working_window[1])<br>  <br>  # Last node driver visits also should be between his time range<br>  time_dimension.CumulVar(end_index).SetRange(driver_working_window[0], driver_working_window[1])<br>  <br><br>for location_idx, location in enumerate(locations):<br>  index = manager.NodeToIndex(location_idx)<br>  window = [time_to_minutes(node_data[&#39;visiting_time_from&#39;]), time_to_minutes(node_data[&#39;visiting_time_to&#39;])]<br>  <br>  # For location at location_idx set the time window.<br>  time_dimension.CumulVar(index).SetRange(window[0], window[1])</pre><h3>Solving the Problem</h3><p>Now as we have defined our problem to RoutingModel, we now have to just find the solution.</p><p>ortools provides different types of algorithms by which you can solve this problem. There are basically 2 types of “set” of searching algorithms</p><ul><li>First Solution ( Greedy Algorithms ):<br>PATH_CHEAPEST_ARC, GLOBAL_CHEAPEST_ARC, SAVINGS, PARALLEL_CHEAPEST_INSERTION, CHRISTOFIDES, …</li><li>Metaheuristics: <br>GUIDED_LOCAL_SEARCH, TABU_SEARCH, SIMULATED_ANNEALING, …</li></ul><p>As VRP is an NP-hard problem, it takes too much time to find a global optimal solution, so for business use, we first find a <strong>feasible solution quickly using a first solution strategy</strong>, and then <strong>optionally improve it using metaheuristics within a time limit</strong> to get a good-enough solution in a reasonable time.</p><pre>from ortools.constraint_solver import routing_enums_pb2<br><br>search_parameters = pywrapcp.DefaultRoutingSearchParameters()<br>search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC<br>search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH<br>search_parameters.time_limit.FromSeconds(10)</pre><h3>Conclusion</h3><p>So now you know that there’s a whole squad of smart algorithms and delivery heroes working behind the scenes to make sure your milk, fruits, and sugar arrive just in time.</p><p>Thanks to Blinkit and some clever route-planning wizardry, you get to enjoy the easy part — while the real adventure happens on the roads!</p><p>Thanks for reading! If you enjoyed this, don’t forget to hit that clap 👏button and subscribe for more awesome stories and tech deep-dives coming your way. Stay curious and keep exploring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65832b5ac1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LLMs Use Vector Databases for Long-Term Memory: A Beginner’s Guide]]></title>
            <link>https://yashbabiya.medium.com/how-llms-use-vector-databases-for-long-term-memory-a-beginners-guide-e0990e6a0a3f?source=rss-891ffb54cf5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0990e6a0a3f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Yash Babiya]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 07:51:58 GMT</pubDate>
            <atom:updated>2025-04-26T07:51:58.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdQS59Jh85nClNjISmbb1g.png" /></figure><p>Vector databases are becoming the secret weapon that helps Large Language Models (LLMs) remember your conversations over time. In this article, we’ll explore how these powerful tools work together to give AI a better memory, breaking down complex concepts into simple explanations that anyone can understand.</p><h3>What’s the Problem with LLM Memory?</h3><p>Large Language Models face a significant challenge: they find it difficult to retain information from long conversations. Think about talking to someone with short-term memory issues — you might have a great conversation, but if you return an hour later, they’ve forgotten most of what you discussed. That’s essentially what happens with many AI systems.</p><p>When you interact with an LLM, it can only “see” a limited amount of text at once (called a context window). This means that after a certain point, earlier parts of your conversation get pushed out and forgotten. For complex tasks that require remembering many details over time, this creates major problems.</p><h3>Understanding Vector Databases: Your AI’s Memory Bank</h3><p>To understand vector databases, let’s start with a simple analogy.</p><h3>What is a Vector, Anyway?</h3><p>Think of a <strong>vector</strong> like a set of coordinates that tells you where to find something. Just as we might say “go 3 blocks north and 2 blocks east” to locate a coffee shop, a vector uses numbers to locate information in a conceptual space.</p><p>In the context of AI, a vector is a series of numbers that represents a piece of information. For example:</p><ul><li>The sentence “I love pizza” might be converted to [0.2, 0.8, -0.3, 0.5, …]</li><li>While “I hate pizza” might be [0.2, -0.7, -0.3, 0.4, …]</li></ul><p>Notice how some numbers are similar while others differ? That’s because these vectors capture the meaning of the text — similar meanings have similar vectors.</p><h3>How Vector Databases Work</h3><p>Imagine your traditional library catalog as a regular database:</p><ul><li>Books are organized by title, author, or subject in neat rows and columns</li><li>To find a book, you need to know exactly what you’re looking for</li></ul><p>Now imagine a <strong>vector database</strong> as a magical library where:</p><ul><li>Books are organized by their actual meaning and content</li><li>Similar books naturally cluster together in the space</li><li>You can ask “find me something like this book” and get relevant results</li><li>The library remembers which books you’ve read and enjoyed before.</li></ul><h3>How LLMs Use Vector Databases for Memory</h3><p>So how do LLMs use these vector databases to remember your conversations? Let’s break it down:</p><h3>1. Storing Memories as Vectors</h3><p>When you chat with an LLM, important pieces of your conversation (like your preferences, questions, or key information) get converted into vectors and stored in a vector database. This works like taking notes during a conversation.</p><p>Think of it like this:</p><ul><li>Regular memory: Taking a photograph (exact, but limited space)</li><li>Vector memory: Writing down key points in a notebook (compact, can store more)</li></ul><h3>2. Retrieving Relevant Information</h3><p>When you ask a new question or continue a conversation, the LLM:</p><ol><li>Converts your new input into a vector</li><li>Searches the vector database for similar vectors (representing related past conversations)</li><li>Retrieves the most relevant information</li><li>Uses this context to generate a more informed response</li></ol><p>This is similar to how you might flip through your notebook to find relevant notes before answering a question.</p><h3>3. Managing Memory Efficiently</h3><p>Not everything needs to be remembered forever. Modern systems like <strong>VIMBank</strong> (a vector storage long-term memory model) use clever techniques to manage memory efficiently:</p><ul><li><strong>Dynamic memory updating</strong>: Important information gets reinforced</li><li><strong>Forgetting curve</strong>: Less important details gradually fade, just like human memory</li><li><strong>Optimized storage</strong>: Only the most useful information is kept</li></ul><p>This mimics how your brain might remember your best friend’s birthday but forget what you had for lunch three weeks ago.</p><h3>Real-World Examples</h3><p>Let’s look at some everyday scenarios to understand how this technology helps:</p><h3>The Personal Assistant</h3><p>Imagine talking to an AI assistant throughout your day:</p><p><strong>Without long-term memory</strong>:</p><ul><li>You: “What’s a good recipe for lasagna?”</li><li>AI gives recommendations</li><li>Later that day: “Can I make that vegetarian?”</li><li>AI: “Make what vegetarian? I don’t know what you’re referring to.”</li></ul><p><strong>With vector database memory</strong>:</p><ul><li>You: “What’s a good recipe for lasagna?”</li><li>AI gives recommendations</li><li>Later that day: “Can I make that vegetarian?”</li><li>AI: “Yes, for the lasagna recipe I suggested earlier, you can substitute the meat with lentils or plant-based meat alternatives…”</li></ul><h3>The Healthcare Companion</h3><p>Consider an AI helping with healthcare management:</p><p><strong>Without long-term memory</strong>:</p><ul><li>Monday: You discuss your medication schedule and symptoms</li><li>Wednesday: “How am I doing compared to Monday?”</li><li>AI: “I don’t have information about your condition on Monday.”</li></ul><p><strong>With vector database memory</strong>:</p><ul><li>Monday: You discuss your medication schedule and symptoms</li><li>Wednesday: “How am I doing compared to Monday?”</li><li>AI: “Your headaches seem to have improved since Monday, but you mentioned new joint pain which wasn’t present before…”</li></ul><h3>Benefits of Vector-Based Memory</h3><p>Using vector databases for LLM memory provides several important advantages:</p><ul><li><strong>Better conversation quality</strong>: The AI remembers context, preferences, and previous interactions</li><li><strong>Lower computational costs</strong>: Reduces repeated reasoning.</li><li><strong>Higher success rate</strong>: Improves task decision quality.</li><li><strong>Personalization</strong>: Remembers your preferences without asking repeatedly</li><li><strong>Efficiency</strong>: Avoids repeating the same information multiple times</li></ul><h3>Conclusion</h3><p>Vector databases are revolutionizing how LLMs remember and understand context. By converting conversations into mathematical vectors and storing them efficiently, these systems can maintain coherent interactions over much longer periods.</p><p>This technology mimics how humans remember concepts rather than exact words, allowing AI to be more helpful, personalized, and efficient. While the underlying math and technology are complex, the idea is simple: give AI a smart notebook to remember what matters, forget what doesn’t, and use that memory to have better conversations.</p><p>As LLMs continue to evolve, these memory mechanisms will become increasingly sophisticated, leading to AI assistants that truly understand you over time — remembering your preferences, past conversations, and needs without constantly starting from scratch.</p><p>Thanks for reading! If you enjoyed this, feel free to leave a comment or share it with someone who might find it helpful. Stay curious! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0990e6a0a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JavaScript works?]]></title>
            <link>https://blog.stackademic.com/how-javascript-works-bfdd2ef7a13d?source=rss-891ffb54cf5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfdd2ef7a13d</guid>
            <category><![CDATA[call-stack]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[task-queues]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[execution-context]]></category>
            <dc:creator><![CDATA[Yash Babiya]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 08:57:49 GMT</pubDate>
            <atom:updated>2024-12-11T14:31:42.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*inTaFRaBXJbcK5H5n6AnBg.jpeg" /></figure><p>JavaScript is a versatile and widely used programming language that plays a crucial role in web development. It’s the backbone of interactivity and dynamic functionality on the web. Understanding how JavaScript works is essential for anyone looking to build web applications, from simple websites to complex web-based systems.</p><p>In this article, we’ll try to understand how Javascript runs behind the scenes and explore the key components that make it all possible.</p><p>So, Basically there are 4 things that we need to understand,</p><ol><li>Execution Context</li><li>Call Stack</li><li>Task Queue</li><li>Event Loop</li></ol><h3>1. Execution Context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgtE700t-Se8lsl7mXuTLg.png" /></figure><p>Think of the <strong>Execution Context</strong> like a <strong>workspace</strong> where JavaScript runs your code. Imagine you’re sitting at a desk with a notepad. Every time you start working on a new task, you clear the desk, put down a fresh sheet of paper, and start writing.</p><p>In JavaScript:</p><ul><li>Whenever a function is called or the program starts, a new workspace (execution context) is created.</li><li>It’s where JavaScript keeps track of the current variable values and which code it should run.</li></ul><pre>function greet() {<br>  let name = &quot;Alice&quot;;<br>  console.log(&quot;Hello, &quot; + name);<br>}<br><br>greet(); // When this function is called, a new &quot;workspace&quot; is created</pre><h3>2. Call Stack</h3><p>Imagine the <strong>Call Stack</strong> as a <strong>to-do list</strong> where tasks are handled one at a time. When you have multiple tasks, you always deal with the top one first. Once it’s done, you check it off and move on to the next one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mze4lAQjzdeBjEqHAbSDiA.png" /></figure><p>In JavaScript:</p><ul><li>Every time a function is called, it gets added to the <strong>Call Stack</strong>.</li><li>When the function finishes, it is removed from the stack.</li><li>If one function calls another, the new function goes <strong>on top</strong> of the stack.</li></ul><pre>function sayHi() {<br>  console.log(&quot;Hi&quot;);<br>}<br><br>function greetUser() {<br>  sayHi(); // This function call goes on top of the stack<br>  console.log(&quot;Welcome!&quot;);<br>}<br>greetUser();</pre><ol><li>When greetUser() is called, it’s added to the stack.</li><li>Inside greetUser(), sayHi() is called, and it’s placed on top of the stack.</li><li>sayHi() is executed and then removed from the stack.</li><li>greetUser() continues and then is removed from the stack.</li></ol><h3>3. Task Queue</h3><p>The <strong>Task Queue</strong> (also called the <strong>Message Queue</strong> or <strong>Callback Queue</strong>) is a <strong>waiting area</strong> for <strong>asynchronous tasks</strong> that are ready to be executed <strong>after</strong> the synchronous code (Call Stack) is done. These are tasks like:</p><ul><li>setTimeout and setInterval callbacks</li><li>DOM events like click, keypress</li><li>fetch and other async operations</li></ul><p><strong>Key differences from the Call Stack</strong>:</p><ul><li>The Task Queue operates in a <strong>First In, First Out (FIFO)</strong> order, meaning tasks are handled in the order they arrived.</li><li>The Task Queue <strong>does not execute code</strong> directly. It <strong>holds tasks until</strong> the <strong>Call Stack is empty</strong>, and then the <strong>Event Loop</strong> moves them from the Task Queue to the Call Stack.</li></ul><p>Example:</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Hello from the Task Queue!&quot;);<br>}, 1000);<br>console.log(&quot;End&quot;);</pre><ul><li>&quot;Start&quot; is logged first because it’s synchronous.</li><li>setTimeout is <strong>asynchronous</strong>, so it’s placed in the Task Queue to run <strong>after 1 second</strong>.</li><li>&quot;End&quot; is logged immediately because the Call Stack is still working.</li><li>After 1 second, the Event Loop ( We’ll learn about it next ) sees that the Call Stack is <strong>empty</strong> and moves the setTimeout callback from the <strong>Task Queue</strong> to the <strong>Call Stack</strong> to be executed.</li></ul><h3>4. Event Loop</h3><p>The <strong>Event Loop</strong> is like a <strong>manager</strong> that keeps track of all your tasks and makes sure they are handled in the right order. Think of it as a person watching the to-do list (Call Stack) and a second list called the <strong>Task Queue</strong> (where async tasks like setTimeout or API calls wait).</p><p>In JavaScript:</p><ul><li>If the Call Stack is empty (no tasks are being executed), the Event Loop picks up tasks from the <strong>Task Queue</strong> and puts them into the Call Stack to be executed.</li><li>This is how JavaScript handles tasks that should run <strong>later</strong> (e.g., timers, button clicks, or API responses).</li></ul><p>Let’s look at the same example of Task Queue :</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Hello from the future!&quot;);<br>}, 2000);<br>console.log(&quot;End&quot;);</pre><ol><li>&quot;Start&quot; is logged first.</li><li>setTimeout is placed in the <strong>Task Queue</strong> to run <strong>after</strong> 2 seconds.</li><li>&quot;End&quot; is logged.</li><li>After 2 seconds, the Event Loop sees the Call Stack is empty, and it moves the setTimeout task to the Call Stack.</li><li>&quot;Hello from the future!&quot; is finally logged.</li></ol><p>This GIF from Geek For Geeks might be useful to understand both Event Loop and Task Queue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWvOxQSspLSUGCQ4Qye1pQ.gif" /></figure><p>In summary:</p><ul><li><strong>Execution Context</strong>: The workspace where a specific task runs.</li><li><strong>Call Stack</strong>: The to-do list, where only the top task is being executed.</li><li><strong>Task Queue:</strong> The Waiting Area, where asynchronous tasks waits for being executed.</li><li><strong>Event Loop</strong>: The manager that moves tasks from the waiting area (Task Queue) to the active list (Call Stack) when the time is right.</li></ul><p>Understanding these concepts will give you deeper insight into how JavaScript works under the hood and help you write better, more efficient code!</p><p>I hope this might be useful for you, if you like this post Please hit clap 👏 , leave a comment below and Share. Thanks :)</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfdd2ef7a13d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-javascript-works-bfdd2ef7a13d">How JavaScript works?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Basics of Next.js]]></title>
            <link>https://blog.stackademic.com/the-basics-of-next-js-85dc12c23462?source=rss-891ffb54cf5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/85dc12c23462</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Yash Babiya]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 09:04:40 GMT</pubDate>
            <atom:updated>2024-08-05T01:30:55.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbbQORcuECy8BXsK9mVseA.jpeg" /></figure><p>While React has been a popular choice for many, there are instances where Next.js shines even brighter. In this exploration, we’ll learn about 3 basic yet powerful concepts of Next.js.</p><ol><li>Routing</li><li>Pre-rendering</li><li>Client Side Data Fetching</li></ol><h3>Routing</h3><p>With Next.js we have a complete file based routing for instance whenever we add any page inside “src/pages” folder It would automatlically create the end point</p><p>For nested routing like /about/me we have to create a folder named “about” and then we have to create a file named me.js</p><h4>Dynamic Routing</h4><p>Now, This is good if we only have 2 or 3 pages but what If we have dynamic routes like /blog/1 where 1 is our blog’s id ??</p><p>Then we need to use something known as Dynamic Routing which is simply put the variable part of your URL inside “[]” and create a file.</p><p>For Example, If we need a end point like /blog/:id then we need to create a folder named as “blog” in “pages” and then add a file named “[id].js” inside blog folder.</p><p>Now whenever you hit to the api /blog/1 the value of the id would be 1.</p><p>The values of these variables can be get using useRouter hook.</p><pre>const router = useRouter()<br>const idOfBlog = router.query.id</pre><h4>Authenticating</h4><p>If you want to authenticate the user before serving the data there are several ways you can do this.</p><p>First By using <strong>middlewares</strong>,</p><p>Middlewares are basically the functions that runs before the request is completed. you can create the middlewares to validate if user is allowed to view a specific page or not</p><p>Second way is useful when you are using “<strong>Server side props</strong>” ( more on this below ). As it runs the first whenever you request a page, you can put the validation logic there and can redirect it to login or other page if user is unauthorised.</p><h3>Pre-rendering</h3><p>By default, Next.js <strong>pre-renders</strong> every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript.</p><h4>Next.js has two forms of pre-rendering:</h4><p>(The difference is in <strong>when</strong> it generates the HTML for a page.)</p><ol><li>Static Generation</li><li>Server Side Rendering</li></ol><blockquote>Please Note that this would only show the difference when your app is in production, for local both will behave the same.</blockquote><h4>Static Generation :</h4><p>The HTML is generated at <strong>build time</strong> and will be reused on each request.</p><p>If we have a web page that has the data that does not change often, at that time this is a great way to optimise your site.</p><p>If we have a blog post and every blog URL has a endpoint as</p><p>/blogs/<strong>:id</strong></p><p>This “id” can be unique for every blog and depending upon that each blog has it’s own unique content.</p><p>For this Next.js provides function</p><p><strong><em>getStaticPaths()</em></strong></p><p>It would be exported from the dynamic page ( src/pages/blogs/[id].js ).</p><pre>export async function getStaticPaths() {<br>  const res = await fetch(&#39;https://.../blogs&#39;)<br>  const allBlogs = await res.json()<br> <br>  const paths = allBlogs.map((blog) =&gt; ({<br>    params: { id: blog.id },<br>  })) // array of id of each blog<br>  return { paths, fallback: false } // fallback is false, So for any other value of &quot;id&quot; it would return 404 <br>}</pre><p>This function gets called at <strong>build time</strong> and it lets us specify which paths we want to pre-render.</p><p>Now this would only create the dynamic paths, but we also need to fetch the data of blog from these specific “id”s.</p><p>So this means that our <strong>content</strong> is also depending upon external Data.</p><p>When the <strong>Content</strong> is depending upon external Data, we need to use</p><p><strong><em>getStaticProps()</em></strong></p><p>this function is need to be exported from the component which requires the external data.</p><pre>export async function getStaticProps({ params }) {<br><br>  const res = await fetch(`https://.../blog/${params.id}`)<br>  const blogDetails = await res.json()<br> <br><br>  return { props: { blogDetails } }<br>}</pre><p>This function gets all the data at the <strong>build time. </strong>and map the data inside the props.</p><blockquote>If our data changes after the build it would still return the page with same old data that was at the build time. To overcome this problem we can use <strong><em>unstable_revalidate, </em></strong>here we can specify the time period after which it’ll refresh the static data from the Database. So this is the reason why we should use static site generation only in case when our data is not changing frequently.</blockquote><h4><strong>Server Side Rendering</strong></h4><p>The HTML is generated on <strong>each request</strong>.</p><p>To use Server-side Rendering for a page, we need to export an async function called <strong>getServerSideProps()</strong>. This function will be called by the server on every request.</p><blockquote>You can compare it with the get request call in useEffect that we use to get the data from server when it renders.</blockquote><pre>export async function getServerSideProps() {<br>  // Fetch data from external API<br>  const res = await fetch(`https://.../data`)<br>  const data = await res.json()<br> <br>  // Pass data to the page via props<br>  return { props: { data } }<br>}</pre><p>This function will run when we request a specific page. It’ll get all the data first create a HTML page and then it’ll return that page.</p><blockquote>These 3 functions will not be sent to the client side.</blockquote><h3>Client Side Data Fetching</h3><p>Client-side data fetching is useful when</p><ul><li>Your page doesn’t require SEO indexing.</li><li>You don’t need to pre-render your data.</li><li>The content of your pages needs to update frequently.</li></ul><p>Unlike the server-side rendering APIs, we can use client-side data fetching at the component level.</p><p>Next.js has created a React hook library for data fetching called <a href="https://swr.vercel.app/">SWR</a>.</p><p>It handles caching, revalidation, focus tracking, refetching on intervals, and more.</p><pre>import useSWR from &#39;swr&#39;<br> <br>const getData = (...args) =&gt; fetch(...args).then((res) =&gt; res.json())<br> <br>function Profile() {<br>  const { data, error } = useSWR(&#39;/api/get-data&#39;, getData)<br> <br>  if (error) return &lt;div&gt;Failed to load the data&lt;/div&gt;<br>  if (!data) return &lt;div&gt;Loading...&lt;/div&gt;<br> <br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{data.title}&lt;/h1&gt;<br>      &lt;p&gt;{data.post}&lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>I hope you got the basic understanding of Next.js and when you should use it over React.</p><p>If you have any other additions to this post please leave a comment below and if you like this post please hit clap 👏 and share.</p><p>Thanks.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85dc12c23462" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-basics-of-next-js-85dc12c23462">The Basics of Next.js</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>