<?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 Ashutosh Singh on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Singh on Medium]]></description>
        <link>https://medium.com/@ashutoshsingh_70348?source=rss-19f5946a32a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-8XAvIUnR8XBAnq-</url>
            <title>Stories by Ashutosh Singh on Medium</title>
            <link>https://medium.com/@ashutoshsingh_70348?source=rss-19f5946a32a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:17:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshsingh_70348/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[Deploy n8n on Linux VM with Docker in 10 Minutes]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/deploy-n8n-on-linux-vm-with-docker-in-10-minutes-32c0c264a4dd?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c0c264a4dd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[n8n-workflow]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 17:52:48 GMT</pubDate>
            <atom:updated>2026-01-16T17:52:48.851Z</atom:updated>
            <content:encoded><![CDATA[<p>n8n is a powerful workflow automation tool that lets you connect APIs, automate tasks, and build integrations — all with a visual editor. Best part? You can self-host it in minutes using Docker.</p><p>In this guide, I’ll show you how to deploy n8n on a Linux VM with Docker, set up HTTPS with Nginx, and get it production-ready.</p><p>What You’ll Need</p><p>- Linux VM (Ubuntu 20.04+ recommended)</p><p>- 2GB RAM minimum (4GB for production)</p><p>- SSH access with sudo privileges</p><p>- Domain name (optional, for SSL)</p><p>Step 1: Install Docker</p><p>SSH into your VM and run:</p><p>```bash</p><p># Update system</p><p>sudo apt update &amp;&amp; sudo apt upgrade -y</p><p># Install Docker</p><p>sudo apt install -y apt-transport-https ca-certificates curl software-properties-common</p><p>curl -fsSL <a href="https://download.docker.com/linux/ubuntu/gpg">https://download.docker.com/linux/ubuntu/gpg</a> | sudo gpg — dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg</p><p>echo “deb [arch=$(dpkg — print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> $(lsb_release -cs) stable” | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</p><p>sudo apt update</p><p>sudo apt install -y docker-ce docker-ce-cli containerd.io</p><p># Install Docker Compose</p><p>sudo curl -L “https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)” -o /usr/local/bin/docker-compose</p><p>sudo chmod +x /usr/local/bin/docker-compose</p><p># Start Docker</p><p>sudo systemctl start docker</p><p>sudo systemctl enable docker</p><p>sudo usermod -aG docker $USER</p><p>```</p><p>Step 2: Deploy n8n with Docker Compose</p><p>Create your deployment directory and configuration:</p><p>```bash</p><p>mkdir -p ~/n8n &amp;&amp; cd ~/n8n</p><p>nano docker-compose.yml</p><p>```</p><p>Paste this configuration:</p><p>```yaml</p><p>version: ‘3.8’</p><p>services:</p><p>n8n:</p><p>image: n8nio/n8n:latest</p><p>container_name: n8n</p><p>restart: unless-stopped</p><p>ports:</p><p>- “5678:5678”</p><p>environment:</p><p>- N8N_BASIC_AUTH_ACTIVE=true</p><p>- N8N_BASIC_AUTH_USER=admin</p><p>- N8N_BASIC_AUTH_PASSWORD=ChangeThisPassword123!</p><p>- GENERIC_TIMEZONE=America/New_York</p><p>- TZ=America/New_York</p><p>volumes:</p><p>- n8n_data:/home/node/.n8n</p><p>volumes:</p><p>n8n_data:</p><p>```</p><p>Start n8n:</p><p>```bash</p><p>docker-compose up -d</p><p>```</p><p>Step 3: Configure Firewall</p><p>Open port 5678:</p><p>```bash</p><p>sudo ufw allow ssh</p><p>sudo ufw allow 5678/tcp</p><p>sudo ufw enable</p><p>```</p><p><strong>**Access n8n:**</strong> Open `http://your-vm-ip:5678` in your browser and log in with your credentials.</p><p>— -</p><p>Production Setup (Optional but Recommended)</p><p>Add HTTPS with Nginx</p><p>Install Nginx and Certbot:</p><p>```bash</p><p>sudo apt install -y nginx certbot python3-certbot-nginx</p><p>```</p><p>Create Nginx config:</p><p>```bash</p><p>sudo nano /etc/nginx/sites-available/n8n</p><p>```</p><p>Add the following configuration:</p><p>```nginx</p><p>server {</p><p>listen 80;</p><p>server_name your-domain.com;</p><p>location / {</p><p>proxy_pass <a href="http://localhost:5678;">http://localhost:5678;</a></p><p>proxy_http_version 1.1;</p><p>proxy_set_header Upgrade $http_upgrade;</p><p>proxy_set_header Connection ‘upgrade’;</p><p>proxy_set_header Host $host;</p><p>proxy_set_header X-Real-IP $remote_addr;</p><p>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</p><p>proxy_set_header X-Forwarded-Proto $scheme;</p><p>}</p><p>}</p><p>```</p><p>Enable and get SSL certificate:</p><p>```bash</p><p>sudo ln -s /etc/nginx/sites-available/n8n /etc/nginx/sites-enabled/</p><p>sudo nginx -t</p><p>sudo systemctl restart nginx</p><p># Get SSL certificate</p><p>sudo ufw allow ‘Nginx Full’</p><p>sudo certbot — nginx -d your-domain.com</p><p>```</p><p>Update `docker-compose.yml` environment:</p><p>```yaml</p><p>environment:</p><p>- N8N_PROTOCOL=https</p><p>- WEBHOOK_URL=https://your-domain.com/</p><p>- N8N_HOST=your-domain.com</p><p>```</p><p>Restart n8n: `cd ~/n8n &amp;&amp; docker-compose restart`</p><p>— -</p><p>PostgreSQL for Production (Optional)</p><p>Replace your `docker-compose.yml` with this:</p><p>```yaml</p><p>version: ‘3.8’</p><p>services:</p><p>postgres:</p><p>image: postgres:15-alpine</p><p>container_name: n8n-postgres</p><p>restart: unless-stopped</p><p>environment:</p><p>- POSTGRES_USER=n8n</p><p>- POSTGRES_PASSWORD=secure_password_123</p><p>- POSTGRES_DB=n8n</p><p>volumes:</p><p>- postgres_data:/var/lib/postgresql/data</p><p>healthcheck:</p><p>test: [‘CMD-SHELL’, ‘pg_isready -U n8n’]</p><p>interval: 5s</p><p>timeout: 5s</p><p>retries: 10</p><p>n8n:</p><p>image: n8nio/n8n:latest</p><p>container_name: n8n</p><p>restart: unless-stopped</p><p>ports:</p><p>- “5678:5678”</p><p>environment:</p><p>- DB_TYPE=postgresdb</p><p>- DB_POSTGRESDB_HOST=postgres</p><p>- DB_POSTGRESDB_PORT=5432</p><p>- DB_POSTGRESDB_DATABASE=n8n</p><p>- DB_POSTGRESDB_USER=n8n</p><p>- DB_POSTGRESDB_PASSWORD=secure_password_123</p><p>- N8N_BASIC_AUTH_ACTIVE=true</p><p>- N8N_BASIC_AUTH_USER=admin</p><p>- N8N_BASIC_AUTH_PASSWORD=ChangeThisPassword123!</p><p>volumes:</p><p>- n8n_data:/home/node/.n8n</p><p>depends_on:</p><p>postgres:</p><p>condition: service_healthy</p><p>volumes:</p><p>n8n_data:</p><p>postgres_data:</p><p>```</p><p>— -</p><p>Quick Maintenance Commands</p><p><strong>**View logs:**</strong></p><p>```bash</p><p>docker-compose logs -f n8n</p><p>```</p><p><strong>**Update n8n:**</strong></p><p>```bash</p><p>cd ~/n8n</p><p>docker-compose pull</p><p>docker-compose down</p><p>docker-compose up -d</p><p>```</p><p><strong>**Backup workflows:**</strong></p><p>```bash</p><p>docker exec n8n n8n export:workflow — all — output=/home/node/.n8n/backups/workflows.json</p><p>docker cp n8n:/home/node/.n8n/backups ./backups</p><p>```</p><p><strong>**Backup database:**</strong></p><p>```bash</p><p>docker exec n8n-postgres pg_dump -U n8n n8n &gt; n8n_backup_$(date +%Y%m%d).sql</p><p>```</p><p>— -</p><p>Pro Tips</p><p>- <strong>**Always use strong passwords**</strong> for basic auth and database</p><p>- <strong>**Enable HTTPS in production**</strong> with Let’s Encrypt (free)</p><p>- <strong>**Use PostgreSQL**</strong> for production workloads</p><p>- <strong>**Set up regular backups**</strong> — automate with cron jobs</p><p>- <strong>**Monitor resources**</strong> with `docker stats`</p><p>- <strong>**Keep updated**</strong> — run `docker-compose pull` monthly</p><p>---</p><p>Troubleshooting</p><p><strong>**Can&#39;t access n8n?**</strong></p><p>- Check if running: `docker ps`</p><p>- View logs: `docker-compose logs -f n8n`</p><p>- Verify firewall: `sudo ufw status`</p><p><strong>**Container won&#39;t start?**</strong></p><p>- Check logs: `docker-compose logs n8n`</p><p>- Inspect container: `docker inspect n8n`</p><p><strong>**SSL issues?**</strong></p><p>- Ensure DNS points to your VM</p><p>- Test Nginx: `sudo nginx -t`</p><p>---</p><p>Wrap Up</p><p>That&#39;s it! You now have n8n running on your Linux VM with Docker. You can:</p><p>- Access the visual workflow editor</p><p>- Connect to hundreds of services</p><p>- Build powerful automations</p><p>- Keep your data under your control</p><p>Want to learn more? Check out:</p><p>- [n8n Documentation](https://docs.n8n.io/)</p><p>- [n8n Community](https://community.n8n.io/)</p><p>- [n8n GitHub](https://github.com/n8n-io/n8n)</p><p>Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c0c264a4dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP): Bridging AI Agents and Real-World Action with Simple, Standardized…]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/model-context-protocol-mcp-bridging-ai-agents-and-real-world-action-with-simple-standardized-8e53d2d083a1?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e53d2d083a1</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 17:46:40 GMT</pubDate>
            <atom:updated>2025-07-14T17:46:40.227Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Context Protocol (MCP): Bridging AI Agents and Real-World Action with Simple, Standardized Servers</h3><p>Artificial intelligence is incredibly smart — but often, when AI agents need to <em>act</em> rather than just <em>talk</em>, they struggle. That’s because connecting AI to tools, data, and services usually means building complex, one-off integrations for every single app.</p><p><strong>Model Context Protocol (MCP)</strong> is changing that by providing a standardized way for AI agents to plug into almost any tool or service — no complex coding required.</p><p>In this post, I’ll introduce MCP and then dive into a practical example: building your own MCP server that fetches live weather data, which an AI agent like Claude can use to answer questions about forecasts and alerts.</p><h3>What Is Model Context Protocol (MCP)?</h3><p>MCP is an open protocol developed by Anthropic to help AI agents communicate with external tools seamlessly. Think of it as a universal translator between AI and real-world applications.</p><p>Instead of AI developers creating custom APIs or special logic for each new tool, MCP standardizes how requests and responses are structured, making it easy to build “smart adapters” — called MCP servers — that expose tools and data to AI hosts.</p><p>This means:</p><ul><li>AI agents can call functions or fetch data from any MCP-compatible server.</li><li>Servers tell AI agents what capabilities (tools) they support.</li><li>Communication happens in a clear, structured format (typically JSON).</li><li>You can chain multiple tools together in complex workflows without manual coding.</li></ul><h3>Building Your Own MCP Server: A Weather Example</h3><p>To show how MCP works in practice, let’s walk through building a simple <strong>weather server</strong> using Python. This server will expose two tools:</p><ul><li>get-alerts: Fetch active weather alerts for a U.S. state.</li><li>get-forecast: Get a weather forecast for a given latitude and longitude.</li></ul><p>AI agents like Claude can connect to this server and call these tools on demand, answering your weather questions with up-to-date info.</p><h3>Setting Up Your Environment</h3><p>Make sure you have:</p><ul><li>Python 3.10+</li><li>The Python MCP SDK (version 1.2.0 or higher)</li><li>The uv command-line tool installed (used for running MCP servers)</li></ul><p>To install uv, run:</p><pre>curl -LsSf https://astral.sh/uv/install.sh | sh</pre><p>Restart your terminal afterward to make sure uv is recognized.</p><p>Next, create your project folder and set up a Python virtual environment:</p><pre>uv init weather<br>cd weather<br>uv venv<br>source .venv/bin/activate<br>uv add &quot;mcp[cli]&quot; httpx<br>touch weather.py</pre><h3>Writing the Weather Server</h3><p>Open weather.py and start by importing packages and initializing the MCP server:</p><pre>from typing import Any<br>import httpx<br>from mcp.server.fastmcp import FastMCP<br><br>mcp = FastMCP(&quot;weather&quot;)<br><br>NWS_API_BASE = &quot;https://api.weather.gov&quot;<br>USER_AGENT = &quot;weather-app/1.0&quot;</pre><h3>Helper Functions</h3><p>These will fetch and format data from the U.S. National Weather Service API:</p><pre>async def make_nws_request(url: str) -&gt; dict[str, Any] | None:<br>    headers = {<br>        &quot;User-Agent&quot;: USER_AGENT,<br>        &quot;Accept&quot;: &quot;application/geo+json&quot;<br>    }<br>    async with httpx.AsyncClient() as client:<br>        try:<br>            response = await client.get(url, headers=headers, timeout=30.0)<br>            response.raise_for_status()<br>            return response.json()<br>        except Exception:<br>            return None<br><br>def format_alert(feature: dict) -&gt; str:<br>    props = feature[&quot;properties&quot;]<br>    return f&quot;&quot;&quot;<br>Event: {props.get(&#39;event&#39;, &#39;Unknown&#39;)}<br>Area: {props.get(&#39;areaDesc&#39;, &#39;Unknown&#39;)}<br>Severity: {props.get(&#39;severity&#39;, &#39;Unknown&#39;)}<br>Description: {props.get(&#39;description&#39;, &#39;No description available&#39;)}<br>Instructions: {props.get(&#39;instruction&#39;, &#39;No specific instructions provided&#39;)}<br>&quot;&quot;&quot;</pre><h3>Implementing the MCP Tools</h3><p>Define the two tools the server will expose:</p><pre>@mcp.tool()<br>async def get_alerts(state: str) -&gt; str:<br>    url = f&quot;{NWS_API_BASE}/alerts/active/area/{state}&quot;<br>    data = await make_nws_request(url)<br><br>    if not data or &quot;features&quot; not in data:<br>        return &quot;Unable to fetch alerts or no alerts found.&quot;<br><br>    if not data[&quot;features&quot;]:<br>        return &quot;No active alerts for this state.&quot;<br><br>    alerts = [format_alert(feature) for feature in data[&quot;features&quot;]]<br>    return &quot;\n---\n&quot;.join(alerts)<br><br>@mcp.tool()<br>async def get_forecast(latitude: float, longitude: float) -&gt; str:<br>    points_url = f&quot;{NWS_API_BASE}/points/{latitude},{longitude}&quot;<br>    points_data = await make_nws_request(points_url)<br><br>    if not points_data:<br>        return &quot;Unable to fetch forecast data for this location.&quot;<br><br>    forecast_url = points_data[&quot;properties&quot;][&quot;forecast&quot;]<br>    forecast_data = await make_nws_request(forecast_url)<br><br>    if not forecast_data:<br>        return &quot;Unable to fetch detailed forecast.&quot;<br><br>    periods = forecast_data[&quot;properties&quot;][&quot;periods&quot;]<br>    forecasts = []<br>    for period in periods[:5]:<br>        forecast = f&quot;&quot;&quot;<br>{period[&#39;name&#39;]}:<br>Temperature: {period[&#39;temperature&#39;]}°{period[&#39;temperatureUnit&#39;]}<br>Wind: {period[&#39;windSpeed&#39;]} {period[&#39;windDirection&#39;]}<br>Forecast: {period[&#39;detailedForecast&#39;]}<br>&quot;&quot;&quot;<br>        forecasts.append(forecast)<br><br>    return &quot;\n---\n&quot;.join(forecasts)</pre><h3>Running the Server</h3><p>Add the following at the bottom to run your MCP server:</p><pre>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&#39;stdio&#39;)</pre><p>Run your server with:</p><pre>uv run weather.py</pre><h3>Connecting Your Server to an MCP Host (Claude for Desktop)</h3><p>To use your server with an AI agent like Claude for Desktop:</p><ol><li>Open Claude’s config file at:<br> ~/Library/Application Support/Claude/claude_desktop_config.json (create it if it doesn’t exist).</li><li>Add your server config:</li></ol><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;weather&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [<br>        &quot;--directory&quot;,<br>        &quot;/ABSOLUTE/PATH/TO/weather&quot;,<br>        &quot;run&quot;,<br>        &quot;weather.py&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Make sure you replace /ABSOLUTE/PATH/TO/weather with your actual project directory and the full path to uv if needed.</p><p>3. Restart Claude for Desktop.</p><h3>Testing Your MCP Weather Server</h3><p>In Claude for Desktop, open the tools panel and look for get-alerts and get-forecast.</p><p>Try queries like:</p><ul><li><em>“What’s the weather forecast in New York?”</em></li><li><em>“Are there any weather alerts in California?”</em></li></ul><p>Claude will call your MCP server tools behind the scenes, fetch live data, and give you natural language answers — all powered by your custom MCP server.</p><h3>Why MCP Is a Game-Changer for AI Development</h3><ul><li><strong>No more brittle, manual integrations:</strong> Build once, connect anywhere.</li><li><strong>Plug-and-play AI tools:</strong> Easily add new capabilities to AI agents.</li><li><strong>Multi-tool workflows:</strong> Chain together actions for complex tasks.</li><li><strong>Open ecosystem:</strong> Developers can share MCP servers and clients across apps.</li></ul><h3>Ready to Build Your Own MCP Server?</h3><p>Whether it’s weather, project management, finance, or any other domain, MCP lets you expose your data and services to AI agents in minutes.</p><p>Explore the MCP ecosystem, try building your own servers, and join the revolution that’s making AI agents <em>do</em> — not just think.</p><p>Learn more and get started here: <a href="https://modelcontextprotocol.io/introduction">modelcontextprotocol.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e53d2d083a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Agentic AI with LangGraph: A Deep Dive into Tools, Agents, and Code]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/building-agentic-ai-with-langgraph-a-deep-dive-into-tools-agents-and-code-34031a4c5662?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/34031a4c5662</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:10:29 GMT</pubDate>
            <atom:updated>2025-04-21T17:10:29.238Z</atom:updated>
            <content:encoded><![CDATA[<p>As the world shifts toward more <strong>autonomous AI systems</strong>, frameworks like LangGraph are emerging as powerful solutions for orchestrating complex, <strong>agent-based workflows</strong>.</p><p>In this post, we’ll explore how to:</p><ul><li>Design <strong>agentic systems</strong> using LangGraph</li><li>Equip them with <strong>tools</strong></li><li>Use <strong>LangChain agents</strong> inside LangGraph</li><li>And, of course, walk through working <strong>code</strong> 🎯</li></ul><p><strong>💡 Why Agentic AI?</strong></p><p>Traditional AI models follow a linear prompt-response paradigm. But sometimes, we need them to <strong>reason, reflect, and interact with tools</strong> — or even other agents — to complete complex tasks. That’s where agentic AI comes in.</p><p>LangGraph provides a graph-based programming model built on top of <strong>LangChain</strong>, enabling:</p><ul><li><strong>Stateful execution</strong></li><li><strong>Multi-agent collaboration</strong></li><li>Built-in support for <strong>tools</strong>, memory, retries, and more</li></ul><p><strong>🧱 Architecture Overview</strong></p><p>Let’s say we want to build a simple <strong>research assistant</strong> with:</p><ul><li>A <strong>Planner Agent</strong> to decide what to do</li><li>A <strong>Research Agent</strong> to search the web</li><li>A <strong>Summarizer Agent</strong> to condense findings</li><li>Access to tools like <strong>BingSearchAPI</strong> or <strong>Wikipedia</strong></li></ul><p>This would look like a <strong>graph</strong> where nodes are agents and tools, and edges define how outputs move across the system.</p><p><strong>🧰 Step 1: Setup</strong></p><p>Install dependencies</p><pre>pip install langgraph langchain openai</pre><p>Optional: Search tool support</p><pre>pip install langchainhub langchain-community</pre><p><strong>🤖 Step 2: Define Tools</strong></p><pre>from langchain.tools import Tool<br>from langchain_community.tools import DuckDuckGoSearchRun<br><br>search_tool = Tool(<br>    name=&quot;search_web&quot;,<br>    func=DuckDuckGoSearchRun().run,<br>    description=&quot;Use this to search the web for current information&quot;<br>)</pre><p><strong>🧠 Step 3: Define Agents</strong></p><pre>from langchain.agents import initialize_agent, AgentType<br>from langchain.chat_models import ChatOpenAI<br><br>llm = ChatOpenAI(temperature=0)<br><br># Research agent<br>research_agent = initialize_agent(<br>    tools=[search_tool],<br>    llm=llm,<br>    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,<br>    verbose=True<br>)<br><br># Summarizer<br>def summarize_text(text):<br>    return llm.predict(f&quot;Summarize the following:\n\n{text}&quot;)</pre><p><strong>🔁 Step 4: Build the LangGraph</strong></p><pre>from langgraph.graph import StateGraph, END<br><br># Shared state format<br>class AgentState(dict):<br>    pass<br><br># Define node functions<br>def planner_node(state):<br>    query = state[&quot;input&quot;]<br>    return {&quot;task&quot;: f&quot;Find recent news about: {query}&quot;}<br><br>def research_node(state):<br>    result = research_agent.run(state[&quot;task&quot;])<br>    return {&quot;research_result&quot;: result}<br><br>def summarizer_node(state):<br>    summary = summarize_text(state[&quot;research_result&quot;])<br>    return {&quot;summary&quot;: summary}<br><br># Construct the graph<br>graph = StateGraph(AgentState)<br><br>graph.add_node(&quot;planner&quot;, planner_node)<br>graph.add_node(&quot;researcher&quot;, research_node)<br>graph.add_node(&quot;summarizer&quot;, summarizer_node)<br><br># Add edges<br>graph.set_entry_point(&quot;planner&quot;)<br>graph.add_edge(&quot;planner&quot;, &quot;researcher&quot;)<br>graph.add_edge(&quot;researcher&quot;, &quot;summarizer&quot;)<br>graph.add_edge(&quot;summarizer&quot;, END)<br><br># Compile<br>app = graph.compile()</pre><p><strong>🧪 Step 5: Run the Graph</strong></p><pre>response = app.invoke({&quot;input&quot;: &quot;AI breakthroughs in 2025&quot;})<br>print(response[&quot;summary&quot;])</pre><p><strong>🔍 Output Example</strong></p><pre>AI breakthroughs in 2025 include advancements in multimodal models, more robust AI safety techniques, and increasing regulatory oversight. Notably, OpenAI and other leaders are collaborating on governance frameworks to ensure responsible AI deployment.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34031a4c5662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cold Email Generator with Streamlit and LangChain]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/building-a-cold-email-generator-with-streamlit-and-langchain-65bef36e2eb6?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bef36e2eb6</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 00:58:05 GMT</pubDate>
            <atom:updated>2024-09-22T00:58:05.785Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s competitive job market, companies are constantly seeking new ways to stand out from the crowd. One powerful approach is to leverage AI to create cold emails tailored to job postings on company websites. This blog will walk you through how I built a Cold Email Generator using <strong>Streamlit</strong>, <strong>LangChain</strong>, <strong>ChromaDB</strong>, and <strong>ChatGroq</strong>. It’s designed to scrape job descriptions from a URL, identify the required skills, and generate personalized cold emails.</p><h3>Tech Stack:</h3><ul><li><strong>Streamlit</strong>: For the frontend and interface.</li><li><strong>LangChain</strong>: For managing the flow of operations.</li><li><strong>ChromaDB</strong>: To store and retrieve portfolio-related data.</li><li><strong>ChatGroq</strong>: For AI-based job extraction and email generation.</li></ul><p>Let’s break down the code and functionality step by step.</p><h3>Streamlit App: User Interface</h3><p>The first part of the app is built with <strong>Streamlit</strong>, which provides an intuitive interface for the user to input the URL of a job posting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cO_Qf0Yhtd4vWBf8ZzltQ.png" /></figure><ul><li><strong>URL Input</strong>: Users can input the job posting URL.</li><li><strong>Submit Button</strong>: When clicked, the app processes the input URL and generates a cold email.</li></ul><p>Loading and Cleaning the Web Data</p><p>Once the URL is submitted, the web data is loaded and cleaned using a custom utility. I used <strong>WebBaseLoader</strong> from the langchain_community package to scrape the content and passed it to a cleaning function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*q48BCnOiU-pDll4m35j4kg.png" /></figure><p>Here, clean_text is a function responsible for preparing the raw HTML data for processing.</p><p><strong>Extracting Job Details</strong></p><p>The core of the application lies in its ability to extract job information (like skills, experience, and description) from the scraped text. For this, I used <strong>ChatGroq</strong>, a powerful large language model (LLM) through LangChain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBt4Ds3zEr77HEbGvgMnqw.png" /></figure><p>The prompt here asks the model to extract relevant job details. <strong>Prompt engineering</strong> is crucial to ensure the LLM generates output in the required format.</p><p><strong>Querying Portfolio for Relevant Links</strong></p><p>The next step involves querying a stored portfolio using <strong>ChromaDB</strong>. The portfolio contains relevant projects and skills stored as vector embeddings. These embeddings help find the most relevant links based on the job description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*RjOsXajNzJvaWABpeG2Nbw.png" /></figure><p>By using the skills extracted from the job description, the app queries the database to retrieve links to relevant projects, which can be used to tailor the cold email.</p><p><strong>Crafting the Cold Email</strong></p><p>With the job details and relevant links ready, it’s time to craft the cold email. For this, I used another <strong>ChatGroq</strong> prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-7U0FJ-47k6yKhCCMEuNA.png" /></figure><p>This prompt generates a cold email that references specific portfolio projects, making it personalized and relevant to the target company.</p><p><strong>Bringing it All Together</strong></p><p>When the user clicks the “Submit” button, the app follows these steps:</p><ol><li>Scrapes the job data from the input URL.</li><li>Cleans and extracts job details like role, experience, and skills.</li><li>Queries the portfolio database for relevant project links.</li><li>Generates a cold email tailored to the job posting.</li></ol><p>The generated email is then displayed on the app using st.code().</p><h3><strong>Conclusion</strong></h3><p>By combining the strengths of <strong>Streamlit</strong>, <strong>LangChain</strong>, <strong>ChromaDB</strong>, and <strong>ChatGroq</strong>, this Cold Email Generator serves as a powerful tool to automate and personalize outreach efforts. Whether you’re a recruiter or a job seeker, automating email generation based on job postings can save time and improve the relevance of your outreach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bef36e2eb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing State in Asynchronous Functions in React]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/managing-state-in-asynchronous-functions-in-react-f27b0f7b9870?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f27b0f7b9870</guid>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 19:35:52 GMT</pubDate>
            <atom:updated>2024-04-16T19:35:52.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When working with asynchronous functions in React, developers may encounter a common issue: state updates using the useState hook do not immediately reflect the expected value. This can lead to unexpected behavior in your application, particularly when attempting to access the state within the scope of an asynchronous function. In this blog post, we&#39;ll explore the cause of this problem and provide a solution using the useRef hook.</p><h3>Problem Statement</h3><p>When you update state using the useState hook within an asynchronous function in a React component, the state changes may not be reflected immediately. This can be problematic when you need to rely on the latest state value in the asynchronous function, as it may not be updated in time.</p><p>Here’s an example:</p><pre>import React, { useState, useRef, useEffect } from &quot;react&quot;;<br><br>const ExampleComponent = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const countRef = useRef(count);<br><br>  useEffect(() =&gt; {<br>    countRef.current = count;<br>  }, [count]);<br><br>  const handleButtonClick = async () =&gt; {<br>    setCount(count + 1);<br>    setTimeout(() =&gt; {<br>      console.log(count); //Logs 0<br>      console.log(countRef.current); //Logs 1<br>    }, 1000);<br>  };<br>  return &lt;button onClick={handleButtonClick}&gt;Click me&lt;/button&gt;;<br>};<br><br>export default ExampleComponent;</pre><p>In this example, when you click the button, count logs as 0 and countRef.current logs as 1. Let&#39;s explore why this happens.</p><h3>Cause of the Issue</h3><p>To understand the issue, we need to look at how React handles state updates and how the call stack and event loop play a role in this process.</p><ol><li>Calling setCount: When you call setCount(count + 1), it schedules an update to the count state. This update is asynchronous, so the function continues executing without immediately applying the state change.</li><li>Setting up the timeout: After scheduling the state update, the function sets up a timeout using setTimeout. The timeout function is added to the event queue with a delay of 1 second.</li><li>Function completion: Once the timeout is set up, the handleButtonClick function completes its execution and exits the call stack.</li><li>State update: React batches state updates and applies them asynchronously. Since the function has completed execution and exited the call stack, React’s state update mechanism applies the state change, updating count to 1.</li><li>useEffect updates countRef.current: After the state update, the useEffect hook runs because count changed. This updates countRef.current to reflect the new value of count (which is now 1).</li><li>Timeout function execution: After the 1-second delay, the timeout function is taken from the event queue and pushed onto the call stack for execution. The function logs the values of count and countRef.current.</li><li>Logging values: Since the timeout function was scheduled before the state update occurred, it initially captures the original value of count (0). However, countRef.current was updated in real time by the useEffect hook and correctly reflects the new value of count (1).</li></ol><p>This sequence of events explains the discrepancy in values logged by the timeout function.</p><h3>Solution: Using useRef</h3><p>The use of useRef helps you access the most current state value within an asynchronous function. Unlike useState, updating a useRef value does not trigger a re-render. By updating countRef.current whenever count changes using useEffect, you can ensure that countRef.current always has the latest state value.</p><p>In the example code above, countRef.current correctly logs the updated state value (1) because it is synchronized with the latest state by the useEffect hook. Meanwhile, the count variable logs the older value (0) because it was captured at the time the timeout function was set up.</p><h3>Conclusion</h3><p>Understanding how React handles state updates in asynchronous functions can be crucial for managing state effectively in your application. By using useRef in conjunction with useState, you can accurately track the current state value and avoid discrepancies in asynchronous functions.</p><p>We hope this detailed explanation has clarified the cause of state value discrepancies in asynchronous functions and how to resolve them using useRef. Let us know your thoughts and experiences with this approach in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f27b0f7b9870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate GooglePay in React]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/integrate-googlepay-in-react-deb89551bbd4?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb89551bbd4</guid>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[cybersource]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[google-pay]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 17:08:55 GMT</pubDate>
            <atom:updated>2024-04-16T17:08:55.985Z</atom:updated>
            <content:encoded><![CDATA[<p>When processing payments, you often use a checkout form where customers input their shipping and payment information. However, this process can be a hassle for your customers. They may not remember the 16-digit card number, the security code, or the card’s expiration date. They might also be skeptical about the security of the website, even if it has an SSL certificate and a secure lock icon in the address bar. Additionally, customers must repeatedly enter the same information across various online shopping platforms.</p><p>These obstacles can create friction in the checkout process and potentially reduce sales. To provide a smoother and simpler checkout experience, the Google Pay API can give you easy access to your customers’ stored payment details saved in their Google accounts. By using the Google Pay API, your customers won’t have to manually enter their card information at checkout, streamlining the purchasing process.</p><h3>Load the Google Pay API JavaScript Library</h3><p>First, add the script tag to your application’s index.html file to load the Google Pay JavaScript library.</p><pre>&lt;script<br>  async<br>  src=&quot;https://pay.google.com/gp/p/js/pay.js&quot;<br>  onload​=&quot;onGooglePayLoaded()&quot;&gt;<br>&lt;/script&gt;</pre><h3>Initialize Google Pay API</h3><p>As soon as the script is loaded, construct the PaymentsClient object. Begin by instantiating the client object globally in the window object, which you will use to make calls to the Google Pay API from your component later on.</p><pre>function onGooglePayLoaded() {<br>  window.googlePayClient = new google.payments.api.PaymentsClient({<br>    environment: &quot;TEST&quot;<br>  });<br>}</pre><p>The payment client is initialized with a PaymentOptions object. For the TEST environment, you don’t need to register with Google. In the TEST environment, Google will give access to real card details, but you won’t be able to charge them. To enable actual payments, you need to register with Google for PRODUCTION access.</p><h3>Configure the Payment Methods</h3><p>In the App.js file, define the card networks and the authentication methods that will be allowed by your application</p><pre>const { googlePayClient } = window;<br><br>const baseCardPaymentMethod = {<br>  type: &quot;CARD&quot;,<br>  parameters: {<br>    allowedCardNetworks: [&quot;VISA&quot;, &quot;MASTERCARD&quot;],<br>    allowedAuthMethods: [&quot;PAN_ONLY&quot;, &quot;CRYPTOGRAM_3DS&quot;]<br>  }<br>};</pre><h3>Define the API Version</h3><p>After you have configured the payment methods, define the Google Pay API version that will be used to process the payment, along with the allowedPaymentMethods property to which you need to pass the baseCardPaymentMethod object.</p><pre>const googlePayBaseConfiguration = {<br>  apiVersion: 2,<br>  apiVersionMinor: 0,<br>  allowedPaymentMethods: [baseCardPaymentMethod]<br>};</pre><h3>Determine Readiness to Pay With Google Pay</h3><p>Now that the payment client is configured and defined, check whether Google Pay API is ready to make payments. This also includes checking whether the API is supported for the current device and browser.</p><p>Check the readiness as soon as the component is mounted. If it is a class component, use the componentDidMount() lifecycle method, and if it is a functional component, use the useEffect hook.</p><pre>function App() {<br>  // ...<br>  useEffect(() =&gt; {<br>    googlePayClient<br>      .isReadyToPay(googlePayBaseConfiguration)<br>      .then(res =&gt; {<br>        if (res.result) {<br>          createAndRenderPayButton();<br>        } else {<br>          alert(&quot;Unable to pay using Google Pay&quot;);<br>        }<br>      })<br>      .catch(function (err) {<br>        console.error(&quot;Error determining readiness to use Google Pay: &quot;, err);<br>      });<br>  }, []);<br>}</pre><p>The isReadyToPay() method takes in the base configuration as its argument and determine readiness to pay. As it is asynchronous in nature, you need to attach the .then() and .catch() calls to it. If there’s a successful response, render the Google Pay Button to the user. Otherwise, show alternative payment methods as a fallback.</p><h3>Add the Pay With GPay Button</h3><p>Now, when you know that the user is ready to make a payment, call the second API, <strong>createButton</strong>(). The <strong>createButton</strong>() method will return the Pay with GPay button HTML element. You can pass options like buttonColor and <strong>buttonType</strong> to style the button so that it blends in well with your overall site colors.</p><p>Set the button HTML in your component’s state so that it can be rendered by JSX using the <em>dangerouslySetInnerHTML</em> prop.</p><pre>const [gPayBtn, setGPayBtn] = useState(null);<br><br>function createAndAddButton() {<br>  if (googlePayClient) {<br>    const googlePayButton = googlePayClient.createButton({<br>      buttonColor: &quot;default&quot;,<br><br>      buttonType: &quot;long&quot;,<br><br>      onClick: processPayment<br>    });<br><br>    setGPayBtn(googlePayButton);<br>  }<br>}<br><br>return (<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;h1&gt;Click the Pay button&lt;/h1&gt;<br>    &lt;div<br>      onClick​={processPayment}<br>      dangerouslySetInnerHTML={{ __html: gPayBtn &amp;&amp; gPayBtn.innerHTML }}<br>    /&gt;<br>  &lt;/div&gt;<br>);</pre><p>When the button is clicked, call processPayment(), which will start the payment process.</p><h3>Payment</h3><p>Once you add the button to your page and the user clicks on the Google Pay Button, call the loadPaymentData() method to open up the Google Pay payment window. Construct the paymentDataRequest object, which includes a set of payment configurations which will be used for this particular transaction.</p><pre>function processPayment() {<br>  // ...<br>  googlePayClient<br>    .loadPaymentData(paymentDataRequest)<br>    .then(function (paymentData) {<br>      console.log(paymentData);<br>    })<br>    .catch(function (err) {<br>      console.log(err);<br>    });<br>}</pre><p>In addition to the payment credentials, you can also request additional information such as email, phone number, shipping address, billing address, etc.</p><pre>const cardPaymentMethod = {<br>  type: &quot;CARD&quot;,<br>  tokenizationSpecification: tokenizationSpecification,<br>  parameters: {<br>    allowedCardNetworks: [&quot;VISA&quot;, &quot;MASTERCARD&quot;],<br>    allowedAuthMethods: [&quot;PAN_ONLY&quot;, &quot;CRYPTOGRAM_3DS&quot;],<br>    billingAddressRequired: true,<br>    billingAddressParameters: {<br>      format: &quot;FULL&quot;,<br>      phoneNumberRequired: true<br>    }<br>  }<br>}</pre><p>The transaction and merchant information, along with the base configuration object, should be included in the paymentDataRequest object.</p><pre>const transactionInfo = {<br>  totalPriceStatus: &quot;FINAL&quot;,<br>  totalPrice: &quot;123.45&quot;,<br>  currencyCode: &quot;USD&quot;<br>};<br><br>const merchantInfo = {<br>  // merchantId: &#39;01234567890123456789&#39;, Only in PRODUCTION<br>  merchantName: &quot;Your Merchant Name&quot;<br>};<br><br>const paymentDataRequest = {<br>  ...googlePayBaseConfiguration,<br>  ...{<br>    allowedPaymentMethods: [cardPaymentMethod],<br>    transactionInfo,<br>    merchantInfo<br>   }<br>}</pre><p>tokenizationSpecification is an object which contains the payment request tokenization parameters. Here, you define which payment gateway you’ll be using in your application.</p><pre>const tokenizationSpecification = {<br>  type: &quot;PAYMENT_GATEWAY&quot;,<br>  parameters: {<br>    gateway: &quot;example&quot;,<br>    gatewayMerchantId: &quot;gatewayMerchantId&quot;<br>  }<br>}; </pre><p>The tokenization specification defines how the payment method chosen by your customers is managed and used to complete a transaction. When you’ve constructed the request object, pass it to loadPaymentData, an async call which will open a Google payment sheet. After the user makes a selection, Google will return you a paymentData object, which consists of metadata about the user’s selection. It includes the payment token, which you can use to complete the transaction. At this point, you have carried out all of the required steps, and your transaction is ready to be completed.</p><h3>Complete Source Code</h3><pre>import React, { useState, useEffect } from &quot;react&quot;;<br>import &quot;./styles.css&quot;;<br><br>const { googlePayClient } = window;<br><br>const baseCardPaymentMethod = {<br>  type: &quot;CARD&quot;,<br>  parameters: {<br>    allowedCardNetworks: [&quot;VISA&quot;, &quot;MASTERCARD&quot;],<br>    allowedAuthMethods: [&quot;PAN_ONLY&quot;, &quot;CRYPTOGRAM_3DS&quot;]<br>  }<br>};<br><br>const googlePayBaseConfiguration = {<br>  apiVersion: 2,<br>  apiVersionMinor: 0,<br>  allowedPaymentMethods: [baseCardPaymentMethod]<br>};<br><br>export default function App() {<br>  const [gPayBtn, setGPayBtn] = useState(null);<br><br>  function createAndAddButton() {<br>    if (googlePayClient) {<br>      const googlePayButton = googlePayClient.createButton({<br>        buttonColor: &quot;default&quot;,<br><br>        buttonType: &quot;long&quot;,<br><br>        onClick: processPayment<br>      });<br><br>      setGPayBtn(googlePayButton);<br>    }<br>  }<br><br>  function processPayment() {<br>    console.log(&quot;test&quot;);<br>    const tokenizationSpecification = {<br>      type: &quot;PAYMENT_GATEWAY&quot;,<br>      parameters: {<br>        gateway: &quot;Cybersource&quot;,<br>        &quot;stripe:version&quot;: &quot;stub_data&quot;,<br>        &quot;stripe:publishableKey&quot;: &quot;stub_data&quot;<br>      }<br>    };<br><br>    const cardPaymentMethod = {<br>      type: &quot;CARD&quot;,<br>      tokenizationSpecification: tokenizationSpecification,<br>      parameters: {<br>        allowedCardNetworks: [&quot;VISA&quot;, &quot;MASTERCARD&quot;],<br>        allowedAuthMethods: [&quot;PAN_ONLY&quot;, &quot;CRYPTOGRAM_3DS&quot;],<br>        billingAddressRequired: true,<br>        billingAddressParameters: {<br>          format: &quot;FULL&quot;,<br>          phoneNumberRequired: true<br>        }<br>      }<br>    };<br><br>    const transactionInfo = {<br>      totalPriceStatus: &quot;FINAL&quot;,<br>      totalPrice: &quot;123.45&quot;,<br>      currencyCode: &quot;USD&quot;<br>    };<br><br>    const merchantInfo = {<br>      // merchantId: &#39;01234567890123456789&#39;, Only in PRODUCTION<br>      merchantName: &quot;Example Merchant Name&quot;<br>    };<br><br>    const paymentDataRequest = {<br>      ...googlePayBaseConfiguration,<br>      ...{<br>        allowedPaymentMethods: [cardPaymentMethod],<br>        transactionInfo,<br>        merchantInfo<br>      }<br>    };<br><br>    googlePayClient<br>      .loadPaymentData(paymentDataRequest)<br>      .then(function (paymentData) {<br>        console.log(paymentData);<br>      })<br>      .catch(function (err) {<br>        console.log(err);<br>      });<br>  }<br><br>  useEffect(() =&gt; {<br>    googlePayClient<br>      .isReadyToPay(googlePayBaseConfiguration)<br>      .then(function (response) {<br>        if (response.result) {<br>          createAndAddButton();<br>        } else {<br>          alert(&quot;Unable to pay using Google Pay&quot;);<br>        }<br>      })<br>      .catch(function (err) {<br>        console.error(&quot;Error determining readiness to use Google Pay: &quot;, err);<br>      });<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;Click the Pay button&lt;/h1&gt;<br>      &lt;div<br>        onClick​={processPayment}<br>        dangerouslySetInnerHTML={{ __html: gPayBtn &amp;&amp; gPayBtn.innerHTML }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Conclusion</h3><p>Given the fact that the checkout process can be one of the worst experiences a user faces, you should consider integrating Google Pay with all your e-commerce applications.</p><p>Remember, Google Pay API won’t process the payment; it will be done by a payment processor like Cybersource, Stripe or Paypal.</p><p>Google Pay plays a vital role in facilitating the exchange of sensitive information between the user and the payment processor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb89551bbd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering Roulette: Choosing the Right Approach for Your Web Project]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/rendering-roulette-choosing-the-right-approach-for-your-web-project-fb7a8422a56a?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7a8422a56a</guid>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[static-site-generation]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:11:05 GMT</pubDate>
            <atom:updated>2024-03-26T13:11:05.937Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of web development is brimming with choices, and selecting the optimal rendering strategy is crucial for crafting exceptional user experiences. This blog will unveil the four main contenders in the rendering ring: Client-side Rendering (CSR), Server-side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR).</p><p><strong>Client-Side Rendering (CSR): The King of Interaction<br></strong>Imagine a website that feels like a living organism, constantly adapting to your clicks and scrolls. That’s the magic of CSR. Here, the browser takes center stage, rendering the content using JavaScript. This approach boasts:</p><ul><li><strong>Enhanced Interactivity:</strong> CSR excels in creating dynamic and responsive web applications, ideal for single-page applications (SPAs).</li><li><strong>Reduced Server Load:</strong> The server’s responsibility is minimized, as it primarily serves raw data, leading to potentially lower server costs.</li></ul><p><strong>How does CSR work?</strong></p><p>Upon loading a page, the client’s browser retrieves minimal HTML and JavaScript. The JavaScript fetches data and renders components dynamically. However, SEO can be compromised due to search engines struggling to index content rendered via JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSvArBp-y3ZPCfTgwuAIGQ.png" /></figure><p>However, CSR isn’t without its challenges:</p><ul><li><strong>SEO Hiccups:</strong> Search engines can struggle to index content heavily reliant on JavaScript, potentially hindering your website’s discoverability.</li><li><strong>Initial Load Wait:</strong> Browsers need time to download and execute JavaScript, which can lead to a slight delay in displaying the initial content.</li></ul><p><strong>Server-side Rendering (SSR): SEO Superstar</strong></p><p>For websites that crave top billing on search engine results pages (SERPs), SSR is your champion. With SSR, the server does the heavy lifting, generating the full HTML content before sending it to the browser. This translates to:</p><ul><li><strong>SEO Prowess:</strong> Search engines can easily crawl and index your content, boosting your website’s ranking potential.</li><li><strong>Faster Initial Load Times:</strong> Pre-rendered HTML ensures content appear on the screen swiftly, keeping users engaged.</li></ul><p><strong>How does SSR work?</strong></p><p>When a user requests a page, the server fetches the necessary data and generates the HTML content. The fully rendered page is then sent to the client. Despite the benefits, SSR can introduce challenges related to server load and complex data fetching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-geOnaoKe6b3ka1I6WVkYA.png" /></figure><p>But even SSR has its Achilles’ heel:</p><ul><li><strong>Server Load Concerns:</strong> Rendering on the server can be resource-intensive, especially for highly dynamic applications.</li><li><strong>Complexity Considerations:</strong> Implementing SSR can add complexity to your development process, requiring additional considerations for data fetching.</li></ul><p><strong>Static Site Generation (SSG): The Speed Demon</strong></p><p>For websites that prioritize lightning-fast loading times and rock-solid security, SSG is the clear favorite. Here’s the gist:</p><ul><li><strong>Blazing Performance:</strong> Pages are pre-rendered as static HTML files during the build time, eliminating the need for on-the-fly rendering, resulting in exceptional performance.</li><li><strong>Enhanced Security:</strong> Static HTML files are less vulnerable to security breaches compared to dynamic content.</li></ul><p><strong>How does SSG work?</strong></p><p>During the build phase, the application generates HTML files for each page. These static files are then served to users, minimizing the need for server-side rendering and database queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Di1j5U5BRODqH00ru5PZAg.png" /></figure><p>However, SSG comes with limitations:</p><ul><li><strong>Limited Interactivity:</strong> Real-time updates can be tricky with SSG, as content changes require rebuilding the entire website.</li><li><strong>Less Dynamic Content:</strong> If your website demands highly dynamic content updates, SSG might not be the most suitable choice.</li></ul><p><strong>Incremental Static Regeneration (ISR): The Refreshing Compromise</strong></p><p>ISR offers a compelling blend of SSG and SSR. Similar to SSG, pages are pre-rendered at build time. However, ISR introduces a layer of dynamism:</p><ul><li><strong>Balancing Act:</strong> Pages are periodically re-rendered in the background based on pre-defined intervals or specific triggers, ensuring content stays relatively fresh.</li><li><strong>Flexibility:</strong> ISR provides more control over content updates compared to traditional SSG, making it suitable for websites with frequently changing content.</li></ul><p><strong>How does ISR work?</strong></p><p>Static pages are generated at build time, and dynamic pages are regenerated incrementally based on specific triggers. This strategy balances the benefits of static content and real-time data updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_ZNczN2cMnKRRL_lCb4zw.png" /></figure><p>Of course, ISR isn’t without its considerations:</p><ul><li><strong>Triggering Challenges:</strong> Defining the appropriate triggers for content regeneration is crucial to avoid unnecessary server load and ensure content timeliness.</li></ul><p><strong>Choosing Your Rendering Champion</strong></p><p>The optimal rendering approach depends on your project’s specific needs. Here’s a quick guide:</p><ul><li><strong>Highly Interactive SPAs:</strong> CSR is your go-to choice.</li><li><strong>SEO-focused Websites:</strong> SSR is a strong contender.</li><li><strong>Content-driven Websites with Static Content:</strong> SSG shines in this scenario.</li><li><strong>Websites with a Mix of Static and Dynamic Content:</strong> Consider ISR for the best of both worlds.</li></ul><p>By understanding these rendering strategies, you can make informed decisions when building your next web project, ensuring exceptional performance, user experience, and SEO. Remember, experimentation is key! Explore different approaches and see what works best for your specific website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7a8422a56a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Unlocking the Power of System Design: Key Strategies for Scalability, Performance, and Fault…]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/unlocking-the-power-of-system-design-key-strategies-for-scalability-performance-and-fault-1552ad7dd670?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1552ad7dd670</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 10:43:36 GMT</pubDate>
            <atom:updated>2023-06-13T10:43:36.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Unlocking the Power of System Design: Key Strategies for Scalability, Performance, and Fault Tolerance”</h3><ol><li>Read-Heavy System: In a read-heavy system, implementing a cache can significantly improve performance. By caching frequently accessed data in memory, subsequent read requests can be served faster, reducing the load on the underlying data storage.</li><li>Low Latency Requirement: To achieve low latency, a combination of cache and Content Delivery Network (CDN) can be utilized. Caching frequently accessed data in memory reduces the time to retrieve it, while a CDN helps serve content from servers located closer to the user, minimizing network latency.</li><li>Write-Heavy System: For a write-heavy system, using message queues for asynchronous processing can be beneficial. Instead of directly processing write requests, the system can enqueue them in a message queue for later processing, allowing for better scalability and fault tolerance.</li><li>ACID Compliance: If ACID (Atomicity, Consistency, Isolation, Durability) compliance is required, opting for a Relational Database Management System (RDBMS) or SQL database is recommended. These databases provide strong transactional guarantees to ensure data integrity.</li><li>Unstructured Data: When dealing with unstructured data, such as text documents or JSON, a NoSQL database is a suitable choice. NoSQL databases offer flexible schema designs and horizontal scalability, making them efficient for handling unstructured data.</li><li>Complex Data (Videos, Images, Files): Storing and retrieving complex data like videos, images, or files can be efficiently handled using Blob/Object storage. Blob storage allows you to store large binary objects, while object storage provides a scalable and durable solution for managing files and media.</li><li>Complex Pre-computation: Message queues and cache can be used for complex pre-computation tasks. By breaking down the computation into smaller units and utilizing message queues to distribute the workload, the system can leverage the power of parallel processing. Caching the results can further enhance performance.</li><li>High-Volume Data Search: To efficiently handle high-volume data search requirements, implementing a search index or search engine is recommended. These technologies enable fast and optimized searching, making it easier to retrieve relevant information from a large dataset.</li><li>Scaling SQL Database: When scaling a SQL database, implementing database sharding is a common approach. Sharding involves partitioning the database across multiple servers based on a specific criterion (e.g., user ID, geographical location), allowing for horizontal scaling and distributing the load.</li><li>High Availability, Performance, &amp; Throughput: To achieve high availability, performance, and throughput, utilizing a load balancer is crucial. Load balancers distribute incoming traffic across multiple servers, ensuring efficient resource utilization, minimizing downtime, and improving system performance.</li><li>Global Data Delivery: Employing a Content Delivery Network (CDN) helps deliver data globally. A CDN consists of geographically distributed servers that cache and serve content from locations closer to end users, reducing latency and improving data delivery speed.</li><li>Graph Data: Graph databases are ideal for handling graph data structures and relationships. They provide efficient traversal and querying capabilities, making them suitable for scenarios like social networks, recommendation systems, or knowledge graphs.</li><li>Scaling Various Components: Horizontal scaling is a preferred approach when scaling various components. It involves adding more servers to the system to distribute the load, ensuring improved performance, and accommodating increased demand.</li><li>High-Performing Database Queries: Database indexes can greatly enhance the performance of database queries. By creating indexes on frequently queried columns, the database can quickly locate the desired data, resulting in faster query execution.</li><li>Bulk Job Processing: For processing bulk jobs, using batch processing and message queues is effective. The system can divide the bulk job into smaller batches, process them asynchronously using message queues, and ensure efficient resource utilization.</li><li>Server Load Management: Implementing a rate limiter helps manage server load. It allows controlling the number of requests processed within a specific timeframe, preventing overloading of the servers and ensuring fair resource allocation.</li><li>Microservices Architecture: Utilizing an API Gateway is recommended in a microservices architecture. An API Gateway acts as a single entry point for clients and handles request routing, authentication, rate limiting, and other cross-cutting concerns for microservices.</li><li>Redundancy for Single Point of Failure: Implementing redundancy is essential to mitigate the risk of single points of failure. By replicating critical components or services across multiple servers or data centers, the system can continue operating even if one instance fails.</li><li>Fault-Tolerance and Durability: Employing data replication ensures fault tolerance and durability. By replicating data across multiple servers or data centers, the system can withstand failures while maintaining data integrity and availability.</li><li>User-to-User Communication: Websockets are commonly used for user-to-user communication. Websockets provide real-time, bidirectional communication between clients and servers, allowing instant updates and enabling features like chat or live collaboration.</li><li>Failure Detection in Distributed Systems: Implementing a heartbeat mechanism helps detect failures in distributed systems. Heartbeats are periodic signals sent between nodes to confirm their availability. If a node stops sending heartbeats, it can be assumed to have failed.</li><li>Data Integrity: Checksum algorithms can be used to ensure data integrity. By calculating a checksum (e.g., using CRC32, SHA-256) for data and comparing it with the received checksum, the system can verify that the data has not been corrupted or tampered with during transmission.</li><li>Efficient Server Scaling: Consistent hashing is a technique that facilitates efficient server scaling. It ensures that when the number of servers changes, only a small fraction of keys need to be remapped, minimizing the impact on the overall system.</li><li>Decentralized Data Transfer: The Gossip Protocol is a suitable approach for decentralized data transfer. It allows nodes in a distributed system to exchange information in a peer-to-peer manner, ensuring data consistency and fault tolerance.</li><li>Location-Based Functionality: Location-based functionality can be implemented using spatial data structures like Quadtree or Geohash. These structures organize geographic data in a way that enables efficient indexing, searching, and proximity-based calculations.</li><li>Avoid Specific Technology Names: When discussing system design, it’s generally advisable to use generic terms rather than specific technology names. This helps focus on the design principles and concepts rather than tying the solution to a particular technology stack.</li><li>High Availability and Consistency Trade-Off: In scenarios where high availability and consistency are conflicting requirements, eventual consistency can be a suitable trade-off. Eventual consistency allows for temporary inconsistencies between replicas, prioritizing availability and partition tolerance.</li><li>Domain Name Query: When resolving domain names, the Domain Name System (DNS) plays a crucial role. DNS translates human-readable domain names into IP addresses, allowing clients to locate the servers associated with a particular domain.</li><li>Handling Large Data in Network Requests: Implementing pagination is an effective technique for handling large data in network requests. Instead of retrieving all data in a single request, pagination divides the data into smaller chunks, enabling efficient retrieval and reducing the strain on network resources.</li><li>Cache Eviction Policy: The Least Recently Used (LRU) cache eviction policy is often preferred. In LRU, the least recently accessed items are evicted from the cache when space is needed. This policy maximizes the cache’s effectiveness by keeping the most frequently accessed items available.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1552ad7dd670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Theorem]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/cap-theorem-f809786cfc63?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f809786cfc63</guid>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[distributed-system-design]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 18:56:47 GMT</pubDate>
            <atom:updated>2023-04-29T18:56:47.072Z</atom:updated>
            <content:encoded><![CDATA[<p>The CAP theorem is a fundamental principle in distributed computing that states that it is impossible for a distributed system to simultaneously provide all three of the following guarantees:</p><ol><li>Consistency — all nodes in the system see the same data at the same time, regardless of where the data is updated.</li><li>Availability — every request received by a non-failing node in the system must result in a response.</li><li>Partition tolerance — the system continues to function even when network partitions occur, which means that the system can still operate even if communication between nodes is lost or delayed.</li></ol><p>In other words, the CAP theorem states that a distributed system can only guarantee two out of these three properties at any given time, and must therefore make trade-offs between them.</p><p>To better understand the theorem, let’s consider a hypothetical scenario. Imagine that you are an entrepreneur who has started a business of remembering things for people. If someone wants to remember something, they can call you, and you will write it down in your diary. When they call back, you will remind them of the information.</p><p>As your business grows, you begin to receive an overwhelming number of calls, making it impossible for you to remember everything. So you ask your wife to help you out. Now, whenever someone calls with a request, you write it down in your diary, and your wife also makes a note in her diary. Once both diaries have been updated, you can respond to the request. This way, every diary is updated, ensuring consistency in your database.</p><p>However, suppose your wife is not available one day. In that case, you won’t be able to take any new requests for the entire day, which is an availability problem. To solve this issue, you start writing down all entries in your diary and then ask your wife to note them down when she is available.</p><p>But what happens when you and your wife have a fight and aren’t talking to each other? In this case, there is a network partition, and you must choose between consistency and availability. If you want to maintain consistency, you will have to tell the new customer that you can’t take their entry. On the other hand, if you want your system to be available, you can write down the entry in your diary, even though it will create a consistency issue.</p><p>The CAP theorem states that in a distributed system when there is a network partition, you must choose between consistency and availability. However, there is a third factor to consider: partition tolerance. In other words, the system should be able to continue to function despite network partitions.</p><p>Furthermore, there is an extension to the CAP theorem known as PACELC, which states that when there is no network partition, you must choose between latency and consistency. This means that the system should be able to function with minimal latency while still maintaining consistency.</p><p>To achieve eventual consistency, you could add a middleman, like a cache, to check for any updates made during the partitioned period and ask your wife to write them down when the partition is resolved.</p><p>In conclusion, the CAP theorem helps us understand the trade-offs between consistency, availability, and partition tolerance in a distributed system. It reminds us that no distributed system can have it all, and we must choose which factors are most important to our specific use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f809786cfc63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharding Vs Partioning]]></title>
            <link>https://medium.com/@ashutoshsingh_70348/sharding-vs-partioning-eee7b25780a0?source=rss-19f5946a32a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee7b25780a0</guid>
            <category><![CDATA[database-optimization]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 04:28:37 GMT</pubDate>
            <atom:updated>2023-04-27T04:28:37.113Z</atom:updated>
            <content:encoded><![CDATA[<p>As data grows, databases become more complex and challenging to manage. To keep up with increasing amounts of data, database administrators must consider partitioning or sharding as viable options. Both techniques aim to distribute data across multiple servers and reduce the load on a single server. However, they differ in their approach and functionality. In this blog, we’ll explore the differences between sharding and partitioning and the best use cases for each technique.</p><p>Sharding is a method of distributing data across multiple servers or nodes, allowing for horizontal scaling. In a sharded system, data is split into multiple smaller subsets called shards. Each shard contains a subset of the data and is stored on a different server. When a query is submitted, the system determines which shard contains the requested data and retrieves it from that server. Sharding requires significant planning and implementation, and data must be carefully divided to ensure that each shard receives an equal load of data.</p><p>Partitioning, on the other hand, is a method of dividing a database table into smaller subsets called partitions. Each partition contains a subset of the data and is stored on a different server. Partitioning is typically used to improve query performance and reduce server load. When a query is submitted, the system determines which partition contains the requested data and retrieves it from that server. Partitioning can be implemented in several ways, including range partitioning, hash partitioning, and list partitioning.</p><p>So, what are the main differences between sharding and partitioning?</p><ol><li>Data Distribution: Sharding distributes data across multiple servers or nodes, while partitioning divides a table into smaller subsets and distributes them across multiple servers.</li><li>Query Performance: Sharding can improve query performance by reducing the amount of data that needs to be retrieved from a single server. Partitioning improves query performance by reducing server load and optimizing the retrieval of data.</li><li>Scalability: Sharding allows for horizontal scaling, meaning that more servers can be added to the system as data grows. Partitioning also allows for horizontal scaling, but only to a certain extent.</li><li>Data Complexity: Sharding requires careful planning and implementation, and data must be divided in a way that ensures each shard receives an equal load of data. Partitioning is simpler to implement and requires less planning, but it still requires careful consideration of data distribution.</li></ol><p>In conclusion, both sharding and partitioning are useful techniques for managing large amounts of data. Sharding is typically used in larger systems where scalability is a priority, while partitioning is used in smaller systems where query performance is the primary concern. Ultimately, the choice between sharding and partitioning will depend on the specific needs and requirements of your database system. By understanding the differences between these two techniques, you can make an informed decision and optimize your database for maximum efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee7b25780a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>