<?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[GenAI with Mubashir]]></title><description><![CDATA[GenAI with Mubashir]]></description><link>https://genaiwithmub.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 20 Sep 2026 00:52:24 GMT</lastBuildDate><atom:link href="https://genaiwithmub.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Query Transformation - RAG series]]></title><description><![CDATA[Hey everyone, welcome to the Gen AI series.
I hope you have enjoyed the previous blog where we discussed step by step how to chat to our PDF using RAG approach.
We will be continuing that code and modifying it to get more accurate results.
Introducti...]]></description><link>https://genaiwithmub.hashnode.dev/query-transformation-rag-series</link><guid isPermaLink="true">https://genaiwithmub.hashnode.dev/query-transformation-rag-series</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[genai]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[Mubashir Ahmed]]></dc:creator><pubDate>Wed, 23 Apr 2025 13:09:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745413678240/0795afc9-53d2-467e-9398-7f48ae460310.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey everyone, welcome to the Gen AI series.</p>
<p>I hope you have enjoyed the previous <a target="_blank" href="https://genaiwithmub.hashnode.dev/rag-decomposed">blog</a> where we discussed step by step how to chat to our PDF using RAG approach.</p>
<p>We will be continuing that code and modifying it to get more accurate results.</p>
<h2 id="heading-introduction-to-query-transformation">Introduction to Query Transformation</h2>
<p>The entire game is of getting relevant answer to the user, getting what the user not just ‘asked‘, but what the user intends to ask.</p>
<p>We are already aware of Google search, do we get only what we have searched for, or all the things related and relevant to that query?</p>
<p>User’s query is not accurate enough to get what he actually needs</p>
<p>It has to be polished enough to get that specific thing from the AI</p>
<p>User’s Query - can be more abstract and can be less abstract as well</p>
<blockquote>
<p>Ek example -</p>
<p>Let’s say aap ki ek dukaan hai hardware ki, waha pe sirf aap ku pata hai ki konsi chiz kidhar hai and kya naam hai etc etc</p>
<p>Ab aap ko zarurat padgayi ki ek ladke ko dukaan par rakhe - gaahak bahut zyada hai, dukaan badi hai</p>
<p>Ab usko kuch kuch chize malum hai, lekin experience dukaan ka nahi hai</p>
<p>Isliye wo pehle din se sahi kaam nahi karega, galtiya karega, ek maango koi aur chiz laayega,</p>
<p>isko pehle se hi samjhana hoga ki gaahak kya kahega - gaahak shyd kuch aur puche, gaahak ko shyd na maloom ho us chiz ke bare me, gaahak galti se kuch aur puch le</p>
<p>Ab aapko ye sab train karna hoga so that apka ladka jab aap na ho dukaan par, jab bhi wo usko sambhal sake</p>
<p>Aise hi RAGs ka masla hai, they are intelligent, but still we need to polish them and make them reiterate on what user has asked and what to respond to him…</p>
</blockquote>
<h2 id="heading-parallel-query-fan-out-retrieval">Parallel Query - Fan out retrieval</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745387141677/06f53e15-f7c4-4021-8c08-8a30ecea00cc.png" alt class="image--center mx-auto" /></p>
<p>Let’s explore how this approach works</p>
<p>So, here we will be using langchain package</p>
<p>First, we have to import Multi Query Retriever</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> langchain.retrievers.multi_query <span class="hljs-keyword">import</span> MultiQueryRetriever
<span class="hljs-keyword">from</span> langchain_openai <span class="hljs-keyword">import</span> ChatOpenAI
</code></pre>
<p>Then, we need to call this Multi Query retriever on the regular retriever we have</p>
<p>Before that, we need multiple queries generated from the user query, so we are using ChatOpenAI model to perform that task</p>
<pre><code class="lang-python">llm = ChatOpenAI(
    model_name=<span class="hljs-string">"gpt-4o-mini"</span>,
    temperature=<span class="hljs-number">0</span>,
    openai_api_key=os.environ.get(<span class="hljs-string">"OPENAI_API_KEY"</span>)  
)
</code></pre>
<p>Next, we will be using multi query retriever to do multiple similarity searches and get relevant chunks from them and then we can derive the context for our AI model</p>
<pre><code class="lang-python">retriever = QdrantVectorStore.from_existing_collection(
    url=<span class="hljs-string">"http://localhost:6333"</span>,
    collection_name=<span class="hljs-string">"langchain_learning"</span>,
    embedding=embedder
)

multi_query_retriever = MultiQueryRetriever.from_llm(
    retriever=retriever.as_retriever(),
    llm=llm
)
</code></pre>
<p>Final step is to set the context and log our output, here it internally selects unique chunks from multiple results and returns that</p>
<pre><code class="lang-python">relevant_docs = multi_query_retriever.invoke(user_query)

