<?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 Subhasmita Sahoo on Medium]]></title>
        <description><![CDATA[Stories by Subhasmita Sahoo on Medium]]></description>
        <link>https://medium.com/@subhasmitasahoo.247?source=rss-a633e438814f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9J0LFsrVgVVvUn37.jpg</url>
            <title>Stories by Subhasmita Sahoo on Medium</title>
            <link>https://medium.com/@subhasmitasahoo.247?source=rss-a633e438814f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:01:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@subhasmitasahoo.247/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[ Tracing LLM Reasoning with LangSmith (RAG Demo with Anime!)]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/tracing-llm-reasoning-with-langsmith-rag-demo-with-anime-4144c4fc8698?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4144c4fc8698</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langsmith]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 06:16:32 GMT</pubDate>
            <atom:updated>2025-06-19T06:38:30.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔍 Tracing LLM Workflows with LangSmith (RAG Demo with Anime!)</h3><p>This week, I tried out LangSmith — a tool that helps you <strong>trace and understand how your LLM pipeline works</strong>, step by step.</p><p>To explore it, I built a small demo using one of my favorite anime: <em>The Apothecary Diaries</em>.</p><p>The idea was simple:</p><blockquote><em>Ask a question → pull info from the web → let the AI answer → see how it all worked behind the scenes.</em></blockquote><p>It’s a basic <strong>RAG </strong>project that fetches live text from the web (Wikipedia), finds relevant parts, and uses GPT-4o to answer questions — while LangSmith shows exactly what happened at each step.</p><h3>🚀 What does this demo do?</h3><ol><li>You ask a question like:<br> <em>Why is curiosity both a gift and a curse for Maomao?</em></li><li>The app:</li></ol><ul><li>Fetches text from the web</li><li>Splits it into chunks</li><li>Finds the most relevant ones</li><li>Sends that to GPT-4o for an answer</li><li>And traces the whole flow using LangSmith</li></ul><h3>🛠 Tools I used</h3><ul><li><strong>LangChain</strong> — for chaining all the steps</li><li><strong>FAISS</strong> — for retrieving relevant text</li><li><strong>OpenAI (GPT-4o)</strong> — for generating the answer</li><li><strong>LangSmith</strong> — for tracing and debugging</li><li><strong>BeautifulSoup</strong> — to scrape Wikipedia</li></ul><h3>🧪 What’s cool about LangSmith?</h3><p>With LangSmith, I could:</p><ul><li>See a graph of how the model answered</li><li>Check what prompt it saw</li><li>Review what documents were used</li><li>Replay and tweak the model call in a visual playground</li></ul><p>It made the overall flow so much transparent — and helped me debug the process easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTNMKOMhSs6JW0Qp3PsUlg.png" /></figure><h3>💡 Want to try it?</h3><p>Here’s how to get started:</p><ol><li><strong>Install dependencies</strong></li></ol><p>These libraries cover LangChain components, tracing via LangSmith, embeddings, FAISS for retrieval, and web scraping.</p><pre>pip install langchain langsmith langchain-openai openai faiss-cpu beautifulsoup4</pre><p><strong>2. Set your API keys</strong></p><p>Before running the script:</p><p>Get the API Keys:</p><ul><li>For OpenAI: Go to <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a> → Log in and click <strong>“Create new secret key” → </strong>Copy the key — it will start with sk-...</li><li>For LangSmith: Go to <a href="https://smith.langchain.com/">https://smith.langchain.com</a> → Login → Click your profile icon → <strong>Settings</strong> → <strong>Create API Key → </strong>Copy the generated key — it will start with ls-...</li></ul><p>Now export your API keys:</p><pre>export OPENAI_API_KEY=your-openai-key<br>export LANGSMITH_API_KEY=your-langsmith-key<br>export LANGSMITH_TRACING=true</pre><p><strong>3. Write your script</strong></p><p>Create a file like rag_trace_apothecary.py and copy this basic version:</p><pre>from langchain.tools import Tool<br>from langchain.chains import RetrievalQA<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_openai import ChatOpenAI<br>from langsmith import traceable<br><br>import requests<br>from bs4 import BeautifulSoup<br>from langchain_core.documents import Document<br><br># Fetch and clean live Wikipedia page<br>def fetch_apothecary_text():<br>    url = &quot;https://en.wikipedia.org/wiki/The_Apothecary_Diaries&quot;<br>    res = requests.get(url)<br>    soup = BeautifulSoup(res.text, &quot;html.parser&quot;)<br>    paragraphs = soup.select(&quot;div.mw-parser-output &gt; p&quot;)<br>    text = &quot;\n&quot;.join(p.get_text() for p in paragraphs if p.get_text().strip())<br>    return text<br><br># Convert text to LangChain Documents<br>def get_docs_from_web():<br>    raw_text = fetch_apothecary_text()<br>    splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)<br>    docs = splitter.create_documents([raw_text])<br>    return docs<br><br># RAG chain setup<br>@traceable(name=&quot;dynamic-rag-apothecary&quot;)<br>def ask_anime_question(query: str):<br>    docs = get_docs_from_web()<br>    embeddings = OpenAIEmbeddings()<br>    vectorstore = FAISS.from_documents(docs, embeddings)<br>    retriever = vectorstore.as_retriever()<br>    llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0.7)<br><br>    qa_chain = RetrievalQA.from_chain_type(<br>        llm=llm,<br>        retriever=retriever,<br>        return_source_documents=True<br>    )<br><br>    result = qa_chain.invoke({&quot;query&quot;: query})<br>    print(&quot;Answer:\n&quot;, result[&quot;result&quot;])<br>    print(&quot;\n Sources:\n&quot;, result[&quot;source_documents&quot;])<br><br># Try it<br>ask_anime_question(&quot;Why is curiosity both a gift and a curse for Maomao?&quot;)</pre><p><strong>4. Run your script</strong></p><pre>python rag_trace_apothecary.py</pre><p><strong>4. See your trace</strong></p><p>Head over to <a href="https://smith.langchain.com/">https://smith.langchain.com/</a> to explore your full trace!</p><h3>🔁 Next Step: Play with Playground</h3><p>Try to improve the quality by changing the final step prompt in the playground (below is an example):</p><blockquote>Use the following pieces of context to answer the user’s question. <br>If the context does not have the answer, just say that you don’t know, don’t try to make up an answer.</blockquote><h3>🌱 Final thoughts</h3><p>This was a simple test project (please ignore the quality — thats not the goal of this exploration), and it helped me get familiar with LangSmith — and how to trace every step without tons of logs statements/guesses.</p><p>Happy tracing 😊!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4144c4fc8698" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Hosting a Simple ML App with Gradio + Hugging Face Spaces]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/building-and-hosting-a-simple-ml-app-with-gradio-hugging-face-spaces-ef1886933892?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1886933892</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[gradio]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Mon, 26 May 2025 18:57:06 GMT</pubDate>
            <atom:updated>2025-05-26T19:15:31.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I’ve been exploring tools outside my day-to-day work setup at Google — just for fun. This time I was exploring easier ways to build and host ML apps without worrying about frontend or infrastructure setup. This led me to trying out <strong>Gradio</strong> and <strong>Hugging Face Spaces</strong>, and I was genuinely impressed by how quick and intuitive the process was.</p><p>Together, they make a great pair if you want to:</p><ul><li>Share an ML prototype quickly</li><li>Demo an idea to a friend or PM</li><li>Learn to deploy apps without DevOps overhead</li></ul><p>In this post, I’ll walk through a simple step-by-step guide to build a demo using Gradio + Hugging face Spaces.</p><h3>🧩 Why Gradio + Hugging Face Spaces?</h3><h4>Gradio: Build the Interface</h4><p>Gradio is a Python library that lets you quickly build interactive UIs for your ML models — with just a few lines of code.</p><p>➡️ No need for HTML or JavaScript — it’s all pure Python.</p><h4>Hugging Face Spaces: Host the App</h4><p>Hugging Face Spaces is a platform that lets you host your Gradio app for free (with some usage limits), directly from a GitHub repo or file upload. It takes care of:</p><ul><li>Installing dependencies from requirements.txt</li><li>Running your app and giving you a public link</li><li>Handling environment variables (e.g. API keys)</li><li>Automatically restarting the app when you make updates</li></ul><p>➡️ No need to set up cloud infra, Docker, or servers — Spaces handles it all.</p><h3>🪜 Step-by-Step Guide to a Simple Demo</h3><p>For a test project, this is a sample demo of a tiny app that takes a text prompt from the user and generates a response using OpenAI’s gpt-3.5-turbo. Nothing fancy — just a clean textbox interface and a Python function under the hood.</p><p>You don’t need to install anything locally. You can do this entirely inside the Hugging Face interface:</p><ol><li>Step 1: Go to <a href="https://huggingface.co/spaces">huggingface.co/spaces</a> and click <strong>“Create new Space”</strong>.</li><li>Choose <strong>Gradio</strong> as your SDK and give your Space a name.</li><li>In the Space interface, click <strong>Files → Contribute → Create New file</strong> and create a file called app.py. Paste in the below Python code.</li></ol><pre>import openai<br>import os<br>import gradio as gr<br><br>client = openai.OpenAI(api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;))<br><br>def generate_text(prompt):<br>    response = client.chat.completions.create(<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>    )<br>    return response.choices[0].message.content<br><br>demo = gr.Interface(fn=generate_text, inputs=&quot;text&quot;, outputs=&quot;text&quot;)<br>demo.launch()</pre><p>4. Create a requirements.txt file and add:</p><pre>openai&gt;=1.0.0<br>gradio</pre><p>5. (Optional) Now create an OpenAI key in <a href="https://platform.openai.com/api-keys">https://platform.openai.com/api-keys</a> and copy the key.</p><p>6. Go to the Space <strong>Settings</strong> and add a <strong>Secret</strong> with:</p><ul><li><strong>Name:</strong> OPENAI_API_KEY</li><li><strong>Value:</strong> Paste your OpenAI key</li></ul><p>7. That’s it — Your app will build and deploy automatically!</p><p>Now go to https://huggingface.co/spaces/&lt;user_name&gt;/&lt;space_name&gt; to see the demo. (Example: <a href="https://huggingface.co/spaces/ssmita25/dummy">https://huggingface.co/spaces/ssmita25/dummy</a>).</p><p>Below is a screenshot of the demo with above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nl_4Sh0_pcLIEAM0lRr2Kg.png" /></figure><h3>📦 What I Loved</h3><ul><li>No HTML, no JS — pure Python</li><li>Built and deployed in under a few minutes</li><li>Hugging Face auto-renders your app and gives you a live URL</li><li>Supports both static and dynamic apps (e.g. chatbots, image demos)</li></ul><h3>🔐 But What About API Keys and Costs?</h3><p>This is important: If your app uses a paid API like OpenAI’s — you are <strong>responsible</strong> for every call made, even by strangers using your demo.</p><p>To keep it safe:</p><ul><li>Don’t hardcode your OpenAI API key in public code</li><li>Don’t expose the key in public Spaces</li><li>Use environment variables if possible (Spaces supports them)</li><li>Add simple logging or rate limits</li><li>Or keep the app private, and just share a screenshot or video</li></ul><p>If you want a more secure setup, I recommend adding a small backend proxy (FastAPI or Flask) that holds the key and exposes a limited endpoint to Gradio.</p><h3>🧪 Try It Yourself</h3><p>You can try:</p><ul><li>Follow the steps to create the first simple demo</li><li>Try it with a free Hugging Face model instead of OpenAI</li><li>Add your own UI tweaks (e.g. temperature slider, chat history). Explore more UI components at <a href="https://www.gradio.app/playground">https://www.gradio.app/playground</a>.</li></ul><p>This was a fun side experiment — a small step toward building usable tools. Hope it helps you too!</p><p>Let me know if you try it — or build something of your own!</p><p>#gradio #huggingface #openaidemo #mlops #aiapps #machinelearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1886933892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on with Agent2Agent: A Beginner’s Guide]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/hands-on-with-agent2agent-a-beginners-guide-d7f84d497ceb?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7f84d497ceb</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agent2agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 21:45:31 GMT</pubDate>
            <atom:updated>2025-04-12T23:33:39.521Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@subhasmitasahoo.247/agent2agent-a2a-explained-in-simple-words-76999496710d">previous post</a>, I shared a simple explanation of Agent2Agent (A2A) — what it is and why it matters.</p><p>If that sparked your curiosity, this post is for you! Let’s walk through how you can try A2A yourself, even if you’re just getting started.</p><h3><strong>Step 1: Start a codespace</strong></h3><blockquote>Start a codespace from Google’s <a href="https://github.com/google/A2A?tab=readme-ov-file#getting-started">A2A repo link</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*umfKh1rVKm-YADUtvhSsEA.png" /></figure><h3><strong>Step 2: Get Google API Key</strong></h3><blockquote>Create a Google API key using <a href="https://cloud.google.com/docs/authentication/api-keys#create">this guide</a>.</blockquote><h3>Step 3: Start an agent</h3><blockquote>Now, lets start a specialized agent. For my demo, I used the <a href="https://github.com/google/A2A/tree/main/samples/python/agents/langgraph">langraph agent</a> for currency conversions. Run the below commands sequentially (<a href="https://github.com/google/A2A/blob/main/samples/python/hosts/cli/README.md">original guide</a>):</blockquote><pre>cd samples/python/agents/langgraph<br><br>echo &quot;GOOGLE_API_KEY=&lt;YOUR_KEY&gt;&quot; &gt; .env<br><br># Change 8080 to any other port<br>uv run . --host 0.0.0.0 --port 8080 </pre><h3>Step 4: Test your agent with CLI</h3><blockquote>Now, let’s test your hosted agent with CLI. Run the below commands step-by-step (<a href="https://github.com/google/A2A/blob/main/samples/python/hosts/cli/README.md">original guide</a>):</blockquote><pre>cd samples/python<br><br>echo &quot;GOOGLE_API_KEY=&lt;YOUR_KEY&gt;&quot; &gt; .env<br><br># &quot;http://localhost:8080&quot; is your agent started above.<br>uv run hosts/cli --agent http://localhost:8080</pre><blockquote>This will then prompt you to ask a question to send to the agent. Try this query: “<em>usd to inr”. </em>It should then give you a nice JSON response.</blockquote><blockquote>If you see an error like “<em>An error occurred while streaming the response: 403 Generative Language API has not been used in project</em>”, enable the API using the provided link in the terminal.</blockquote><h3>Step 3: Bring up a UI demo</h3><blockquote>Run the below commands to start the demo (<a href="http://echo &quot;GOOGLE_API_KEY=&lt;YOUR_KEY&gt;&quot; &gt; .env">original guide</a>):</blockquote><pre>curl -LsSf https://astral.sh/uv/install.sh | sh<br><br>cd demo/ui<br><br>echo &quot;GOOGLE_API_KEY=&lt;YOUR_KEY&gt;&quot; &gt; .env<br><br>uv run main.py</pre><blockquote>The above bring up a demo: <a href="http://0.0.0.0:12000/">http://0.0.0.0:12000</a>. On clicking the link in terminal, you can see an UI like below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJSicDoj6jP-JjC_06HW-Q.png" /></figure><h3>Step 5: Add your agent to UI demo</h3><blockquote>Now, add your agent by going to the “Agents” tab.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14bqIEi0wu4zR5hRXADLvw.png" /></figure><blockquote>On adding the agent, it should show a screenshot shown below. Now click on “Save”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgakB9KMLaRL0Ij44fhXXQ.png" /></figure><h3>Step 6: Test your query in UI demo</h3><blockquote>Go to “Home” tab using the left menu and enter your query. And you should get a response, shown below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep7VcIYj_RL7yuV_aZpkLQ.png" /></figure><h3>My final demo</h3><p>This is my final demo: <a href="https://youtu.be/dcXmKrjwEys">https://youtu.be/dcXmKrjwEys</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z9qa0E-Ar7EjDAIOEPdiA.png" /></figure><h3>Conclusion</h3><p>That’s it — you’ve just taken your first step into the world of multi-agent AI systems! 🎉</p><p>A2A opens up a lot of possibilities, from smarter assistants to modular systems that grow with your needs.</p><p>If you build something cool or have any questions, feel free to drop a comment or message. I’d love to hear how you’re exploring A2A!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7f84d497ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent2Agent (A2A) — Explained in Simple Words]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/agent2agent-a2a-explained-in-simple-words-76999496710d?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/76999496710d</guid>
            <category><![CDATA[agent2agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 21:41:01 GMT</pubDate>
            <atom:updated>2025-04-12T22:05:11.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>Agent2Agent (A2A) — Explained in Simple Words</h3><p>Ever wished about all your favorite AI assistants/agents to work like a team, instead of doing everything alone or you manually coordinating them? That’s what Agent2Agent (A2A) makes possible.</p><h3>What is A2A?</h3><p>A2A is a way for multiple AI agents to talk, collaborate, and solve complex tasks together — each focusing on what they’re best at.</p><p>Let me explain with a simple example.</p><h3>Real-World Example: Personal Investment Assistant</h3><p>Imagine you’re using an AI assistant to manage your money.</p><blockquote>You ask: <em>“Should I invest in Company X this quarter?”</em></blockquote><p>Instead of answering directly, your assistant calls in help from other expert agents:</p><blockquote>🧾 <strong>Financial Data Agent</strong> pulls Company X’s latest numbers</blockquote><blockquote>📈 <strong>Market Analysis Agent</strong> checks industry trends and forecasts</blockquote><blockquote>⚠️ <strong>Risk Assessment Agent</strong> looks at potential risks and volatility</blockquote><blockquote>These agents share insights, discuss among themselves (yes, really!), and work together.<br> Your assistant then gives you a well-rounded, data-backed answer.</blockquote><p>That’s the power of A2A — AI agents working as a team, just like people do.</p><h3>How is A2A different from MCP?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwaOskPKfz74KwaSZoREng.png" /></figure><h3>Conclusion</h3><p>To wrap it up — A2A is like giving your AI assistant a team of experts to collaborate with.</p><ul><li>It’s flexible, scalable, and feels a lot like how we humans work together — bringing in different people (or agents!) based on their strengths.</li><li>Need a new capability? Just plug in a new agent — no complex rewiring needed.</li></ul><p>It’s just like how we collaborate with others in real life — bring in the right people (or agents!) and get better results.</p><p>I’m excited about the possibilities A2A unlocks, especially as problems get more complex and need more specialized intelligence.</p><p>👉 If you’re curious to try it out yourself, check out <a href="https://medium.com/@subhasmitasahoo.247/hands-on-with-a2a-a-beginners-guide-d7f84d497ceb">Hands-on with Agent2Agent: A Beginner’s Guide</a> — I walk through how to test A2A step-by-step, even if you’re just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76999496710d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Model Context Protocol (MCP): A Beginner’s Guide]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/getting-started-with-model-context-protocol-mcp-a-beginners-guide-0c1c43e3e140?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c1c43e3e140</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[brave-browser]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 19:23:39 GMT</pubDate>
            <atom:updated>2025-04-05T19:23:39.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we begin, lets start with some intro to MCP.</p><h3>What is Model Context Protocol (MCP)?</h3><p>MCP is an approach (or protocol) to connect AI assistants like Claude to external sources of information and tools. It was created by Anthropic to make it easier for AI to connect to specialized tools.</p><p>Think of MCP as a bridge that connects AI assistants to the outside world. Without MCP, these AI assistants can only use information it learned during its training. With MCP, now they can perform more richer operations like:</p><ul><li>Fetch latest information from internet</li><li>Making use of databases to manage data</li><li>Processing local files in your computer</li></ul><h3>A Simple Example</h3><p><strong>Without MCP:</strong></p><p><em>The model was unable to answer on latest information.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhfZPiNqn2Cjnfe3oePIBA.png" /></figure><p><strong>With MCP:</strong></p><p><em>The model used external tools (in this case “Brave Search”) to browse and answer on latest information.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcBaVDi_ecYWLbftzb3LQg.png" /></figure><h3>Before You Begin</h3><p>Now, let’s get started with the setup so that you can play around with it. I’ve tested these instructions myself and compiled them from multiple sources to create the steps that finally worked for me. <strong>All the instructions are for MacOS environment</strong>.</p><h3>Step 1: Set Up Your Environment</h3><pre># Install NVM<br>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash<br># Activate NVM in your shell<br>source ~/.bashrc # or ~/.zshrc depending on your shell setup<br># Install the latest LTS version of Node.js<br>nvm install - lts<br># Verify NPX is installed<br>npx -v</pre><h3>Step 2: Install Claude Desktop</h3><p>Download and install the Claude desktop application from: <a href="https://claude.ai/download">https://claude.ai/download</a></p><h3>Step 3: Choose Your MCP Server</h3><p>You can use this repo to pick your favourite MCP server: <a href="https://github.com/modelcontextprotocol/servers/tree/main">https://github.com/modelcontextprotocol/servers/</a></p><p>For this guide, we’ll use the <strong>Brave Search</strong> server.</p><h3>Step 4: Set Up Brave Search API</h3><ol><li>Create an API key at: <a href="https://brave.com/search/api/">https://brave.com/search/api/</a></li><li>Create a configuration file named claude_desktop_config.json with the following content:</li></ol><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;brave-search&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [<br>        &quot;-y&quot;,<br>        &quot;@modelcontextprotocol/server-brave-search&quot;<br>      ],<br>      &quot;env&quot;: {<br>        &quot;BRAVE_API_KEY&quot;: &quot;&lt;key&gt;&quot; # Add your key here.<br>      }<br>    }<br>  }<br>}</pre><p>3. Add your “Brave API key” to environment variable as well.</p><pre>export BRAVE_API_KEY=YOUR_BRAVE_A_KEY_HERE</pre><h3>Step 5: Launch the MCP Server</h3><pre>npx @modelcontextprotocol/server-brave-search</pre><h3>Step 6: Test Your Setup</h3><ol><li>Restart your “Claude Desktop App”. You should see the below two icons in your Desktop App. For some reason, I had to restart 2–3 times, before I could see these icons.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTUgdYoue1vHKl1_-Pvn8g.png" /></figure><p>2. Now, try a query that requires current information, such as: “Search the web for ‘Nvidia stock price’”. And you should be able to see something like this (shared in the example section):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nm6Tc4GHZo8x6QQQWVJvsA.png" /></figure><h3>Next Steps</h3><ul><li>Build a custom MCP server.</li><li>Create custom orchestration combining multiple MCP servers</li><li>Share your experience :)</li></ul><p><em>Happy Exploring!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c1c43e3e140" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tree-of-Thoughts: Making LLMs Think Like Humans]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/tree-of-thoughts-making-llms-think-like-humans-5b82401c0146?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b82401c0146</guid>
            <category><![CDATA[tree-of-thought]]></category>
            <category><![CDATA[llm-reasoning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 13:48:45 GMT</pubDate>
            <atom:updated>2024-11-10T14:32:45.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyLH4cJgSja7c-jkUDQw4Q.png" /><figcaption>From <a href="https://arxiv.org/pdf/2305.10601">https://arxiv.org/pdf/2305.10601</a> (<a href="https://www.promptingguide.ai/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FTOT.3b13bc5e.png&amp;w=3840&amp;q=75">Image url</a>)</figcaption></figure><h3>System-1 vs System-2 Thinking</h3><p>Have you ever wondered how we make decisions? Psychologists talk about two types of thinking: System-1 and System-2.</p><ul><li>System-1 is our fast, automatic thinking — like how you don’t have to think about walking or recognizing a friend’s face.</li><li>System-2 is our slower, more deliberate thinking — like solving a complex math problem or planning your next career move.</li></ul><p>This concept was popularized by Daniel Kahneman in his book “Thinking, Fast and Slow”. So how is “Tree-of-Thoughts (or ToT)” related to System-1 vs System-2 thinking? Read below.</p><h3>How Do LLMs Think Differently?</h3><p>Current Large Language Models (LLMs) process information through neural architectures that generate text using probability-based token predictions. While they can perform both quick associations (similar to System-1) and complex reasoning tasks (like System-2), their thought process remains fundamentally different from human cognition and can be difficult to analyze.</p><h3><strong>Tree-of-Thoughts: Bridging the Gap</strong></h3><p>This is where Tree-of-Thoughts (ToT) comes in — an approach that attempts to make AI reasoning more systematic and human-like. ToT implements a structured decision-making framework that mirrors aspects of human System-2 thinking:</p><ol><li>Generation: Creates multiple potential solution paths (like brainstorming different approaches)</li><li>Evaluation: Assesses the promise of each path (similar to human judgment)</li><li>Decision: Either proceeds with the best option or backtracks to explore alternatives</li></ol><p>By incorporating this systematic approach, ToT helps LLMs better handle complex reasoning tasks that typically require human-like deliberate System-2 thinking. While it doesn’t perfectly replicate human cognition, it represents an important step toward more thoughtful and transparent AI reasoning.</p><p>To understand how this differs from other approaches, let’s look at solving a math problem: <em>25 × 68.</em></p><p><strong>Basic prompting</strong></p><blockquote>Human: What’s 25 × 68?</blockquote><blockquote>AI: 1700</blockquote><p><strong>Chain-of-Thought (CoT)</strong></p><blockquote>Human: What’s 25 × 68?</blockquote><blockquote>AI: Let me solve this step by step:</blockquote><blockquote>— First, 25 × 60 = 1500</blockquote><blockquote>— Then, 25 × 8 = 200</blockquote><blockquote>— Total: 1500 + 200 = 1700</blockquote><p><strong>Tree-of-Thought (ToT)</strong></p><blockquote>Human: What’s 25 × 68?</blockquote><blockquote>AI: Let me explore different methods to solve this:</blockquote><blockquote><strong>Path 1:</strong></blockquote><blockquote>Breaking into tens and ones</blockquote><blockquote>— 25 × 60 = 1500</blockquote><blockquote>–25 × 8 = 200</blockquote><blockquote>— Total = 1500 + 200 = 1700</blockquote><blockquote>Confidence: High (simple breakdown, fewer steps)</blockquote><blockquote><strong>Path 2:</strong></blockquote><blockquote>Using 25 = 100/4</blockquote><blockquote>–68 × 100 = 6800</blockquote><blockquote>–6800 ÷ 4 = 1700</blockquote><blockquote>Confidence: Medium (division involved, potential for rounding errors)</blockquote><blockquote><strong>Path 3:</strong></blockquote><blockquote>Using distribution</blockquote><blockquote>— (20 + 5) × (60 + 8)</blockquote><blockquote>— (20 × 60) + (20 × 8) + (5 × 60) + (5 × 8)</blockquote><blockquote>— 1200 + 160 + 300 + 40 = 1700</blockquote><blockquote>Confidence: Medium (more steps, higher chance of errors)</blockquote><blockquote>✅ <strong>Final Answer</strong>:</blockquote><blockquote>1700 Choosing Path 1 because:</blockquote><blockquote>— Simpler computation</blockquote><blockquote>— Fewer steps</blockquote><blockquote>— Lower chance of errors</blockquote><p>As you can see above the reasoning to get the solution is very transparent. The key difference is:</p><ul><li>In Basic prompting, the model did not take/show any steps and just gave the answer.</li><li>With Chain-of-Thought, while it solved the problem with steps, but considered only one approach.</li><li>With Tree-of-Thoughts, it explored multiple approaches and evaluates each one — much like how a human expert might tackle a problem.</li></ul><h3>Why Does This Matter?</h3><p>This matters because in real-world scenarios, the ability to consider and evaluate different approaches is crucial. Think about doctors diagnosing complex symptoms or engineers debugging tricky problems — they rarely follow just one linear path of thinking.</p><p>This approach also reminds me of my maths class in school. Remember getting partial credit for showing your steps, even if you made a small calculation error at the end? That’s because the thinking process do matters!</p><p>As LLMs based systems become more integrated into complex decision-making processes — from medical diagnosis to financial planning — this ability to think systematically becomes increasingly important. Tree-of-Thoughts represents a step toward making AI reasoning more transparent and more similar to human expert thinking.</p><h3>Implementing Tree-of-Thoughts</h3><p>If you are interested in implementing ToT, here’s a simple guide to how you can proceed. The core of ToT requires three main components:</p><ol><li><strong>A Thought Generator</strong> — Creates multiple possible paths at each step</li><li><strong>An Evaluator</strong> — Assesses how promising each path is and selects the best path(s)</li><li><strong>An Orchestrator</strong>— Keeps track of the different paths and steps, orchestrates the search and generates the final answer.</li></ol><p>Below is a simple conceptual implementation of core components of ToT, a production-ready system would require additional components and careful consideration of prompt engineering, evaluation metrics, and search/selection strategies.</p><pre>def generate_thoughts(state, num_thoughts_per_step=3):<br> &quot;&quot;&quot;Generate k possible next thoughts from current state&quot;&quot;&quot;<br> prompt = f&quot;&quot;&quot;<br> Current state: {state}<br> Generate {num_thoughts_per_step} different approaches to proceed.<br> Describe each approach and include pros and cons for each.<br> &quot;&quot;&quot;<br> return parse_thought_list(llm(prompt)) # Your LLM call here and parse it to get list of thoughts.<br><br>def evaluate_thoughts(thoughts, goal):<br> &quot;&quot;&quot;Evaluate each thought&#39;s potential&quot;&quot;&quot;<br> prompt = f&quot;&quot;&quot;<br> Goal: {goal}<br> Rate each approach below and explain why:<br> {thoughts}<br> &quot;&quot;&quot;<br> return parse_thought_scores(llm(prompt)) # Your LLM call here and parse it to get score for each thought.<br><br>...<br><br>def get_tot_response(initial_state, goal, max_steps=5, num_thoughts_per_step=3):<br>    &quot;&quot;&quot;The main orchestrator to get the final response with ToT.&quot;&quot;&quot;<br>    current_states = [initial_state]<br>    for step in range(max_steps):<br>        new_states = []<br>        for state in current_states:<br>            thoughts = generate_thoughts(state, num_thoughts_per_step)<br>            scores = evaluate_thoughts(thoughts, goal)<br>            # Implement to select the top thought(s).<br>            best_thoughts = select_best_thoughts(thoughts, scores)<br>            new_states.extend(best_thoughts)<br>        current_states = new_states<br>    return select_best_path(current_states)</pre><h3>Further Reading</h3><p>Want to dive deeper? Check out the original research paper at <a href="https://arxiv.org/pdf/2305.10601">https://arxiv.org/pdf/2305.10601</a>.</p><p>Please feel free to add your thoughts below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b82401c0146" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Out-of-bag Evaluation]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/out-of-bag-evaluation-2b971f4a58e7?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b971f4a58e7</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 09:05:24 GMT</pubDate>
            <atom:updated>2024-06-11T09:09:47.564Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on the Kaggle “<a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques">House Prices</a>” challenge, I came across this neat metric called “out-of-bag evaluation” (OOB). It’s a way to check the accuracy of a Random Forest model without needing extra data, similar to cross-validation.</p><p><strong>Idea</strong>: To begin with, <em>Random forest</em> is a collection of <em>Decision trees</em>. When each “tree” in the Random Forest is built, only a portion of the training data is used. This leaves the rest of the training data for mini testing of that specific tree. The table below illustrates how this works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*YntIGSOpg3QQgnK-" /><figcaption><a href="https://developers.google.com/machine-learning/decision-forests/out-of-bag">https://developers.google.com/machine-learning/decision-forests/out-of-bag</a></figcaption></figure><p>In the above example, we have 6 examples in training data, with which a Random Forest with 3 trees is built. Each tree is made using 6 examples, where each example is sampled from the training data with replacement.</p><ul><li>Tree 1: Uses all houses <em>except</em> house #3, so we can test the tree on house #3.</li><li>Tree 2: Uses all houses <em>except</em> house #2, #4, and #6, so we can test the tree on house #2, #4, and #6.</li><li>Tree 3: Uses all houses <em>except</em> house #1 and #5, so we can test the tree on house #1 and #5.</li></ul><p>This way, each tree gets evaluated on data it hasn’t seen before, giving us a reliable estimate of how well our model will do in the real world.</p><p>Hope this article helped! Any relevant feedback is appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b971f4a58e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Journey of my first Kaggle Challenge (Titanic)]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/journey-of-my-first-kaggle-challenge-titanic-7652f3fa44e3?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7652f3fa44e3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 12:15:15 GMT</pubDate>
            <atom:updated>2024-06-09T12:15:15.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p><a href="https://www.kaggle.com/competitions/titanic">Problem</a>: To build a predictive model that answers the question: “<em>what sorts of people were more likely to survive?</em>” using passenger data (ie name, age, gender, socio-economic class, etc). This is the recommended <a href="https://www.kaggle.com/code/prashant111/random-forest-classifier-tutorial">tutorial by Kaggle</a> for beginners.</p><p>As a crucial first step, I revisited the theory behind RandomForestClassifier, a powerful machine learning algorithm well-suited for this type of prediction problem. Below is a brief summary on the intuition behind this algorithm.</p><h3>Intuition Behind Random Forest</h3><p>The Random Forest algorithm is a supervised machine learning algorithm, adept at tackling both <a href="https://www.kaggle.com/code/jaciaebubechi/classification-and-regression-problems-in-machine">classification and regression tasks</a>. However, to truly grasp its inner workings, it’s essential to first understand its building block: the Decision Tree.</p><p>A Decision Tree makes predictions through a series of sequential “if-else” decisions (like a Flow-Chart). For example, below is the sample dataset for the Titanic problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msqAyr0Nk5aOWtfNm3zEkQ.png" /></figure><p>Below is a sample decision tree based on two features ([‘Pclass’, ‘Sex’]):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dR4QMXFhHtUbDXIKyyzjHA.png" /></figure><p>While being useful, they can become overly sensitive to the training data, hindering their ability to generalize to new, unseen information. This is where the Random Forest comes in.</p><p>A Random <em>Forest</em> is a group of Decision <em>Trees</em> (easy to imagine!). Each tree is built using different sample of the data and features, introducing a healthy dose of randomness. This diversity is key. When it’s time to make a prediction, the Random Forest consults all its trees and arrives at a consensus through majority voting. This makes the Random Forest far more robust and reliable than a single Decision Tree.</p><h3><strong>Additional Notes</strong></h3><p>To solidify my understanding, I wrapped up the tutorial by diving into the “<a href="https://www.kaggle.com/learn/intro-to-machine-learning">Intro to Machine Learning</a>” module. Inspired by one of the <a href="https://www.kaggle.com/code/gusthema/titanic-competition-w-tensorflow-decision-forests">solutions</a>, I delved into the world of GradientBoostedTreesModel, exploring resources such as:</p><ul><li><a href="https://www.analyticsvidhya.com/blog/2021/09/gradient-boosting-algorithm-a-complete-guide-for-beginners/">Gradient Boosting Algorithm: A Complete Guide for Beginners</a></li><li><a href="https://www.analyticsvidhya.com/blog/2021/09/adaboost-algorithm-a-complete-guide-for-beginners/">AdaBoost Algorithm: Understand, Master and Implement AdaBoost</a></li><li><a href="https://www.analyticsvidhya.com/blog/2021/03/introduction-to-adaboost-algorithm-with-python/">Introduction to AdaBoost Algorithm with Python</a></li></ul><p>While I haven’t yet submitted a solution based on the GradientBoostedTreesModel, it’s certainly on my to-do list!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7652f3fa44e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Consolidated Guide to Web Worker]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/web-worker-a5692a86765e?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5692a86765e</guid>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 13:50:27 GMT</pubDate>
            <atom:updated>2020-08-02T14:12:15.663Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Note: This is a consolidation of the useful links related to Web worker. All the high level concepts are added directly as text. To know more in detail, please refer the added links. I had collected all this information when I was working on implementing Web worker in JavaScript as a beginner.</blockquote><h3>Introduction</h3><p>Web worker is a way to address the single-threaded nature of JavaScript. JavaScript being a single threaded language, doesn’t provide capability for parallel processing like any other language. Though there is a clear impact of it on the performance, another major concern is about user experience. Since the interaction of the user with the browser window is handled in the same single thread of Javascript, blocking the thread with any computationally intensive task will delay the user interaction response. This issue can be handled using a Web worker, by running the computationally intensive tasks asynchronously in the background/ worker thread. Web workers are not a part of JS, instead these are part of the browser features which can be accessed via JS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*C76LUuGweL7Uk5GwAyX2EA.png" /></figure><h4>Browser Support</h4><p>Currently, it is supported in almost all the recent versions of the popular browsers except Opera Mini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvPKVNZa02FVcRFELldO0Q.png" /><figcaption>LInk: <a href="https://caniuse.com/#feat=webworkers">https://caniuse.com/#feat=webworkers</a></figcaption></figure><h3>Types of Web worker</h3><p>There are three types of Web workers.</p><ol><li>Dedicated worker</li><li>Shared worker</li><li>Service worker</li></ol><h3>Dedicated Worker</h3><p>A dedicated worker is only accessible by the script that called it.</p><p>For more details, please refer the Mozilla <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Dedicated_workers">Documentation</a>. This documentation also explains steps for creating a Web worker in JavaScript.</p><h3>Shared Worker</h3><p>A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframe or even workers. All those browsing contexts which are accessing the shared Web worker must share the exact same origin (same protocol, host, and port). Communication happens via port object. A port is opened explicitly for the communication between the main script and the worker.</p><h4>Browser Support</h4><p>Currently, it is supported in few browsers as compared to dedicated worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wubDDnf0XsaIC-ccz-YDXQ.png" /><figcaption>Link: <a href="https://caniuse.com/#feat=sharedworkers">https://caniuse.com/#feat=sharedworkers</a></figcaption></figure><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHfkeNT_rBCidyX1-4qo-w.png" /></figure><p>We can kill a shared Worker by closing all the pages of the domain that created it. (Needs to be verified. Maybe even the terminate() method can be used. This was mentioned in a stack overflow discussion <a href="https://stackoverflow.com/questions/21625419/is-it-possible-to-terminate-a-running-web-worker">link</a>. )</p><p>Note that, they can’t be spawn inside a dedicated worker, as it is not available in global context</p><p>For more, please refer the following:</p><ul><li><a href="https://stackoverflow.com/questions/30830000/how-to-call-shared-worker-from-the-web-worker">How to call shared worker from Web worker</a></li><li><a href="https://stackoverflow.com/questions/30741686/spawning-a-shared-worker-in-a-dedicated-worker">Spawning shared worker in dedicated worker</a></li><li>Mozilla <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Shared_workers">Documentation</a></li></ul><h3>Service Worker</h3><p>It is a client-side programmable proxy between the web app and outside the world. They run independent of the application and can receive messages when not active. It is idle when not in use and restart when needed. For persistence, it can be integrated with IndexedDB. For details regarding communication, please refer <a href="https://ponyfoo.com/articles/serviceworker-messagechannel-postmessage">Service worker and message Channel</a>. They are primary used for the following purposes:</p><ul><li>as caching agent,</li><li>for handling networking requests,</li><li>storage for offline usages,</li><li>offline experience</li><li>to handle push messaging</li></ul><p>Following are the limitations of this type of Web worker:</p><ul><li>only available in HTTPS protocol</li><li>can’t access DOM elements, similar to dedicated Web worker</li></ul><p>Following is the life cycle of a Service Worker:</p><ul><li>Download — The browser downloads the .js file that contains the service worker</li><li>Register &amp; Installation — The browser knows about where the service worker js file lives</li><li>Activate — When the service worker starts controlling the pages.</li></ul><h4>Browser Support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zupu8ej3JWS_O1DJhJi5QA.png" /><figcaption>Link: <a href="https://caniuse.com/#search=service%20worker">https://caniuse.com/#search=service%20worker</a></figcaption></figure><p>For more, please refer</p><ul><li><a href="https://blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and-use-cases-52b19ad98b58">Service workers life cycle</a></li><li><a href="https://codeburst.io/an-introduction-to-service-workers-in-javascript-27d6376460c2">Introduction to service workers</a></li></ul><h3>Other types of worker</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Other_types_of_worker">Documentation</a></li></ul><h3>Important notes regarding Web worker</h3><ul><li>The worker object is creating using the constructor new Worker() (for dedicated worker) that takes a JS file as the parameter</li><li>Once the worker is created, it can communicate with the main thread via message passing. Ex. postmessage, onMessage, or using broadcast channel (limited browser compatibility).</li><li>The data is copied, if standard method passing is used. This is discussed in detail in the later section.</li><li>Workers don’t have access to all features of JavaScript. For example, they can’t access the DOM object. They can’t access some properties of the window object. Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers">this</a> as the reference to know more about the features availability to the Web worker.</li><li>Worker can spawn new worker as long as the workers are hosted within the same origin as the parent page</li><li>Creation of a new Web worker takes a significant amount of time. The creation happens in the worker thread. All the message passing that is invoked is queued until the Web worker script is compiled and the worker is created. Also, the code size plays a major role in this scenario.</li></ul><h3>Broadcast Channels</h3><p>These are useful for communication between different browsing contexts like windows/tabs, iframe, Web workers, and service workers. Messages which are posted to the channel are delivered to all the listeners. It works similar to pub/sub model. It is mainly useful for one-to-many communications between scripts on the same origin.</p><h4>Browser Support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bD2VqH5NvrTcLPJp47IY6g.png" /><figcaption>LInk: <a href="https://caniuse.com/#search=broadcast%20channel">https://caniuse.com/#search=broadcast%20channel</a></figcaption></figure><p>For more, please refer</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">MDN documentation</a></li><li><a href="https://developers.google.com/web/updates/2016/09/broadcastchannel">Google Developer documentation</a></li></ul><h3>Message passing in Web worker</h3><h3>Default message passing method</h3><p>By default, the data passed between the worker and the main thread is copied, not shared. Objects are serialised and deserialised while message passing is done. This is implemented via structured cloning methods. The data may be any value or JavaScript object handled by the <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/The_structured_clone_algorithm">structured clone</a> algorithm, which includes cyclical references.</p><p>Following JavaScript entities that don’t work with structured clone algorithm (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#Things_that_dont_work_with_structured_clone">Documentations</a>)</p><ul><li>Error</li><li>Function</li><li>DOM nodes</li></ul><h3>Using transferable</h3><p>Recently, few browsers have the support for message passing via transferring ownership, rather than making a duplicate object while message passing. This results in huge performance improvement for large data sets. This is similar to pass by reference.</p><p>Once the object is transferred to the other context, it can no longer be accessed in the current context. The object passed is cleared in the current context. If we try to access the object, an empty object is returned (without any error). <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">MessagePort</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap">ImageBitmap</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas">OffscreenCanvas</a> implement the transferrable interface.</p><h4>Browser support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESSx7FffD0HkhS6T9jlGjw.png" /><figcaption>Link: <a href="https://caniuse.com/#feat=mdn-api_transferable">https://caniuse.com/#feat=mdn-api_transferable</a></figcaption></figure><p>For more, please refer</p><ul><li>Mozilla <a href="https://developer.mozilla.org/en-US/docs/Web/API/Transferable">Documentation</a></li><li><a href="https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast">Transferable Objects: Lightning Fast</a></li><li><a href="https://www.joji.me/en-us/blog/performance-issue-of-using-massive-transferable-objects-in-web-worker/">Performance issue of using massive transferable objects in Web Worker</a></li></ul><h3>Using SharedArrayBuffer</h3><p>This approach combines the best of the above two approaches. This can be used to share the object (only the buffer is shared) between the main thread and multiple Web workers. Also, at the same time the object is not copied while message passing. This construct allows us to create views on shared, typed memory.</p><p>Both the main thread and the worker thread can access the same chunk of memory for both reading and writing at the same time. This could lead to race conditions. This is discussed in more detail in the following section.</p><h4>Browser support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rq0e06riiPQc9YZtj5AawQ.png" /><figcaption>LInk: <a href="https://caniuse.com/#feat=sharedarraybuffer">https://caniuse.com/#feat=sharedarraybuffer</a></figcaption></figure><p>For more, please refer</p><ul><li><a href="https://hacks.mozilla.org/2017/06/a-cartoon-intro-to-arraybuffers-and-sharedarraybuffers/">Introduction to how SharedArrayBuffer works</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">MDN Documentation</a></li><li><a href="https://lucasfcosta.com/2017/04/30/JavaScript-From-Workers-to-Shared-Memory.html">Introduction to Shared Memory in JS</a></li></ul><h3>Race conditions in shared Array Buffer and atomics</h3><p>In SharedArrayBuffer, the same chunk of memory can be accessed by different contexts (or threads) for reading and writing. This can lead to race conditions. This can be solved by atomics. Atomics ensure that we can read and write data in a predictable order. It allows locking mechanism while accessing the variable to protect it from other threads.</p><p>Some of the supported built-in methods:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wait">Atomics.wait</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wake">Atomics.wake</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/compareExchange">Atomics.compareExchange</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/store">Atomics.store</a></li></ul><p>For more, please refer</p><ul><li><a href="https://hacks.mozilla.org/2017/06/avoiding-race-conditions-in-sharedarraybuffers-with-atomics/">Avoiding race conditions using atomics</a></li><li><a href="https://weekly-geekly.github.io/articles/332194/index.html">Race streams and atomics</a></li><li><a href="https://medium.com/@SitePen/the-return-of-sharedarraybuffers-and-atomics-a254032e00a6">Return of sharedArrayBuffer and atomics</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics">MDN Documentation</a></li></ul><h3>Message Channel and Inter worker communication</h3><p>The communication between Web workers can be done via messageChannel.</p><p>Following are the steps in high level</p><ul><li>Create a message channel</li><li>Have two ports (port1, port2) that can be used by the sendingWorker and receivingWorker respectively.</li><li>Send the channel port using transferrable to both the worker</li><li>In the sendingWorker onMessage (self.onMessage), use port1.postMessage to pass the messages.</li><li>In the receivingWorker onMessage (self.onmessage), use port2.onMessage to receive the buffered messages.</li></ul><p>Refer these documents for more information</p><ul><li><a href="https://2ality.com/2017/01/messagechannel.html">Communication using Message Channel</a>.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel">MDN Documentation for MessageChannel</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API">MDN Documentation for MessageChanneling API</a></li></ul><h3>Worker Pool</h3><p>This is similar to the Thread Pool concept, to create a pool of workers and use the worker from the pool when required. This is not supported natively in javascript. Needs to be implemented manually.</p><p>Following are the steps involved:</p><ul><li>Define number of workers that would be needed for the processing</li><li>Have a class for the worker pool that creates the specified number of web workers and stores it.</li><li>Whenever required, ask for an idle worker from the pool and execute the task. After the task is done, return it to the worker pool.</li></ul><p>To know the maximum numbers of thread that can be used on user’s system, use <strong><em>window.navigator.hardwareConcurrency property</em></strong>.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency">MDN Documentation</a></li><li>Browser support</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBGRl7j4BqIwa3VT7c2X-w.png" /><figcaption>LInk: <a href="https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency">https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency</a></figcaption></figure><h3>Measuring performance in Web worker (using chrome tracing)</h3><p>Please refer my other medium post for this: <a href="https://medium.com/@subhasmitasahoo.247/measuring-web-worker-performance-c27ccdf9c176">Measuring Web Worker Performance</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5692a86765e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring Web Worker Performance]]></title>
            <link>https://medium.com/@subhasmitasahoo.247/measuring-web-worker-performance-c27ccdf9c176?source=rss-a633e438814f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27ccdf9c176</guid>
            <category><![CDATA[chrome-developer-tools]]></category>
            <category><![CDATA[javascript-performance]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Subhasmita Sahoo]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 13:24:58 GMT</pubDate>
            <atom:updated>2020-08-02T13:24:58.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Profiling steps using chrome tracing:</h3><ul><li>start a new session of Chrome by starting Chrome with — user-data-dir=/tmp/tmp-chrome-session command line flag.</li><li>Navigate to the Web page for which you want to measure performance and prepare to start the workload (but don’t start it yet).</li><li>In a new tab navigate to “chrome://tracing”</li><li>Press the “Record” button</li><li>Select “Javascript and rendering” radio button</li><li>Press “Edit categories” and select “v8.gc” and “v8.runtime_stats”</li><li>Press the “Record” button</li><li>Go back to your web page (using Web worker) and start the workload</li><li>Once workload completes, go to the tracing tab and press “Stop”</li><li>Save the trace and analyse the performance.</li></ul><h4>For Shared Worker</h4><ul><li>Use <strong><em>chrome://inspect/#workers</em></strong></li><li>This opens a window displaying the active shared workers and service workers in the browser</li><li>Click on the <strong><em>inspect</em></strong> button for displaying the particular worker. On clicking it opens up a display the same as the developer console.</li></ul><h4>Using Chrome Task Manager</h4><ul><li>Chrome manager shows the memory footprint, CPU usage, Network, process Id for each tab.</li><li>To open: <em>Chrome -&gt; More Tools -&gt; Task Manager</em></li><li><a href="https://bugs.chromium.org/p/chromium/issues/detail?id=572225">Reference</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27ccdf9c176" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>