<?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 Karan Shaw on Medium]]></title>
        <description><![CDATA[Stories by Karan Shaw on Medium]]></description>
        <link>https://medium.com/@shawkaran2002?source=rss-9178492c0930------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FxPCL8m4yF95NbRevtkAlA.jpeg</url>
            <title>Stories by Karan Shaw on Medium</title>
            <link>https://medium.com/@shawkaran2002?source=rss-9178492c0930------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:43:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shawkaran2002/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[From If-Else Chaos to Clean Graphs: Mastering Agent Workflows with LangGraph]]></title>
            <link>https://medium.com/@shawkaran2002/from-if-else-chaos-to-clean-graphs-mastering-agent-workflows-with-langgraph-cd9faaa86d8e?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9faaa86d8e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chaicode]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 20:22:50 GMT</pubDate>
            <atom:updated>2025-06-30T20:22:50.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQtOj6_8Wsf1FO5NZQfxvQ.png" /></figure><h3>The Problem</h3><p>Let’s build an agentic workflow based on the following use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*fdXig4DWmSLDmFON.png" /></figure><h4>Workflow Description:</h4><p>In this workflow, the user submits a query which is first analyzed to determine whether it’s related to coding. For this initial classification, we use <strong>GPT-4.1-nano</strong>, as it’s both fast and cost-efficient.</p><ul><li><strong>If the query is related to coding</strong>, we pass it to <strong>GPT-4.1</strong>, which is well-suited for handling complex computational tasks.<br>The result, along with the original user query, is then sent again to <strong>GPT-4.1</strong> to validate the generated code’s accuracy.<br>If the accuracy is <strong>above 95%</strong>, we display the code to the user.<br>If not, the system retries to generate a more accurate version until the threshold is met.</li><li><strong>If the query is general (non-coding-related)</strong>, it is processed using <strong>GPT-4.1-mini</strong>, and the generated response is directly returned to the user.</li></ul><h4>Code for the workflow described above</h4><p>Although this workflow is relatively simple — with only a few steps and limited branching — it’s still manageable to write and follow. However, imagine a scenario where there are <strong>20 or more nodes</strong>. The code would quickly become messy, filled with nested if-else blocks, repeated logic, and poor readability.</p><p>This is exactly where <strong>LangGraph</strong> shines. It abstracts away the low-level control flow logic by letting developers focus solely on <strong>defining nodes</strong>. These nodes can even be reused or shared independently. LangGraph then compiles these into a stateful graph and handles the flow for you.</p><pre>def classify_query(query: str) -&gt; bool:<br>    # Returns True if it&#39;s a coding query, otherwise False using GPT-4.1-nano<br>    ...<br><br>def general_query(query: str) -&gt; str:<br>    # Handle general queries using GPT-4.1-mini<br>    ...<br><br>def coding_query(query: str) -&gt; str:<br>    # Generate code using GPT-4.1<br>    ...<br><br>def coding_validate_query(query: str, code: str) -&gt; float:<br>    # Validate code using GPT-4.1 and return accuracy as a float<br>    ...<br><br>query = input(&quot;&gt; &quot;)<br><br>is_coding_query = classify_query(query)<br><br>if not is_coding_query:<br>    print(f&quot;Bot: {general_query(query)}&quot;)<br>else:<br>    while True:<br>        model_result = coding_query(query)<br>        accuracy = coding_validate_query(query, model_result)<br>        if accuracy &lt; 95:<br>            continue<br>        else:<br>            print(f&quot;Bot: {model_result} with accuracy {accuracy}%&quot;)<br>            break</pre><h3>LangGraph</h3><p>Before building the workflow, it’s important to understand that every <strong>graph (or workflow)</strong> in this system operates on a <strong>state</strong>.</p><p>When the graph starts, this <strong>state is passed into the graph</strong>, and it flows through each node. Each <strong>node</strong> represents a unit of logic — typically an API call to an LLM — and is responsible for <strong>updating the state</strong> with its results.</p><p>Meanwhile, <strong>edges</strong> define how the state transitions between nodes. They act as paths that determine <strong>which node comes next</strong>, based on logic, conditions, or simple sequencing.</p><p>It’s also important to note that <strong>nodes always return a state</strong>, unless the node is specifically a <strong>routing node</strong>.</p><ul><li><strong>Standard nodes</strong> (like those making LLM calls or performing transformations) take in the current state, perform some logic, and return an updated version of that state.</li><li><strong>Routing nodes</strong>, on the other hand, don’t return a modified state. Instead, they return a <strong>string or condition</strong> that determines the next path (i.e., which edge to follow next).</li></ul><p>This distinction allows LangGraph to separate <strong>data processing</strong> from <strong>control flow</strong>, making the workflow both modular and easy to reason about.</p><p>Every LangGraph workflow has two special nodes: START and END.</p><ul><li>START: This is the <strong>entry point</strong> of the graph. It defines where the execution begins. You typically connect it to the first functional node (like a classifier or input handler).</li><li>END: This is the <strong>termination point</strong> of the graph. Once the state reaches this node, the workflow completes, and the final state is returned to the caller.</li></ul><p>These two nodes help define the execution boundary of the workflow. They make it easy to structure and visualize the beginning and end of an agent’s lifecycle.</p><p>Now, let’s build the same workflow using LangGraph. The workflow will change slightly and look like this based on the information above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tz4N76w1zGW7l-ZV.png" /></figure><h4>Code for the agent workflow using LangGraph</h4><pre>from typing import Literal<br>from dotenv import load_dotenv<br>from typing_extensions import TypedDict<br>from openai import OpenAI<br>from pydantic import BaseModel<br>from langgraph.graph import START, StateGraph, END</pre><p>Here we are importing the required modules. Standard typing utilities like TypedDict and Literal are used to define the structure and control flow of the shared state, while pydantic.BaseModel helps enforce structured responses from the LLMs. The dotenv package is used to load environment variables—such as the OpenAI API key—from a .env file.</p><pre>load_dotenv()<br>client = OpenAI()</pre><p>After loading the environment, we create an instance of the OpenAI client, which is used throughout the workflow to call different models like gpt-4.1-nano, gpt-4.1, and gpt-4.1-mini.</p><pre># These helps to control the model to return a STRUCTURE RESPONSE.<br># We can pass this to the model client so that we get the <br># output from the model like the below classes.<br># pydantic in python is zod in typescript<br>class ClassifyMessageResponse(BaseModel):<br>    is_coding_problem: bool<br><br><br>class CodeAccuracyResponse(BaseModel):<br>    accuracy_percentage: int</pre><p>To ensure that the models return well-structured and parsable outputs, two Pydantic classes are defined: ClassifyMessageResponse for determining whether a query is related to coding, and CodeAccuracyResponse for capturing the accuracy score of the generated code. These act like runtime schemas, similar to how zod is used in TypeScript.</p><pre>class State(TypedDict):<br>    query: str<br>    llm_result: str | None<br>    accuracy_percentage: str | None<br>    is_coding_problem: bool | None</pre><p>Next, we define the State, a TypedDict that serves as the shared memory passed between nodes in the workflow. It contains keys like query, llm_result, accuracy_percentage, and is_coding_problem, which each node can update as needed.</p><p>Next, we will create all the functional and routing nodes. Each node accepts the state as a parameter and returns the state if it is a functional or standard node, or a string (the name of the node) if it is a routing node.</p><pre>def classify_query(state: State):<br>    print(&quot;⚠️ classify_query&quot;)<br><br>    query = state[&quot;query&quot;]<br>    CLASSIFY_SYSTEM_PROMPT = &quot;&quot;&quot;<br>        You are an AI Assistant. Your job is to detect if the user&#39;s query is related to coding or not.<br>        Return the response in boolean. True for coding query and False for general qurey.<br>    &quot;&quot;&quot;<br>    res = client.beta.chat.completions.parse(<br>        model=&quot;gpt-4.1-nano&quot;,<br>        response_format=ClassifyMessageResponse,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: CLASSIFY_SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query},<br>        ],<br>    )<br>    is_coding_problem = res.choices[0].message.parsed.is_coding_problem<br>    state[&quot;is_coding_problem&quot;] = is_coding_problem<br>    return state</pre><p>classify_query, uses the gpt-4.1-nano model to quickly and cost-effectively determine if the user’s query is related to coding. It update value of is_coding_problem parameter key in the state.</p><pre>def route_query(state: State) -&gt; Literal[&quot;general_query&quot;, &quot;coding_query&quot;]:<br>    is_coding_problem = state[&quot;is_coding_problem&quot;]<br>    if is_coding_problem:<br>        return &quot;coding_query&quot;<br><br>    return &quot;general_query&quot;</pre><p>Check the is_coding_problem is true or not. If true it returns the name of the node(Below you will see the how we are giving the name). By this route node we can make more complex workflows.</p><pre>def coding_query(state: State):<br>    print(&quot;⚠️ coding_query&quot;)<br><br>    query = state[&quot;query&quot;]<br><br>    CODING_SYSTEM_PROMPT = &quot;&quot;&quot;<br>        You are a Coding Expert Agent<br>    &quot;&quot;&quot;<br>    res = client.chat.completions.create(<br>        model=&quot;gpt-4.1&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: CODING_SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query},<br>        ],<br>    )<br>    llm_result = res.choices[0].message.content<br>    state[&quot;llm_result&quot;] = llm_result<br>    return state</pre><p>Uses gpt-4.1 to generate a code solution for the given query. Stores the result in llm_result of the state.</p><pre>def general_query(state: State):<br>    print(&quot;⚠️ general_query&quot;)<br><br>    query = state[&quot;query&quot;]<br>    res = client.chat.completions.create(<br>        model=&quot;gpt-4.1-mini&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query},<br>        ],<br>    )<br>    llm_result = res.choices[0].message.content<br>    state[&quot;llm_result&quot;] = llm_result<br>    return state</pre><p>For non-coding queries, this node uses gpt-4.1-mini to generate a general answer.</p><pre>def coding_validate_query(state: State):<br>    print(&quot;⚠️ coding_validate_query&quot;)<br><br>    query = state[&quot;query&quot;]<br>    llm_result = state[&quot;llm_result&quot;]<br>    SYSTEM_PROMPT = f&quot;&quot;&quot;<br>        You are expert in calculating accuracy of the code according to the question.<br>        Return the percentage of accuracy between 0 to 100.<br>        <br>        User Query: {query}<br>        Code: {llm_result}<br>    &quot;&quot;&quot;<br>    res = client.beta.chat.completions.parse(<br>        model=&quot;gpt-4.1&quot;,<br>        response_format=CodeAccuracyResponse,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query},<br>        ],<br>    )<br>    accuracy_percentage = res.choices[0].message.parsed.accuracy_percentage<br>    print(&quot;Accuracy from function: &quot;, accuracy_percentage)<br>    state[&quot;accuracy_percentage&quot;] = accuracy_percentage<br>    return state</pre><p>Takes the code generated and asks GPT-4.1 to <strong>evaluate its accuracy</strong> against the original query.</p><p>Saves the accuracy_percentage in the state as int.</p><pre>def route_code_validate_query(state: State) -&gt; Literal[END, &quot;coding_query&quot;]:<br>    accuracy = state[&quot;accuracy_percentage&quot;]<br>    if accuracy &lt; 95:<br>        return &quot;coding_query&quot;<br>    return END</pre><p>Checks whether the accuracy is &lt; 95. If yes, loops back to coding_query to regenerate and If no, moves to END.</p><pre>graph_builder = StateGraph(State)</pre><p>Initializes a new graph where each node operates on a shared state defined by the State. It sets up the structure for building and connecting workflow nodes that will process and update this state.</p><pre># Defining Nodes<br>graph_builder.add_node(&quot;classify_query&quot;, classify_query)<br>graph_builder.add_node(&quot;route_query&quot;, route_query)<br>graph_builder.add_node(&quot;coding_query&quot;, coding_query)<br>graph_builder.add_node(&quot;general_query&quot;, general_query)<br>graph_builder.add_node(&quot;coding_validate_query&quot;, coding_validate_query)<br>graph_builder.add_node(&quot;route_code_validate_query&quot;, route_code_validate_query)</pre><p>Defining all the nodes that need to be in the graph. The add_node() method takes the name of the node and the action or function that the node is supposed to perform.</p><pre># Defining Edges<br>graph_builder.add_edge(START, &quot;classify_query&quot;)<br>graph_builder.add_conditional_edges(&quot;classify_query&quot;, route_query)<br>graph_builder.add_edge(&quot;general_query&quot;, END)<br>graph_builder.add_edge(&quot;coding_query&quot;, &quot;coding_validate_query&quot;)<br>graph_builder.add_conditional_edges(&quot;coding_validate_query&quot;, route_code_validate_query)</pre><p>Defining all the edges that connect the nodes and specify the flow of direction to achieve the desired result.</p><p>The add_edge() method takes two arguments: the source and the destination. The add_conditional_edges() method is used for routing nodes, where the first argument is the source, and the second is the routing node function or action.</p><pre># Compile the graph<br>graph = graph_builder.compile()</pre><p>Once the graph is fully defined, it is compiled into an executable object using graph_builder.compile().</p><pre>def main():<br>    user_query = input(&quot;&gt; &quot;)<br><br>    state:  State = {<br>        &quot;query&quot;: user_query,<br>        &quot;llm_result&quot;: None,<br>        &quot;accuracy_percentage&quot;: None,<br>        &quot;is_coding_problem&quot;: False<br>    }<br><br>    response = graph.invoke(state)<br><br>    print(f&quot;Bot: {response}&quot;)<br><br>main()</pre><p>Here, we take the user_query and create a state object. To run the entire <strong>agentic workflow</strong>, we use graph.invoke(state) to get the result.</p><pre># Output<br>(venv) ➜  06-langgraph python graph.py<br>&gt; Hi, my name is Karan<br>⚠️ classify_query<br>⚠️ general_query<br>Bot: {&#39;query&#39;: &#39;Hi, my name is Karan&#39;, &#39;llm_result&#39;: &#39;Hello Karan! How can I assist you today?&#39;, &#39;accuracy_percentage&#39;: None, &#39;is_coding_problem&#39;: False}<br><br>(venv) ➜  06-langgraph python graph.py<br>&gt; Write a Python function to remove duplicates from a list using only a set<br>⚠️ classify_query<br>⚠️ coding_query<br>⚠️ coding_validate_query<br>Accuracy from function:  100<br>Bot: {&#39;query&#39;: &#39;Write a Python function to remove duplicates from a list using only a set&#39;, &#39;llm_result&#39;: &#39;Absolutely! If you want to **remove duplicates from a list** using only a `set`, and preserve no specific order, you can simply do:\n\n```python\ndef remove_duplicates(lst):\n    return list(set(lst))\n```\n\nThis converts the list to a set (which removes duplicates) and then back to a list.\n\n## Example:\n```python\ndata = [1, 2, 2, 3, 4, 4, 5]\nunique = remove_duplicates(data)\nprint(unique)  # Output could be: [1, 2, 3, 4, 5] (order not guaranteed)\n```\n\n**Note:**  \nIf you need to **preserve the original order** while using a set to check for duplicates (which you said &quot;using only a set&quot;; so we\&#39;ll avoid `dict` or other standard approaches):\n\n```python\ndef remove_duplicates(lst):\n    seen = set()\n    result = []\n    for item in lst:\n        if item not in seen:\n            seen.add(item)\n            result.append(item)\n    return result\n```\n\nBut the first, shortest solution above is usually what is meant if order does not matter!&#39;, &#39;accuracy_percentage&#39;: 100, &#39;is_coding_problem&#39;: True}</pre><blockquote><em>I’ve published the complete code for this agentic workflow — </em><strong><em>both with and without LangGraph</em></strong><em> — as GitHub Gists. You can explore them side by side to better understand the structural differences and benefits of using LangGraph.</em></blockquote><blockquote><em>👉 </em><a href="https://gist.github.com/karanShaw000/7a8300d3021bbbed89590feee08d3830"><strong><em>View the Gists here</em></strong></a></blockquote><blockquote><em>These examples should help reinforce the concepts discussed and serve as a starting point for building your own agentic systems.</em></blockquote><h3>Wrapping Up</h3><ul><li>Defined a simple agentic workflow that classifies user queries and handles them differently based on type.</li><li>Compared imperative (if-else) logic vs. a graph-based approach to highlight complexity scaling.</li><li>Introduced StateGraph to structure workflows using nodes and edges while managing shared state.</li><li>Used routing nodes to control flow, including conditional branching and retry loops.</li><li>Demonstrated how LangGraph simplifies logic, improves modularity, and makes workflows easier to maintain.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9faaa86d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Another Jargon to Expose: RAG (Retrieval-Augmented Generation)]]></title>
            <link>https://medium.com/@shawkaran2002/another-jargon-to-expose-rag-retrieval-augmented-generation-224f594f7b5d?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/224f594f7b5d</guid>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[chaicode]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 20:06:45 GMT</pubDate>
            <atom:updated>2025-06-30T20:06:45.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDPeMRaKPqenKO5Fsz_XxQ.png" /></figure><p>From the title, you already know the full form of <strong>RAG</strong> — <em>Retrieval-Augmented Generation</em>. Sounds fancy, right?</p><p>It’s one of those buzzwords that can make beginners think it’s some ultra-advanced, PhD-level technology that only big companies can build.</p><p><strong>But here’s the truth:</strong><br><strong>No, it’s not.</strong></p><p>At the time of writing this article, there’s one thing I want you to remember:</p><blockquote><em>In the AI world, </em><strong><em>90% is marketing, 9% is coding, and 1% is real-world adoption</em></strong><em>.</em></blockquote><p>Once you see through the jargon, you’ll realise that RAG is not some magic — it’s just a clever combination of <strong>search + generate</strong>.</p><p>By the end of this article, <strong>you’ll not only understand what RAG is</strong>,<br>but you’ll also be confident enough to <strong>build your own RAG pipeline</strong>.</p><p>Let’s break it down.</p><h3>Business Point of View: Why RAG Actually Matters</h3><p>We know that LLMs are <strong>pre-trained</strong> and can handle general tasks quite well.<br>But the real question is:</p><blockquote><strong><em>Can an LLM actually help a business solve its specific problems?</em></strong><em><br></em><strong><em>The answer is: No.</em></strong></blockquote><p>Let’s take an example.</p><p>Suppose a business wants to build a <strong>chatbot</strong> where employees can ask questions and retrieve data from a <strong>large internal data source</strong> — like PDFs, databases, images, audio files, and more.</p><h4>First Approach: Fine-Tune the Model on Internal Data</h4><p>The first idea that usually comes to mind is to <strong>train the model using the company’s data</strong>. Then, whenever we query the model, it responds using that internal knowledge.</p><p>This might seem like it would work — but it’s <strong>not optimal</strong> for a business environment.</p><p>Why?</p><ul><li>Business data changes <strong>every second</strong>.</li><li>Fine-tuning a model takes at least <strong>24 hours</strong>, sometimes more.</li><li>Re-training the model every time the data changes is <strong>costly</strong> and <strong>time-consuming</strong>.</li><li>And most importantly, the model will always be <strong>outdated</strong>, because it’s trained on a snapshot of data — not live information.</li></ul><p>So businesses not only bear the cost of fine-tuning, but they also lose the ability to access <strong>real-time data</strong>.</p><h4>Second Approach: Use a SOTA Model with Prompt Engineering</h4><p>An alternative is to take a <strong>SOTA (State of the Art)</strong> model — like GPT-4.1 or Claude Sonnet 4 — and use <strong>prompting techniques</strong> to feed it the business data through system prompts.</p><blockquote><strong>SOTA</strong> is another buzzword that simply means <strong>“best in the market”</strong> for a specific task. At the time of writing, <strong>GPT-4.1</strong> and <strong>Claude Sonnet 4</strong> are considered SOTA models in the LLM space.</blockquote><p>You can even go further and give the chatbot access to tools like:</p><ul><li>write_to_db</li><li>generate_report</li></ul><p>This makes the chatbot <strong>agentic</strong>, meaning it can reason and take actions.<br>However, there’s one major limitation:</p><blockquote><strong><em>Token Limit Exceeded.</em></strong></blockquote><p>At the time of writing this article, <strong>all SOTA models have a token limit</strong>.<br>You simply can’t send the entire business data into the model — it’s just too large. And without access to all relevant data, the model can’t always give the right answer.</p><h4>The RAG : A Practical Solution</h4><p>This brings us to the real solution — <strong>the RAG pipeline</strong>.</p><p>With some clever optimizations, RAG helps us <strong>overcome the token limit issue</strong>.<br>Instead of sending all data to the model, RAG allows the LLM to <strong>retrieve only the relevant information it needs</strong> — just in time, just enough.</p><p>So, in simple terms:</p><blockquote><strong><em>RAG = Letting the LLM access external data sources efficiently to produce accurate results.</em></strong></blockquote><h4>Where Developers Come In</h4><p>This is where <strong>we, as developers</strong>, play a key role — <br>We work on <strong>optimizing data retrieval</strong> from the source so that the LLM gets exactly what it needs to respond intelligently, without wasting tokens or resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JO2bwuPONH_4w6eF.png" /></figure><h3>What Happens Under the Hood of RAG</h3><p>Generally, there are <strong>two main phases</strong> in any RAG-based application.</p><blockquote>In this section, we’ll use a <strong>PDF file</strong> as an example to explain how text is extracted and processed. How we give text to get text. However, the same method can be applied to <strong>other data formats</strong> too — such as images (using OCR), audio files (using speech-to-text), or even structured databases.</blockquote><h4>Ingestion / Indexing Phase:</h4><ul><li>In this phase, the data (PDF) is first <strong>converted to text</strong> using PDF parsers. After that, the text is <strong>chunked or split</strong> — paragraph by paragraph, page by page, or sentence by sentence — depending on the specific use case.</li><li>Once we have the chunks, we generate <strong>vector embeddings</strong> for each one using an embedding model. These <strong>embeddings</strong> with <strong>content</strong> and <strong>metadata</strong> of the chunks are then <strong>stored in a vector database</strong>.</li></ul><blockquote>Metadata can contain the page number of the PDF or any related data about the content of the chunk or data(PDF).</blockquote><p>The purpose of vector embeddings is to <strong>capture the semantic relationships</strong> between chunks, allowing us to compare and retrieve relevant pieces of information based on similarity in vector space.</p><h4>Retrieval Phase:</h4><p>In this phase, we take the <strong>user’s query</strong> and convert it into a <strong>vector embedding</strong> using the same embedding model used during indexing.<br>Then, using this query embedding, we <strong>search the vector database</strong> to find and retrieve the most <strong>semantically similar chunks</strong> of content.</p><p>Next, we <strong>construct a prompt</strong> by combining:</p><ul><li>The <strong>retrieved context</strong> (from the vector search)</li><li>The <strong>original user query</strong></li></ul><p>This prompt is then sent to the LLM, which generates a <strong>relevant and meaningful response</strong> based on the provided context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rSNdmWyQgBT-uyCL.png" /></figure><h3>Conclusion</h3><p>RAG isn’t just another AI buzzword — it’s a practical way to make LLMs work with real, ever-changing business data.</p><p>Instead of retraining models or overloading prompts, RAG lets us retrieve only what’s needed, when it’s needed.</p><p>As developers, our job is to optimize that flow.<br><strong>RAG is not magic — it’s smart engineering.</strong></p><p>I even built a project using RAG to see it in action — and trust me, it’s much more doable than it sounds.</p><ul><li>Project Demo Link: <a href="https://chat-with-pdf-rag-app.streamlit.app/">https://chat-with-pdf-rag-app.streamlit.app/</a></li><li>Project Github Link: <a href="https://github.com/karanShaw000/Chat-with-pdf-RAG-App">https://github.com/karanShaw000/Chat-with-pdf-RAG-App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=224f594f7b5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI-Agent: Mini-Cursor in Your Terminal]]></title>
            <link>https://medium.com/@shawkaran2002/build-an-ai-agent-mini-cursor-in-your-terminal-fd3ee1617ed7?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3ee1617ed7</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[chaicode]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 20:05:57 GMT</pubDate>
            <atom:updated>2025-06-30T20:05:57.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KOQ6gf5Tr6ihJZba" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What if your terminal could think like a developer?</h3><p>Meet <strong>Mini-Cursor</strong>, an AI-powered coding assistant that doesn’t just generate code — it plans, acts, and learns like a real developer. It asks questions, makes decisions, runs terminal commands, and observes the output to guide the next step — all inside your terminal.</p><h3>What is AI Agent?</h3><p>Think of <strong>AI agents</strong> as computers with a <strong>brain, hands, and legs</strong>.</p><p>AI is just a <strong>brain</strong> — it thinks, responds, and tells you <em>how</em> to do things. For example, it can tell you the command to create a folder, but it won’t actually run that command for you.</p><p>But an <strong>AI Agent</strong> goes a step further. It doesn’t just tell you what to do — it actually <strong>does it</strong>.</p><blockquote><em>It’s like giving AI a pair of hands and feet — the ability to act in the real world using tools you provide.</em></blockquote><p><strong>Analogy:</strong></p><blockquote>AI = Brain<em><br></em>Tools = Hands and Legs</blockquote><p>When you connect the brain with real tools, you get an <strong>agent</strong> that can think <em>and</em> do.</p><h3>How Can AI Agents Handle the Latest Tasks If They’re Pre-Trained?</h3><p>It’s true — traditional AI models are <strong>pre-trained</strong> on data that may be weeks or months old. They don’t automatically know the latest tools, APIs, or commands introduced yesterday.</p><p>So how do AI agents keep up?</p><p><strong>Answer:</strong> By using <strong>tools</strong> that connect to the real world.</p><p>Instead of retraining the whole model (which takes time and resources), we let the AI <strong>call a tool</strong> — like hitting an API, running a script, or fetching real-time data. This allows it to <strong>stay current</strong> and <strong>execute live tasks</strong>, even if it was trained on older data.</p><blockquote><em>The AI doesn’t need to “know everything” — it just needs to know </em>how to find or run the thing<em> that knows.</em></blockquote><p>Here comes the real magic — <a href="https://medium.com/@shawkaran2002/talk-smart-to-ai-how-prompting-helps-you-escape-the-gigo-trap-d0cac7c4b725"><strong>prompting</strong></a>.</p><p>Even though AI models are pre-trained, you can still <strong>teach them new things</strong> at runtime by providing the right <strong>context</strong> through prompts.</p><p>So, if you’ve built a tool like run_command, you simply describe how it works in the system prompt:</p><blockquote>“<em>run_command takes a list of command arguments, executes them in the terminal, and returns the result.”</em></blockquote><p>Now, the AI understands it can use that tool — just like giving instructions to a junior developer.</p><p>By describing the tools clearly, you unlock the agent’s ability to:</p><ul><li>Choose which tool is best for the task</li><li>Pass the correct input</li><li>React based on the result</li></ul><blockquote><em>Prompting acts like a bridge between the AI’s static brain and your dynamic environment.</em></blockquote><p>In short, you <strong>don’t need to retrain the AI</strong> — you just need to give it a good prompt and the right tools.</p><h3>What Is Mini-Cursor?</h3><p>Mini-Cursor is an AI agent framework that mimics the problem-solving workflow of a software engineer.</p><p>The core technique behind Mini-Cursor is called <a href="https://medium.com/@shawkaran2002/talk-smart-to-ai-how-prompting-helps-you-escape-the-gigo-trap-d0cac7c4b725"><strong>Chain of Thought Prompting</strong></a>. Instead of jumping directly to the answer, the AI is encouraged to reason through each step — planning, acting, and evaluating along the way.</p><p>For example:</p><blockquote><strong><em>User Query</em></strong><em>: “Build a Todo app using React”</em></blockquote><blockquote><em>The AI doesn’t just respond with a full project at once.<br>Instead, it says:</em></blockquote><blockquote><em>🧠: “I will scaffold a Vite React project using TypeScript.”<br>🛠️: </em><em>npm create vite@latest client -- --template react-ts</em></blockquote><blockquote><em>🧠 “React app scaffolded successfully.”<br>❓: “What should we name the project?”</em></blockquote><p>You can see the <a href="https://github.com/karanShaw000/min-cursor/blob/main/prompt.py">system prompt</a> I used to enable this kind of structured thinking.</p><p>It plans, acts, observes, asks, and gives real results — just like a real assistant.</p><p>Mini-Cursor follows a reasoning and execution loop:</p><pre>ask → plan → act → observe → output</pre><p>This loop allows the agent to interact with the environment (like the terminal), clarify intent, and adapt based on real-time feedback — making it feel like a real developer assistant.</p><h3>How I Built the AI Agent: Mini-Cursor</h3><p>Now that we understand what AI agents are and how they work — let me walk you through <strong>how I built Mini-Cursor</strong>, a terminal-based AI agent that thinks like a developer and executes real commands step-by-step.</p><h4>Import Libraries and Setup</h4><p>Let’s walk through the main logic behind Mini-Cursor — how it uses OpenAI’s model, processes each step, and connects to system-level tools.</p><pre>import subprocess<br>from openai import OpenAI<br>from dotenv import load_dotenv<br>from openai.types.chat import ChatCompletionMessageParam<br>import json<br>from prompt import system_prompt</pre><h4>Load Environment and Initialize OpenAI Client</h4><pre>load_dotenv()<br>client = OpenAI()</pre><h4>Tools</h4><p>This tool allows the agent to securely execute terminal commands.</p><pre>def run_command(cmd: list[str]) -&gt; str:<br>    try:<br>        result = subprocess.run(<br>            cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True<br>        )<br>        return result.stdout.strip()<br>    except Exception as e:<br>        return f&quot;Command failed with error: {str(e)}&quot;</pre><h4>Tool Registry</h4><pre>available_tool = {<br>    &quot;run_command&quot;: run_command,<br>}</pre><h4>Message Setup and Interaction Loop</h4><pre>messages: list[ChatCompletionMessageParam] = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt}<br>]</pre><h4>Main Loop</h4><p>This is where the magic happens — handling plan/act/ask/output steps dynamically.</p><pre>while True:<br>    query = input(&quot;&gt; &quot;)<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query})<br><br>    while True:<br>        response = client.chat.completions.create(<br>            model=&quot;gpt-4.1&quot;,<br>            messages=messages,<br>            response_format={&quot;type&quot;: &quot;json_object&quot;},<br>        )<br>        messages.append(<br>            {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response.choices[0].message.content}<br>        )<br><br>        parsed_json = json.loads(response.choices[0].message.content)<br><br>        if parsed_json.get(&quot;step&quot;) == &quot;plan&quot;:<br>            print(f&quot;🧠: {parsed_json.get(&#39;content&#39;)}&quot;)<br>            continue</pre><h4>Handle “act” Step</h4><p>The act step is where the AI can actually <strong>perform tasks</strong> or <strong>respond to real-world changes</strong>. This is the stage where we allow it to interact with the environment — whether that&#39;s executing terminal commands, running scripts, or checking for the latest events using the tools we provide.</p><p>Unlike traditional AI, which can only suggest actions, the act step <strong>bridges thought and execution</strong>.<br>This is the power of <strong>Chain of Thought</strong> Prompting.</p><pre>        if parsed_json.get(&quot;step&quot;) == &quot;act&quot;:<br>            tool_name = parsed_json.get(&quot;function&quot;)<br>            tool_input = parsed_json.get(&quot;input&quot;)<br><br>            print(f&quot;🛠️: {tool_name} with input {tool_input}&quot;)<br><br>            if available_tool[tool_name]:<br>                output = &quot;&quot;<br>                if tool_input:<br>                    output = available_tool[tool_name](tool_input)<br>                else:<br>                    output = available_tool[tool_name]()<br><br>                messages.append(<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: json.dumps({&quot;step&quot;: &quot;observe&quot;, &quot;content&quot;: output}),<br>                    }<br>                )<br>                continue</pre><h4>Handle “ask” Step</h4><pre>        if parsed_json.get(&quot;step&quot;) == &quot;ask&quot;:<br>            print(f&quot;❓: {parsed_json.get(&#39;content&#39;)}&quot;)<br>            askedQuery = input(&quot;&gt; &quot;)<br>            messages.append(<br>                {<br>                    &quot;role&quot;: &quot;user&quot;,<br>                    &quot;content&quot;: json.dumps({&quot;step&quot;: &quot;observe&quot;, &quot;content&quot;: askedQuery}),<br>                }<br>            )<br>            continue</pre><h4>Final Output</h4><pre>        if parsed_json.get(&quot;step&quot;) == &quot;output&quot;:<br>            print(f&quot;Result: {parsed_json.get(&#39;content&#39;)}&quot;)<br>            break</pre><h3>Links</h3><ol><li>Github: <a href="https://github.com/karanShaw000/min-cursor">https://github.com/karanShaw000/min-cursor</a></li><li>Demo: <a href="https://www.linkedin.com/posts/karanshaw000_ai-genai-agenticai-activity-7342589604476112897-Pb82?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAADHNfw0Bj3exN1YUZCG849FggUEVBdVdXU8">https://www.linkedin.com/posts/karanshaw000_ai-genai-agenticai-activity-7342589604476112897-Pb82</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3ee1617ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imagine Having Hitesh Sir as Your Coding Buddy — Anytime!]]></title>
            <link>https://medium.com/@shawkaran2002/imagine-having-hitesh-sir-as-your-coding-buddy-anytime-9f4a63634988?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4a63634988</guid>
            <category><![CDATA[prompting-technique]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[chaicode]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 05:48:33 GMT</pubDate>
            <atom:updated>2025-06-26T05:48:33.433Z</atom:updated>
            <content:encoded><![CDATA[<h3>Imagine Having Hitesh Sir as Your Coding Buddy — Anytime!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DsdbMce2t_znC8kB" /><figcaption>Photo by <a href="https://unsplash.com/@frank_leuderalbert?utm_source=medium&amp;utm_medium=referral">Frank Leuderalbert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>We all wish we had a personal mentor available anytime we got stuck in code. Inspired by Hitesh Choudhary’s energetic teaching style and practical insights, I decided to build an AI chatbot that mimics his personality, tone, and even his Hinglish speaking style. Meet the Hitesh Choudhary AI Bot — a fun, educational, and helpful coding buddy, powered by AI.</p><h3>What I have Built?</h3><p>This project is an AI-powered chatbot designed to respond like <a href="https://x.com/Hiteshdotcom"><strong>Hitesh Choudhary</strong></a> — not just with the right answers, but with his unique personality. We’re blending AI with a real human voice, tone, and attitude.</p><p>Key components of what we’re building:</p><ul><li>A chatbot powered by GPT (OpenAI) that understands and replies in a natural, relatable way.</li><li>A carefully crafted persona using prompt engineering to make sure the bot talks like Hitesh Sir.</li><li>A frontend (using React or Next.js) where users can interact with the bot .</li><li>A backend setup to manage API requests and ensure smooth performance.</li></ul><p>The ultimate aim is to give users the feeling that Hitesh Choudhary is personally mentoring them — available anytime they need help, guidance, or a push to keep coding.</p><h3>What I Learned?</h3><p>The most important thing I learned from this project is how critical prompt writing is. It’s not just about asking the AI to respond — it’s about clearly defining <em>what the AI should be</em>, and making sure it understands the purpose behind the conversation.</p><p>To make the AI bot behave like Hitesh Choudhary, I had to dive deep into <strong>persona-based prompting</strong>. This required a lot of research into Hitesh Sir’s tone, style, and language.</p><p>For this, I heavily used <strong>Few-Shot Prompting</strong>, where you provide multiple examples to help the AI understand <em>how</em> someone speaks, not just <em>what</em> they say. I collected examples from:</p><ul><li>His personal portfolio and website</li><li>YouTube video comments (to understand how the audience sees him)</li><li>Most importantly, his <strong>live streams</strong>, where he answers chat questions spontaneously</li></ul><blockquote>If you want to know more about<strong> Few-Shot Prompting</strong>, you can check out my blog on “<a href="https://medium.com/@shawkaran2002/talk-smart-to-ai-how-prompting-helps-you-escape-the-gigo-trap-d0cac7c4b725">Talk Smart to AI</a>” where I discussed on <strong>Prompting</strong> in details like <strong>prompting styles and techniques</strong>.</blockquote><p>These real, unscripted moments gave me the best insights into how he explains things — sometimes casually, sometimes sarcastically, but always in a way that makes things clear and relatable.</p><p>This project showed me that <strong>good AI output starts with great input</strong>, and if you want personality in your bot, you have to first understand the person deeply.</p><h3>Tech Stack Used</h3><ol><li>NextJS — Full Stack Framework.</li><li>OpenAI Javascript SDK and API Keys.</li></ol><h3>Github and Deployed Links</h3><ol><li>Github: <a href="https://github.com/karanShaw000/Hitesh-AI-Chatbot">https://github.com/karanShaw000/Hitesh-AI-Chatbot</a></li><li>Deployed: <a href="https://hitesh-ai-chatbot.vercel.app/">https://hitesh-ai-chatbot.vercel.app/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4a63634988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talk Smart to AI: How Prompting Helps You Escape the GIGO Trap.]]></title>
            <link>https://medium.com/@shawkaran2002/talk-smart-to-ai-how-prompting-helps-you-escape-the-gigo-trap-d0cac7c4b725?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0cac7c4b725</guid>
            <category><![CDATA[prompting-technique]]></category>
            <category><![CDATA[chaicode]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 05:41:55 GMT</pubDate>
            <atom:updated>2025-06-26T05:50:37.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsRk0imyJZTeE9wd" /><figcaption>Photo by <a href="https://unsplash.com/@juanjodev02?utm_source=medium&amp;utm_medium=referral">Juanjo Jaramillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We’ve all heard the old programming adage: <strong>GIGO — Garbage In, Garbage Out.</strong> In the age of AI, it’s more relevant than ever. Large language models like ChatGPT or Gemini are incredibly powerful, but they’re only as good as the prompts they receive. If you feed the model vague, messy, or poorly structured inputs, don’t be surprised when the output is confusing, irrelevant, or just plain wrong.</p><p><strong>Prompting</strong> is the new keyboard shortcut for controlling AI — a mix of art and logic that turns raw potential into useful results. Whether you’re a developer, writer, student, or entrepreneur, learning how to guide AI through well-crafted prompts is the key to unlocking its full value.</p><p>In this blog, we’ll break down:</p><ul><li><strong>What is prompting?</strong></li><li><strong>Different styles of prompting</strong> — from basic to advanced.</li><li><strong>Proven techniques</strong> to get better, faster, and more relevant results from AI.</li></ul><h3><strong>What is Prompting?</strong></h3><p><strong>Prompting</strong> is the act of giving instructions or input to an AI model to generate a desired output.</p><p>Think of it like talking to a super-smart assistant — your words (the prompt) guide what the assistant does. Whether you ask it to write a poem, explain code, summarize an article, or plan your day, the AI responds based on how you ask.</p><p>In simple terms:</p><ul><li>The <strong>prompt</strong> is your command or question.</li><li>The <strong>response</strong> is the AI’s answer or action.</li></ul><p>Prompting is not just about <em>what</em> you ask, but <em>how</em> you ask it. A small tweak in wording, structure, or tone can completely change the quality and relevance of the output.</p><h3>Prompting Styles: The 3 Core formats developers should aware of</h3><p>When working with AI models <strong>prompt structure matters.</strong> Different models expect different input formats to interpret instructions correctly. Here are the three most common prompting styles developers should be aware of:</p><h4><strong>Alpaca Prompt</strong></h4><p>Originally used in Stanford’s Alpaca model (a fine-tuned LLaMA), this format is <strong>simple and human-readable</strong>.</p><p><strong>Use Case:</strong> Great for instruction-following models trained in a Q&amp;A or tutoring style.</p><p>Structure:</p><pre>### Instruction: Explain what a closure is in JavaScript.<br>### Response: A closure is...</pre><h4><strong>ChatML Format (Used by OpenAI Models)</strong></h4><p>Popularized by OpenAI (e.g., GPT-3.5, GPT-4), this format mimics a <strong>multi-turn chat structure</strong> using system, user, and assistant roles.</p><p><strong>Use Case:</strong> Ideal for conversational models and chat-based interactions. Supports roles, instructions, and better context management.</p><p>Structure:</p><pre>{ &quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;....&quot;},<br>{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;....&quot;},<br>{ &quot;role&quot;: &quot;assitant&quot;, &quot;content&quot;: &quot;....&quot;},</pre><blockquote><em>Here you can see the use of the </em><strong><em>system role</em></strong><em>. This role acts like a control panel for developers — it lets us steer the AI’s behavior in a specific direction that suits our use case. As developers, we rarely want a generic, one-size-fits-all AI. We want responses tailored to our product, tone, or domain.</em></blockquote><blockquote><em>In this blog, we’ll mainly use the </em><strong><em>system role</em></strong><em> to show how you can shape the AI’s thinking and output to match your exact needs.</em></blockquote><h4><strong>INST Format (Instruction Format)</strong></h4><p>Used in models like <strong>Vicuna</strong> or <strong>FastChat</strong>, INST format wraps instruction and response in special tokens.</p><p><strong>Use Case:</strong> Often used in open-source fine-tuned models that expect structured tokens to distinguish input from output.</p><p><strong>Structure:</strong></p><pre>[INST]What is programming?[/INST]<br>[RESP]Programming is the process of ....[/RESP]</pre><blockquote><strong>ChatML is now the standard way to prompt AI models.</strong> Most developers use this format because it works across popular APIs like OpenAI. Even if the model under the hood is LLaMA or something else, the system usually converts ChatML to the right format automatically. Unless you’re working directly with a specific model, <strong>ChatML is what 99% of developers will use.</strong></blockquote><h3>Prompting Techniques</h3><p>Now that we understand what prompting is, let’s explore some core <strong>techniques</strong> used to get better and more reliable responses from AI models. These techniques help you guide the model more effectively, depending on the task complexity and desired output.</p><p>Here are the <strong>four main prompting techniques</strong>:</p><h4>Zero-Shot Prompting (a.k.a. One-Shot)</h4><p>In zero-shot prompting, you simply ask the AI a question or give a task <strong>without any example</strong>. It relies entirely on the model’s pre-training.</p><pre>from openai import OpenAI<br>from dotenv import load_dotenv<br>from openai.types.chat import ChatCompletionMessageParam<br><br>load_dotenv()<br><br>client = OpenAI()<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>    You are a helpful and experienced math teacher. <br>    Explain concepts clearly and step-by-step, using simple language when needed. <br>    Always encourage the student and make sure they understand the logic behind each step.<br>    If the question involves calculation, show your working. Be calm, supportive, and never assume prior knowledge beyond what&#39;s asked.<br>&quot;&quot;&quot;<br><br>messages: list[ChatCompletionMessageParam] = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>]<br><br>while True:<br>    prompt = input(&quot;Query &gt; &quot;)<br><br>    if prompt.lower() in {&quot;exit&quot;, &quot;quit&quot;}:<br>        print(&quot;Exiting...&quot;)<br>        break<br><br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br><br>    res = client.chat.completions.create(<br>        model=&quot;gpt-4.1-mini&quot;,<br>        messages=messages,<br>    )<br>    model_content = res.choices[0].message.content<br>    messages.append(<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: res.choices[0].message.content}<br>    )<br><br>    print(&quot;Teacher GPT: &quot;, model_content)<br><br># Output<br>#<br># Query &gt; 5 * 3 / 5 + 24 * 3<br># Teacher GPT:  Let&#39;s work through the expression step by step:<br>#<br># The expression is:<br>#<br># \[ 5 \times 3 \div 5 + 24 \times 3 \]<br>#<br># ### Step 1: Follow the order of operations (PEMDAS/BODMAS)<br># - Multiplication and division come before addition.<br># - Do multiplication and division from left to right.<br>#<br># ### Step 2: Calculate \( 5 \times 3 \)<br># \[ 5 \times 3 = 15 \]<br>#<br># Expression becomes:<br># \[ 15 \div 5 + 24 \times 3 \]<br>#<br># ### Step 3: Calculate \( 15 \div 5 \)<br># \[ 15 \div 5 = 3 \]<br>#<br># Expression becomes:<br># \[ 3 + 24 \times 3 \]<br>#<br># ### Step 4: Calculate \( 24 \times 3 \)<br># \[ 24 \times 3 = 72 \]<br>#<br># Expression becomes:<br># \[ 3 + 72 \]<br>#<br># ### Step 5: Add \( 3 + 72 \)<br># \[ 3 + 72 = 75 \]<br>#<br># ### Final answer:<br># \[<br># \boxed{75}<br># \]<br>#<br># If you have any questions about any of these steps, feel free to ask! You&#39;re doing great!<br># Query &gt; exit<br># Exiting...</pre><h4>Few-Shot Prompting</h4><p>Here, you give the model <strong>a few examples</strong> before your actual query. This helps it learn the pattern you want it to follow — all within the same prompt.</p><pre>from openai import OpenAI<br>from dotenv import load_dotenv<br>from openai.types.chat import ChatCompletionMessageParam<br><br>load_dotenv()<br><br>client = OpenAI()<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>    You are a helpful and experienced math teacher. <br>    Explain concepts clearly and step-by-step, using simple language when needed. <br>    Always encourage the student and make sure they understand the logic behind each step.<br>    If the question involves calculation, show your working. Be calm, supportive, and never assume prior knowledge beyond what&#39;s asked.<br>    <br>    Examples:<br>    User: What is the area of a triangle with base 10 cm and height 5 cm?<br>    Assistant: To find the area of a triangle, we use the formula:<br>        Area = ½ × base × height   <br>        Here, base = 10 cm and height = 5 cm.        <br>        So,<br>        Area = ½ × 10 × 5 = 25 cm²       <br>        The area of the triangle is 25 square centimeters.<br><br>    Examples:<br>    User: Can you explain what a prime number is?<br>    Assistant: Of course! A prime number is a number that has exactly two factors: 1 and itself. <br>        That means it can only be divided evenly by 1 and the number itself.<br>        For exmaple: 2 is prime, 3 is prime, 4 is not prime.<br>&quot;&quot;&quot;<br><br>messages: list[ChatCompletionMessageParam] = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>]<br><br>while True:<br>    prompt = input(&quot;Query &gt; &quot;)<br><br>    if prompt.lower() in {&quot;exit&quot;, &quot;quit&quot;}:<br>        print(&quot;Exiting...&quot;)<br>        break<br><br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br><br>    res = client.chat.completions.create(<br>        model=&quot;gpt-4.1-mini&quot;,<br>        messages=messages,<br>    )<br>    model_content = res.choices[0].message.content<br>    messages.append(<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: res.choices[0].message.content}<br>    )<br><br>    print(&quot;Teacher GPT: &quot;, model_content)<br><br># Output<br>#<br># Query &gt; 5 * 3 / 5 + 24 * 3<br># Teacher GPT:  Let&#39;s solve the expression step-by-step:<br># \[5 \times 3 \div 5 + 24 \times 3\]<br>#<br># Step 1: Multiply \(5 \times 3\)<br># \[5 \times 3 = 15\]<br>#<br># Now the expression becomes:<br># \[15 \div 5 + 24 \times 3\]<br>#<br># Step 2: Divide \(15 \div 5\)<br># \[15 \div 5 = 3\]<br>#<br># Now the expression becomes:<br># \[3 + 24 \times 3\]<br>#<br># Step 3: Multiply \(24 \times 3\)<br># \[24 \times 3 = 72\]<br>#<br># Now the expression becomes:<br># \[3 + 72\]<br>#<br># Step 4: Add \(3 + 72\)<br># \[3 + 72 = 75\]<br>#<br># So, the value of the expression is **75**.<br>#<br># If you want, I can explain any part again! You&#39;re doing great!</pre><h4>Chain-of-Thought Prompting (CoT)</h4><p>This technique encourages the model to <strong>show its reasoning step by step</strong> instead of jumping directly to the final answer. It improves accuracy, especially for logic or math-heavy tasks. Here we make the model to act like human. We human first sees the problem, understand, then works on it, comes with output and last we validates.</p><pre>from openai import OpenAI<br>from dotenv import load_dotenv<br>import json<br>from openai.types.chat import ChatCompletionMessageParam<br><br>load_dotenv()<br><br>client = OpenAI()<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>    You are a helpful and experienced math teacher. <br>    Explain concepts clearly and step-by-step, using simple language when needed. <br>    Always encourage the student and make sure they understand the logic behind each step.<br>    If the question involves calculation, show your working. Be calm, supportive, and never assume prior knowledge beyond what&#39;s asked.<br>    <br>    The steps are you get a user input, you analyse, you think, you think again, and think for several times and then return the output with an explanation. <br><br>    Follow the steps in sequence that is &quot;analyse&quot;, &quot;think&quot;, &quot;output&quot;, &quot;validate&quot; and finally &quot;result&quot;.<br><br>    Rules:<br>    1. Follow the strict JSON output as per schema.<br>    2. Always perform one step at a time and wait for the next input.<br>    3. Carefully analyse the user query,<br><br>    Output Format:<br>    {{ &quot;step&quot;: &quot;string&quot;, &quot;content&quot;: &quot;string&quot; }}<br><br>    Example:<br>    Input: What is 2 + 2<br>    Output: {{ &quot;step&quot;: &quot;analyse&quot;, &quot;content&quot;: &quot;Alight! The user is interest in maths query and he is asking a basic arthematic operation&quot; }}<br>    Output: {{ &quot;step&quot;: &quot;think&quot;, &quot;content&quot;: &quot;To perform this addition, I must go from left to right and add all the operands.&quot; }}<br>    Output: {{ &quot;step&quot;: &quot;output&quot;, &quot;content&quot;: &quot;4&quot; }}<br>    Output: {{ &quot;step&quot;: &quot;validate&quot;, &quot;content&quot;: &quot;Seems like 4 is correct ans for 2 + 2&quot; }}<br>    Output: {{ &quot;step&quot;: &quot;result&quot;, &quot;content&quot;: &quot;2 + 2 = 4 and this is calculated by adding all numbers&quot; }}<br>&quot;&quot;&quot;<br><br>messages: list[ChatCompletionMessageParam] = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>]<br><br>while True:<br>    prompt = input(&quot;Query &gt; &quot;)<br><br>    if prompt.lower() in {&quot;exit&quot;, &quot;quit&quot;}:<br>        print(&quot;Exiting...&quot;)<br>        break<br><br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br><br>    while True:<br>        res = client.chat.completions.create(<br>            model=&quot;gpt-4.1-mini&quot;,<br>            response_format={&quot;type&quot;: &quot;json_object&quot;},<br>            messages=messages,<br>        )<br>        messages.append(<br>            {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: res.choices[0].message.content}<br>        )<br><br>        if res.choices[0].message.content is None:<br>            print(&quot;⚠️ Assistant returned no content.&quot;)<br>            continue<br><br>        parsed_response = json.loads(res.choices[0].message.content)<br><br>        if parsed_response.get(&quot;step&quot;) != &quot;result&quot;:<br>            print(&quot;Think:&quot;, parsed_response.get(&quot;content&quot;))<br>            continue<br><br>        print(&quot;Parsed response:&quot;, parsed_response.get(&quot;content&quot;))<br><br>        break<br># Output<br>#<br># Query &gt; 5 * 3 / 5 + 24 * 3<br># Think: The user has provided an arithmetic expression involving multiplication, division, and addition: 5 * 3 / 5 + 24 * 3. The question is to evaluate this expression step-by-step.<br># Think: I need to remember the order of operations: multiplication and division are performed first from left to right, then addition. So I will first calculate 5 * 3, then divide by 5, and also calculate 24 * 3. Finally, I&#39;ll add the results together.<br># Think: Calculate 5 * 3 = 15. Then, 15 / 5 = 3. Next, calculate 24 * 3 = 72. Finally, add 3 + 72 = 75.<br># Think: I have followed the order of operations carefully, and the calculations look correct: 5*3=15, 15/5=3, 24*3=72, and 3+72=75.<br># Parsed response: The value of the expression 5 * 3 / 5 + 24 * 3 is 75. We first multiplied and divided as per order of operations, then added the final results.<br># Query &gt; exit<br># Exiting...</pre><h4>Self-Consistency Prompting</h4><p>The main goal of this prompting is to get multiple responses from multiple models and use one model to compare all the responses to make the final response accurate.</p><p><strong>Use Case:</strong> Tasks where accuracy and reliability matter — like exams, coding problems, or fact-checking.</p><blockquote>Here, <strong>Accuracy Increases</strong> but <strong>Cost</strong> also <strong>Increases.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*s3Au3VwOmUXXzL1K.png" /></figure><pre>from openai import OpenAI<br>from dotenv import load_dotenv<br>from openai.types.chat import ChatCompletionMessageParam<br><br>load_dotenv()<br><br><br>client = OpenAI()<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>    You are a helpful and experienced math teacher. <br>    Explain concepts clearly and step-by-step, using simple language when needed. <br>    Always encourage the student and make sure they understand the logic behind each step.<br>    If the question involves calculation, show your working. Be calm, supportive, and never assume prior knowledge beyond what&#39;s asked.<br>    <br>    Examples:<br>    User: What is the area of a triangle with base 10 cm and height 5 cm?<br>    Assistant: To find the area of a triangle, we use the formula:<br>        Area = ½ × base × height   <br>        Here, base = 10 cm and height = 5 cm.        <br>        So,<br>        Area = ½ × 10 × 5 = 25 cm²       <br>        The area of the triangle is 25 square centimeters.<br><br>    Examples:<br>    User: Can you explain what a prime number is?<br>    Assistant: Of course! A prime number is a number that has exactly two factors: 1 and itself. <br>        That means it can only be divided evenly by 1 and the number itself.<br>        For exmaple: 2 is prime, 3 is prime, 4 is not prime.<br>&quot;&quot;&quot;<br><br>messages: list[ChatCompletionMessageParam] = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>]<br><br>while True:<br>    prompt = input(&quot;Query &gt; &quot;)<br><br>    if prompt.lower() in {&quot;exit&quot;, &quot;quit&quot;}:<br>        print(&quot;Exiting...&quot;)<br>        break<br><br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br><br>    nano_res = client.chat.completions.create(<br>        model=&quot;gpt-4.1-nano&quot;,<br>        messages=messages,<br>    )<br><br>    print(&quot;nano teacher GPT: &quot;, nano_res.choices[0].message.content)<br><br>    mini_res = client.chat.completions.create(<br>        model=&quot;gpt-4.1-mini&quot;,<br>        messages=messages,<br>    )<br><br>    print(&quot;mini teacher GPT: &quot;, mini_res.choices[0].message.content)<br><br>    comparison_prompt = f&quot;&quot;&quot;<br>        User: {prompt}<br>        Nano Answer: {mini_res.choices[0].message.content}<br>        Mini Answer: {nano_res.choices[0].message.content}<br>        I have two answer one from Nano and another from Mini of the above question. I want you to compare these answers.<br>        Cases:<br>            Case 1: Both are correct answer.<br>            Assistant:&quot;Both are correct answers....&quot; and then choose any one answer from above.<br><br>            Case 2: Any one answer is correct. Let&#39;s say Nano is correct.<br>            Assistant:&quot;Nano answer is correct....&quot; and then choose Nano&#39;s answer from above.<br><br>            Case 3: Any one answer is correct. Let&#39;s say Mini is correct.<br>            Assistant:&quot;Mini answer is correct....&quot; and then choose Mini&#39;s answer from above.<br><br>            Case 4: Both answers are wrong.<br>            Assistant:&quot;Both answers are wrong...&quot; and then give your answer for the User question.<br>    &quot;&quot;&quot;<br>    res = client.chat.completions.create(<br>        model=&quot;gpt-4.1&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: comparison_prompt}<br>        ],<br>    )<br><br>    messages.append(<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: res.choices[0].message.content}<br>    )<br><br>    print(&quot;Teacher GPT: &quot;, res.choices[0].message.content)<br><br># Output<br># Query &gt; 5 * 3 / 5 + 24 * 3<br># nano teacher GPT:  Let&#39;s solve this step by step, following the order of operations (PEMDAS/BODMAS):<br>#<br># 1. First, handle the multiplication and division from left to right:<br>#    - \( 5 \times 3 = 15 \)<br>#    - \( 15 \div 5 = 3 \)<br>#    - \( 24 \times 3 = 72 \)<br>#<br># 2. Now, the expression becomes:<br>#    \[<br>#    3 + 72<br>#    \]<br>#<br># 3. Finally, add:<br>#    \[<br>#    3 + 72 = 75<br>#    \]<br>#<br># So, the answer is **75**!<br>#<br># mini teacher GPT:  Let&#39;s work through the expression step-by-step:<br># The expression is:<br># 5 * 3 / 5 + 24 * 3<br>#<br># Step 1: Multiply 5 by 3<br># 5 * 3 = 15<br>#<br># Now the expression is:<br># 15 / 5 + 24 * 3<br>#<br># Step 2: Divide 15 by 5<br># 15 / 5 = 3<br>#<br># Now the expression is:<br># 3 + 24 * 3<br>#<br># Step 3: Multiply 24 by 3<br># 24 * 3 = 72<br>#<br># Now the expression is:<br># 3 + 72<br>#<br># Step 4: Add 3 and 72<br># 3 + 72 = 75<br>#<br># So, the result of the expression is **75**.<br>#<br># If you want, I can explain any step in more detail!<br>#<br># Teacher GPT:  Both are correct answers. Both the Nano and Mini answers correctly solve the expression step-by-step and get the final answer of 75.<br>#<br># Here is one of the answers, chosen from above (Nano):<br>#<br># Let&#39;s work through the expression step-by-step:<br>#<br># The expression is:<br># 5 * 3 / 5 + 24 * 3<br>#<br># Step 1: Multiply 5 by 3<br># 5 * 3 = 15<br>#<br># Now the expression is:<br># 15 / 5 + 24 * 3<br>#<br># Step 2: Divide 15 by 5<br># 15 / 5 = 3<br>#<br># Now the expression is:<br># 3 + 24 * 3<br>#<br># Step 3: Multiply 24 by 3<br># 24 * 3 = 72<br>#<br># Now the expression is:<br># 3 + 72<br>#<br># Step 4: Add 3 and 72<br># 3 + 72 = 75<br>#<br># So, the result of the expression is **75**.<br>#<br># If you want, I can explain any step in more detail!<br># Query &gt; exit<br># Exiting...</pre><blockquote>Until now, the fundamental prompting techniques have been One-Shot, Few-Shot, and Chain-of-Thought prompting. Most advanced prompting methods developed later are built on top of these core techniques, with added twists or specific use-case adaptations. Like in Self-Consistency we could have use CoT for the Teacher AI Example.</blockquote><h4>Persona-based Prompting</h4><p><strong>Persona-based prompting</strong> is a technique where you guide the AI to adopt a specific role or identity — like a math teacher, doctor, interviewer, mentor, or even a sarcastic friend.</p><p>It builds on <strong>zero-shot or few-shot prompting</strong>, but adds a <strong>personality layer</strong> to control the tone, style, and depth of the AI’s responses.</p><p>For <strong>more accurate and consistent behavior</strong>, we often use <strong>few-shot prompting with 40–80 carefully crafted examples</strong>, helping the AI learn to respond exactly like the persona we want to create.</p><blockquote>I have built a persona-based AI chatbot who talks like “<strong>Hitesh Choudhary</strong>” and also written a blog on it you can <a href="https://medium.com/@shawkaran2002/imagine-having-hitesh-sir-as-your-coding-buddy-anytime-9f4a63634988">check it out</a>.</blockquote><h3>Conclusion: Key Takeaways on Prompting for Developers</h3><ol><li><strong>Prompting is your control panel for AI</strong> — it lets you guide the model’s behavior with simple, structured input.</li><li><strong>Garbage In, Garbage Out (GIGO)</strong> applies strongly — well-crafted prompts = high-quality output.</li><li><strong>Prompting styles matter</strong>:</li></ol><ul><li><strong>Alpaca</strong> for simple instructions</li><li><strong>ChatML</strong> for chat-based interaction (used by most APIs)</li><li><strong>INST format</strong> for token-based open models</li></ul><p>4.<strong> ChatML is the current standard</strong> — most developers use it, and it’s auto-converted internally for many models.</p><p>5.<strong> The</strong> system role is powerful — use it to set tone, behavior, or personality of the AI for your specific use case.</p><p>6.<strong> Use advanced techniques</strong> for better accuracy:</p><ul><li><strong>Zero-shot</strong> for quick tasks</li><li><strong>Few-shot</strong> for pattern learning</li><li><strong>Chain-of-Thought</strong> for step-by-step logic</li><li><strong>Self-consistency</strong> for reliability in reasoning</li><li><strong>Persona-Based</strong> for controlling tone, style, and behavior by assigning the AI</li></ul><p>7.<strong> Prompting is both a skill and a tool</strong> — the more you practice, the more precise and useful your AI outputs become.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0cac7c4b725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to GenAI: The Surprising Technology That Feels Magical]]></title>
            <link>https://medium.com/@shawkaran2002/an-introduction-to-genai-the-surprising-technology-that-feels-magical-ef2692bfa2c1?source=rss-9178492c0930------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef2692bfa2c1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[prompting-technique]]></category>
            <dc:creator><![CDATA[Karan Shaw]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 05:17:41 GMT</pubDate>
            <atom:updated>2025-06-26T05:17:41.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PZ1KUuvCDmiJPp9Z" /><figcaption>Photo by <a href="https://unsplash.com/@siva_photography?utm_source=medium&amp;utm_medium=referral">Levart_Photographer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will see an overview how a <strong>transformer(LLMs)</strong> works behind the scenes. This AI world is full of jargon because of marketing, which confuses lot of people. This article will be full of theory and information so take a cup of tea and enjoy reading.</p><blockquote>In the AI world, there are two main categories: Researchers, who focus on mathematics, data science, and model development, and Developers, who implement pre-trained models like LLMs into applications to enhance user experience. <br>This article primarily targets developers interested in integrating AI into their applications.</blockquote><h3>What is GenAI?</h3><p>Let’s start with first jargon word <strong><em>“GenAI”</em></strong> — <strong>Generative AI</strong>, which means AI who generate something you tell to generate by telling it (prompt) and the generated result can be anything — text, speech, document or video, etc. So, GenAI are ChatGPT, Claude, Gemini etc. They have one thing in common which is <strong><em>GPT ( Not talking about ChatGPT. All the above mention GenAI are GPTs. For marketing OpenAI was first so they took the name GPT word).</em></strong></p><h3>What is Transformer — The blackbox?</h3><p>When we first hear the word <strong>Transformer</strong>, we might imagine a program that converts one thing into another. And that’s exactly the essence of it. Think of it as a <strong>black box</strong> — you give it an input, and it gives you a transformed output, often in a completely different form, tone, or language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UOAfeJKKznQImKzW.png" /></figure><p>For example, if a Transformer model is given the word <strong>“hello”</strong>, it might return <strong>“namaste”</strong> — acting like a translator. But what’s fascinating is that you don’t see what happens inside. You don’t see how it breaks down the word, understands the meaning, context, or grammar rules. It simply takes in your request and outputs a result that feels intelligent, human-like, and relevant.</p><p>In the case of GPT, the Transformer works like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LcTDCp1uPLLH-WVo.png" /></figure><ol><li>You give it a sentence or a question — that’s your input. Then, the model tries to guess what should come next, <strong>one word at a time</strong>.</li><li>It starts by predicting the next word. Once it chooses that word, it adds it to the sentence. Then it looks at the new, longer sentence and tries to guess the next word again. This continues — word by word — until it has a complete answer or sentence.</li><li>It’s a bit like how we talk when we’re thinking out loud. You say one word, then think what fits next, then say that, and keep going until your thought is finished.</li><li>So instead of giving you the whole reply in one go, GPT is actually <strong>building the sentence step by step</strong>, thinking about what makes the most sense each time.</li></ol><h3>What basic jargon does everyone need to know?</h3><p>Let’s start with the example “<strong>This sounds familiar to me.” — </strong>In <strong><em>English</em></strong> we say its a <strong><em>sentence</em></strong> and a sentence is collection of <strong><em>words</em></strong> whereas in <strong><em>GenAI</em></strong> we say sequence and a <strong><em>sequence</em></strong> is a collection of <strong><em>tokens</em></strong>.</p><blockquote><em>These </em><strong><em>tokens</em></strong><em> are what GenAI companies use to charge in subscriptions.</em></blockquote><p>If a user provides input to LLMs, we call it the <strong><em>Input Sequence</em></strong>, and the output generated by LLMs is called the <strong><em>Output Sequence</em></strong>.</p><blockquote>Breakdown of sequence into tokens varies on the LLMs. Here for simplicity we break the sequence into tokens with words. Each LLM’s has its own vocabulary. You can check how each LLM’s break the sequences here</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtR2xEfS7VBpXrZASj0Xew.png" /></figure><h3>How the Transformer works?</h3><p>Now we will see what happens inside the blackbox.</p><p>We all agree that computers are good at numbers. They can understand number and work on them easily as compare to text, images, etc.</p><p>Before making predictions, the input sequences are converted into matrices that capture the real-world meaning of the input. This process of step we call <strong>Input Embeddings</strong>. Below we will discuss what are the steps of Input embeddings:</p><ol><li><strong>Tokenisation:</strong></li></ol><p>Its a process where the given input sequences is breakdown into smallers token and each token is given a unique number which is based on which LLMs we use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*OTI2-_PAralBGAtW.png" /></figure><pre> import tiktoken;<br> <br> enc = tiktoken.encoding_for_model(&quot;gpt-4o&quot;)<br> <br> text = &quot;Hello, I am John Doe&quot;<br> <br> tokens = enc.encode(text);<br> print(&quot;Tokens: &quot;, tokens);<br> # Tokens:  [13225, 11, 357, 939, 5928, 78200]</pre><p>2. <strong>Vector Embeddings:</strong></p><p>Here each numbers are given a meaning which is related to our real world. We use a vector space where each number has a relationship with each other. This tokens then converted to unique matrices which contains its meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*tqQ0DemK14ESOwSc.png" /></figure><p>3. <strong>Positional Encoding:</strong></p><p>Position of words in a sentence makes it meaningful but one word changes its position the sentence’s meaning changes. Same goes for the token we generate. Here we add positions meta data to each token so it persists its position and meaning of the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*mQrAS6LOgacz6s9Q.png" /></figure><p>4. <strong>Multi-Head Attention:</strong></p><p>Before knowing Multi-Head Attention, let’s see what <strong>Self Attention</strong> is ?</p><p>Self Attention is the process where each token talk to other token in the sequence to understand its meaning.</p><p>For example: <em>“The dog chased the ball because it was shiny.”</em></p><p>so what “it” refers to? is it <strong>“the dog”</strong> or <strong>“the boy”.</strong> Here Self Attention comes into the play where it <strong>look at every word</strong> and figure out that <strong>“it”</strong> most likely refers to <strong>“the ball”</strong> — because of the word <strong>“shiny.”</strong></p><p>Now <strong>Multi-Head Attention</strong> means doing the process of <strong>Self-Attention</strong> in parallel where each process analysis different part of the sequence.</p><p>The above steps are comes in <strong>Input Embedding.</strong> Now the matrices we get after input embedding then we predicts the next token and after repeated process LLM gives the relatable predicted output.</p><h3>Phases of GenAI Model</h3><p>There are mainly two phases of a GenAI Model:</p><ol><li><strong>Training Phase:</strong></li></ol><p>Here we teach the model by giving huge amount of data, pattern, etc. In this phase,</p><ul><li>We give the model one input and its <strong>required</strong> <strong>output</strong>.</li><li>The model predicts the output of the <strong>given</strong> <strong>input</strong> lets say <strong>predicted output.</strong></li><li>Model calculate the difference between the <strong>predicted output</strong> and <strong>required output,</strong> lets say <strong>error.</strong></li><li>If the <strong>error</strong> is high, the model <strong>adjusts its internal settings</strong> (called parameters or weights) to improve next time (This process is called <strong><em>Back Propagate</em></strong>).</li><li>This continues until model’s predictions are <strong>close enough</strong> to the correct answers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*262GSu2KD5GY_Q4T.png" /></figure><p>2. <strong>Inference Phase:</strong></p><p>In this phase, user uses the model, gives input (prompt) and generates the output based on the pre-trained data.</p><h3>Recap: Putting It All Together</h3><ul><li>Learned the meaning of GenAI and GPT.</li><li>Learned about the transformer and what happen in AI Transformer.</li><li>Overview what happens inside the Transformer.</li><li>Phases of a AI model.</li></ul><p>Now you know that GenAI isn’t magic. You provide some input, and it generates an output that seems magical, but behind the scenes, it’s just doing some number crunching.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef2692bfa2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>