<?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"><channel><title><![CDATA[Rohit Kadam — Code & Beyond]]></title><description><![CDATA[Rohit Kadam — Code & Beyond]]></description><link>https://rohitkadam.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 04 Nov 2026 17:58:50 GMT</lastBuildDate><atom:link href="https://rohitkadam.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Agentic AI: From Chatbot to Action-Hero]]></title><description><![CDATA[A beginner-friendly guide to building smart AI agents using the ReAct technique.]]></description><link>https://rohitkadam.hashnode.dev/agentic-ai-from-chatbot-to-action-hero</link><guid isPermaLink="true">https://rohitkadam.hashnode.dev/agentic-ai-from-chatbot-to-action-hero</guid><category><![CDATA[genai]]></category><category><![CDATA[agentic AI]]></category><category><![CDATA[react-agents]]></category><dc:creator><![CDATA[Rohit Kadam]]></dc:creator><pubDate>Tue, 23 Sep 2025 08:08:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758614797765/baaf9994-42c7-407b-bba3-48c1762c7e7c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction-when-simple-chatbots-arent-enough">Introduction: When Simple Chatbots Aren’t Enough</h2>
<p>Imagine you’ve built a chatbot using OpenAI’s language model. This chatbot is smart—it can understand questions in English and answer with helpful information. But there’s a catch: the chatbot only knows what was in its training data. It’s like having a super-intelligent librarian who knows every book in the library, but nothing about what’s happening outside right now.</p>
<p>Let’s say you ask it,</p>
<blockquote>
<p><em>“Do I need an umbrella to go to the office today in Pune?”</em></p>
</blockquote>
<p>The chatbot understands you want weather advice, but unless it has live weather data, it can’t help. Training the model to know every update about the world would be impossible—and would make the model huge and slow to update!</p>
<p>This limitation isn’t just with chatbots. Our own brains work the same way. If someone asks, “Do I need an umbrella for Pune today?”—without checking the weather app or stepping outside, it’s just a guess.</p>
<p>So, how do we build chatbots that can help with real-world, everyday questions? We let them use tools—just like we use apps or search engines.</p>
<h3 id="heading-meet-agentic-ai-the-next-step">Meet Agentic AI: The Next Step</h3>
<p>Now, picture an AI that’s more like an assistant than a parrot. This AI can:</p>
<ul>
<li><p>Understand your question using the language model’s skills.</p>
</li>
<li><p>Decide which tools (like a weather website, calculator, or map) it should use to fetch the answer.</p>
</li>
<li><p>Read the results, make sense of them, and reply in natural, friendly language.</p>
</li>
</ul>
<p>This is called an <strong>Agent</strong> in AI.</p>
<p><strong>Agent = LLM + Tools</strong></p>
<ul>
<li><p>The LLM (Large Language Model) is good at understanding and talking.</p>
</li>
<li><p>The tools are extra resources—apis, search engines, calculators, anything that fetches fresh data or does tasks.</p>
</li>
</ul>
<p><strong>Real-life analogy:</strong></p>
<p>Think of the agent as a friend who’s great with words (LLM), but also carries a smartphone loaded with useful apps (tools). When you ask her about today’s weather, she checks her weather app before answering.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1758623017131/dbea7eb6-79f5-4596-a074-bb65c3ab0ed1.png" alt class="image--center mx-auto" /></p>
<p><strong>Why Agents Matter</strong></p>
<p>Agents solve the biggest limitation in LLMs: They connect “knowing how to talk” with “being able to do.” By combining LLMs with tools, your chatbot stops being just a talker and becomes a true doer. It’s like giving your chatbot a Swiss army knife.</p>
<hr />
<h2 id="heading-lets-build-budget-manager-agent-with-react">Let’s Build: Budget Manager Agent (with ReAct)</h2>
<p>Suppose the chatbot now acts like a smart financial assistant. You ask:</p>
<blockquote>
<p><em>“Can you increase my groceries budget by 5000?”</em></p>
</blockquote>
<p>A plain chatbot can understand the request but might not know your current budget, nor can it update anything in real life. An agent, however, solves this by thinking step-by-step and using tools—just how people work out their budgets with a calculator or spreadsheet.</p>
<p>Let’s see how such an agent works from scratch, using the ReAct technique.</p>
<p><strong>What is ReAct? The “Think, Act, Observe” Way</strong></p>
<p>ReAct stands for <strong>Reasoning</strong> <strong>+ Acting.</strong></p>
<p>Instead of going straight to the final answer, the AI:</p>
<ul>
<li><p><strong>Thinks</strong> about the problem, breaking it into simple pieces.</p>
</li>
<li><p><strong>Acts</strong> by using tools like a calculator, database, or search engine.</p>
</li>
<li><p><strong>Observes</strong> the results, learns from new info, and continues until done.</p>
</li>
</ul>
<p>It loops through these gears again and again, just like a person does when managing a budget.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1758521841630/ed19110e-6274-4825-a5d2-9276d69d67f9.png" alt class="image--center mx-auto" /></p>
<p><strong>Example of ReAct prompting</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>User Prompt</strong></td><td><em>Can you increase my groceries budget by 5000?</em></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Thought</strong></td><td>I need to first check the current amount of the groceries budget before adding 5000rs.</td></tr>
<tr>
<td><strong>Action</strong></td><td>getBudget(“groceries”)</td></tr>
<tr>
<td><strong>Observation</strong></td><td>{"name":"groceries","amount":10000}</td></tr>
<tr>
<td><strong>Thought</strong></td><td>The current groceries budget is 10000rs. I will now update it to add 5000rs more.</td></tr>
<tr>
<td><strong>Action</strong></td><td>updateBudget(“groceries”, 15000)</td></tr>
<tr>
<td><strong>Observation</strong></td><td>Budget updated successfully</td></tr>
<tr>
<td><strong>Final Answer</strong></td><td>The groceries budget has been successfully updated to 15000rs.</td></tr>
</tbody>
</table>
</div><p>ReAct agents execute sequentially:</p>
<blockquote>
<p>Think → Act → Observe → Repeat.</p>
</blockquote>
<p><strong>Why Use ReAct Agents?</strong></p>
<ul>
<li><p><strong>No guessing!</strong> Agents don’t jump to answers—they gather info, do calculations, and double-check using tools.</p>
</li>
<li><p><strong>Just like humans</strong>: Think about how you’d budget for the month. First, you check what you spent, then decide what to add, and maybe use a calculator or app.</p>
</li>
<li><p><strong>Flexible for all scenarios:</strong> From adding to a grocery budget to planning for a holiday or tracking project expenses, agents can loop through steps with any tools you provide</p>
</li>
</ul>
<p>Imagine giving your chatbot access to:</p>
<ul>
<li><p>Spreadsheets or financial APIs</p>
</li>
<li><p>Calculators for quick math</p>
</li>
<li><p>Databases for storing and fetching budgets</p>
</li>
</ul>
<p>The ReAct agent calls the tools as needed, then returns easy-to-understand answers in natural language.</p>
<hr />
<h2 id="heading-coding-the-budget-manager-agent">Coding the Budget Manager Agent:</h2>
<h3 id="heading-1-setting-up-imports-and-initialization">1. Setting Up: Imports and Initialization</h3>
<p>Start by loading important modules and setting up an in-memory store for budgets:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import necessary modules and configuration</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"dotenv/config"</span>;
<span class="hljs-keyword">import</span> { OpenAI } <span class="hljs-keyword">from</span> <span class="hljs-string">"openai"</span>;