SYSTEM_PROMPT = <span class="hljs-string">f"""
    You are a helpful AI assistant who has access to a specific document of user,
    and user will ask questions from it, answer only those,
    i have given you context from where you have to answer it

    context=<span class="hljs-subst">{relevant_docs}</span>
"""</span>

response = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages = [
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: SYSTEM_PROMPT},
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: user_query},
    ]
)

print(response.choices[<span class="hljs-number">0</span>].message.content)
</code></pre>
<p>The output i got for the question “Explain the major challenges faced during AI model deployment.“</p>
<blockquote>
<p>The major challenges faced during AI model deployment include:</p>
<ol>
<li><p><strong>Adjusting Workflows</strong>: Developers need to adapt their existing workflows, prompts, and data to work with the new models, which can have unique quirks, strengths, and weaknesses.</p>
</li>
<li><p><strong>Versioning and Evaluation Infrastructure</strong>: Without proper infrastructure in place for versioning and monitoring the performance of the models, deployment can lead to numerous complications and operational headaches.</p>
</li>
<li><p><strong>Regulatory Changes</strong>: Regulations surrounding AI technologies are constantly evolving. For example, AI resources can be heavily regulated as national security issues, and compliance with regulations such as the GDPR can be costly and complex.</p>
</li>
<li><p><strong>Compute Resource Availability</strong>: Changes in laws can suddenly limit access to compute resources, such as being banned from purchasing GPUs from certain vendors, impacting the ability to deploy models effectively.</p>
</li>
<li><p><strong>Intellectual Property Concerns</strong>: There are uncertainties regarding intellectual property when utilizing models trained on data that may not be owned by the developer. This can create hesitancies, especially for companies deeply invested in their IP.</p>
</li>
</ol>
<p>These challenges highlight the importance of thorough planning and consideration of the evolving landscape of AI deployment.  </p>
</blockquote>
<p>Stay tuned, as we will discuss more approaches in Query Transformation in our upcoming blogs</p>
<ul>
<li><p>Reciprocate Rank Fusion</p>
</li>
<li><p>Query Decomposition</p>
</li>
</ul>
<p>Well, this is the end of one of the concepts of Advanced Rag approaches - Parallel Query Retrieval.</p>
<p>See you in the next blog</p>
<p>Let’s connect here on <a target="_blank" href="https://x.com/Mubashir_061">Twitter</a></p>
<p>Peace out ✌️</p>
]]></content:encoded></item><item><title><![CDATA[RAG decomposed]]></title><description><![CDATA[Hey folks, welcome back again to GenAI series
This is your friend Mubashir
Today we’ll be discussing an interesting thing that is RAG…
I have covered all the steps in detail, open your vs code or any IDE you use, and let’s code together
Rerieval-Augm...]]></description><link>https://genaiwithmub.hashnode.dev/rag-decomposed</link><guid isPermaLink="true">https://genaiwithmub.hashnode.dev/rag-decomposed</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[genai]]></category><dc:creator><![CDATA[Mubashir Ahmed]]></dc:creator><pubDate>Sat, 19 Apr 2025 06:25:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745043845089/dc10bce9-22a0-40c9-89c1-1441306a12be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey folks, welcome back again to GenAI series</p>
<p>This is your friend <a target="_blank" href="https://x.com/Mubashir_061">Mubashir</a></p>
<p>Today we’ll be discussing an interesting thing that is RAG…</p>
<p>I have covered all the steps in detail, open your vs code or any IDE you use, and let’s code together</p>
<p>Rerieval-Augmented Generation — an AI technique that combines the power of retrieving information using LLMs, so that accuracy and context-awareness of AI models can be enhanced.</p>
<p>Getting relevant data to the user according to their needs is a difficult thing</p>
<ol>
<li><p>Indexing → Data source - chunking - Vector embeddings - stored in vector DB</p>
</li>
<li><p>User asks a query → make vector embeddings - search in vector DB - we get relevant chunks - filter out the chunks - AI being called (with relevant chunks and user query)</p>
</li>
<li><p>Implementation- Langchain</p>
</li>
</ol>
<p>Let’s make a RAG on PDFs - in simple terms, let’s talk to our pdfs…</p>
<p>first step is to install pdfloader</p>
<pre><code class="lang-python">pip install langchain_community pypdf
</code></pre>
<h3 id="heading-lets-first-start-by-loading-a-pdf">Let’s first start by loading a PDF</h3>
<p>So, we need to give path to our loader - here is a dynamic way to give path using pathlib library.</p>
<p>After calling load() function - print what the loader has, and you will see the contents of your pdf</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> langchain_community.document_loaders <span class="hljs-keyword">import</span> PyPDFLoader
<span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path

file_path = Path(__file__).parent / <span class="hljs-string">"AI_Engineering.pdf"</span>
loader = PyPDFLoader(file_path)

docs = loader.load()

