<?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 Jainishah on Medium]]></title>
        <description><![CDATA[Stories by Jainishah on Medium]]></description>
        <link>https://medium.com/@jainishah1641?source=rss-c82d81e819f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oMRbtWh_TjZv3aEA</url>
            <title>Stories by Jainishah on Medium</title>
            <link>https://medium.com/@jainishah1641?source=rss-c82d81e819f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:05:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jainishah1641/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 Multi-Agent Customer Support System with OpenAI Agents SDK]]></title>
            <link>https://medium.com/@jainishah1641/building-a-multi-agent-customer-support-system-with-openai-agents-sdk-8e0d081357c6?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e0d081357c6</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[openai-agents-sdk]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 06:18:50 GMT</pubDate>
            <atom:updated>2026-09-30T07:09:01.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqhMSOpjAPPCxKlIH2zHXw.jpeg" /></figure><p>Building this project to understand multiple agent with handoffs, custom function tools, input guardrails, hosted tool like WebSearchTools and structured output with pydantic.</p><p>In this project, I built a <strong>Customer Support Agent System</strong> using the OpenAI Agents SDK.</p><p>The system combines:</p><ul><li>Multiple specialized agents</li><li>Agent-to-agent handoffs</li><li>Custom function tools</li><li>Input guardrails</li><li>Web search</li><li>Structured outputs with Pydantic</li><li>A simulated order database</li><li>Asynchronous agent execution</li></ul><p>The overall architecture looks like this:</p><pre><br>                         │       Customer      │<br>                         └──────────┬──────────┘<br>                                    │<br>                                    ▼<br>                         ┌─────────────────────┐<br>                         │   Triage Agent      │<br>                         │                     │<br>                         │ Understands request │<br>                         │ and routes it       │<br>                         └──────────┬──────────┘<br>                                    │<br>                  ┌─────────────────┼─────────────────┐<br>                  │                 │                 │<br>                  ▼                 ▼                 ▼<br>        ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐<br>        │  Order Status   │ │  Refund Agent   │ │   FAQ Agent     │<br>        │     Agent       │ │                 │ │                 │<br>        └────────┬────────┘ └────────┬────────┘ └────────┬────────┘<br>                 │                   │                   │<br>                 ▼                   ▼                   ▼<br>          lookup_order         process_refund       Web Search</pre><p>Before anything reaches the triage agent, an <strong>input guardrail</strong> checks whether the message is actually a customer-support request.</p><h3>Why use multiple agents?</h3><p>A common approach to building an AI customer support system is to create one large agent with every tool available to it.</p><p>For example:</p><pre>Customer<br>   ↓<br>One Large Agent<br>   ├── lookup_order<br>   ├── process_refund<br>   ├── web_search<br>   ├── cancellation<br>   ├── account management<br>   └── everything else</pre><p>This can work for a small prototype, but as the system grows, the agent has to reason about more tools and more responsibilities.</p><p>Instead, I separated responsibilities:</p><pre>Triage Agent<br>    │<br>    ├── Order Status Agent<br>    │       └── lookup_order()<br>    │<br>    ├── Refund Agent<br>    │       └── process_refund()<br>    │<br>    └── FAQ Agent<br>            └── Web Search</pre><p>The triage agent doesn’t need to know how an order is retrieved or how a refund is processed.</p><p>Its main responsibility is:</p><blockquote><em>Understand the customer’s intent and send the request to the appropriate specialist.</em></blockquote><p>This is where <strong>handoffs</strong> become useful.</p><h3>1. Setting up the project</h3><p>I’m using Python with the OpenAI Agents SDK.</p><p>The basic imports are:</p><pre>from dotenv import load_dotenv<br>import asyncio <br>from pydantic import BaseModel<br>from agents import (    <br>      Agent,    <br>      Runner,    <br>      function_tool,    <br>      input_guardrail,    <br>      GuardrailFunctionOutput,    <br>      WebSearchTool<br>)</pre><h3>2. Creating custom tools</h3><p>The first requirement is giving our agents access to business functionality.</p><p>For this demo, I’m using an in-memory dictionary as a simulated order database.</p><p>In a production application, this could be replaced with a real database or an internal service accessed through something like MCP.</p><pre>ORDERS_DB = {<br>    &quot;ORD-001&quot;: {<br>        &quot;item&quot;: &quot;Wireless Headphones&quot;,<br>        &quot;status&quot;: &quot;Shipped&quot;,<br>        &quot;eta&quot;: &quot;October 5&quot;<br>    },<br>    &quot;ORD-002&quot;: {<br>        &quot;item&quot;: &quot;Python Programming Book&quot;,<br>        &quot;status&quot;: &quot;Delivered&quot;,<br>        &quot;eta&quot;: &quot;September 29&quot;<br>    },<br>    &quot;ORD-003&quot;: {<br>        &quot;item&quot;: &quot;USB-C Cable 3-pack&quot;,<br>        &quot;status&quot;: &quot;Processing&quot;,<br>        &quot;eta&quot;: &quot;October 12&quot;<br>    },<br>}</pre><h3>Order lookup tool</h3><p>The @function_tool decorator exposes a normal Python function as a tool that the agent can call.</p><pre>@function_tool<br>def lookup_order(order_id: str) -&gt; str:<br>    &quot;&quot;&quot;Look up the status of a customer order by order ID.&quot;&quot;&quot;<br><br>    order = ORDERS_DB.get(order_id.upper())<br><br>    if order:<br>        return (<br>            f&quot;Order {order_id.upper()}:\n&quot;<br>            f&quot;  Item: {order[&#39;item&#39;]}\n&quot;<br>            f&quot;  Status: {order[&#39;status&#39;]}\n&quot;<br>            f&quot;  Estimated Arrival: {order[&#39;eta&#39;]}&quot;<br>        )<br><br>    return (<br>        f&quot;Order {order_id} not found. &quot;<br>        &quot;Please check the order ID and try again.&quot;<br>    )</pre><p>The important part here is that the agent doesn’t directly manipulate the database.</p><p>Instead, it decides when the tool is needed:</p><pre><strong>Customer:<br></strong>&quot;Where is my order ORD-001?&quot;</pre><pre>        ↓</pre><pre>Order Status Agent</pre><pre>        ↓</pre><pre>lookup_order(&quot;ORD-001&quot;)</pre><pre>        ↓</pre><pre>Order information</pre><pre>        ↓</pre><pre>Agent explains result to customer</pre><p>This creates a clean separation between the agent’s reasoning and the application’s business logic.</p><h3>3. Creating a refund tool</h3><p>The refund agent gets a different tool.</p><pre>@function_tool<br>def process_refund(order_id: str, reason: str) -&gt; str:<br>    &quot;&quot;&quot;Process a refund request for an order.&quot;&quot;&quot;<br><br>    order = ORDERS_DB.get(order_id.upper())<br><br>    if not order:<br>        return f&quot;Cannot process refund: Order {order_id} not found.&quot;<br><br>    if order[&quot;status&quot;] == &quot;Processing&quot;:<br>        return (<br>            f&quot;Refund for {order_id.upper()} cannot be processed &quot;<br>            &quot;because the order hasn&#39;t shipped yet. &quot;<br>            &quot;It can be cancelled instead.&quot;<br>        )<br><br>    return (<br>        f&quot;Refund initiated for order {order_id.upper()}:\n&quot;<br>        f&quot;  Item: {order[&#39;item&#39;]}\n&quot;<br>        f&quot;  Reason: {reason}\n&quot;<br>        f&quot;  Return amount will be credited within &quot;<br>        &quot;5-7 business days.&quot;<br>    )</pre><p>Now the refund agent can interact with the business logic without needing access to the order lookup implementation.</p><p>This is an important design principle for agent systems:</p><blockquote><em>Give each agent only the tools it needs for its responsibility.</em></blockquote><h3>4. Adding input guardrails</h3><p>One problem with a customer support agent is that users can ask it anything.</p><p>For example:</p><pre>&quot;Can you write me a poem about cats?&quot;</pre><p>That’s not a customer support request.</p><p>Rather than letting the main agent process it, we can validate the input first.</p><p>For this, I created a small guardrail agent.</p><pre>class SupposeCheck(BaseModel):<br>    is_support_question: bool<br>    reasoning: str</pre><p>This is where <strong>Pydantic structured output</strong> becomes useful.</p><p>Instead of relying on a free-form response such as:</p><p>Yes, this seems like customer support.</p><p>we ask the model to produce a predictable structure:</p><pre>{<br>    &quot;is_support_question&quot;: true,<br>    &quot;reasoning&quot;: &quot;The customer is asking about an order.&quot;<br>}</pre><p>The checker agent looks like this:</p><pre>guardrail_checker = Agent(<br>    name=&quot;Support Topic Checker&quot;,<br>    instructions=&quot;&quot;&quot;<br>    Determine if the user&#39;s message is a customer support question.<br><br>    Valid topics:<br>    - order status<br>    - refund<br>    - returns<br>    - product questions<br>    - shipping<br>    - FAQs<br><br>    Invalid topics:<br>    - personal advice<br>    - jokes<br>    - coding help<br>    - unrelated conversations<br><br>    Return is_support_question=True ONLY for<br>    customer support topics.<br>    &quot;&quot;&quot;,<br>    output_type=SupportCheck,<br>)</pre><p>The output_type tells the agent to produce the Pydantic model instead of an arbitrary text response.</p><h3>5. Implementing the guardrail</h3><p>Now we connect that checker to an input guardrail.</p><pre>@input_guardrail<br>async def support_only(ctx, agent, input):<br>    result = await Runner.run(<br>        guardrail_checker,<br>        input,<br>        context=ctx.context<br>    )<br><br>    final = result.final_output_as(SupportCheck)<br><br>    return GuardrailFunctionOutput(<br>        output_info={<br>            &quot;reasoning&quot;: final.reasoning<br>        },<br>        tripwire_triggered=not final.is_support_question,<br>    )</pre><p>The key property is:</p><pre>tripwire_triggered=not final.is_support_question</pre><p>If the checker determines that the request isn’t related to customer support, the main workflow is stopped.</p><p>So the flow becomes:</p><pre>Customer Message<br>       │<br>       ▼<br>Input Guardrail<br>       │<br>       ├── Not Support ──→ Block<br>       │<br>       ▼<br>   Triage Agent</pre><p>This is useful because the guardrail is independent of the specialist agents.</p><h3>6. Creating the Order Status Agent</h3><p>Now we can create our first specialist.</p><pre>order_agent = Agent(<br>    name=&quot;Order_Status_Agent&quot;,<br><br>    handoff_description=(<br>        &quot;Handles questions about order status, &quot;<br>        &quot;shipping and delivery.&quot;<br>    ),<br><br>    instructions=&quot;&quot;&quot;<br>    You help customers check their order status.<br><br>    Use the lookup_order tool to find order information.<br><br>    If the customer doesn&#39;t provide an order ID,<br>    ask for it.<br><br>    Be friendly and professional.<br>    &quot;&quot;&quot;,<br><br>    tools=[lookup_order],<br>)</pre><p>There are two important things here.</p><p>First:<br>tools = [lookup_order]</p><p>The order agent only gets the tool it needs.</p><p>Second: <br>handoff_description = ...</p><p>This description helps the triage agent understand when this specialist should receive a request.</p><h3>7. Creating the Refund Agent</h3><p>The refund agent follows the same pattern.</p><pre>refund_agent = Agent(<br>    name=&quot;Refund_Agent&quot;,<br><br>    handoff_description=(<br>        &quot;Handles refund requests, returns, &quot;<br>        &quot;and cancellations.&quot;<br>    ),<br><br>    instructions=&quot;&quot;&quot;<br>    You help customers with refunds and returns.<br><br>    Use the process_refund tool to initiate refunds.<br><br>    Always ask for the order ID and reason<br>    before processing.<br><br>    Be empathetic and helpful.<br>    &quot;&quot;&quot;,<br><br>    tools=[process_refund],<br>)</pre><pre>Order Agent<br>    └── lookup_order<br><br>Refund Agent<br>    └── process_refund<br><br>Each specialist has a focused responsibility.</pre><h3>8. Adding web search to the FAQ agent</h3><p>Not every customer question should come from our internal database.</p><p>Some questions may require current information.</p><p>For example:</p><pre>&quot;What is the current return policy?&quot;</pre><p>For this use case, the FAQ agent can use web search.</p><pre>faq_agent = Agent(<br>    name=&quot;FAQ_Agent&quot;,<br><br>    handoff_description=(<br>        &quot;Handles general product questions &quot;<br>        &quot;and frequently asked questions.&quot;<br>    ),<br><br>    instructions=&quot;&quot;&quot;<br>    You answer general customer questions and FAQs.<br><br>    Use web search when you need current information.<br><br>    Common topics:<br>    - shipping policies<br>    - return windows<br>    - product details<br><br>    Be helpful and concise.<br>    &quot;&quot;&quot;,<br><br>    tools=[WebSearchTool()],<br>)</pre><p>This creates a different kind of tool integration.</p><p>The first two agents use <strong>custom application tools</strong>.</p><p>The FAQ agent uses a <strong>hosted tool</strong>.</p><p>So we have two types of capabilities:</p><pre>Custom Tools<br>    ├── lookup_order<br>    └── process_refund<br>Hosted Tool<br>    └── WebSearchTool</pre><h3>9. Creating the triage agent</h3><p>Now we need the front door of the system.</p><p>The triage agent receives every valid support request.</p><pre>triage_agent = Agent(<br>    name=&quot;Customer_Support_Triage&quot;,<br><br>    instructions=&quot;&quot;&quot;<br>    You are the front-line customer support agent.<br><br>    Your job is to understand the customer&#39;s issue<br>    and route them to the right specialist.<br><br>    Order status, shipping, delivery questions<br>        -&gt; Order Status Agent<br><br>    Refund requests, returns, cancellations<br>        -&gt; Refund Agent<br><br>    General questions, product information, FAQs<br>        -&gt; FAQ Agent<br><br>    Be warm, professional and route quickly.<br>    &quot;&quot;&quot;,<br><br>    handoffs=[<br>        order_agent,<br>        refund_agent,<br>        faq_agent<br>    ],<br><br>    input_guardrails=[<br>        support_only<br>    ],<br>)</pre><p>The architecture is now complete.</p><pre>                      Customer<br>                          │<br>                          ▼<br>                  Input Guardrail<br>                          │<br>                          ▼<br>                   Triage Agent<br>                    /    |    \<br>                   /     |     \<br>                  ▼      ▼      ▼<br>               Order   Refund   FAQ<br>                │        │       │<br>                ▼        ▼       ▼<br>             Lookup    Refund   Search<br>              Tool      Tool     Tool</pre><h3>10. Running the system</h3><p>Because the Agents SDK supports asynchronous execution, I created an async handler.</p><pre>async def handle_customer(message: str):<br>    print(f&quot;Customer: {message}&quot;)<br><br>    try:<br>        result = await Runner.run(<br>            triage_agent,<br>            message<br>        )<br><br>        print(<br>            f&quot;{result.last_agent_name}: &quot;<br>            f&quot;{result.final_output}&quot;<br>        )<br><br>    except Exception:<br>        print(<br>            &quot;Blocked: This doesn&#39;t appear &quot;<br>            &quot;to be a support question.&quot;<br>        )</pre><p>Then we can run several test cases.</p><h3>Test 1: Order Status</h3><pre>await handle_customer(&quot;Where is my Order ORD-001?&quot;)</pre><p>The expected flow is:</p><pre>Customer<br>   │<br>   ▼<br>Guardrail<br>   │<br>   ▼<br>Triage Agent<br>   │<br>   ▼<br>Order Status Agent<br>   │<br>   ▼<br>lookup_order(&quot;ORD-001&quot;)<br>   │<br>   ▼<br>Order information</pre><p>The tool returns information such as:</p><pre>Order ORD-001:<br>  Item: Wireless Headphones<br>  Status: Shipped<br>  Estimated Arrival: October 5</pre><p>The Order Status Agent then converts that tool output into a customer-friendly response.</p><h3>Test 2: Refund Request</h3><pre>await handle_customer(    <br>    &quot;I want a refund for my order ORD-002. &quot;    <br>    &quot;The book arrived damaged.&quot;<br>)</pre><p>The flow changes:</p><pre>Customer<br>   │<br>   ▼<br>Guardrail<br>   │<br>   ▼<br>Triage Agent<br>   │<br>   ▼<br>Refund Agent<br>   │<br>   ▼<br>process_refund()<br>   │<br>   ▼<br>Refund result</pre><p>The triage agent doesn’t need to call process_refund itself.</p><p>It simply hands the conversation to the specialist that has the appropriate capability.</p><h3>Test 3: General FAQ</h3><pre>await handle_customer(&quot;Where is the Amazon return policy?&quot;)</pre><p>This request is routed to the FAQ agent.</p><pre>Customer<br>   │<br>   ▼<br>Triage Agent<br>   │<br>   ▼<br>FAQ Agent<br>   │<br>   ▼<br>WebSearchTool<br>   │<br>   ▼<br>Current information</pre><p>This is particularly useful for information that can change over time.</p><p>Instead of embedding a potentially outdated answer into the application’s prompt, the agent can search for current information.</p><h3>Test 4: Off-topic request</h3><p>Finally:</p><pre>await handle_customer(&quot;Can you help me write a poem about cats?&quot;)</pre><p>The request goes through the support-topic checker.</p><p>The structured output might look conceptually like:</p><pre>{<br>    &quot;is_support_question&quot;: false,<br>    &quot;reasoning&quot;: &quot;The user is asking for creative writing.&quot;<br>}</pre><p>The guardrail then triggers:</p><pre>tripwire_triggered=True</pre><p>The request never reaches the triage workflow.</p><pre>Customer<br>   │<br>   ▼<br>Support Guardrail<br>   │<br>   X<br>Blocked</pre><p>This is a simple example, but the same pattern can be useful for production systems where an agent should operate within a specific business domain.</p><h3>The complete architecture</h3><p>Putting everything together:</p><pre><br>                         │     Customer     │<br>                         └────────┬─────────┘<br>                                  │<br>                                  ▼<br>                       ┌─────────────────────┐<br>                       │   Input Guardrail   │<br>                       │                     │<br>                       │ Is this a support   │<br>                       │ request?            │<br>                       └──────────┬──────────┘<br>                                  │<br>                     ┌────────────┴────────────┐<br>                     │                         │<br>                  Invalid                    Valid<br>                     │                         │<br>                     ▼                         ▼<br>                  Blocked              ┌───────────────┐<br>                                       │ Triage Agent  │<br>                                       └───────┬───────┘<br>                                               │<br>                     ┌─────────────────────────┼────────────────────────┐<br>                     │                         │                        │<br>                     ▼                         ▼                        ▼<br>             ┌───────────────┐        ┌───────────────┐       ┌───────────────┐<br>             │ Order Status  │        │ Refund Agent  │       │   FAQ Agent   │<br>             │     Agent     │        │               │       │               │<br>             └───────┬───────┘        └───────┬───────┘       └───────┬───────┘<br>                     │                        │                        │<br>                     ▼                        ▼                        ▼<br>              lookup_order()          process_refund()          WebSearchTool</pre><h3>Why this architecture works</h3><p>There are three important concepts working together here.</p><h3>1. Handoffs separate responsibilities</h3><p>Instead of one agent trying to do everything, the triage agent delegates the conversation to a specialist.</p><p>This makes the system easier to extend.</p><p>For example, we could later add:</p><pre>Triage Agent<br>    ├── Order Agent<br>    ├── Refund Agent<br>    ├── FAQ Agent<br>    ├── Account Agent<br>    └── Technical Support Agent</pre><p>without putting every tool into a single agent.</p><h3>2. Function tools connect AI to application logic</h3><p>The model itself shouldn’t directly access our database or execute arbitrary business operations.</p><p>Instead, we expose controlled functions:</p><pre>lookup_order(...)<br>process_refund(...)</pre><p>This gives the application control over what the agent can actually do.</p><h3>3. Guardrails enforce boundaries</h3><p>The support guardrail prevents unrelated requests from entering the workflow.</p><p>This becomes increasingly important as agents gain access to more tools and business operations.</p><h3>What I learned from this project</h3><p>The main takeaway for me is that building an agentic system isn’t just about giving an LLM a prompt.</p><p>The useful part is designing the <strong>system around the model</strong>.</p><p>In this project, each component has a specific responsibility:</p><pre>Guardrail<br>    ↓<br>Validate the request<br>    ↓<br>Triage Agent<br>    ↓<br>Understand intent and route <br><br>Specialist Agent<br>    ↓<br>Handle the specific domain<br><br>Tool<br>    ↓<br>Perform an actual application operation<br><br>Structured Output<br>    ↓<br>Keep important model decisions machine-readable<br></pre><p>That separation makes the system easier to reason about and gives the application more control over what the AI can do.</p><p>The same architecture can be extended beyond customer support into areas like IT help desks, internal operations, e-commerce, financial services, and other workflows where different tasks require different tools and domain-specific agents.</p><p>The complete source code for this project is available on GitHub: <a href="https://github.com/DevJaini/customer-support-agent-system"><strong>Customer Support Agent System</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e0d081357c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First AI Agent: From a Simple Prompt to Tool-Using AI]]></title>
            <link>https://medium.com/@jainishah1641/your-first-ai-agent-from-a-simple-prompt-to-tool-using-ai-cc7d11b52d4c?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7d11b52d4c</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 12:09:40 GMT</pubDate>
            <atom:updated>2026-09-30T07:16:37.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNDIv--ROQELFR62xf3KoQ.jpeg" /></figure><p>In this walkthrough, we’ll build a simple <strong>AI math agent</strong> using Python and LangChain. It can decide when to use tools for addition, subtraction, multiplication, division, and square roots.</p><p>The interesting part isn’t the math. It’s seeing what actually happens when an LLM is given tools and allowed to decide <strong>which tool to call and when</strong>.</p><p>Our agent will be able to handle questions like:</p><blockquote>What is 25 multiplied by 4?</blockquote><blockquote>Calculate the square root of 144 and then multiply it by 5.</blockquote><p>Instead of hardcoding the calculation flow ourselves, we give the model access to several tools. The model decides which tool it needs based on the user’s request.</p><h3>1. Initialize the Model</h3><p>First, we create the chat model:</p><pre>from langchain.chat_models import init_chat_model<br><br>model = init_chat_model(&quot;openai:gpt-4o-mini&quot;)</pre><p>At this point, we simply have an LLM that can understand and generate text.</p><h3>2. Give the AI Some Tools</h3><p>An agent becomes more useful when it can interact with functions instead of only generating text.</p><p>We’ll create five simple tools:</p><pre>from langchain.tools import tool<br>import math<br><br>@tool<br>def add(a: float, b: float) -&gt; float:<br>    &quot;&quot;&quot;Add two numbers.&quot;&quot;&quot;<br>    return a + b<br><br>@tool<br>def subtract(a: float, b: float) -&gt; float:<br>    &quot;&quot;&quot;Subtract two numbers.&quot;&quot;&quot;<br>    return a - b<br><br><br>@tool<br>def multiply(a: float, b: float) -&gt; float:<br>    &quot;&quot;&quot;Multiply two numbers.&quot;&quot;&quot;<br>    return a * b<br><br><br>@tool<br>def divide(a: float, b: float) -&gt; float:<br>    &quot;&quot;&quot;Divide two numbers.&quot;&quot;&quot;<br>    if b == 0:<br>        raise ValueError(&quot;Cannot divide by zero.&quot;)<br>    return a / b<br><br><br>@tool<br>def square_root(a: float) -&gt; float:<br>    &quot;&quot;&quot;Calculate the square root of a number.&quot;&quot;&quot;<br>    if a &lt; 0:<br>        raise ValueError(&quot;Cannot calculate square root of a negative number.&quot;)<br>    return math.sqrt(a)</pre><p>The @tool decorator turns the Python function into something the agent can call.</p><p>There are two important things here:</p><ol><li>Type hints: They tell the model what kind of arguments the tool expects.</li></ol><pre>a: float<br>b: float</pre><p>2. Docstrings: The model uses the tool’s description to understand what the tool does.</p><p>So when defining tools for an agent, the function isn&#39;t just code. Its description becomes part of the information the LLM uses to decide whether that tool is appropriate.</p><pre>&quot;&quot;&quot;Multiply two numbers.&quot;&quot;&quot;</pre><h3>3. Create the Agent</h3><p>Now we give the model access to our tools:</p><pre>from langchain.agents import create_agent<br><br>agent = create_agent(<br>    model=model,<br>    tools=[<br>        add,<br>        subtract,<br>        multiply,<br>        divide,<br>        square_root<br>    ],<br>)</pre><p>This is where our normal LLM starts behaving more like an <strong>agent</strong>.</p><p>Instead of only answering the user’s question directly, it can:</p><ol><li>Understand the request</li><li>Decide whether a tool is needed</li><li>Select a tool</li><li>Provide arguments to the tool</li><li>Receive the tool result</li><li>Continue processing</li><li>Return the final answer</li></ol><p>Conceptually:</p><pre>User<br> ↓<br>Agent<br> ↓<br>Should I use a tool?<br> ↓<br>Choose tool<br> ↓<br>Execute tool<br> ↓<br>Get result<br> ↓<br>Final response</pre><p>For a multi-step question, this process can happen multiple times.</p><h3>4. Run the Agent</h3><p>We can now create a small helper function:</p><pre>def run_agent(question: str):<br>    &quot;&quot;&quot;Run the agent and print the execution trace.&quot;&quot;&quot;<br><br>    print(f&quot;User: {question}&quot;)<br><br>    result = agent.invoke({<br>        &quot;message&quot;: [(&quot;user&quot;, question)],<br>    })<br><br>    print(&quot;Agent:&quot;, result)</pre><p>And call it:</p><pre>run_agent(&quot;What is 25 multiplied by 4?&quot;)</pre><p>The important thing is that <strong>we didn’t tell the agent to call </strong><strong>multiply()</strong>.</p><p>We only gave it the available tools.</p><p>The model decides that multiplication is the appropriate tool based on the request and the tool description.</p><h3>5. A More Interesting Example</h3><p>Now try:</p><pre>run_agent(<br>    &quot;Calculate the square root of 144 and multiply the result by 5.&quot;<br>)</pre><p>The agent needs more than one operation.</p><p>Conceptually, the flow becomes:</p><pre>User:<br><br>Calculate √144 × 5<br>        ↓<br>Agent chooses square_root<br>        ↓<br>square_root(144)<br>        ↓<br>12<br>        ↓<br>Agent chooses multiply<br>        ↓<br>multiply(12, 5)<br>        ↓<br>60<br>        ↓<br>Final answer</pre><p>That’s the key idea behind tool-using agents.</p><p>The developer doesn’t necessarily have to hardcode the exact sequence of operations.</p><p>The model can determine the next action from the available tools and the current state of the conversation.</p><h3>6. Why This Is Different From a Normal LLM</h3><p>A normal LLM might simply generate: The answer is 60.</p><p>But with tools, the model can actually delegate work to external functions.</p><h4><strong>That’s a big shift:</strong></h4><p><strong>LLM only <br></strong>User → LLM → Answer</p><p><strong>versus:</strong></p><pre>Tool-using agent<br><br>User<br>  ↓<br>LLM<br>  ↓<br>Choose tool<br>  ↓<br>Execute code<br>  ↓<br>Observe result<br>  ↓<br>LLM<br>  ↓<br>Answer</pre><p>The LLM is no longer responsible for doing everything itself.</p><p>It can decide <strong>what action should happen next</strong>, while your application controls what actions are actually available.</p><h3>7. The Part I Find Most Important</h3><p>The interesting part of this example isn’t the calculator.</p><p>It’s the boundary between the <strong>LLM and your application code</strong>.</p><p>The LLM is good at understanding a natural-language request and deciding what action makes sense.</p><p>Your Python code is responsible for actually performing that action.</p><p>The model can decide: <em>“I need the divide tool.”</em></p><p>Your application owns that logic.</p><p>Instead, imagine tools like:</p><pre>get_customer()<br>search_transactions()<br>create_report()<br>send_email()<br>query_database()<br>get_weather()<br>create_ticket()</pre><p>Now the same agent pattern starts becoming useful in real applications.</p><h3>What We Built</h3><p>In only a few pieces of code, we created an agent that can:</p><ul><li>Understand natural-language requests</li><li>Select from multiple tools</li><li>Pass arguments to tools</li><li>Use multiple tools for one request</li><li>Use tool results to continue its task</li><li>Return a final response to the user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*oRJOhzEekAlc9bGZVQ9JpQ.png" /></figure><p>And that’s the basic idea of an AI agent: <strong>an LLM that can choose and use actions, rather than only generate text.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7d11b52d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Type a URL and Press Enter]]></title>
            <link>https://medium.com/@jainishah1641/what-really-happens-when-you-type-a-url-and-press-enter-e22c1ca7c858?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e22c1ca7c858</guid>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 13:41:06 GMT</pubDate>
            <atom:updated>2026-09-10T13:41:06.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6DEElBTbT-gsQxJBA0XpQ.jpeg" /></figure><p>When you type something like:</p><pre>https://example.com/products?id=123</pre><p>into your browser and press <strong>Enter</strong>, a lot happens before you see the webpage.</p><p>At a high level:</p><p><strong>URL → DNS → IP address → TCP → TLS → HTTP → Server → Response → Browser parsing → DOM/CSSOM → Rendering</strong></p><p>Let’s break it down step by step.</p><h3>1. The Browser Reads the URL</h3><p>First, the browser needs to understand what you entered.</p><p>For:</p><pre>https://example.com/products?id=123</pre><p>the URL contains several parts:</p><pre>https://     → Protocol<br>example.com  → Domain<br>/products    → Path<br>?id=123      → Query parameters</pre><p>The browser now knows <strong>where</strong> you want to go and <strong>how</strong> it should communicate with that server.</p><p>But there is one problem.</p><p>Computers communicate over IP addresses, not domain names.</p><p>So the browser needs to find the IP address for:</p><pre>example.com</pre><p>That’s where DNS comes in.</p><h3>2. DNS Resolution: Finding the IP Address</h3><p>DNS stands for <strong>Domain Name System</strong>.</p><p>Its job is basically:</p><pre>example.com → 93.184.216.34</pre><p>The browser doesn’t immediately ask a DNS server. It first checks whether it already knows the answer.</p><p>A simplified lookup path is:</p><pre>Browser DNS cache<br>       ↓<br>Operating System DNS cache<br>       ↓<br>Router cache<br>       ↓<br>ISP DNS resolver<br>       ↓<br>Root DNS server<br>       ↓<br>TLD DNS server<br>       ↓<br>Authoritative DNS server<br>       ↓<br>IP address</pre><h3>Browser cache</h3><p>The browser may already have recently resolved the domain.</p><p>If it has:</p><pre>example.com → IP</pre><p>it can reuse that information.</p><h3>Operating system cache</h3><p>If the browser doesn’t have the answer, the operating system may have it cached.</p><h3>Router cache</h3><p>The request can also be handled by the local router or network DNS infrastructure.</p><h3>ISP DNS resolver</h3><p>If nobody locally knows the answer, the request goes to a <strong>DNS recursive resolver</strong>, often provided by your ISP or configured separately.</p><p>The resolver does the work of finding the answer.</p><p>It may first ask a <strong>root nameserver</strong>:</p><blockquote><em>“Who handles </em><em>.com domains?&quot;</em></blockquote><p>The root server points it toward the .com <strong>TLD (Top-Level Domain) nameserver</strong>.</p><p>The TLD server then tells the resolver:</p><blockquote><em>“The authoritative nameserver for </em><em>example.com is over there.&quot;</em></blockquote><p>The resolver asks the authoritative nameserver for the actual record.</p><p>Eventually:</p><pre>example.com<br>      ↓<br>IP address</pre><p>The resolver caches the result so future requests can be faster.</p><h3>3. Now the Browser Knows Where to Connect</h3><p>Suppose DNS returns:</p><pre>93.184.216.34</pre><p>The browser can now communicate with the server.</p><p>For HTTPS, the browser generally establishes a <strong>TCP connection</strong> first.</p><pre>Browser<br>   ↓<br>93.184.216.34</pre><h3>4. TCP Connection</h3><p>TCP provides a reliable connection between the browser and server.</p><p>It starts with the famous <strong>three-way handshake</strong>:</p><pre>Client → SYN → Server<br>Client ← SYN-ACK ← Server<br>Client → ACK → Server</pre><p>In simple terms:</p><p><strong>Client:</strong> “Can we communicate?”</p><p><strong>Server:</strong> “Yes, I can hear you.”</p><p><strong>Client:</strong> “Great, let’s start.”</p><p>Now the TCP connection is established.</p><blockquote><em>With modern HTTP/3, this is different: HTTP/3 uses QUIC over UDP rather than TCP. But TCP is still important for understanding HTTP/1.1 and HTTP/2.</em></blockquote><h3>5. HTTPS and the TLS Handshake</h3><p>If the URL starts with:</p><pre>https://</pre><p>the connection needs encryption.</p><p>That’s where <strong>TLS (Transport Layer Security)</strong> comes in.</p><p>You may hear people call this an <strong>SSL handshake</strong>, but modern HTTPS uses TLS rather than the old SSL protocols.</p><p>The browser and server negotiate things such as:</p><ul><li>encryption algorithms</li><li>cryptographic keys</li><li>server identity</li></ul><p>The server also provides a certificate that the browser can validate.</p><p>The goal is to establish a secure encrypted connection:</p><pre>Browser ←──── encrypted connection ────→ Server</pre><p>Now the browser can safely send the HTTP request.</p><h3>6. The Browser Sends an HTTP Request</h3><p>The browser creates an HTTP request.</p><p>For example:</p><pre>GET /products HTTP/1.1<br>Host: example.com<br>Accept: text/html<br>User-Agent: Chrome</pre><p>The request travels through the network to the server.</p><p>The server receives it and processes it.</p><p>That might involve:</p><pre>Load balancer<br>      ↓<br>Web server<br>      ↓<br>Application server<br>      ↓<br>Database<br>      ↓<br>Other services</pre><p>The exact architecture depends on the application.</p><h3>7. The Server Sends an HTTP Response</h3><p>The server eventually sends something back.</p><p>For example:</p><pre>HTTP/1.1 200 OK<br>Content-Type: text/html</pre><p>followed by the response body:</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;My Website&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Hello World&lt;/h1&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The browser receives the response as <strong>bytes</strong>.</p><p>And this is where the browser’s real work begins.</p><h3>8. Bytes Become Characters</h3><p>At the network level, the browser receives binary data:</p><pre>01101000 01110100 01101101 01101100 ...</pre><p>The browser uses the appropriate character encoding, commonly UTF-8, to interpret those bytes as characters:</p><pre>&lt;html&gt;</pre><p>Now the browser has text that it can parse.</p><h3>9. Characters Become Tokens</h3><p>The browser’s HTML parser reads the characters and breaks them into meaningful pieces called <strong>tokens</strong>.</p><p>For example:</p><pre>&lt;h1&gt;Hello&lt;/h1&gt;</pre><p>becomes concepts like:</p><pre>StartTag: h1<br>Text: Hello<br>EndTag: h1</pre><p>These tokens are then used to construct the DOM.</p><h3>10. Tokens Become the DOM</h3><p>DOM stands for <strong>Document Object Model</strong>.</p><p>The browser converts the HTML structure into a tree.</p><p>For:</p><pre>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Hello&lt;/h1&gt;<br>    &lt;p&gt;Welcome&lt;/p&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>the browser builds something conceptually like:</p><pre>Document<br>   │<br>   └── html<br>        │<br>        └── body<br>             ├── h1<br>             │    └── &quot;Hello&quot;<br>             │<br>             └── p<br>                  └── &quot;Welcome&quot;</pre><p>This is the <strong>DOM tree</strong>.</p><p>JavaScript can interact with this tree.</p><p>For example:</p><pre>document.querySelector(&quot;h1&quot;)</pre><h3>11. CSS Becomes the CSSOM</h3><p>The browser also downloads and parses CSS.</p><p>For example:</p><pre>h1 {<br>  font-size: 32px;<br>}</pre><p>The browser builds another structure called the <strong>CSSOM (CSS Object Model)</strong>.</p><p>So now we have:</p><pre>HTML → DOM<br>CSS  → CSSOM</pre><p>The browser combines information from both to determine how elements should look.</p><h3>12. DOM + CSSOM → Render Tree</h3><p>The browser uses the DOM and CSSOM to create the <strong>render tree</strong>.</p><p>Conceptually:</p><pre>HTML<br> ↓<br>DOM ─────────┐<br>             ├──→ Render Tree<br>CSS           │<br> ↓            │<br>CSSOM ────────┘</pre><p>The render tree contains the information needed to display visible elements.</p><h3>13. Layout</h3><p>Next, the browser calculates where everything should appear.</p><p>For example:</p><pre>Header<br> ├── Logo<br> └── Navigation</pre><pre>Main<br> ├── Heading<br> └── Content</pre><p>The browser calculates:</p><ul><li>width</li><li>height</li><li>position</li><li>margins</li><li>padding</li><li>font sizes etc.</li></ul><p>This process is called <strong>layout</strong>.</p><h3>14. Paint and Composite</h3><p>Finally, the browser needs to actually display the pixels.</p><p>It paints things such as:</p><pre>Text<br>Colors<br>Borders<br>Images<br>Shadows<br>Backgrounds</pre><p>Modern browsers may then divide the page into layers and use the GPU for parts of the final composition.</p><p>Eventually:</p><pre>Pixels → Your Screen</pre><p>And you see the webpage.</p><h3>The Complete Picture</h3><p>So the simplified end-to-end flow is:</p><pre>URL<br>                  ↓<br>            Parse URL<br>                  ↓<br>            DNS Resolution<br>                  ↓<br>              IP Address<br>                  ↓<br>          TCP Connection<br>             (HTTPS)<br>                  ↓<br>           TLS Handshake<br>                  ↓<br>           HTTP Request<br>                  ↓<br>               Server<br>                  ↓<br>          HTTP Response<br>                  ↓<br>               Bytes<br>                  ↓<br>            Characters<br>                  ↓<br>              Tokens<br>                  ↓<br>                DOM<br>                  +<br>               CSSOM<br>                  ↓<br>            Render Tree<br>                  ↓<br>               Layout<br>                  ↓<br>                Paint<br>                  ↓<br>              Composite<br>                  ↓<br>               Screen</pre><p>And that’s what happens behind a simple action that looks like:</p><p><strong>Type URL → Press Enter → Webpage appears.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22c1ca7c858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Music Recommendation System with a Decision Tree in Python]]></title>
            <link>https://medium.com/@jainishah1641/building-a-music-recommendation-system-with-a-decision-tree-in-python-3338c32047f1?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3338c32047f1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree-classifier]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 12:50:01 GMT</pubDate>
            <atom:updated>2026-09-30T07:15:58.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdsGifmNATW7Zw_33YkaeA.jpeg" /></figure><p>A simple machine-learning project is one of the best ways to understand how data, training, prediction, and model evaluation work together.</p><p>In this project, we will build a basic music recommendation system using Python and a Decision Tree Classifier. The model will predict a person’s preferred music genre based on two features:</p><ul><li>Age</li><li>Gender</li></ul><p>We will also learn how to split data, measure accuracy, save the trained model, and visualize the decision tree.</p><h3>Importing the Required Libraries</h3><pre>import pandas as pd<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br>from sklearn import tree<br>import joblib</pre><p>Each library has a specific purpose.</p><h3>Pandas</h3><pre>import pandas as pd</pre><p>Pandas is used to read and manage tabular data.</p><p>Our data is stored inside a CSV file called music.csv.</p><p>The dataset may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIA7UlGYBPDANagTDhu9fQ.png" /><figcaption>Music CSV file</figcaption></figure><h3>DecisionTreeClassifier</h3><pre>from sklearn.tree import DecisionTreeClassifier</pre><p>This imports the Decision Tree algorithm from scikit-learn.</p><p>A decision tree learns rules from the data.</p><p>For example, it may learn something like:</p><pre>If age is less than 25 and gender is 1:<br>    Predict HipHop<br>Otherwise:<br>    Predict Classical</pre><p>The actual rules are created automatically during training.</p><h3>Train-Test Split</h3><pre>from sklearn.model_selection import train_test_split</pre><p>This function divides the dataset into two parts:</p><ul><li>Training data</li><li>Testing data</li></ul><p>The training data teaches the model.</p><p>The testing data checks how well the model performs on information it has not seen before.</p><h3>Accuracy Score</h3><pre>from sklearn.metrics import accuracy_score</pre><p>This calculates how many predictions were correct.</p><p>For example, if the model predicts 8 out of 10 values correctly, its accuracy is 80%.</p><h3>Joblib</h3><pre>import joblib</pre><p>Joblib is used to save a trained model into a file.</p><p>This means we do not need to train the model every time we run the program.</p><h3>Tree Module</h3><pre>from sklearn import tree</pre><p>This module provides tools for working with decision trees.</p><p>We use it to export the trained model into a visual tree file.</p><h3>Reading the Dataset</h3><pre>music_data = pd.read_csv(&quot;music.csv&quot;)</pre><p>This line reads the CSV file and stores it inside a pandas DataFrame called music_data.</p><p>You can inspect the first few rows using:</p><pre>print(music_data.head())</pre><p>The music.csv file should be located in the same folder as your Python file or Jupyter Notebook.</p><h3>Separating Features and Target</h3><pre>X = music_data.drop(columns=[&quot;genre&quot;])<br>y = music_data[&quot;genre&quot;]</pre><p>In machine learning, X usually represents the input features.</p><p>For this project, the features are:</p><ul><li>Age</li><li>Gender</li></ul><p>The genre column is removed from X because it is the value we want the model to predict.</p><pre>X = music_data.drop(columns=[&quot;genre&quot;])</pre><p>The variable y contains the target or correct answer.</p><pre>y = music_data[&quot;genre&quot;]</pre><p>The relationship the model is trying to learn is:</p><pre>Age + Gender → Music Genre</pre><h3>Splitting the Data</h3><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y<br>)</pre><p>This divides the dataset into training and testing sections.</p><h3>test_size</h3><pre>test_size=0.2</pre><p>This means:</p><ul><li>80% of the data is used for training</li><li>20% of the data is used for testing</li></ul><p>If the dataset contains 100 rows, 80 rows are used for training and 20 are used for testing.</p><h3>random_state</h3><pre>random_state=42</pre><p>The data is divided randomly.</p><p>Setting a random state ensures that the same data split is created every time the program runs.</p><p>The number 42 is commonly used, but any integer can be selected.</p><h3>stratify</h3><pre>stratify=y</pre><p>This helps keep a similar percentage of every music genre in both the training and testing sets.</p><p>For example, if 30% of the original dataset contains HipHop, stratification tries to maintain approximately the same percentage in both sets.</p><h3>Creating the Decision Tree Model</h3><pre>model = DecisionTreeClassifier(<br>    max_depth=5,<br>    random_state=42<br>)</pre><p>This creates a new Decision Tree model.</p><p>At this point, the model has not learned anything.</p><h3>max_depth</h3><pre>max_depth=5</pre><p>This limits the number of levels in the decision tree.</p><p>Without a limit, the model may create a very large tree and memorize the training data.</p><p>This problem is known as overfitting.</p><p>Overfitting happens when a model performs very well on training data but performs poorly on new data.</p><h3>Training the Model</h3><pre>model.fit(X_train, y_train)</pre><p>The fit() method trains the model.</p><p>The model examines each person’s age and gender along with their preferred music genre.</p><p>It then creates decision rules that separate the genres as accurately as possible.</p><p>After this step, the model is ready to make predictions.</p><h3>Making Predictions</h3><pre>predictions = model.predict(X_test)</pre><p>The trained model receives the testing data and predicts a genre for each row.</p><p>The predictions are stored inside the predictions variable.</p><p>The testing data is important because the model did not see it during training.</p><p>This gives us a more realistic understanding of model performance.</p><h3>Measuring Accuracy</h3><pre>score = accuracy_score(y_test, predictions)</pre><pre>print(f&quot;Accuracy: {score:.2%}&quot;)</pre><p>The accuracy_score() function compares:</p><ul><li>Actual genres stored in y_test</li><li>Predicted genres stored in predictions</li></ul><p>If the result is:</p><pre>Accuracy: 75.00%</pre><p>it means the model correctly predicted 75% of the testing examples.</p><p>A high accuracy score does not always mean a model is perfect. The dataset may be small, imbalanced, or missing important features.</p><p>For a learning project, however, accuracy is a useful starting point.</p><h3>Visualizing the Decision Tree</h3><pre>tree.export_graphviz(<br>    model,<br>    out_file=&quot;music-recommender.dot&quot;,<br>    feature_names=X.columns,<br>    class_names=model.classes_,<br>    label=&quot;all&quot;,<br>    rounded=True,<br>    filled=True<br>)</pre><p>This creates a file called:</p><pre>music-recommender.dot</pre><p>The file contains instructions for drawing the decision tree.</p><p>It can be opened using Graphviz, a VS Code Graphviz extension, or an online DOT file viewer.</p><h3>feature_names</h3><pre>feature_names=X.columns</pre><p>This displays the input column names inside the tree.</p><p>In this project, the feature names are age and gender.</p><h3>class_names</h3><pre>class_names=model.classes_</pre><p>This displays the possible output genres.</p><p>Using model.classes_ is safer than manually writing the genre names because it follows the exact class order used by the trained model.</p><h3>rounded</h3><pre>rounded=True</pre><p>This gives the tree boxes rounded corners.</p><h3>filled</h3><pre>filled=True</pre><p>This adds colors to the tree nodes.</p><p>The colors help show which genre is being predicted and how pure each node is.</p><h3>Understanding a Decision Tree Node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3GoZwuqG-M9qC3xKDkt5w.png" /></figure><p>A node look like this:</p><pre>age &lt;= 25.5<br>gini = 0.44<br>samples = 18<br>value = [2, 12, 4]<br>class = HipHop</pre><h3>Decision Rule</h3><pre>age &lt;= 25.5</pre><p>If the condition is true, the tree moves to the left branch.</p><p>If it is false, the tree moves to the right branch.</p><h3>Gini</h3><p>The Gini value measures how mixed the classes are inside a node.</p><p>A Gini value of 0 means all records inside the node belong to the same class.</p><p>A higher value means the node contains a mixture of different genres.</p><h3>Samples</h3><pre>samples = 18</pre><p>This means 18 training records reached this node.</p><h3>Value</h3><pre>value = [2, 12, 4]</pre><p>This shows how many records belong to each class.</p><p>The order follows the classes stored inside:</p><pre>model.classes_</pre><h3>Class</h3><pre>class = HipHop</pre><p>This is the final prediction for that node.</p><p>The model normally selects the class with the largest count.</p><h3>Saving the Trained Model</h3><pre>joblib.dump(model, &quot;music-recommender.joblib&quot;)</pre><p>This saves the trained model into a file.</p><p>The saved file contains the rules learned by the decision tree.</p><p>Saving the model is useful when the model needs to be used inside:</p><ul><li>A website</li><li>A mobile application</li><li>A REST API</li><li>A recommendation service</li></ul><p>The model can be loaded later without training it again.</p><h3>Loading the Model</h3><pre>model = joblib.load(&quot;music-recommender.joblib&quot;)</pre><p>This loads the previously trained model.</p><p>Once loaded, the model can immediately make predictions.</p><h3>Predicting a Genre for One Person</h3><pre>new_person = pd.DataFrame(<br>    [[21, 1]],<br>    columns=[&quot;age&quot;, &quot;gender&quot;]<br>)</pre><pre>prediction = model.predict(new_person)</pre><pre>print(f&quot;Recommended genre: {prediction[0]}&quot;)</pre><p>This example predicts a music genre for a person whose:</p><ul><li>Age is 21</li><li>Gender value is 1</li></ul><p>Using a DataFrame is better than passing a plain list because the input includes the same column names that were used during training.</p><p>The meaning of the gender values depends on how the dataset was created.</p><p>For example:</p><pre>1 = Male<br>0 = Female</pre><p>The model does not understand these meanings automatically. It only learns patterns from the values provided in the dataset.</p><h3>Complete Code</h3><pre>import pandas as pd<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br>from sklearn import tree<br>import joblib</pre><pre># Read the dataset<br>music_data = pd.read_csv(&quot;music.csv&quot;)</pre><pre># Separate input features and target<br>X = music_data.drop(columns=[&quot;genre&quot;])<br>y = music_data[&quot;genre&quot;]</pre><pre># Split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42,<br>    stratify=y<br>)</pre><pre># Create the model<br>model = DecisionTreeClassifier(<br>    max_depth=5,<br>    random_state=42<br>)</pre><pre># Train the model<br>model.fit(X_train, y_train)</pre><pre># Make predictions<br>predictions = model.predict(X_test)</pre><pre># Measure accuracy<br>score = accuracy_score(y_test, predictions)</pre><pre>print(f&quot;Accuracy: {score:.2%}&quot;)</pre><pre># Export the decision tree<br>tree.export_graphviz(<br>    model,<br>    out_file=&quot;music-recommender.dot&quot;,<br>    feature_names=X.columns,<br>    class_names=model.classes_,<br>    label=&quot;all&quot;,<br>    rounded=True,<br>    filled=True<br>)</pre><pre># Save the trained model<br>joblib.dump(model, &quot;music-recommender.joblib&quot;)</pre><h3>Common Mistakes</h3><h3>Using the Wrong Variable Name</h3><p>Python is case-sensitive.</p><p>This is incorrect:</p><pre>train_test_split(X, Y)</pre><p>because the target variable was created as lowercase y.</p><p>The correct version is:</p><pre>train_test_split(X, y)</pre><h3>Training and Testing on the Same Data</h3><p>This code trains on the complete dataset:</p><pre>model.fit(X, y)</pre><p>It is acceptable when creating a final production model, but it should not be used when measuring accuracy.</p><p>For evaluation, train the model using:</p><pre>model.fit(X_train, y_train)</pre><h3>Predicting One Value and Comparing It with the Entire Test Set</h3><p>This is incorrect:</p><pre>predictions = model.predict([[21, 1]])<br>score = accuracy_score(y_test, predictions)</pre><p>The prediction contains only one result, while y_test may contain several values.</p><p>To calculate accuracy, predict the complete testing set:</p><pre>predictions = model.predict(X_test)<br>score = accuracy_score(y_test, predictions)</pre><h3>Final Workflow</h3><p>The complete machine-learning process is:</p><pre>Load the CSV file<br>        ↓<br>Separate features and target<br>        ↓<br>Split the dataset<br>        ↓<br>Create the model<br>        ↓<br>Train the model<br>        ↓<br>Make predictions<br>        ↓<br>Measure accuracy<br>        ↓<br>Visualize the tree<br>        ↓<br>Save the trained model<br>        ↓<br>Load it later for new predictions</pre><h3>Conclusion</h3><p>This project demonstrates the basic steps involved in building a machine-learning model.</p><p>We loaded a dataset, separated the input and output columns, trained a Decision Tree Classifier, evaluated its accuracy, visualized its decisions, and saved the model for future use.</p><p>Although this music recommendation system is simple, the same process is used in larger machine-learning applications. The main differences are the amount of data, the number of features, and the complexity of the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3338c32047f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis vs Memcached: Caching Benchmarks for High-Traffic Apps (2025)]]></title>
            <link>https://medium.com/@jainishah1641/redis-vs-memcached-caching-benchmarks-for-high-traffic-apps-2025-5cce021f8293?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cce021f8293</guid>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[caching-memory]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 23:50:15 GMT</pubDate>
            <atom:updated>2025-06-28T23:50:15.217Z</atom:updated>
            <content:encoded><![CDATA[<p>I tested both with 1 million requests to see which one scales better, uses less RAM, and costs less to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yuJhwBp2OZ5kuU7l2f2pg.png" /></figure><h3>🚀 Introduction</h3><blockquote><em>When your web app crosses 10k or 100k daily active users, database performance bottlenecks come fast. The easiest solution? Add a caching layer.</em></blockquote><blockquote><em>But the age-old question for full-stack developers is: </em><strong><em>Should you pick Redis or Memcached?</em></strong></blockquote><blockquote><em>Both are in-memory key-value stores, super fast, and widely supported but they behave differently under real workloads.</em></blockquote><blockquote><em>I wanted real data, so I ran my own benchmarks with </em><em>memtier_benchmark on an AWS t3.large instance, simulating 1 million requests with mixed read/write patterns.</em></blockquote><blockquote><em>Here’s exactly how they performed plus my real-world lessons for high-traffic apps.</em></blockquote><h3>⚙️ 1. Why This Benchmark?</h3><p>I run a SaaS platform that serves thousands of concurrent users daily. Caching helps us:<br>✅ Reduce database load<br>✅ Speed up response times<br>✅ Keep costs under control</p><p>Redis and Memcached are the two biggest options but they differ:</p><ul><li><strong>Redis</strong> supports persistence, Pub/Sub, data structures (lists, sets, sorted sets).</li><li><strong>Memcached</strong> is simpler, multi-threaded, and great for ephemeral, purely in-memory caching.</li></ul><p>Most people just pick Redis because it’s trendy but Memcached can still outperform Redis in certain scenarios.</p><h3>🧩 2. My Test Setup</h3><p>🔍 <strong>Cloud Environment</strong></p><ul><li>AWS t3.large (2 vCPUs, 8GB RAM)</li><li>Ubuntu 22.04 LTS</li></ul><p>🔍 <strong>Tools</strong></p><ul><li><a href="https://github.com/RedisLabs/memtier_benchmark">memtier_benchmark</a>: stress test for Redis &amp; Memcached</li><li>htop &amp; iostat for CPU/memory stats</li></ul><p>🔍 <strong>Test Scenario</strong></p><ul><li>Key: 32 bytes</li><li>Value: 1KB</li><li>Requests: 1 million total</li><li>Pattern: 90% reads, 10% writes</li><li>Connections: 50 concurrent clients</li></ul><p>🔍 <strong>Configuration</strong></p><ul><li>Redis: default, maxmemory-policy allkeys-lru</li><li>Memcached: default, max memory 512MB</li></ul><h3>📊 3. The Raw Benchmark Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9AvSLogxLwMIOFe0VecnA.png" /></figure><p><strong>💡 Takeaway:<br></strong>✅ Memcached handled more operations per second and had slightly lower latency.<br>✅ Redis used a bit more CPU &amp; RAM for the same workload expected, since it supports richer data structures.</p><h3>⚖️ 4. Feature Trade-Offs</h3><p><strong>✨ Redis Pros:</strong><br>✅ Supports advanced data types (Lists, Sets, Sorted Sets, Hashes)<br>✅ Persistence options (RDB, AOF) for backup<br>✅ Pub/Sub &amp; Streams for messaging<br>✅ Strong community &amp; ecosystem</p><p><strong>⚡ Memcached Pros:</strong><br>✅ Simpler &amp; blazing fast for pure key-value<br>✅ Multi-threaded by default scales better on multi-core CPUs<br>✅ Smaller memory footprint for same dataset<br>✅ Slightly easier to manage for ephemeral caches (sessions, pages)</p><p><strong>🚫 Redis Cons:</strong><br>❌ Single-threaded for commands → can bottleneck on heavy writes unless you shard or use Redis Cluster<br>❌ Slightly higher RAM usage due to extra features</p><p><strong>🚫 Memcached Cons:</strong><br>❌ No persistence: if it crashes, cache is gone<br>❌ No Pub/Sub, no Lua scripting, no advanced data structures<br>❌ Harder to scale horizontally without external sharding logic</p><h3>🗝️ 5. Real-World Lessons</h3><p>✨ If you need advanced features (sorted sets, pub/sub, streams) <strong>Redis</strong> wins.<br>✨ If you just need raw read speed for ephemeral cache (sessions, rendered pages) <strong>Memcached</strong> can be faster and cheaper.<br>✨ For massive scale, Redis Cluster helps distribute load but adds operational complexity. Memcached’s multi-threaded nature can be simpler for a single-node cache with big RAM.</p><p><strong>My use case:</strong><br>I ended up running Redis for user session storage (since I wanted persistence) and Memcached for ephemeral page fragment caching. Using both gave the best cost-performance balance.</p><h3>📂 6. My Benchmark Code</h3><p>If you want to replicate my test:</p><ul><li><a href="#">GitHub Repo</a> <em>(Put your real repo link!)</em></li><li>Includes Docker Compose files for Redis &amp; Memcached</li><li>memtier_benchmark commands:</li></ul><pre>memtier_benchmark -s localhost -p 6379 --protocol redis --requests=1000000 --data-size=1024 --key-pattern=R:R --ratio=9:1 --clients=50</pre><h3>✅ 7. Final Takeaway</h3><blockquote><em>In 2025, Redis is still king if you need more than a simple cache but Memcached holds its ground for raw speed, simplicity, and cost savings.</em></blockquote><blockquote><em>The real answer? Test with your own workload caching isn’t one-size-fits-all.</em></blockquote><p>If you enjoyed this benchmark:</p><ul><li><strong>Follow me on Medium</strong> for more real-world performance tests.</li><li>Drop a comment if you’d like me to compare <strong>Redis vs DynamoDB as a session store</strong>, or test a <strong>multi-region cache setup on AWS</strong> next!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cce021f8293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered JavaScript: Using TensorFlow.js to Build a Real-Time Image Recognition App]]></title>
            <link>https://medium.com/@jainishah1641/ai-powered-javascript-using-tensorflow-js-to-build-a-real-time-image-recognition-app-87355d4bbbf4?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/87355d4bbbf4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[image-recognition]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 16:02:36 GMT</pubDate>
            <atom:updated>2025-03-18T16:02:36.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*etPZjlrIpMuHb7I7.jpg" /></figure><p>Artificial Intelligence (AI) and Machine Learning (ML) are transforming the way we interact with technology. Traditionally, ML models are run on powerful cloud servers, but with the advent of <strong>TensorFlow.js</strong>, we can now run ML models directly in the browser, eliminating latency and enhancing privacy. In this article, we will build a <strong>real-time image recognition app</strong> using TensorFlow.js and a pre-trained ML model.</p><h3>Why TensorFlow.js?</h3><p>TensorFlow.js is an open-source library that allows <strong>training and deploying ML models in the browser</strong> or on <strong>Node.js</strong>. Key benefits include:</p><ul><li><strong>Client-Side Processing</strong>: Reduces server costs and latency.</li><li><strong>Privacy</strong>: No need to send images to external servers.</li><li><strong>WebGL Acceleration</strong>: Utilizes GPU for faster computations.</li><li><strong>Works Offline</strong>: Once loaded, the model can work without internet access.</li></ul><h3>Setting Up the Project</h3><h3>1. Install Dependencies</h3><p>First, we need a basic web setup. Create an index.html file and include TensorFlow.js:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Real-Time Image Recognition&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Real-Time Image Recognition with TensorFlow.js&lt;/h1&gt;<br>    &lt;video id=&quot;video&quot; width=&quot;640&quot; height=&quot;480&quot; autoplay&gt;&lt;/video&gt;<br>    &lt;p id=&quot;result&quot;&gt;Loading model...&lt;/p&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@tensorflow/tfjs&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>2. Load a Pre-trained Model</h3><p>TensorFlow.js provides many pre-trained models. We will use <strong>MobileNet</strong>, a lightweight image recognition model.</p><p>Create a script.js file:</p><pre>const video = document.getElementById(&#39;video&#39;);<br>const resultText = document.getElementById(&#39;result&#39;);</pre><pre>// Load MobileNet Model<br>async function loadModel() {<br>    const model = await tf.loadLayersModel(&#39;https://tfhub.dev/google/tfjs-model/mobilenet_v2/classification/2/default/1&#39;, true);<br>    return model;<br>}</pre><pre>// Start Video Stream<br>async function startVideo() {<br>    const stream = await navigator.mediaDevices.getUserMedia({ video: true });<br>    video.srcObject = stream;<br>}</pre><pre>// Capture and Predict<br>async function predict(model) {<br>    const tensor = tf.browser.fromPixels(video)<br>        .resizeNearestNeighbor([224, 224])<br>        .expandDims()<br>        .toFloat();</pre><pre>    const predictions = await model.predict(tensor).data();<br>    const highestPrediction = predictions.indexOf(Math.max(...predictions));</pre><pre>    resultText.innerText = `Prediction: ${highestPrediction}`;<br>}</pre><pre>// Initialize<br>(async () =&gt; {<br>    const model = await loadModel();<br>    await startVideo();<br>    setInterval(() =&gt; predict(model), 1000);<br>})();</pre><h3>Explanation of Code</h3><ol><li><strong>Load a Pre-trained Model</strong>: We use MobileNet from TensorFlow Hub, a lightweight model designed for fast image classification.</li><li><strong>Start a Video Stream</strong>: Uses navigator.mediaDevices.getUserMedia() to access the webcam.</li><li><strong>Process Image Data</strong>: Captures frames from the video feed, resizes them to 224x224 pixels (the input size for MobileNet), and converts them into a tensor.</li><li><strong>Make Predictions</strong>: The model predicts what is in the frame every second (setInterval).</li><li><strong>Display Results</strong>: The result is displayed in real-time in the browser.</li></ol><h3>Enhancements &amp; Next Steps</h3><ul><li><strong>Better Predictions</strong>: Use a custom-trained model instead of MobileNet for more accurate results.</li><li><strong>Display Labels</strong>: Load ImageNet class labels to display real names instead of index numbers.</li><li><strong>Optimize Performance</strong>: Use WebGL optimizations for faster inference.</li><li><strong>Deploy as a PWA</strong>: Convert this into a Progressive Web App (PWA) for offline functionality.</li></ul><h3>Conclusion</h3><p>With <strong>TensorFlow.js</strong>, JavaScript developers can integrate <strong>real-time AI capabilities</strong> directly into web applications, making machine learning more accessible than ever. By following this guide, you’ve built an <strong>AI-powered image recognition app that runs entirely in the browser</strong>, eliminating server costs and enhancing user privacy.</p><p>Give it a try, customize it, and take your JavaScript applications to the next level with AI! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87355d4bbbf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Backend-as-a-Service (BaaS) Like Firebase]]></title>
            <link>https://medium.com/@jainishah1641/build-your-own-backend-as-a-service-baas-like-firebase-64f6d546105f?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f6d546105f</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[backend-as-a-service]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 16:02:32 GMT</pubDate>
            <atom:updated>2025-03-18T06:05:00.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*muBASJNITzBa6TfH.png" /></figure><p>Building your own <strong>Backend-as-a-Service (BaaS)</strong> like Firebase allows you to provide authentication, real-time database, cloud storage, and hosting services without relying on third-party solutions. In this guide, we’ll build a Firebase-like BaaS using <strong>Node.js (NestJS), PostgreSQL (with Supabase), and AWS S3 for file storage</strong>.</p><h3>Features to Implement</h3><ul><li>User Authentication (JWT-based login/sign-up)</li><li>Real-time Database (PostgreSQL + Supabase)</li><li>File Storage (AWS S3)</li><li>API to manage users, roles, and permissions</li><li>CI/CD for automated deployment</li></ul><h3>Prerequisites</h3><ul><li>Node.js installed</li><li>PostgreSQL database</li><li>AWS account (for S3 bucket)</li><li>Supabase account (optional)</li></ul><h3>Step 1: Setting Up the Project</h3><h3>1.1 Install NestJS and Dependencies</h3><pre>npx @nestjs/cli new my-baas<br>cd my-baas<br>npm install @nestjs/config @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt pg</pre><h3>1.2 Configure Environment Variables (.env)</h3><pre>PORT=5000<br>DATABASE_URL=postgres://your_username:your_password@localhost:5432/your_database<br>JWT_SECRET=your_jwt_secret<br>AWS_ACCESS_KEY_ID=your_aws_key<br>AWS_SECRET_ACCESS_KEY=your_aws_secret<br>AWS_S3_BUCKET=your_s3_bucket_name</pre><h3>Step 2: Implement Authentication</h3><h3>2.1 Create User Entity (src/users/user.entity.ts)</h3><pre>import { Entity, PrimaryGeneratedColumn, Column } from &#39;typeorm&#39;;</pre><pre>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br>  <br>  @Column({ unique: true })<br>  email: string;<br>  <br>  @Column()<br>  password: string;<br>}</pre><h3>2.2 Create Authentication Service (src/auth/auth.service.ts)</h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { User } from &#39;../users/user.entity&#39;;</pre><pre>@Injectable()<br>export class AuthService {<br>  constructor(<br>    @InjectRepository(User) private userRepository: Repository&lt;User&gt;,<br>    private jwtService: JwtService,<br>  ) {}</pre><pre>  async signup(email: string, password: string) {<br>    const hashedPassword = await bcrypt.hash(password, 10);<br>    const user = this.userRepository.create({ email, password: hashedPassword });<br>    await this.userRepository.save(user);<br>    return this.generateToken(user);<br>  }</pre><pre>  async login(email: string, password: string) {<br>    const user = await this.userRepository.findOne({ where: { email } });<br>    if (!user || !(await bcrypt.compare(password, user.password))) {<br>      throw new Error(&#39;Invalid credentials&#39;);<br>    }<br>    return this.generateToken(user);<br>  }</pre><pre>  private generateToken(user: User) {<br>    return { access_token: this.jwtService.sign({ id: user.id, email: user.email }) };<br>  }<br>}</pre><h3>Step 3: Implement Real-time Database with Supabase</h3><h3>3.1 Connect Supabase with PostgreSQL</h3><ul><li>Sign up at <a href="https://supabase.com/"><strong>Supabase</strong></a></li><li>Create a new PostgreSQL database and get the connection string</li><li>Add it to your .env file under DATABASE_URL</li></ul><h3>3.2 Set Up Supabase Client (src/database/supabase.ts)</h3><pre>import { createClient } from &#39;@supabase/supabase-js&#39;;</pre><pre>const supabase = createClient(<br>  process.env.SUPABASE_URL,<br>  process.env.SUPABASE_SERVICE_KEY<br>);</pre><pre>export default supabase;</pre><h3>Step 4: Implement File Storage with AWS S3</h3><h3>4.1 Install AWS SDK</h3><pre>npm install aws-sdk multer multer-s3</pre><h3>4.2 Configure AWS S3 Upload (src/storage/storage.service.ts)</h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import * as AWS from &#39;aws-sdk&#39;;<br>import * as multerS3 from &#39;multer-s3&#39;;<br>import * as multer from &#39;multer&#39;;</pre><pre>AWS.config.update({<br>  accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br>  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br>});</pre><pre>const s3 = new AWS.S3();</pre><pre>@Injectable()<br>export class StorageService {<br>  storage = multer({<br>    storage: multerS3({<br>      s3,<br>      bucket: process.env.AWS_S3_BUCKET,<br>      acl: &#39;public-read&#39;,<br>      metadata: (req, file, cb) =&gt; {<br>        cb(null, { fieldName: file.fieldname });<br>      },<br>      key: (req, file, cb) =&gt; {<br>        cb(null, `${Date.now().toString()}-${file.originalname}`);<br>      },<br>    }),<br>  });<br>}</pre><h3>Step 5: Deploy the BaaS with CI/CD</h3><h3>5.1 Set Up GitHub Actions</h3><p>(.github/workflows/deploy.yml)</p><pre>name: Deploy to AWS<br>on: push<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br>      - name: Install dependencies<br>        run: |<br>          npm install<br>      - name: Deploy to EC2<br>        run: |<br>          ssh -i ~/.ssh/your-key.pem ubuntu@your-ec2-ip &quot;cd my-baas &amp;&amp; git pull &amp;&amp; npm install &amp;&amp; pm2 restart all&quot;</pre><h3>Conclusion</h3><p>Congratulations! 🎉 You have built a <strong>Backend-as-a-Service (BaaS) like Firebase</strong> using <strong>NestJS, PostgreSQL (Supabase), AWS S3, and CI/CD with GitHub Actions</strong>. This setup allows users to authenticate, store files, and interact with a real-time database securely.</p><h3>Next Steps</h3><ul><li>Implement <strong>Role-Based Access Control (RBAC)</strong></li><li>Add <strong>WebSockets for real-time updates</strong></li><li>Optimize database performance with caching (Redis)</li></ul><p>Stay tuned for more advanced tutorials! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f6d546105f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Hero: Deploying a Full-Stack App on AWS with CI/CD]]></title>
            <link>https://medium.com/@jainishah1641/from-zero-to-hero-deploying-a-full-stack-app-on-aws-with-ci-cd-0358873c836b?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0358873c836b</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[ci-cd-devops]]></category>
            <category><![CDATA[full-stack-application]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 20:56:01 GMT</pubDate>
            <atom:updated>2025-03-18T06:00:01.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*MVof7QuVE5H5fPNd.jpg" /></figure><p>Deploying a full-stack application on AWS can be intimidating for beginners, but this guide will break it down step by step. We will use <strong>React.js for frontend</strong>, <strong>Node.js (Express/NestJS) for backend</strong>, and <strong>AWS services</strong> like EC2, S3, RDS, and Route 53. Additionally, we’ll set up <strong>CI/CD with GitHub Actions</strong> to automate deployment.</p><h3>Prerequisites</h3><ul><li>AWS Account</li><li>Basic knowledge of React.js, Node.js (or NestJS)</li><li>GitHub account</li><li>Domain name (optional but recommended)</li></ul><h3>Step 1: Setting Up the Full-Stack Project</h3><h3>1.1 Backend Setup (Node.js + Express)</h3><p>Create a new backend project:</p><pre>mkdir backend &amp;&amp; cd backend<br>npm init -y<br>npm install express cors dotenv mongoose</pre><p>Create server.js:</p><pre>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const app = express();<br>app.use(cors());<br>app.use(express.json());</pre><pre>mongoose.connect(process.env.MONGO_URI, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true,<br>});</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Server is running!&#39;));<br>app.listen(5000, () =&gt; console.log(&#39;Server running on port 5000&#39;));</pre><p>Create .env file:</p><pre>MONGO_URI=mongodb+srv://your_db_connection</pre><h3>1.2 Frontend Setup (React.js)</h3><pre>npx create-react-app frontend<br>cd frontend<br>npm install axios react-router-dom</pre><p>Modify src/App.js:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;</pre><pre>function App() {<br>  const [message, setMessage] = useState(&#39;&#39;);</pre><pre>  useEffect(() =&gt; {<br>    axios.get(&#39;http://localhost:5000/&#39;)<br>      .then(response =&gt; setMessage(response.data))<br>      .catch(error =&gt; console.error(error));<br>  }, []);</pre><pre>  return &lt;h1&gt;{message}&lt;/h1&gt;;<br>}<br>export default App;</pre><h3>Step 2: Deploy Backend to AWS EC2</h3><ol><li><strong>Launch an EC2 Instance:</strong></li></ol><ul><li>Choose Ubuntu 20.04 LTS</li><li>Select t2.micro (free tier)</li><li>Configure security group (allow <strong>ports 22, 5000</strong>)</li><li>SSH into the instance:</li></ul><pre>ssh -i your-key.pem ubuntu@your-ec2-ip</pre><p><strong>2. Install Node.js &amp; Git:</strong></p><pre>sudo apt update &amp;&amp; sudo apt install -y nodejs npm git</pre><p><strong>3. Clone the backend repo &amp; start the server:</strong></p><pre>git clone https://github.com/your-repo.git <br>cd backend <br>npm install <br>node server.js</pre><h3>Step 3: Deploy Frontend to AWS S3 + CloudFront</h3><ol><li><strong>Build the React app:</strong></li></ol><pre>npm run build</pre><p><strong>2. Create an S3 Bucket &amp; Upload Files:</strong></p><ul><li>Create an S3 bucket (your-domain.com)</li><li>Enable static website hosting</li><li>Upload build/ files</li></ul><p><strong>3. Set Up CloudFront for Faster Delivery</strong></p><ul><li>Create a CloudFront distribution</li><li>Select the S3 bucket as the origin</li><li>Update S3 bucket policy to allow public access</li></ul><h3>Step 4: Connect to a Domain with Route 53</h3><ol><li><strong>Buy or Configure a Domain in Route 53</strong></li><li><strong>Add an A Record pointing to EC2 IP (for backend)</strong></li><li><strong>Add a CNAME Record for CloudFront (for frontend)</strong></li></ol><h3>Step 5: Set Up CI/CD with GitHub Actions</h3><h3>5.1 Backend CI/CD</h3><p>Create .github/workflows/backend.yml:</p><pre>name: Backend Deployment<br>on: push<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br>      - name: Install dependencies<br>        run: |<br>          cd backend<br>          npm install<br>      - name: Deploy to EC2<br>        run: |<br>          ssh -i ~/.ssh/your-key.pem ubuntu@your-ec2-ip &quot;cd backend &amp;&amp; git pull &amp;&amp; npm install &amp;&amp; pm2 restart server&quot;</pre><h3>5.2 Frontend CI/CD</h3><p>Create .github/workflows/frontend.yml:</p><pre>name: Frontend Deployment<br>on: push<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br>      - name: Build React app<br>        run: |<br>          cd frontend<br>          npm install<br>          npm run build<br>      - name: Deploy to S3<br>        run: |<br>          aws s3 sync frontend/build s3://your-domain.com --delete</pre><h3>Conclusion</h3><p>Congratulations! 🎉 You’ve successfully deployed a full-stack app on AWS with CI/CD. This setup ensures automated updates, scalability, and reliability.</p><h3>Next Steps</h3><ul><li>Implement <strong>HTTPS with AWS Certificate Manager</strong></li><li>Optimize backend performance with <strong>Load Balancers and Auto Scaling</strong></li><li>Monitor with <strong>AWS CloudWatch</strong></li></ul><p>Stay tuned for more tutorials! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0358873c836b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Your HTML Website on GitHub and Create an Impressive Portfolio]]></title>
            <link>https://medium.com/@jainishah1641/deploy-your-html-website-on-github-and-create-an-impressive-portfolio-28b33e87d021?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b33e87d021</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[html-website]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 02:14:09 GMT</pubDate>
            <atom:updated>2025-03-18T06:06:14.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnU4pQ_KKslT9H0EESBIQw.png" /></figure><p>In this guide, we’ll walk through the process of deploying a simple HTML website to GitHub Pages and turning it into a professional online portfolio. Hosting your portfolio on GitHub is a free and easy way to showcase your work. You don’t need to be an expert in web development to get started.</p><h3>Step 1: Create a GitHub Account</h3><p>Before we begin, make sure you have a <strong>GitHub account</strong>. If you don’t already have one, here’s how to create it:</p><ol><li>Go to <a href="https://github.com/">GitHub</a>.</li><li>Click <strong>Sign Up</strong> in the top right corner and follow the instructions to create an account.</li></ol><h3>Step 2: Create a New GitHub Repository</h3><ol><li>After logging into GitHub, click the <strong>+</strong> icon in the top right corner and select <strong>New Repository</strong>.</li><li>Name your repository (e.g., my-portfolio).</li><li>Set the repository to <strong>Public</strong> (so everyone can see your portfolio).</li><li><strong>Do not initialize with a README</strong> file (unless you want to, but we will create one separately).</li><li>Click <strong>Create repository</strong>.</li></ol><h3>Step 3: Set Up Your Local Project Folder</h3><ol><li>On your computer, create a folder for your website project (e.g., my-portfolio).</li><li>Inside this folder, add your website files (HTML, CSS, JavaScript, images, etc.).</li></ol><h3>Step 4: Initialize Git in Your Project Folder</h3><p>Open <strong>Git Bash</strong> (or terminal on macOS/Linux) and navigate to your project folder:</p><pre>cd path/to/your/project</pre><p>Next, initialize a Git repository:</p><pre>git init</pre><h3>Step 5: Add Your Files to Git</h3><ol><li>Add your files to the repository:</li></ol><pre>git add .</pre><ol><li>Commit the files:</li></ol><pre>git commit -m &quot;Initial commit of my portfolio&quot;</pre><h3>Step 6: Link Your Local Repository to GitHub</h3><ol><li>Go back to your GitHub repository page.</li><li>Copy the URL of your repository (it will look like this: <a href="https://github.com/your-username/my-portfolio.git).">https://github.com/your-username/my-portfolio.git).</a></li><li>Link your local repository to GitHub:</li></ol><pre>git remote add origin https://github.com/your-username/my-portfolio.git</pre><h3>Step 7: Push Your Website Files to GitHub</h3><p>Push your local files to GitHub:</p><pre>git push -u origin master</pre><h3>Step 8: Set Up GitHub Pages</h3><ol><li>Go to your GitHub repository page.</li><li>Click on <strong>Settings</strong> (found in the tabs at the top).</li><li>Scroll down to the <strong>GitHub Pages</strong> section.</li><li>Under <strong>Source</strong>, choose <strong>master branch</strong> (or <strong>main</strong> if that’s what you use).</li><li>After a few moments, GitHub will provide a URL to your deployed site, like <a href="https://your-username.github.io/my-portfolio/">https://your-username.github.io/my-portfolio/.</a></li></ol><h3>Step 9: Customize Your Portfolio (Optional)</h3><p>Now that your basic portfolio is live, you can customize it to make it unique and showcase your work. Here are some suggestions:</p><ul><li><strong>Add a Contact Section</strong>: Include a form or email link for people to contact you.</li><li><strong>Showcase Your Projects</strong>: Display screenshots, descriptions, and links to live projects or code repositories.</li><li><strong>Add a Resume Section</strong>: You can add a link to download your resume in PDF format.</li></ul><h3>Step 10: Update and Maintain Your Portfolio</h3><p>Once your portfolio is live, you can easily update it by making changes to your local files and pushing the changes to GitHub. Here’s how:</p><ol><li>Edit your files locally.</li><li>Stage and commit your changes:</li></ol><pre>git add .<br>git commit -m &quot;Updated my portfolio with new projects&quot;</pre><ol><li>Push the updates:</li></ol><pre>git push origin master</pre><p>Your GitHub Pages site will automatically update.</p><h3>Conclusion:</h3><p>Congratulations! You now have a fully deployed portfolio website on GitHub. With just a few steps, you’ve set up a free hosting solution to showcase your work and projects. GitHub Pages is a powerful tool that allows you to focus on building your portfolio without worrying about server management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b33e87d021" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack Development and DevOps: A Guide for Aspiring Developers]]></title>
            <link>https://medium.com/@jainishah1641/full-stack-development-and-devops-a-guide-for-aspiring-developers-e9c49568b814?source=rss-c82d81e819f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c49568b814</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jainishah]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 22:56:43 GMT</pubDate>
            <atom:updated>2025-03-18T06:08:00.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*ZU55MSirkibSPTIF.jpg" /></figure><p>Becoming a full-stack developer with DevOps expertise is one of the most rewarding career paths in tech today. Whether you’re just starting or looking to enhance your skills, mastering the right technologies and best practices can set you apart. In this guide, we’ll explore essential tools, industry trends, and key strategies to help you accelerate your journey into full-stack development and DevOps.</p><h3>Understanding Full-Stack Development</h3><p>A full-stack developer is responsible for both frontend and backend development. To succeed, you should have a solid understanding of:</p><ul><li><strong>Frontend:</strong> HTML, CSS, JavaScript, React.js, Vue.js, or Angular</li><li><strong>Backend:</strong> Node.js, Python, Java, or Ruby on Rails</li><li><strong>Databases:</strong> SQL (MySQL, PostgreSQL) and NoSQL (MongoDB, Firebase)</li><li><strong>APIs &amp; Authentication:</strong> REST, GraphQL, OAuth, JWT</li></ul><p>Mastering these technologies enables you to build scalable, user-friendly applications.</p><h3>Why DevOps Matters for Developers</h3><p>DevOps bridges the gap between software development and IT operations, improving collaboration, automation, and deployment efficiency. Key DevOps skills include:</p><ul><li><strong>Version Control:</strong> Git, GitHub, GitLab</li><li><strong>Containerization:</strong> Docker, Kubernetes</li><li><strong>CI/CD Pipelines:</strong> Jenkins, GitHub Actions</li><li><strong>Cloud Computing:</strong> AWS, Azure, Google Cloud</li><li><strong>Infrastructure as Code:</strong> Terraform, Ansible</li></ul><p>Understanding DevOps ensures smoother deployments, faster iterations, and improved system reliability.</p><h3>Key Strategies for Success</h3><h4>1️⃣ Focus on Hands-On Learning</h4><p>Building projects is the best way to solidify your knowledge. Start with simple applications and gradually move to complex systems. Contribute to open-source projects to gain real-world experience.</p><h4>2️⃣ Stay Updated with Industry Trends</h4><p>The tech industry evolves rapidly. Follow blogs, join forums, and take online courses to keep up with new technologies and best practices.</p><h4>3️⃣ Master Problem-Solving &amp; Algorithms</h4><p>Technical interviews often test data structures and algorithms. Platforms like LeetCode, HackerRank, and CodeSignal help you practice coding challenges and improve problem-solving skills.</p><h4>4️⃣ Build a Strong Portfolio</h4><p>A well-structured portfolio showcasing your projects, GitHub repositories, and blog posts will make you stand out to recruiters and hiring managers.</p><h4>5️⃣ Network &amp; Contribute to the Community</h4><p>Attend tech meetups, contribute to forums, and engage with the developer community. Networking can lead to job opportunities and valuable mentorship.</p><h3>Resources to Accelerate Your Learning</h3><p>📌 <strong>Frontend Development:</strong> MDN Web Docs, freeCodeCamp<br> 📌 <strong>Backend Development:</strong> The Odin Project, Node.js Docs<br> 📌 <strong>DevOps &amp; Cloud Computing:</strong> DevOps School, AWS Training<br> 📌 <strong>Problem-Solving &amp; Algorithms:</strong> LeetCode, Cracking the Coding Interview<br> 📌 <strong>Tech Communities:</strong> Dev.to, Hashnode, Stack Overflow</p><h3>Conclusion</h3><p>Mastering full-stack development and DevOps takes dedication, but with the right mindset and resources, anyone can achieve success. Focus on building real projects, staying updated, and networking within the community to accelerate your growth.</p><p>💬 <strong>What’s your biggest challenge in full-stack development? Let’s discuss in the comments!</strong></p><p>🚀 <strong>Follow for more insights on web development, DevOps, and software engineering!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c49568b814" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>