<span class="hljs-comment">// This will hold all our budgets (like a little database in memory)</span>
<span class="hljs-keyword">const</span> budgetTable = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">"groceries"</span>, <span class="hljs-number">10000</span>]]);

<span class="hljs-comment">// Create a openAI object, you can use gemini key and baseURL</span>
<span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({
  <span class="hljs-attr">apiKey</span>: process.env[<span class="hljs-string">"OPENAI_API_KEY"</span>]
});
</code></pre>
<h3 id="heading-2-budget-tools-basic-functions">2. Budget Tools: Basic Functions</h3>
<p>These functions help the agent create, update, fetch, or delete budgets. Each one focuses on a single job to keep things tidy.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add a new budget</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createBudget</span>(<span class="hljs-params">name, amount</span>) </span>{
  <span class="hljs-keyword">if</span> (budgetTable.has(name)) <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget is already created"</span>;
  budgetTable.set(name, amount);
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget added successfully"</span>;
}

<span class="hljs-comment">// Get a budget by name</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBudget</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">if</span> (!budgetTable.has(name)) <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget not found"</span>;
  <span class="hljs-keyword">const</span> amount = budgetTable.get(name);
  <span class="hljs-keyword">return</span> { name, amount };
}

<span class="hljs-comment">// Get all budgets</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllBudget</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>.fromEntries(budgetTable);
}

<span class="hljs-comment">// Update a named budget</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateBudget</span>(<span class="hljs-params">name, newAmount</span>) </span>{
  <span class="hljs-keyword">if</span> (!budgetTable.has(name)) <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget not found"</span>;
  budgetTable.set(name, newAmount);
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget updated successfully"</span>;
}

<span class="hljs-comment">// Delete a budget by name</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteBudget</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">if</span> (!budgetTable.has(name)) <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget not found"</span>;
  budgetTable.delete(name);
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Budget deleted successfully"</span>;
}
</code></pre>
<h3 id="heading-3-tool-selector">3. Tool Selector</h3>
<p>A simple object lets the agent call the right function for each action the LLM asks for.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> TOOLS = {
  createBudget,
  getBudget,
  getAllBudget,
  updateBudget,
  deleteBudget,
};