print(docs[<span class="hljs-number">50</span>])
</code></pre>
<h3 id="heading-now-its-time-for-splitting-the-text">Now it’s time for splitting the text</h3>
<pre><code class="lang-python">pip install langchain_text_splitters
</code></pre>
<p>There is one issue still, while splitting - which one is correct fit for us<br />For PDFs we need RecursiveCharacterTextSplitter</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> langchain_text_splitters <span class="hljs-keyword">import</span> RecursiveCharacterTextSplitter
</code></pre>
<p>Now, we’ll call the text splitter, we need to also mention how many chunks we need and for better context, do we need to have overlaps between chunks?</p>
<pre><code class="lang-python">text_splitter = RecursiveCharacterTextSplitter(chunk_size=<span class="hljs-number">1000</span>, chunk_overlap=<span class="hljs-number">200</span>)
</code></pre>
<p>Once we have set the number if chunks and overlaps, it is time for applying it on our document</p>
<pre><code class="lang-python">split_docs = text_splitter.split_documents(documents=docs)
</code></pre>
<p>Chunking part is done</p>
<p>Now let’s move on with “Embeddings“</p>
<p>Let’s install langchain’s openAI embedding model</p>
<pre><code class="lang-python">pip install langchain-openai
</code></pre>
<p>Now import it</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> langchain_openai <span class="hljs-keyword">import</span> OpenAIEmbeddings
</code></pre>
<p>Let’s call the embedding model and specify a model and our API_KEY</p>
<pre><code class="lang-python">embedder = OpenAIEmbeddings(
    model=<span class="hljs-string">"text-embedding-3-large"</span>,
    api_key=<span class="hljs-string">"YOUR_API_KEY"</span>
)
</code></pre>
<p>Now it is time to embed our document as vectors and store it in a DB, not a regular DB but a vector database.</p>
<p>We’ll go with <a target="_blank" href="https://qdrant.tech/">Qdrant DB</a></p>
<p>Let’s install it</p>
<pre><code class="lang-python">pip install qdrant-client
</code></pre>
<p>After this, we have to setup DB on <a target="_blank" href="https://www.docker.com/get-started/">Docker</a>, so we’ll create a <mark>docker-compose.db.yml</mark> file</p>
<p>Inside that file we have to write the below code</p>
<pre><code class="lang-python">services:
  qdrant:
    image: qdrant/qdrant
    ports:
      - <span class="hljs-number">6333</span>:<span class="hljs-number">6333</span>
</code></pre>
<p>To run this docker file, paste the below command</p>
<pre><code class="lang-python">docker compose -f docker-compose.db.yml up
</code></pre>
<p>Done</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744972325684/a249bef0-c238-4681-82f5-397b6df64198.png" alt class="image--center mx-auto" /></p>
<p>Now it’s time to install langchain-qdrant</p>
<pre><code class="lang-python">pip install langchain-qdrant
</code></pre>
<p>Import Qdrant client and vector store in our code now</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> qdrant_client <span class="hljs-keyword">import</span> QdrantClient
<span class="hljs-keyword">from</span> langchain_qdrant <span class="hljs-keyword">import</span> QdrantVectorStore
</code></pre>
<p>Create a collection now, it needs url of Qdrant db, collection name and the embedder.</p>
<p>This documents parameter will create a collection for us, if there are no collections in vector DB</p>
<pre><code class="lang-python">vector_store = QdrantVectorStore.from_documents(
    documents=[],
    url=<span class="hljs-string">"http://localhost:6333"</span>,
    collection_name=<span class="hljs-string">"langchain_learning"</span>,
    embedding=embedder
)
</code></pre>
<p>Also we need to add those split_docs to our vector_store</p>
<pre><code class="lang-python">vector_store.add_documents(documents=split_docs)
</code></pre>
<p>Now run the code and checkout this url</p>
<pre><code class="lang-python">http://localhost:<span class="hljs-number">6333</span>/dashboard
</code></pre>
<p>Once you see the injection is done, you can check the dashboard</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744975507410/178340f8-0059-4478-b1c1-5292a2a4acd7.png" alt class="image--center mx-auto" /></p>
<p>Now, comment that specific part of storing the data in vector DB as we are done with it</p>
<pre><code class="lang-python"><span class="hljs-comment"># vector_store = QdrantVectorStore.from_documents(</span>
<span class="hljs-comment">#     documents=[],</span>
<span class="hljs-comment">#     url="http://localhost:6333",</span>
<span class="hljs-comment">#     collection_name="langchain_learning",</span>
<span class="hljs-comment">#     embedding=embedder</span>
<span class="hljs-comment"># )</span>