<span class="hljs-comment">// Helper to run the requested action</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleActionCalling</span>(<span class="hljs-params">action, name, amount</span>) </span>{
  <span class="hljs-keyword">const</span> actionCallback = TOOLS[action];
  <span class="hljs-keyword">if</span> (!actionCallback) <span class="hljs-keyword">return</span> <span class="hljs-string">"No such action available"</span>;
  <span class="hljs-keyword">return</span> actionCallback(name, amount);
}
</code></pre>
<h3 id="heading-4-system-message-for-the-agent">4. System Message for the Agent</h3>
<p>Here, describe how the ReAct process works. This prompt guides the AI step-by-step.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> SystemPrompt = <span class="hljs-string">`
You are an AI Assistant that run in loop of THINK, ACTION, and OBSERVATION state.
At the end of the loop you OUTPUT an answer.
Use Action to run one of the actions available to you - then wait till observation.
Observation will be the result of the running those actions.
Perform the task step by step, One step at a time
Output will be in form of json

Your available actions are:
- createBudget:
  This action will create new budget if not exist. You will need to provide name: budget name, amount: budget amount

- getBudget
  This action will return budget amount if exist. You will need to provide budget name

- getAllBudget
  This action will return all the budget user has created.

- updateBudget
  This action will update the existing budget amount. You will need to provide budget name

- deleteBudget
  This action will delete the existing budget, You will need to provide budget name

Example session
{ "state": "input",  "input":  "Create a new dining out budget of ₹5000. Give me the sum of the groceries and dining budgets."}
{ "state": "thought", "thought": "I will need to first create new budget of 5000 for dining" }
{ "state": "action", "action": "createBudget", "name": "dining", "amount": 5000 }
{ "state": "observation", "observation": "Budget added successfully" }
{ "state": "thought", "thought": "I will need to get budget amount for groceries" }
{ "state": "action", "action": "getBudget", "name": "groceries" }
{ "state": "observation", "observation": "{'name': 'groceries', 'amount': 10000 }" }
{ "state": "thought", "thought": "As I have budget of both groceries and dining, so now I can answer the user input" }
{ "state": "output" , "output": "The total budget of groceries and dining is 15000rs "}
`</span>;
</code></pre>
<h3 id="heading-5-tracking-the-conversation">5. Tracking the Conversation</h3>
<p>Keep all messages and events (both user and model responses) in a history array: Help the mode to memory the history conversation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> chatHistory = [
  { <span class="hljs-attr">role</span>: <span class="hljs-string">"system"</span>, <span class="hljs-attr">content</span>: SystemPrompt }
];
</code></pre>
<h3 id="heading-6-the-main-agent-loop">6. The Main Agent Loop</h3>
<p>This function runs the agent. It lets the LLM think, decide on actions, see what happens, and repeat until it’s ready with a final answer.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">agentAI</span>(<span class="hljs-params">userMessage</span>) </span>{
  <span class="hljs-comment">// Step one: add the user's question</span>
  chatHistory.push({
    <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>,
    <span class="hljs-attr">content</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">step</span>: <span class="hljs-string">"input"</span>, <span class="hljs-attr">input</span>: userMessage }),
  });

  <span class="hljs-comment">// The main loop: Think → Act → Observe → Repeat</span>
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> openai.chat.completions.create({
      <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4o-mini"</span>, <span class="hljs-comment">// Choose your GPT model here</span>
      <span class="hljs-attr">messages</span>: chatHistory,
      <span class="hljs-attr">response_format</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">"json_object"</span> },
    });

    <span class="hljs-comment">// Save what the model said next</span>
    <span class="hljs-keyword">const</span> botMessage = response.choices[<span class="hljs-number">0</span>].message.content;
    chatHistory.push({ <span class="hljs-attr">role</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-attr">content</span>: botMessage });

    <span class="hljs-comment">// Figure out what step we’re on</span>
    <span class="hljs-keyword">const</span> step = <span class="hljs-built_in">JSON</span>.parse(botMessage);

    <span class="hljs-keyword">if</span> (step.state === <span class="hljs-string">"output"</span>) {
      <span class="hljs-comment">// Task is done!</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FINAL OUTPUT: "</span>, step);
      <span class="hljs-keyword">break</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (step.state === <span class="hljs-string">"action"</span>) {
      <span class="hljs-comment">// Time to use a tool (like updating or looking up a budget)</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"STEP: "</span>, step);
      <span class="hljs-keyword">const</span> observation = handleActionCalling(
        step.action,
        step.name,
        step.amount
      );
      <span class="hljs-comment">// Report what happened back to the agent</span>
      <span class="hljs-keyword">const</span> observationStep = <span class="hljs-built_in">JSON</span>.stringify({
        <span class="hljs-attr">step</span>: <span class="hljs-string">"observation"</span>,
        observation,
      });
      chatHistory.push({
        <span class="hljs-attr">role</span>: <span class="hljs-string">"developer"</span>,
        <span class="hljs-attr">content</span>: observationStep,
      });
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Any other info (thoughts)</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"STEP: "</span>, step);
    }
  }
}
</code></pre>
<h3 id="heading-7-running-the-agent">7. Running the Agent</h3>
<p>Give it a try by asking to increase the groceries budget:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">await</span> agentAI(<span class="hljs-string">"Can you increase my groceries budget by 5000?"</span>);
</code></pre>
<p><strong>Code Output</strong></p>
<blockquote>
<p>STEP: { state: 'thought', thought: 'I need to first check the current amount of the groceries budget before adding 5000rs.' }<br />STEP: { state: 'action', action: 'getBudget', name: 'groceries' }<br />STEP: {"step":"observation","observation":{"name":"groceries","amount":10000}}<br />STEP: { state: 'thought', thought: 'The current groceries budget is 10000rs. I will now update it to add 5000rs more.' }<br />STEP: { state: 'action', action: 'updateBudget', name: 'groceries', amount: 15000 }<br />STEP: {"step":"observation","observation":"Budget updated successfully"}<br />FINAL OUTPUT: { state: 'output', output: 'The groceries budget has been successfully updated to 15000rs.' }</p>
</blockquote>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Using the ReAct technique to build an agentic AI, like our budget manager, shows how AI can think, act, and learn step-by-step. This makes the AI much more flexible and practical, able to use tools to get up-to-date data and solve real problems.</p>
<p>By combining language understanding with tool usage, developers can create smarter assistants for many tasks, from managing finances to customer support. Keep exploring these ideas to build powerful AI agents that truly help users in everyday life.</p>
]]></content:encoded></item><item><title><![CDATA[Build Your Own AI Chatbot with JavaScript]]></title><description><![CDATA[A Beginner’s Guide to Using OpenAI and Gemini Models]]></description><link>https://rohitkadam.hashnode.dev/build-your-own-ai-chatbot-with-javascript</link><guid isPermaLink="true">https://rohitkadam.hashnode.dev/build-your-own-ai-chatbot-with-javascript</guid><category><![CDATA[genai]]></category><category><![CDATA[openai]]></category><category><![CDATA[beginner]]></category><category><![CDATA[#LearnByDoing]]></category><dc:creator><![CDATA[Rohit Kadam]]></dc:creator><pubDate>Tue, 09 Sep 2025 19:47:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757447652253/b7c14b11-028e-4391-bfec-4d708882b8cb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the previous session, we explored various prompting techniques. Now, let’s put those ideas into action by building a chatbot from scratch. This chatbot will use the prompting skills we’ve picked up before – and you’ll see how easy it is to get started. No matter which programming language you know, if it supports REST API calls, you can build a chatbot. Here, we’ll focus on JavaScript as our main tool.</p>
<p>To power the chatbot’s intelligence, we’ll call modern LLM APIs, like OpenAI (paid, recommend) or Gemini (often has a free tier). All sample code works with both models, so pick whichever suits you best.</p>
<p>In JavaScript, we can use raw REST fetch requests or take the easier route with packages like the official Let’s Code<code>openai</code> library. This not only supports OpenAI, but you can adapt similar code to other models like Gemini and DeepSeek</p>
<hr />
<h2 id="heading-what-youll-need">What You’ll Need</h2>
<ul>
<li><p>Basic knowledge of Javascript.</p>
</li>
<li><p>An API key from <a target="_blank" href="https://platform.openai.com/api-keys">OpenAI</a> (get $5 credits for a start) or a free <a target="_blank" href="https://aistudio.google.com/app/apikey">Gemini</a> model key.</p>
</li>
<li><p>Node.js</p>
</li>
</ul>
<hr />
<h2 id="heading-lets-write-the-code">Let’s Write the Code</h2>
<p>First, install the OpenAI package we’ll use to communicate with the AI:</p>
<pre><code class="lang-bash">npm install openai
</code></pre>
<p>Let create an Agent, The Agent is your chatbot’s brain — an object that will send and receive messages.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { OpenAI } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"openai"</span>)