<span class="hljs-comment"># vector_store.add_documents(documents=split_docs)</span>
</code></pre>
<p>This same we have to do now, but for retrieving the data from the DB</p>
<pre><code class="lang-python">retriever = QdrantVectorStore.from_existing_collection(
    url=<span class="hljs-string">"http://localhost:6333"</span>,
    collection_name=<span class="hljs-string">"langchain_learning"</span>,
    embedding=embedder
)
</code></pre>
<p>Now, let’s do the main thing, getting the data from the DB for which we were writing these many lines of code</p>
<pre><code class="lang-python">relevant_chunks =retriever.similarity_search(
    query=<span class="hljs-string">"What are vector embeddings?"</span>
)
</code></pre>
<p>Done, now just we have to set up the OpenAI’s response for user’s queries (last and the most important part)</p>
<p>Install OpenAI</p>
<pre><code class="lang-python">pip install openai
</code></pre>
<p>import it and write a system prompt for it also include our final output - ‘relevant_chunks‘ variable</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI
client = OpenAI()

SYSTEM_PROMPT = <span class="hljs-string">f"""
    You are a helpful AI assistant who has access to a specific document of user,
    and user will ask questions from it, answer only those,
    i have given you context from where you have to answer it

    context=<span class="hljs-subst">{relevant_chunks}</span>
"""</span>

response = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages = [
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: SYSTEM_PROMPT},
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: user_query},
    ]
)

print(response.choices[<span class="hljs-number">0</span>].message.content)
</code></pre>
<p>boom, you’re done</p>
<p>let’s look at the output for our query</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745043057490/51c244a4-1926-4ec4-adb8-f0102116edcf.png" alt class="image--center mx-auto" /></p>
<p>Hope you’ve enjoyed this, let me know in the comments.</p>
<p>Let’s connect on <a target="_blank" href="https://x.com/Mubashir_061">twitter</a> for further discussions</p>
<p>Peace out ✌️</p>
]]></content:encoded></item><item><title><![CDATA[Prompt Engineering cracked]]></title><description><![CDATA[Hey there fren 👋
Welcome to the GenAI blogs series
Today we are discussing prompt engineering, how to draft a better prompt so that we can utilize AI the best way possible.
What is a prompt??
An instruction given to the model, technically they are t...]]></description><link>https://genaiwithmub.hashnode.dev/prompt-engineering-cracked</link><guid isPermaLink="true">https://genaiwithmub.hashnode.dev/prompt-engineering-cracked</guid><category><![CDATA[genai]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[#PromptEngineering]]></category><category><![CDATA[generative ai]]></category><dc:creator><![CDATA[Mubashir Ahmed]]></dc:creator><pubDate>Fri, 11 Apr 2025 10:36:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744367653898/2aa3488b-0438-4378-b61f-c595e93c8b79.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there fren 👋</p>
<p>Welcome to the GenAI blogs series</p>
<p>Today we are discussing prompt engineering, how to draft a better prompt so that we can utilize AI the best way possible.</p>
<h2 id="heading-what-is-a-prompt">What is a prompt??</h2>
<p>An instruction given to the model, technically they are the initial tokens provided to the model.</p>
<h2 id="heading-alpaca-prompt-self-instruct-method">Alpaca prompt - “Self instruct method“</h2>
<p>Alpaca (Llama-7B) is a model that was trained by meta using self-instruct method - it includes three things → instruction, input and output</p>
<pre><code class="lang-python">Instruction: {instruction}
Input: {input}
Response:
</code></pre>
<h2 id="heading-inst-format-instruction-tuned-models">inst format - Instruction tuned models</h2>
<p>Models trained like this are usually to behave more like helpful assistants rather than just predicting the next word.</p>
<pre><code class="lang-javascript">&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt;
{{ system_prompt }}
&lt;&lt;/SYS&gt;&gt;

{{ user_message }} [/INST]
</code></pre>
<ul>
<li><p>The INST part is filled with instructions that the model has to follow.</p>
</li>
<li><p>System prompt is wrapped inside «SYS»…«/SYS» tags, where the model is assigned with a role.</p>
</li>
<li><p>And finally the user query or message is written.</p>
</li>
</ul>
<pre><code class="lang-javascript">&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt;
You are a helpful and concise AI assistant.
&lt;&lt;/SYS&gt;&gt;

Explain the difference between supervised and unsupervised learning <span class="hljs-keyword">in</span> simple terms. [/INST]
</code></pre>
<h2 id="heading-chat-ml-openai-format">chat ml openai format</h2>
<p>This is the most significant thing, it is used in chatGPT, which is made by openAI.</p>
<pre><code class="lang-javascript">&lt;|system|&gt;
You are a helpful assistant.
&lt;|user|&gt;
Explain gravity <span class="hljs-keyword">in</span> simple terms.
&lt;|assistant|&gt;
Gravity is a force that pulls objects toward each other...
</code></pre>
<p>So, if you have ever tried building upon openAI’s api, then you have definitely used this</p>
<pre><code class="lang-json">[
  {<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 helpful assistant."</span>},
  {<span class="hljs-attr">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">"content"</span>: <span class="hljs-string">"What is gravity?"</span>},
  {<span class="hljs-attr">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-attr">"content"</span>: <span class="hljs-string">"Gravity is..."</span>}
]
</code></pre>
<p>In short, it is a clean, extensible, and readable way for conversations.</p>
<h1 id="heading-prompting-styles">Prompting styles</h1>
<p>In a prompt, there are majorly two parts - Instruction and context</p>
<p>So based on this we have few different styles of prompting</p>
<h2 id="heading-zero-shot-prompting">Zero shot prompting</h2>
<p>In this style - we straight away ask the AI our queries - no context nothing - solely trusting AI’s pre-trained knowledge</p>
<pre><code class="lang-plaintext">Translate the following sentence to French:
"The cat is on the roof."

# it gives the answer as expected
Le chat est sur le toit.
</code></pre>
<h2 id="heading-few-shot-prompting">Few shot prompting</h2>
<p>On contrary, here along with the instruction we provide few examples to the model</p>
<pre><code class="lang-plaintext">Translate English to French:

English: The sun is shining.  
French: Le soleil brille.

English: I love chocolate.  
French: J'aime le chocolat.

English: The cat is on the roof.  
French:
</code></pre>
<p>This style is used when the output is ambiguous or has some hidden knack in it etc</p>
<blockquote>
<p>What is system prompt - sets initial context, so that it can be controlled by developer from getting manipulated by the user</p>
</blockquote>
<h2 id="heading-chain-of-thought-prompting">Chain of thought prompting</h2>
<p>This is the style which even we follow while we solve math problems, like we used to do in high school</p>
<p>So, when we solve step by step then it is less error prone.</p>
<p>I still remember in my 11th standard (inter 1st year) final exams, i lost my marks in simple pythagorean problem just due to skipping 2 steps and landing into a wrong solution.</p>
<p>The same applies here, when AI model addresses any query step by step, it can perform better and be less erroneous.</p>
<p>Let’s take a math question and solve it using AI model using this specific approach</p>
<pre><code class="lang-plaintext">Prompt: "If a train travels 60 km in 1.5 hours,
then continues at twice the speed for another 2 hours,
how far did it go in total? Let’s solve this step by step."
</code></pre>
<pre><code class="lang-plaintext">AI’s Chain-of-Thought Response: 

First, calculate the speed of the train in the first part: 
Speed = 60 km / 1.5 hours = 40 km/h 

In the second part, the train goes at twice the speed: 2 × 40 = 80 km/h

It travels at 80 km/h for 2 hours: 80 × 2 = 160 km 

Total distance = First part + Second part = 60 + 160 = 220 km

Final Answer: 220 km
</code></pre>
<h2 id="heading-self-consistency-prompting">Self consistency prompting</h2>
<p>This builds on Chain of Thought prompting, but more smarter than previous method.</p>
<p>Instead of trusting the model’s <strong>first</strong> chain of thought, we ask it to generate <strong>multiple reasoning paths</strong> and then take a <strong>majority vote</strong> on the answer.</p>
<p>Because sometimes the model gets it right only after a few tries. Picking the most frequent or consistent output improves accuracy.</p>
<h4 id="heading-how-it-works">How it works:</h4>
<ul>
<li><p>Ask the same question multiple times using CoT prompting.</p>
</li>
<li><p>Collect multiple outputs.</p>
</li>
<li><p>Choose the most common or reasonable answer.</p>
</li>
</ul>
<p>It’s like brainstorming with yourself and going with the most agreed-upon solution</p>
<h2 id="heading-role-based-prompting">Role based prompting</h2>
<p>More than just the above styles, AI model can disguise itself as someone else’s personality or say takes up a role.</p>
<p>This is the most general thing we have done in projects and daily prompting i believe.</p>
<pre><code class="lang-plaintext">Act as a linux admin, 
You are an intelligent AI model
You're a math teacher...
</code></pre>
<h2 id="heading-contextual-prompting">Contextual prompting</h2>
<p>This style is specifically used in personalized chatbots, say customer help support bots, where the bot has to be aware of the company’s stuff and the services they do etc</p>
<p>Even when we chat with chatGPT or any other model, the chat history and previous chats matters and it helps us a lot in framing our queries.</p>
<p>This one also a great selling point just to keep the context safe and history of our chats.</p>
<h2 id="heading-multi-modal-prompting">Multi modal prompting</h2>
<p>Modals here refer to different input/output types other than text - audio, video, images, files etc</p>
<p>LLMs like <strong>GPT-4-Vision, Gemini, Claude 3</strong>, or <strong>MM1</strong> can process multiple modalities — and respond in kind.</p>
<p>So, once i tried giving video to gemini and extract the speech in the form of text from it - and boom, it was a banger - this is a great money making thing if properly utilized.</p>
<hr />
<p>I hope you have enjoyed it, let me know in the comments which one do you use the most 😉</p>
<p>Follow me here on <a target="_blank" href="https://x.com/Mubashir_061">X/Twitter</a></p>
<p>Peace out ✌️</p>
]]></content:encoded></item><item><title><![CDATA[Decoding AI Jargons with Chai]]></title><description><![CDATA[You ask a simple question. But behind the scenes, a lot is happening.

Your words get tokenized—broken into tiny pieces—then turned into vector embeddings that carry their meaning. These embeddings pass through encoders, layer after layer, guided by ...]]></description><link>https://genaiwithmub.hashnode.dev/decoding-ai-jargons-with-chai</link><guid isPermaLink="true">https://genaiwithmub.hashnode.dev/decoding-ai-jargons-with-chai</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[ChaiCohort]]></category><category><![CDATA[genai]]></category><category><![CDATA[generative ai]]></category><dc:creator><![CDATA[Mubashir Ahmed]]></dc:creator><pubDate>Tue, 08 Apr 2025 17:29:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744094994267/083b3cc7-6a0a-4326-adaa-0d079d41723e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You ask a simple question. But behind the scenes, a lot is happening.</p>
<blockquote>
<p><em>Your words get</em> <strong><em>tokenized</em></strong>—<em>broken into tiny pieces—then turned into</em> <strong><em>vector embeddings</em></strong> <em>that carry their meaning. These embeddings pass through</em> <strong><em>encoders</em></strong>, <em>layer after layer, guided by</em> <strong><em>attention</em></strong> <em>to focus on the right parts. They travel through a huge</em> <strong><em>transformer</em></strong> <em>model made of deep neural networks, trained on massive amounts of data. The AI looks at everything within its</em> <strong><em>context window</em></strong>, <em>uses learned</em> <strong><em>weights</em></strong> <em>to understand what matters, and runs</em> <strong><em>softmax</em></strong> <em>math to guess the next word. The</em> <strong><em>decoder</em></strong> <em>then builds your reply, picking from a giant</em> <strong><em>vocab</em></strong>.</p>
</blockquote>
<p>Don’t worry 😅, we’ll decode this, step by step.</p>
<h1 id="heading-phase-1-input-and-encoding">Phase 1: Input and Encoding</h1>
<p>Let’s say user gives an input to chatGPT: <em>“What is the meaning of Artificial Intelligence?”</em></p>
<p>This input is first divided into smaller chunks that is tokens (some numbers), as we know machines don’t take input in our language, rather they convert it into numbers, so this is how it goes</p>
<p>Let’s see that in real time from a website called <a target="_blank" href="https://tiktokenizer.vercel.app/">TikTokenizer</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744109039210/c6f09471-2187-402f-b384-77a91e36a4ef.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-tokens-to-vector-embeddings">Tokens to vector embeddings</h3>
<p>Now that the text is being converted to tokens - it’s time for vector embeddings</p>
<p>The main motive of vector embeddings is to get the <em>semantic meaning</em> of the words</p>
<p>Every word has its vector form…</p>
<p>huh, wait 😌</p>
<p>See, imagine you heard a sentence, so your brain processes it first right?</p>
<p>In this AI world, our brain is resembled as a ‘high dimensional map‘, like our brain is full of memories, emotions etc</p>
<p>Similarly, every token has a vector in this high dimensional world.</p>
<p>When we hear the word ‘APPLE‘ - we might think of a fruit / brand - apple or something else.</p>
<p>So, the token of Apple has a vector in AI world and this way AI understands what the user actually meant</p>
<p>This is the entire process of VECTOR EMBEDDING.</p>
<p>Still, there’s a problem…</p>
<p>If we take two sentences say “Earth is bigger than Moon“ and “Moon is bigger than Earth“.</p>
<p>The meaning of both is opposite, but their tokens are same as the words are same in both the sentences though their <em>positions</em> are different.</p>
<p>Exactly, the position matters, the way the words are arranged makes <em>sense</em>, so we just can’t vectorize them, we need to take care of their positions too.</p>
<h3 id="heading-positional-encoding">Positional encoding</h3>
<p>So, the sentences have different meaning due to positions of the words in it.</p>
<p>We know this, but the machine doesn’t, hence we need to specify it by Positional encoding</p>
<p>The part of making sense - is done by positional encoding.</p>
<p>Every token is given a little info related to its context, where now two same words or tokens might not have same position.</p>
<p>You can refer to this <a target="_blank" href="https://medium.com/@sachinsoni600517/positional-encoding-in-transformer-2cc4ec703076">article</a> for in depth explanation of Positional encoding.</p>
<h1 id="heading-phase-2-understanding-the-input">Phase 2: Understanding the Input</h1>
<h3 id="heading-self-attention-mechanism">Self attention mechanism</h3>
<p>This is simply about - which word or token needs more attention.</p>
<p>For example, let’s take a sentence “He poured water into the glass because it was empty.“</p>
<p>Now the words/tokens here communicate with each other and make relationships among them, so that which one needs attention can be determined.</p>
<p>If we look at the sentence, we as a human know - it was empty, here “it“ refers to the glass.</p>
<p>How could the AI determine it, so the token ‘it‘ goes around and makes connections with words to make sense and give proper context at the end.</p>
<blockquote>
<p>Attention is the brain of the model. It lets every word look at other words in the sentence and ask,<br /><strong>“Who matters to me right now?”</strong></p>
</blockquote>
<p>This is just one case, there is a lot to understand, so we need multiple forms of attention, hence the “Multi head attention“ concept.</p>
<h3 id="heading-multi-head-attention">Multi head attention</h3>
<p>Of course, there is not only a single aspect that needs attention, but there are lots of other aspects to look around, so every aspect is handled by single ‘head‘ and the final output comes as a rich, multi-dimensional view of the sentence.</p>
<p>A simple example of this situation would be,</p>
<blockquote>
<p>It’s like having a group of experts in a room — each focusing on a different part of the problem — and then merging their thoughts.</p>
</blockquote>
<h1 id="heading-phase-3-learning-and-decision-making">Phase 3: Learning and Decision making</h1>
<p>Everything we’ve seen so far — tokenization, embeddings, positional encoding, attention —<br />all of it happens <strong>inside a powerful architecture called the Transformer.</strong></p>
<p>Inside this <strong>Transformer</strong> there is an encoder and a decoder, and in between, there’s layer after layer of <strong>deep neural networks.</strong></p>
<p>We have seen encoding part, decoding will be done at the end.</p>
<p>Next up is neural networks, something which we already born with…😉</p>
<h3 id="heading-neural-networks">Neural Networks</h3>
<p>Neural networks can be understood easily if we think of it as our brains 🧠.</p>
<p>Our brains learn by building <strong>associations</strong>.<br />You people remember toppers?<br />how they used to learn easily and faster than others.<br />They used to create <strong>mnemonics</strong>, like:</p>
<blockquote>
<p>🎨 Resistor color code?<br />BB ROY of Great Britain had a Very Good Wife</p>
</blockquote>
<p>This is learning by <strong>connecting ideas</strong> — and the brain reinforces the strongest, smartest ones.</p>
<p>AI tries to do the same thing with <strong>neural networks</strong>.<br />Instead of neurons, we’ve here artificial ones. Instead of mnemonics, we’ve here the <strong>weights</strong> that adjust over time.<br />When a prediction is right, we <strong>reinforce</strong> that path. When it’s wrong, we adjust it — until the system “remembers” what works best.</p>
<p>How do we adjust in Ai world</p>
<p>That’s where <strong>backpropagation</strong> comes in.</p>
<h3 id="heading-back-propagation-and-weights">Back propagation and Weights</h3>
<p>It is like feedback which we humans take to improve and not to repeat any mistake of past.</p>
<p>For example, imagine there is a little kid, who knows nothing about right or wrong.<br />They don’t know what’s right or wrong, and explore and learn on the go.</p>
<p>So, one day, the kid <strong>pushes another child</strong>.<br />The parents scold them. Maybe a slap on the hand. The message is loud and clear that it is not okay…</p>
<p>Next time, the kid <strong>helps someone</strong> — picks up a fallen toy, shares a snack.<br />This time, they get good appreciation, maybe chocolate…<br />The brain of the kid notes it down: “That’s good. Let’s do that again.”</p>
<p>That’s how kids learn. Not by being told everything upfront, but by <strong>trial and error</strong>, followed by <strong>feedback</strong> — negative or positive.</p>
<p>Now AI isn’t much different.</p>
<p>When a model makes a prediction — say, the next word in a sentence — it doesn’t <em>know</em> it’s wrong right away.<br />But once the <strong>error is calculated</strong>, it sends that info <strong>back</strong> through the model (<strong>backpropagation.,.,.,.,</strong>).</p>
<p>Bad guesses = reduce the weights.<br />Good guesses = increase the weights.</p>
<p>Weight is just a number that determines how strong the connection is,</p>
<blockquote>
<p>In neural networks, weights are numerical values associated with connections between neurons, determining the strength of those connections and influencing the network's predictions and learning process.</p>
</blockquote>
<p>Just like a child, over time the model learns what “feels right” based on <strong>rewards and corrections</strong>.</p>
<p>Hope you got it 🙃.</p>
<p><img src="https://www.comet.com/site/wp-content/uploads/2023/07/Screen-Shot-2023-07-16-at-4.37.05-PM.png" alt="The original transformer architecture, as visualized in the 2017 paper that made them famous, Attention Is All You Need." /></p>
<h1 id="heading-phase-4-generating-the-output">Phase 4: Generating the output</h1>
<h3 id="heading-vocab">Vocab</h3>
<p>Vocab is short for Vocabulary, it is just what the <strong>complete set of all tokens</strong> the model knows</p>
<p>So when we say "the model has a vocab of 50,000 tokens", it means:</p>
<p>The model can only understand and generate from <strong>those 50,000 pieces</strong> (words, sub-words, punctuation, etc.)</p>
<p>So, each vocab has 3 things with it</p>
<blockquote>
<p>Unique ID</p>
<p>Vector representation</p>
<p>Logit score</p>
</blockquote>
<h3 id="heading-softmax">Softmax</h3>
<p>Now, it’s time for response - output for the input provided by user</p>
<p>From the trnasformer, after iterating few times, the output is generated asa scores - numbers assigned to each word in the “vocab“</p>
<p>We’ll see what is vocab next.</p>
<p>raw scores are like</p>
<ul>
<li><p>"the": 4.2</p>
</li>
<li><p>"AI": 7.9</p>
</li>
<li><p>"is": 6.3, ...</p>
</li>
</ul>
<p>So these raw scores of output tokens are converted into probability - such that it sums up to 100%</p>
<p>The one with higher percentage will be the ‘output - next word‘, something like this…</p>
<ul>
<li><p><code>"AI"</code>: 72%</p>
</li>
<li><p><code>"is"</code>: 20%</p>
</li>
<li><p><code>"the"</code>: 8%</p>
</li>
</ul>
<h3 id="heading-temperature">Temperature</h3>
<p>So, think of <strong>temperature</strong> as the <strong>level of randomness</strong> in the model’s replies.</p>
<p>This handles the randomness part of the response of an AI model</p>
<p>As we are aware of softmax, it is used to assign probabilities to all tokens in its vocab.</p>
<p>Now comes the temperature part, it tweaks these probabilities <strong>before</strong> the model picks the next token.</p>
<p>Let’s take a small example</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Token</td><td>Probability (Temp = 1.0)</td></tr>
</thead>
<tbody>
<tr>
<td><code>"dog"</code></td><td>0.65</td></tr>
<tr>
<td><code>"cat"</code></td><td>0.25</td></tr>
<tr>
<td><code>"spaceship"</code></td><td>0.10</td></tr>
</tbody>
</table>
</div><p>The lesser the temperature, there’s <strong>highest probability that model will select this often</strong> (here, <code>"dog"</code>)</p>
<p>The higher the temperature, flattens the probabilities, giving less likely words (like <code>"spaceship"</code>) a better chance of being picked.</p>
<h3 id="heading-decoder">Decoder</h3>
<p>The decoder <strong>picks the next token</strong> based on those probabilities (temperature will affect this).</p>
<p>Then it does the same steps again (with the new token added) to generate the <strong>next word</strong>, and so on…</p>
<p>Until you get the full output…</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Perfect, now do you remember the paragraph we read in the beginning?</p>
<blockquote>
<p>Your words get tokenized—broken into tiny pieces—then turned into vector embeddings that carry their meaning. These embeddings pass through encoders, layer after layer, guided by attention to focus on the right parts. They travel through a huge transformer model made of deep neural networks, trained on massive amounts of data. The AI looks at everything within its context window, uses learned weights to understand what matters, and runs softmax math to guess the next word. The decoder then builds your reply, picking from a giant vocab.</p>
</blockquote>
<p>Well… now you’ve decoded it 😤.</p>
<p>So, if we do a quick recap of what we have learnt so far,</p>
<ul>
<li><p><strong>Tokens</strong> are just numberized word-pieces,</p>
</li>
<li><p><strong>Vector embeddings</strong> carry meaning into math,</p>
</li>
<li><p><strong>Attention</strong> helps the model focus,</p>
</li>
<li><p><strong>Transformers</strong> guide the flow,</p>
</li>
<li><p><strong>Neural networks</strong> learn like our brains do,</p>
</li>
<li><p><strong>Backpropagation</strong> corrects mistakes,</p>
</li>
<li><p><strong>Weights</strong> are memory strength,</p>
</li>
<li><p><strong>Softmax</strong> gives options, and <strong>temperature</strong> adds randomness,</p>
</li>
<li><p><strong>Decoder</strong> picks each next word from a massive <strong>vocab</strong>.</p>
</li>
</ul>
<p>So, the next time you chat with an AI, you won’t just think it’s magic.</p>
<p>You’ll see the logic.</p>
<p>And you’ll know:</p>
<blockquote>
<p><em>it’s not a mystery.</em></p>
<p><em>It’s math—beautiful, layered, structured math 👀.</em></p>
</blockquote>
<p>Don’t forget to drop a like ❤️ and a comment if you loved it / learned something by reading this article, feel free to connect with me here on <a target="_blank" href="https://x.com/Mubashir_061">X</a></p>
<p>Peace out ✌️</p>
]]></content:encoded></item></channel></rss>