<span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({
    <span class="hljs-comment">// Replace with your actual API key stored in .env</span>
    <span class="hljs-attr">apiKey</span>: process.env.OPENAI_API_KEY,
})
</code></pre>
<p>Now we have created an OpenAI agent, which will communicate with OpenAI models.</p>
<p>Next, let’s send messages to the agent. We will create a function that sends the user’s input to the chatbot and gets the response. We will be using <code>gpt-4o-mini</code> model but you can try any model provide by the openAI</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMessage</span>(<span class="hljs-params">userMessage</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4o-mini"</span>,
    <span class="hljs-attr">messages</span>: [{ <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: userMessage }],
  });

  <span class="hljs-comment">// Return the bot's reply</span>
  <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].message.content;
}
</code></pre>
<p>That’s it! You can call this function with a message, and it will return the model’s response.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> botReply = <span class="hljs-keyword">await</span> sendMessage(<span class="hljs-string">"Hello, my name is Rohit."</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Bot reply: <span class="hljs-subst">${botReply}</span>`</span>);
<span class="hljs-comment">// Bot reply: Hello, Rohit! How can I assist you today?</span>
</code></pre>
<p>We’ll pause here so you can try this code.</p>
<hr />
<h3 id="heading-questions-you-might-have">Questions You Might Have**…**</h3>
<ul>
<li><p>Is this all there is to building a chatbot?</p>
</li>
<li><p>Why do we use <code>role: "user"</code> in the message?</p>
</li>
<li><p>Can the model remember what I said earlier?</p>
</li>
<li><p>And many more…</p>
</li>
</ul>
<p>Let’s answer these as we move on.</p>
<hr />
<h2 id="heading-understanding-chat-message-roles">Understanding Chat Message Roles</h2>
<p>When chatting with the LLM model, every message has a role to tell the model who is speaking.</p>
<p>There are four types of roles:</p>
<ul>
<li><p><strong>System</strong><br />  This message gives instructions on how the model should behave, including tone, personality, or special rules. It should be the first message sent to the model.</p>
</li>
<li><p><strong>Developer</strong><br />  These are instructions from the app developer. They provide system rules or business logic, like function definitions.</p>
</li>
<li><p><strong>User</strong><br />  Messages from the end user. These are inputs or questions.</p>
</li>
<li><p><strong>Assistant</strong><br />  Replies generated by the model.</p>
</li>
</ul>
<p>Let’s tell the AI to be friendly and give it a name:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMessage</span>(<span class="hljs-params">userMessage</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4o-mini"</span>,
    <span class="hljs-attr">messages</span>: [
      { 
        <span class="hljs-attr">role</span>: <span class="hljs-string">"system"</span>, 
        <span class="hljs-attr">content</span>: <span class="hljs-string">"You are a friendly assistant named Alexa"</span> 
      },
      { <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: userMessage },
    ],
  });

  <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].message.content;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">await</span> sendMessage(<span class="hljs-string">"Hi, I'm Rohit. What's yours?"</span>));
<span class="hljs-comment">// Hi Rohit! I’m Alexa. How can I assist you today?</span>
</code></pre>
<blockquote>
<p>We can’t just use a user role as a system role because the system role has higher priority. The system prompt tells the LLM which instructions should never be changed, even if the user tries to override them. For example, if we set in the system prompt: “Your name is Alexa, and this cannot be changed,” then the model will always follow that, no matter what the user says.</p>
</blockquote>
<hr />
<h2 id="heading-making-your-chatbot-remember">Making Your Chatbot Remember</h2>
<p>Right now, your chatbot can answer questions — but it has no memory of what was said before.</p>
<p>For example, try this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">await</span> sendMessage(<span class="hljs-string">"Hi, I'm Rohit. What's yours?"</span>));
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">await</span> sendMessage(<span class="hljs-string">"Do you remember my name?"</span>));

<span class="hljs-comment">// Hello, Rohit! I'm Alexa. How can I assist you today?</span>
<span class="hljs-comment">// I don’t actually have the ability to remember names.</span>
</code></pre>
<p>You’ll notice that the second response doesn’t remember your name.</p>
<p>That’s because <strong>LLMs are stateless</strong> — they don’t automatically keep track of previous messages.</p>
<p>So, to make your chatbot feel smarter, we need to give it memory by <strong>saving previous messages</strong> and sending them back to the model along with new ones.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Store conversation history here</span>
<span class="hljs-keyword">const</span> chatHistory = [{ 
    <span class="hljs-attr">role</span>: <span class="hljs-string">"system"</span>, 
    <span class="hljs-attr">content</span>: <span class="hljs-string">"You are a friendly assistant named Alexa"</span> 
}];

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMessage</span>(<span class="hljs-params">userMessage</span>) </span>{
  <span class="hljs-comment">// Add user message to history</span>
  chatHistory.push({ <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: userMessage });

  <span class="hljs-comment">// Send full history to the model</span>
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4o-mini"</span>,
    <span class="hljs-attr">messages</span>: chatHistory,
  });

  <span class="hljs-comment">// Add assistant reply to history</span>
  <span class="hljs-keyword">const</span> botMessage = response.choices[<span class="hljs-number">0</span>].message.content;
  chatHistory.push({ <span class="hljs-attr">role</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-attr">content</span>: botMessage });

  <span class="hljs-keyword">return</span> botMessage;
}
</code></pre>
<p>Now, if you ask the bot if it remembers your name, it will, thanks to the <strong>chat history</strong>!<br /><em>We’ll explore memory in more depth in the future.</em></p>
<hr />
<h2 id="heading-using-gemini-models-with-the-same-code">Using Gemini Models with the Same Code</h2>
<p>If you want to try Google’s Gemini models instead of OpenAI, you only need to make a couple of changes – the rest of your chatbot code stays almost the same!</p>
<p>when creating your agent, switch in your <a target="_blank" href="https://aistudio.google.com/app/apikey">Gemini API key</a> and set a special base URL for Gemini:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({
  <span class="hljs-comment">// Use gemini api key</span>
  <span class="hljs-attr">apiKey</span>: process.env.GEMINI_API_KEY,
  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://generativelanguage.googleapis.com/v1beta/openai/"</span>,
});
</code></pre>
<p>Now, whenever you call the <a target="_blank" href="http://openai.chat"><code>openai.chat</code></a><code>.completions.create</code> function, simply use a Gemini model name, such as <code>"gemini-2.5-flash"</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMessage</span>(<span class="hljs-params">userMessage</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    <span class="hljs-attr">model</span>: <span class="hljs-string">"gemini-2.5-flash"</span>, <span class="hljs-comment">//  &lt;&lt;&lt;&lt; use gemini models</span>
    <span class="hljs-attr">messages</span>: [{ <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: userMessage }],
  });

  <span class="hljs-comment">// Return the bot's reply</span>
  <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].message.content;
}
</code></pre>
<p>That’s it! You can swap models as needed (OpenAI or Gemini) just by changing the API key, baseURL, and model name.</p>
<hr />
<h2 id="heading-wrapping-up-your-chatbot-journey">Wrapping Up Your Chatbot Journey</h2>
<p>Awesome! ✨ You’ve just created your own AI-powered chatbot using JavaScript and modern language models like OpenAI. We covered the basics from setup to writing code that sends messages, handles conversation roles, and even remembers chat history.</p>
<p>Try writing your own chatbot code following the steps we covered, and experiment with different prompts and models.</p>
<p><strong>Happy coding — your AI journey is just beginning!</strong></p>
]]></content:encoded></item><item><title><![CDATA[Beyond Basics: Advanced RAG Patterns and Pipelines for Production-Ready AI]]></title><description><![CDATA[Retrieval-Augmented Generation (RAG) has quickly become the go-to approach for building AI applications that combine large language models (LLMs) with…]]></description><link>https://rohitkadam.hashnode.dev/advanced-rag-patterns</link><guid isPermaLink="true">https://rohitkadam.hashnode.dev/advanced-rag-patterns</guid><category><![CDATA[genai]]></category><dc:creator><![CDATA[Rohit Kadam]]></dc:creator><pubDate>Fri, 22 Aug 2025 15:24:33 GMT</pubDate><content:encoded><![CDATA[<h3>Introduction: Why Go Beyond Basic RAG?</h3>
<p>Retrieval-Augmented Generation (RAG) has quickly become the go-to approach for building AI applications that combine large language models (LLMs) with external knowledge. It powers chatbots, search, analytics, and assistants that stay grounded in facts.</p>
<p>But as soon as you move from a simple demo to a production system, new challenges emerge:</p>
<ul>
<li>How do you scale retrieval without slowing down responses?</li>
<li>How do you reduce hallucinations when your documents are noisy or incomplete?</li>
<li>How do you trade off accuracy against latency?</li>
</ul>
<p>This post explores <strong>advanced RAG patterns and pipelines</strong> that we learned in class — practical strategies to take your RAG system from a prototype to a production-grade knowledge engine.</p>
<hr />
<h3>1. Scaling RAG Systems</h3>
<p>A simple RAG pipeline has two steps: retrieve documents and generate answers. In practice, scaling means:</p>
<ul>
<li>Using <strong>sharded vector stores</strong> to handle millions of documents.</li>
<li>Adding <strong>query caches</strong> to avoid repeatedly running expensive retrievals.</li>
<li>Using <strong>asynchronous parallel retrievals</strong> across multiple indexes (structured + unstructured).</li>
</ul>
<p>Think of it as building lanes on a highway: the wider the lanes, the more queries can flow without traffic jams.</p>
<hr />
<h3>2. Accuracy vs Speed: Finding Balance</h3>
<p>Every production system faces a <strong>latency vs quality trade-off</strong>.</p>
<ul>
<li><strong>Higher recall (fetching more documents)</strong> improves accuracy but slows things down.</li>
<li><strong>Smaller retrieval sets</strong> make responses faster but risk missing context.</li>
</ul>
<p>A common trick is <strong>progressive retrieval</strong>: start with fewer docs for speed, and only expand if confidence is low.</p>
<hr />
<h3>3. Query Translation &amp; Sub-Query Rewriting</h3>
<p>Users don’t always ask questions the way your system expects. That’s where <strong>query rewriting</strong> comes in.</p>
<ul>
<li><strong>Query Translation</strong>: Convert natural questions into structured query forms for databases or APIs.</li>
<li><strong>Sub-Query Decomposition</strong>: Break complex questions into smaller queries and stitch results back together.</li>
</ul>
<p>🔎 Example:</p>
<blockquote>
<p>“Compare Tesla’s revenue growth with GM’s R&amp;D spending in the last 3 years.”<br />Instead of one big retrieval, the system reformulates into <strong>two sub-queries</strong> and aggregates.</p>
</blockquote>
<hr />
<h3>4. Using LLM as an Evaluator</h3>
<p>Instead of blindly trusting retrieval, you can let the <strong>LLM act as a critic</strong>:</p>
<ul>
<li>Rank retrieved passages by relevance.</li>
<li>Filter out off-topic results.</li>
<li>Score answers before sending them to the user.</li>
</ul>
<p>Think of it like having a second set of eyes proofreading before the final draft.</p>
<hr />
<h3>5. Ranking Strategies and HyDE</h3>
<p>Retrieval quality is as much about <strong>ranking</strong> as it is about retrieval.</p>
<ul>
<li><strong>Traditional Ranking</strong>: based on cosine similarity in vector space.</li>
<li><strong>Hybrid Strategies</strong>: combine keyword search + dense embeddings.</li>
<li><strong>HyDE (Hypothetical Document Embeddings)</strong>: Ask the LLM to “imagine” a likely answer, embed it, and use that as the query for retrieval. This often pulls in better-contextual documents.</li>
</ul>
<hr />
<h3>6. Corrective RAG</h3>
<p>What if the initial retrieval fails? Corrective RAG introduces a feedback loop where the LLM can say:</p>
<ul>
<li>“I don’t have enough info; let me reformulate the query.”</li>
<li>Re-run retrieval with refined queries.</li>
</ul>
<p>This is like asking follow-up questions during a conversation until you have enough context to give a solid answer.</p>
<hr />
<h3>7. Caching for Speed</h3>
<p>Retrieval and generation are expensive. Smart caching saves cost and latency:</p>
<ul>
<li><strong>Query-level caching</strong>: Store embeddings for common queries.</li>
<li><strong>Document-level caching</strong>: Frequently retrieved docs don’t need recomputation.</li>
<li><strong>Response caching</strong>: Save final answers when queries repeat.</li>
</ul>
<hr />
<h3>8. Contextual Embeddings &amp; Hybrid Search</h3>
<p>Not all embeddings are equal. Improving embedding generation can boost retrieval dramatically:</p>
<ul>
<li><strong>Contextual Embeddings</strong>: Use richer prompt-based embeddings that capture query intent.</li>
<li><strong>Hybrid Search</strong>: Blend vector search with keyword/semantic filters. For example, combine <strong>BM25</strong> for exact matches with <strong>embeddings</strong> for fuzzy matching.</li>
</ul>
<hr />
<h3>9. GraphRAG: Knowledge as a Network</h3>
<p>Instead of treating documents as flat text, <strong>GraphRAG</strong> builds a graph where entities (people, orgs, events) are nodes and relationships are edges. Retrieval then becomes reasoning over connections, not just keyword matches.</p>
<p>Imagine asking: <em>“Who partnered with Tesla in battery technology last year?”</em> — GraphRAG fetches not only Tesla documents but also links partnerships across multiple sources.</p>
<hr />
<h3>10. Production-Ready Pipelines</h3>
<p>Putting it all together for real-world deployment:</p>
<ol>
<li><strong>Multi-stage Pipelines</strong>: Query rewriting → retrieval → ranking → LLM scoring → generation.</li>
<li><strong>Monitoring &amp; Logging</strong>: Track retrieval hit rates, response latency, and hallucination levels.</li>
<li><strong>Human-in-the-loop Feedback</strong>: Gather user ratings to continuously refine retrieval strategies.</li>
<li><strong>Continuous Index Updates</strong>: Keep knowledge bases fresh through automated ingestion.</li>
</ol>
<hr />
<blockquote>
<p>An advanced RAG pipeline combines retrieval, ranking, corrective loops, evaluation, and caching into a feedback-driven architecture for reliable outputs</p>
</blockquote>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755876178306/1ae1f806-0827-45b2-92f0-058f6eb46599.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Conclusion: From RAG to Reliable AI</h3>
<p>Basic RAG is just the starting point. With advanced patterns like <strong>HyDE, corrective feedback, caching, hybrid search, and GraphRAG</strong>, we can build <strong>scalable, accurate, and production-ready pipelines</strong> that transform retrieval from a simple lookup into intelligent knowledge orchestration.</p>
<p>The future of RAG isn’t just about finding documents — it’s about designing <strong>self-improving systems</strong> that reason, adapt, and keep users’ trust.</p>
<hr />
<p>👉 Pro Tip: Start small with one or two techniques (like caching + ranking) and expand gradually. Trying to implement everything at once can add unnecessary complexity.</p>
]]></content:encoded></item><item><title><![CDATA[Discover the Magic of Prompting]]></title><description><![CDATA[5 Essential System Prompt Techniques]]></description><link>https://rohitkadam.hashnode.dev/discover-the-magic-of-prompting</link><guid isPermaLink="true">https://rohitkadam.hashnode.dev/discover-the-magic-of-prompting</guid><category><![CDATA[genai]]></category><category><![CDATA[Prompt]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Rohit Kadam]]></dc:creator><pubDate>Fri, 15 Aug 2025 15:04:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756879110475/a7698702-54d7-48f9-91e1-0862cfe72c91.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most people use AI for small tasks: <em>“Summarize this.”</em> <em>“Explain that.”</em><br />Useful, yes—but that’s only the surface.</p>
<p>The real power comes before the answer, in the instructions that shape how the AI thinks and speaks. That’s the <strong>system prompt</strong>.</p>
<p>Think of the system prompt as quiet guidance for the AI. It quietly sets:</p>
<ul>
<li><p><strong>Who</strong> the AI is: teacher, coder, storyteller</p>
</li>
<li><p><strong>How</strong> it responds: friendly, formal, step-by-step</p>
</li>
<li><p><strong>What rules</strong> it follows: safety, limits, structure</p>
</li>
</ul>
<p>Set this once, and your AI becomes consistent, on-brand, and reliable across every task.</p>
<hr />
<h3 id="heading-the-two-layers-of-prompting">The Two Layers of Prompting</h3>
<ul>
<li><p><strong>System prompt</strong> = the guidebook (which define role, tone, boundaries, style)</p>
</li>
<li><p><strong>User prompt</strong> = the task list (what to do right now)</p>
</li>
</ul>
<p>Example system prompt</p>
<blockquote>
<p>You are a technical writer. Write in clear, simple language for beginner . Use short sentences and examples where possible. Break down steps into lists, avoid heavy jargon, and explain any acronyms. Keep each answer under 200 words.</p>
</blockquote>
<p>User Prompt</p>
<blockquote>
<p>Can you explain me about GenAI?</p>
</blockquote>
<hr />
<h2 id="heading-essential-prompting-techniques">Essential Prompting Techniques</h2>
<h3 id="heading-1-zeroshot-prompting">1) Zero‑Shot Prompting</h3>
<p>What it is: Ask the AI to do a task without giving any examples—just rely on model training.</p>
<p>When to use it</p>
<ul>
<li><p>Common tasks: summaries, lists, rewrites, extractions, sentiment</p>
</li>
<li><p>When speed matters more than precision</p>
</li>
<li><p>As a baseline before adding complexity</p>
</li>
</ul>
<p>Watch out for:</p>
<ul>
<li>Inconsistent results on specialized tasks</li>
</ul>
<p>Ready-to-use prompt:</p>
<blockquote>
<p>Summarize the text into exactly 4 bullets for a daily stand‑up. Each bullet ≤15 words. Prioritize what changed, why it matters, and next steps. If key info is missing, write ‘insufficient detail.’<br />Text: """[paste]"""”</p>
</blockquote>
<p>Tip: Add <strong>clear constraints</strong> (word counts, number of bullets, priorities) to make zero-shot prompts much more stable.</p>
<hr />
<h3 id="heading-2-fewshot-prompting">2) Few‑Shot Prompting</h3>
<p>What it is: Show the AI a few examples before asking for the real output. This helps it learn your format and tone.</p>
<p>When to use it:</p>
<ul>
<li><p>Domain‑specific output (legal, product, finance)</p>
</li>
<li><p>When consistency matters (e.g., formatting logs, writing test cases)</p>
</li>
<li><p>When zero-shot feels too random</p>
</li>
</ul>
<p>Watch out for:</p>
<ul>
<li><p>Too many examples can waste tokens</p>
</li>
<li><p>The AI may copy your examples too literally</p>
</li>
</ul>
<p>Example:</p>
<blockquote>
<p>Convert product reviews into "Positive" or "Negative."</p>
<p>Examples:<br />"I love the battery life!" → Positive<br />"Screen cracked in a week." → Negative</p>
<p>Now classify:<br />"Customer service was slow, but issue was fixed."</p>
</blockquote>
<p>Pro tip: Give <strong>2–3 diverse examples</strong> (not 10+)—enough to set the pattern without overloading.</p>
<hr />
<h3 id="heading-3-chainofthought-thinking-mode">3) Chain‑of‑Thought (Thinking Mode)</h3>
<p>What it is: Ask the AI to perform step‑by‑step reasoning before giving final answer.</p>
<p>Use it for:</p>
<ul>
<li><p>Math, logic, and step-based tasks</p>
</li>
<li><p>Debugging or explaining code</p>
</li>
<li><p>When accuracy matters more than speed</p>
</li>
</ul>
<p>Watch out for:</p>
<ul>
<li><p>Longer, slower responses</p>
</li>
<li><p>Can get verbose if not constrained</p>
</li>
</ul>
<p>Prompt:</p>
<blockquote>
<p>Think step by step, show intermediate reasoning, then give the final answer on the last line prefixed with ‘Final:’.<br />Problem: A store sold 32 apples Monday and twice as many Tuesday. How many in total?”</p>
</blockquote>
<p>Tip: Skip thinking mode for trivial tasks; enable it when accuracy matters. — Use phrases like <em>“show your work”</em> or <em>“explain step by step”</em>—they improve accuracy.</p>
<hr />
<h3 id="heading-4-self-consistency-multiple-reasoning-paths">4) Self-consistency (Multiple Reasoning Paths)</h3>
<p><strong>What it is:</strong> Instead of following a single reasoning chain, the AI explores multiple possible solution paths and then chooses the most consistent or common answer. This reduces errors from “getting stuck” in one line of thought.</p>
<p><strong>When to use it:</strong></p>
<ul>
<li><p>Complex reasoning or multi-step problems</p>
</li>
<li><p>Math, logic puzzles, or decision-making tasks</p>
</li>
<li><p>Situations where accuracy is more important than speed</p>
</li>
</ul>
<p><strong>Watch out for:</strong></p>
<ul>
<li><p>May generate longer responses (since it considers multiple paths)</p>
</li>
<li><p>Works best when you explicitly ask for “step-by-step reasoning” or “check multiple approaches”</p>
</li>
</ul>
<p><strong>Prompt:</strong><br />Solve: A store sold 32 apples Monday and twice as many Tuesday.<br />Check the answer using at least two different methods.</p>
<p><strong>Tip:</strong> Think of self-consistency like getting multiple opinions from experts—if they agree, you can trust the answer more.</p>
<hr />
<h3 id="heading-5-persona-prompting-consistent-identity-amp-voice"><strong>5) Persona Prompting (Consistent Identity &amp; Voice)</strong></h3>
<p><strong>What it is:</strong> Assign the AI a clear identity, expertise, or communication style to maintain throughout the interaction. This ensures answers are aligned with a specific role, like “experienced lawyer,” “friendly tutor,” or “tech blogger.”</p>
<p><strong>When to use it:</strong></p>
<ul>
<li><p>Customer support, coaching, or tutoring scenarios</p>
</li>
<li><p>Creating content with a consistent brand voice</p>
</li>
<li><p>Long sessions where tone and perspective must stay stable</p>
</li>
</ul>
<p><strong>Watch out for:</strong></p>
<ul>
<li><p>Be specific (expertise, tone, audience) to avoid generic responses</p>
</li>
<li><p>Avoid overloading with too many traits—stick to the essentials</p>
</li>
</ul>
<p><strong>Prompt:</strong><br />You are a startup mentor with 15 years of experience.<br />Advise a first-time founder on how to validate their product idea.</p>
<p><strong>Tip:</strong> Think of persona prompting as giving the AI a “job title + personality”—this anchors every response in that role.</p>
<hr />
<h2 id="heading-a-practical-prompt-stack"><strong>A Practical Prompt Stack</strong></h2>
<p>Prompting works best when built in layers—each adds clarity and control.</p>
<ol>
<li><p><strong>System Prompt → Define the foundation</strong><br /> Set once per project: role, tone, rules, and safety.<br /> <em>Example:</em> “You are a mentor. Use short paragraphs, avoid jargon, and give examples.”</p>
</li>
<li><p><strong>Directional Cues → Guide the style</strong><br /> Light instructions that shape audience and focus.<br /> <em>Example:</em> “Explain like I’m five” or “Use bullet points.”</p>
</li>
<li><p><strong>Task Prompt → Instruct the action</strong><br /> The specific request + constraints for this moment.<br /> <em>Example:</em> “Summarize this in 4 bullets, ≤15 words each.”</p>
</li>
<li><p><strong>Technique → Apply the method</strong><br /> Choose the right approach for the task:</p>
<ul>
<li><p>Zero-shot → no examples, fast answer</p>
</li>
<li><p>Few-shot → show 2–3 examples</p>
</li>
<li><p>Chain-of-thought → step-by-step reasoning</p>
</li>
<li><p>Self-consistency → multiple tries, pick majority</p>
</li>
</ul>
</li>
<li><p><strong>Post-Process → Verify the result</strong><br /> Check and refine the output before use:</p>
<ul>
<li><p>Confirm length/constraints</p>
</li>
<li><p>Check tone/style consistency</p>
</li>
<li><p>Run small validations (e.g., facts, logic)</p>
</li>
</ul>
</li>
</ol>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Prompting isn’t magic—it’s design. With the right setup, AI becomes consistent, reliable, and useful.<br />Start small, improve with feedback, and test with real users. The best prompts don’t just work in theory—they work in practice.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Transformers: The Technology Powering Modern LLMs]]></title><description><![CDATA[Learn how GPT leverages transformer architecture to generate AI-powered text.]]></description><link>https://rohitkadam.hashnode.dev/understanding-transformers</link><guid isPermaLink="true">https://rohitkadam.hashnode.dev/understanding-transformers</guid><category><![CDATA[transformers]]></category><category><![CDATA[genai]]></category><category><![CDATA[gpt]]></category><dc:creator><![CDATA[Rohit Kadam]]></dc:creator><pubDate>Wed, 13 Aug 2025 06:39:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/WSreqP00Rs4/upload/6214846543072f689e3023bfe1afbb13.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>First introduced in 2017’s <em>“Attention Is All You Need,”</em> Transformers revolutionized AI. They power today’s most advanced language models — including GPT, Claude, and others — by processing entire text sequences at once and using attention mechanisms to find relationships between words anywhere in the context. This makes them far more capable than older models that generated text one token at a time with limited memory.</p>
<p>Text generation works like this: the model see all the words once, remember the full context and predicts the next word, adds it to the sequence, and repeats.</p>
<p>Example:</p>
<ul>
<li><strong>Write a story</strong> → “Once”</li>
<li><strong>Write a story once</strong> → “Upon”</li>
<li><strong>Write a story once upon</strong> → “A”</li>
</ul>
<blockquote>
<p>Prompt → Look at all words → Predict next word → Add it → Repeat</p>
</blockquote>
<hr />
<h2>⚡ <strong>Transformer Diagram</strong></h2>
<p>The transformer diagram may look scary and make you want to quit GenAI learning—but don’t worry. As developers, we don’t need to go too deep. Let’s explore each part of the transformer at a high level.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756989644726/1e0d1d0b-f70b-4a9e-861e-def614dc8f78.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>🧩 Tokenization: Turning Text into Tokens</h2>
<p><strong>What it is:</strong> Tokenizer breaks the text into smaller pieces called tokens—like words, parts of words, punctuation, or emojis. GenAI models work with these tokens instead of raw sentences, making text easier for them to understand.</p>
<p><strong>Why it matters:</strong> Models understand tokens, not raw text.</p>
<p><strong>Algorithm</strong>:<br />• WordPiece: <em>Splits tricky words into parts.</em><br />• BPE: <em>Groups frequent pairs for efficiency.</em><br />• SentencePiece: <em>Great for languages with no spaces.</em></p>
<p><strong>Example:</strong></p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755061654126/cac527db-f396-4077-83d2-1e39f0c400a9.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Tips</strong><br />• Use the same tokenizer at inference time that was used during training, or embeddings will mismatch.<br />• Count tokens before sending prompts to control cost limits</p>
<pre><code class="language-javascript">function simpleTokenizer(text) {
  return text.match(/(\w+|[^\w\s])/gu) || [];
}
const tokens = simpleTokenizer("Write a story once upon a time!");
console.log(tokens); 
// ["Write","a","story","once","upon","a","time","!"]
</code></pre>
<hr />
<h2>📏 Embeddings: Giving Tokens Numbers</h2>
<p><strong>What it does:</strong> Each token is mapped to a list of numbers called an embedding vector. These numbers let GenAI models compare meanings and find similarities.</p>
<p><strong>Why it matters:</strong> Numbers let the model understand word meaning.</p>
<p><strong>Key properties:</strong><br />• Distances ≈ semantic similarity. The smaller the distance between two embedding vectors, the more similar the words.<br />• Vector arithmetic works: king – man + woman ≈ queen.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755062206745/21fd4226-208b-4c11-b68d-16593b9c8f24.webp" alt="" style="display:block;margin:0 auto" />

<p><strong>Code:</strong></p>
<pre><code class="language-javascript">import { Configuration, OpenAIApi } from "openai";

const openai = new OpenAIApi(new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
}));

async function getEmbedding(text) {
  const response = await openai.createEmbedding({
    model: "text-embedding-ada-002",
    input: text,
  });
  return response.data.data[0].embedding;
}

(async () =&gt; {
  const userQuery = "Write a story once upon a time."
  const embeddingVector = await getEmbedding(userQuery);
  console.log(embeddingVector);
})();
// Each word will be represent in the array of number
// [[ 0.01234567, -0.03456789, ..., 0.00123456], [...]]
</code></pre>
<hr />
<h2>🔍 Self-Attention – Focusing on the Right Words</h2>
<p><strong>What it does:</strong> Each token looks at every other token to decide what’s important for meaning.<br /><strong>Example</strong>:<br />“I put the book on the shelf because it was dusty.”<br />When the model sees “it”, self‑attention lets it check every other word to see what “it” most likely refers to.<br />• Highest connection: “book” (because books can be dusty)<br />• Lower connection: “shelf” (possible but less likely)<br />• Minimal connection: words like “I”, “put”, “because”</p>
<p><strong>Why it matters:</strong> Captures relationships between words, even if they’re far apart in the sentence.</p>
<hr />
<h2>👀 Multi-Head Attention – Seeing Relationships in Different Ways</h2>
<p><strong>Why multiple heads:</strong> Instead of one “view,” the model uses multiple attention heads. Each head captures a different type of relationship — like grammar, theme, or tone.</p>
<p><strong>Example:</strong><br />Imagine reading this sentence: “The bank can guarantee deposits will be safe.”<br />One attention head might focus on financial meanings of bank, another on the action guarantee, while a third looks at deposits. Each “head” understands different parts or meanings simultaneously.</p>
<p><strong>Why it matters:</strong> Combining all these focused views gives the model a richer, fuller understanding of the sentence, capturing multiple relationships and nuances at once.</p>
<hr />
<h2>📍 Positional Encoding — Remembering Word Order</h2>
<p><strong>Problem:</strong> Self-attention alone ignores sequence order. Positional encoding adds small numeric signals telling the model: this is the first token, second token, etc.</p>
<p><strong>Example:</strong><br />Without order info, “dog bites man” and “man bites dog” might look the same. Positional encoding fixes that.<br />• “dog bites man” → (dog: position 1), (bites: position 2), (man: position 3)<br />• “man bites dog” → (man: position 1), (bites: position 2), (dog: position 3)</p>
<hr />
<h2>🧠 Feed-Forward Networks – Thinking Step</h2>
<p><strong>Role:</strong> After attention figures out context, each token’s info goes through a small neural network that adds complexity and non-linear reasoning.</p>
<p><strong>Why it matters:</strong> Turns basic token representations into richer, more abstract concepts.</p>
<p><strong>Example:</strong><br />Sentence: The cat jumped over the fence.<br />Step 1: Self-attention collects context for each word:<br />• cat → “animal”, “subject”, “doing the jumping”<br />• jumped → “action”, “past tense”<br />• fence → “object being jumped over”</p>
<p>Step 2: For each word’s gathered clues, the feed‑forward network transforms them into a deeper meaning:<br />• cat → “small agile animal performing the action”<br />• jumped → “leap movement over obstacle”<br />• fence → “barrier between spaces”</p>
<hr />
<h2>⚖️ Layer Normalization – Keeping Learning Stable</h2>
<p><strong>Purpose:</strong> Like adjusting volume so things don’t get too loud or too quiet during training.</p>
<p><strong>Example:</strong><br />Imagine adjusting thermostat settings in a building so the temperature stays comfortable and doesn’t spike or drop suddenly.<br />Layer normalization keeps the data “temperature” steady during training by normalizing values—avoiding overly large or tiny numbers that can confuse neural networks.</p>
<p><strong>Why this matters</strong>: By stabilizing values, the model learns faster and more reliably without errors or crashes.</p>
<hr />
<h2>🎯 Softmax – Turning Scores into Probabilities</h2>
<p><strong>Function:</strong> The model produces raw scores (logits). Softmax converts them to probabilities that add to 1</p>
<p><strong>Example:</strong><br />If the scores are:<br />• “cat”: 2.5 → 70% chance<br />• “dog”: 1.5 → 20% chance<br />• “hat”: 0.5 → 10% chance <br />The model picks the most likely token as a next token</p>
<p><strong>Use case:</strong> Pick the most likely next token when generating text.</p>
<hr />
<h2>🚀 OpenAI API Text Generation (JavaScript)</h2>
<pre><code class="language-javascript">import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function generateText(prompt) {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini", // Choose the model you prefer
    messages: [{ role: "user", content: prompt }],
    max_tokens: 50,
    temperature: 0.7,
  });
  return response.choices[0].message.content;
}

(async () =&gt; {
  const prompt = "Once upon a time";
  const generatedText = await generateText(prompt);
  console.log("Generated text:", generatedText);
})();
</code></pre>
<hr />
<h2>💡 Tips for Developers</h2>
<ul>
<li><strong>Use existing APIs:</strong> Hugging Face, OpenAI, and others offer easy-to-use SDKs.</li>
<li><strong>Don’t reinvent the wheel:</strong> Let mature libraries handle the heavy lifting; focus on prompt design and fine-tuning for your use case.</li>
<li><strong>Monitor tokens:</strong> Keep prompts under model token limits (for example, 4,096 for GPT‑3) to avoid errors and control costs..</li>
<li><strong>Experiment:</strong> Adjust settings like temperature and top‑k to balance creativity and accuracy in generated text.</li>
</ul>
<hr />
<h2>✅ Conclusion</h2>
<p>Transformers have revolutionized how machines understand and generate language. By breaking down text into tokens, turning those tokens into numbers through embeddings, and applying attention mechanisms paired with thoughtful processing steps like feed-forward networks and normalization, these models achieve remarkable understanding and creativity.</p>
<p>The good news? You don’t need to build these complex models from scratch. With powerful pre-built models and easy-to-use APIs available today, you can harness this technology with just a few lines of code—focusing your energy on crafting great prompts and fine-tuning for your unique applications.</p>
<p>Remember these key takeaways:<br />• <strong>Tokenization</strong> bridges raw language and AI understanding.<br />• <strong>Embeddings</strong> capture meaning as numbers.<br />• <strong>Attention</strong> and <strong>transformer</strong> blocks make sense of context and relationships.<br />• <strong>Layered</strong> processing ensures stable, meaningful output.</p>
<p><strong>Happy coding — and welcome to the future of GenAI! 🚀</strong></p>
]]></content:encoded></item></channel></rss>