<?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 Swetha Voora on Medium]]></title>
        <description><![CDATA[Stories by Swetha Voora on Medium]]></description>
        <link>https://medium.com/@swetha.voora01?source=rss-6fe701a1f764------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XGWVwpNRCfbdj787</url>
            <title>Stories by Swetha Voora on Medium</title>
            <link>https://medium.com/@swetha.voora01?source=rss-6fe701a1f764------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:30:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swetha.voora01/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[The End of Vibe Coding]]></title>
            <link>https://medium.com/@swetha.voora01/the-end-of-vibe-coding-674b10714e5c?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/674b10714e5c</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[kiro]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 05:05:28 GMT</pubDate>
            <atom:updated>2026-03-22T05:05:28.660Z</atom:updated>
            <content:encoded><![CDATA[<p>For the past couple of years, the software engineering world has been obsessed with AI coding assistants. I was using it too and the workflow was pretty standard: open a chatbox, describe what you want, and hope the AI spits out the right code. If it doesn’t, you tweak your prompt and update the model’s context and try again and the turns go on and on until you get it right!</p><p>This is what the industry calls “Vibe Coding.” It’s fast, it’s fun, and it works great to a certain extent.</p><p>But recently, I transitioned to a new AI-native workspace: KIRO IDE (an agentic IDE forked from VS Code). Within my first five minutes of using it, I realized that for enterprise software, the era of vibe coding is over.</p><p>KIRO encourages you to practice Spec-Driven Development. It completely changed how I ship features, standardized our enterprise coding patterns, and most importantly — shifted my day-to-day role from a code-typist to a system architect.</p><p>I want to vividly walk you through exactly what this workflow looks like, how it thinks, and why it is the future of engineering.</p><h3>Vibe Coding vs. Spec-Driven Development</h3><p>Before we dive in, let’s define the difference.</p><p>Vibe Coding is reactive. You say, “Write a Lambda function that processes this S3 event,” and the AI immediately starts dumping Python or TypeScript into your editor. It guesses your architecture as it goes.</p><p>Spec-Driven Development is proactive. Before a single line of code is written, you and the AI collaboratively write specification documents. You define the requirements, edge cases, and architectural design first. The AI only writes code once you, the human engineer, approve the blueprint.</p><figure><img alt="Two panel comparison between vibe-coding and agentic IDE" src="https://cdn-images-1.medium.com/max/1024/1*yHUyWGwInlsC0KaJUJIe2Q.png" /><figcaption>Vibe-coding vs agentic IDE</figcaption></figure><h4>The “<strong>Aha</strong>!” Moment: Context is King</h4><p>My first usage with KIRO was a standard bug fix in my project. Previously, when using standard AI tools, the AI would often hallucinate or have limited context about the codebase. For example, when it came to the database layer, It would hallucinate my partition keys or completely ignore security policies that were necessary to safely deploy a fix.</p><p>With KIRO, the experience was entirely different. I asked it to resolve an issue, and instead of immediately giving me a code snippet, it paused. I watched it do a deep, meticulous sweep of the codebase. It didn’t just look at the file I had open; it combined its searches across multiple services to build an end-to-end context that actually made sense.</p><p>It understood the database entities without me having to explain them. Even though I had to jump in and direct it slightly to fetch a bit more context, its proficiency was ahead of a simple prompt-and-pray tool.</p><h3>Visualizing the Workflow: The .kiro Folder</h3><p>The true magic of KIRO happens when you need to build a completely new feature. Here is exactly what it looks like on your screen.</p><p>When I initiate a “Build a Feature” workflow, KIRO doesn’t just start modifying my code. Instead, it creates a dedicated .kiro/specs/&lt;feature-name&gt;/ folder in my project root. Over a 10-minute back-and-forth conversation, KIRO populates this folder step-by-step:</p><h4>Step 1: requirements.md</h4><p>First, it generates a markdown file detailing the exact scope of the feature. It outlines user-centric stories and system-centric roles. I chat with the model, say things like, “Actually, let’s remove this edge case,” and it refines the document. We don’t move forward until this file is perfect.</p><h4>Step 2: design.md</h4><p>Next, taking the requirements.md and my existing codebase into consideration, it generates a high-level system design document.</p><p>Here is the coolest part: It actually generates Mermaid diagrams right there in the markdown file. I can visually see the boxes and arrows of the system architecture it plans to build. As an engineer, my job here is purely architectural review: Does this system design follow our standard practices? Will it scale? Is this design following our standard patterns?</p><h4>Step 3: tasks.md</h4><p>Once I approve the design, KIRO generates a tasks.md file. This is a gorgeous, step-by-step implementation checklist. Every task has sub-steps detailing the exact files it will create or modify.</p><p>When I give it the green flag to execute, I can literally watch the tasks.md file update in real-time. As it finishes writing the code for a specific task, a green checkmark appears next to the task. If I see it suggesting an unnecessary step (for example, some tasks that are over-engineering by adding too many unit tests), I can just mark that task as “optional” and the AI will skip it.</p><p>(Bonus: I even asked the model to generate a custom markdown file in the KIRO folder — to create Jira-style ticket descriptions and acceptance criteria based on my requirements.md. Translating an architectural design into ready-to-paste Jira Epics saved me so much time!)</p><h3>Taming the AI: What are “Steerings”?</h3><p>If you let an AI run wild, it will write code the way it wants to, not the way you/your company wants it to.</p><p>For example,</p><ul><li>your company might have strict rules about how Cloud Infrastructure is deployed.</li><li>You might require all IAM permissions to be handled in a specific, centralized file rather than attached directly to a resource.</li><li>you might have pre-existing internal utility functions that the AI should reuse instead of writing new code from scratch.</li><li>AI might sometimes name the variables in a vague way, and we might want to ensure good developer experience and code readability by making sure that the variables are always verbose (For example, variable “<strong>file_metadata_attributes</strong>” is much more readable than just “<strong>fields</strong>”. Right?)</li></ul><p>If the AI doesn’t know these rules, it will write code that fails your PR review.</p><p>To fix this, KIRO uses Steerings.</p><p>Inside the <strong>.kiro/steerings/</strong> folder, you create highly detailed markdown rules. I explicitly/manually wrote out the exact coding patterns and architectural standards I follow in a new markdown file within my project, and asked KIRO to <strong>refine</strong> this markdown file into a project level steering document.</p><p>I set these steerings to “<strong>manual</strong>” inclusion. Now, whenever I start a new user query in the KIRO chat and tag this steering to my query, the steerings files which have the structural and technical rules are automatically injected into the AI’s brain. It guarantees that the AI ships code perfectly aligned with our internal enterprise patterns.</p><h3>The Future: Hooks, Powers, and Skills</h3><p>Pretty sure I’m just scratching the surface of what this IDE can do. While Steerings dictate the rules the AI must follow, KIRO also has features called Hooks, Powers, and Skills.</p><p>From my understanding so far, these are the “hands” of the IDE — executable actions that allow the AI to automate background tasks, interact with external systems, and run pre-deployment checks.</p><h3>The Evolving Role of the Software Engineer</h3><p>Tools like KIRO make shipping new features unbelievably fast. But there is a dangerous misconception that AI IDEs mean you don’t need to understand code anymore.</p><p>In reality, <strong>the exact opposite is true.</strong></p><p>Because the AI is writing the boilerplate, my day-to-day has shifted. I spend much more time in brainstorming, reviewing Mermaid diagrams, following good coding practices, and thinking about system architecture.</p><p>But when that tasks.md file generates, I have to possess an extreme understanding of the codebase.</p><p>As a developer using Agentic AI, you are no longer just the typist writing the functions; you are the Senior Engineer reviewing the architecture, and someone possessing strong grasp of the codebase and coding practices. You must be hyper-aware of every minute code change, understand why it is being made, and know whether it is the right decision for your system.</p><p>Vibe coding is fun for learning. But for enterprise development, Spec-Driven Development is the future — and we are just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674b10714e5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented Generation (RAG) Series — Part 6]]></title>
            <link>https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part-6-579a0639c406?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/579a0639c406</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[query-routing]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 06:18:21 GMT</pubDate>
            <atom:updated>2026-03-06T06:31:16.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Query Routing + Unified Interface (Structured + Unstructured in One App)</h3><p>In this final part of the series, we complete the architecture that was promised early on — a single user interface where users can ask both:</p><ul><li><strong>unstructured/document questions</strong> (PDF knowledge-base questions), and</li><li><strong>structured/database questions</strong> (analytics/SQL-type questions),</li></ul><p>while a <strong>query router</strong> automatically sends each question to the correct pipeline.</p><p>If you want everything exactly as implemented and fixed in this article, clone the repo from <a href="https://github.com/SwethaVoora/RAG_Pipeline"><strong>here</strong></a>.</p><h3>What We Built in Part 6</h3><p>Compared to Part 5, we made these core additions:</p><ol><li>Added a new <strong>router.py</strong> module for <strong>intent classification.</strong></li><li>Added a new <strong>orchestrator.py</strong> module to route + execute queries centrally.</li><li>Updated <strong>app.py</strong> to call orchestrator instead of directly invoking only unstructured RAG.</li></ol><p>This gives us a clean architecture:</p><ul><li>UI stays simple.</li><li>Routing logic stays isolated.</li><li>Structured and unstructured systems stay specialized.</li></ul><h3>Why Query Routing Matters</h3><p>Query routing is not about complexity. It’s about respecting the nature of the question. In a multi-source RAG system, the first job is choosing the right retrieval/reasoning path before generation begins.</p><p>In this project, we now have two specialized paths:</p><ul><li>an unstructured conversational RAG path for document context,</li><li>and a structured LangGraph SQL agent path for database analytics.</li></ul><p>Both are useful, but they are useful for different question types.</p><p>A query router works like triage:</p><ul><li>“Is this question asking for document-grounded context?”</li></ul><p>or</p><ul><li>“Is this question asking for structured, table-driven insight?”</li></ul><p>That one decision decides which backend should execute. Without that decision layer, users get inconsistent behavior and reduced answer quality.</p><p>With routing, users still see one interface, but internally the system chooses the right specialist for the job.</p><h3>Important Note Before Running</h3><p>As we discussed in Part 5, we migrated to Google’s Gemini API to keep this project completely free. Because of this, we need to re-index our documents so our vector embeddings match the new model.</p><p><strong>NOTE</strong>: Reminder, you can clone from my repo <a href="https://github.com/SwethaVoora/RAG_Pipeline">here</a>, If you just want to run the project locally, to understand the concepts.</p><p>So, Open your terminal and make sure to activate your virtual environment, and run the below command:</p><p>python indexing_pipeline.py</p><p><strong>NOTE:</strong> If you skip this, retrieval quality can degrade because embeddings come from different model spaces.</p><p>So, lets go through what has changed in this part. As you already understand — Im going to walk you through the changes to integrate query routing into our streamlit application. Below is the user flow we are targeting:</p><ol><li>User sends a query in Streamlit.</li><li>router.py classifies intent (structured / unstructured).</li><li>orchestrator.py dispatches:<br>- structured -&gt; LangGraph SQL agent<br>- unstructured -&gt; conversational RAG chain</li><li>Unified response returns to UI.</li><li>UI also shows route and router reason.</li></ol><h3>Code Walkthrough</h3><p>I have created a new script router.py in our root folder. This script serves as the source for all the helper methods we need for routing the user messages.</p><p>Firstly, We have a RouteDecision object defined.</p><pre>from dataclasses import dataclass<br><br><br>@dataclass<br>class RouteDecision:<br>    route: str<br>    reason: str<br>    confidence: float</pre><p>This makes routing outputs explicit and readable:</p><ul><li>route: which path to run</li><li>reason: why that choice was made</li><li>confidence: simple score for observability/debugging</li></ul><h3>Keyword dictionaries</h3><p>For simplicity, lets use a regex/rule based matching as the source of truth for routing user messages.</p><pre><br>STRUCTURED_KEYWORDS = {<br>    &quot;sql&quot;,<br>    &quot;table&quot;,<br>    &quot;database&quot;,<br>    &quot;supabase&quot;,<br>    &quot;postgres&quot;,<br>    &quot;postgresql&quot;,<br>    &quot;schema&quot;,<br>    &quot;users&quot;,<br>    &quot;user id&quot;,<br>    &quot;orders&quot;,<br>    &quot;order_items&quot;,<br>    &quot;products&quot;,<br>    &quot;revenue&quot;,<br>    &quot;sales&quot;,<br>    &quot;count&quot;,<br>    &quot;group by&quot;,<br>    &quot;join&quot;,<br>}<br><br>UNSTRUCTURED_KEYWORDS = {<br>    &quot;pdf&quot;,<br>    &quot;document&quot;,<br>    &quot;policy&quot;,<br>    &quot;bofa&quot;,<br>    &quot;safe deposit&quot;,<br>    &quot;disclosure&quot;,<br>    &quot;vault&quot;,<br>    &quot;knowledge base&quot;,<br>}</pre><p>These are deterministic intent cues:</p><ul><li>if query looks SQL/business-table heavy -&gt; structured</li><li>if query looks document/policy heavy -&gt; unstructured</li></ul><h3>Prior route helper</h3><pre>def _last_assistant_route(chat_history: list[dict]) -&gt; str | None:<br>    for message in reversed(chat_history):<br>        if message.get(&quot;role&quot;) == &quot;assistant&quot; and message.get(&quot;route&quot;) in {&quot;structured&quot;, &quot;unstructured&quot;}:<br>            return message[&quot;route&quot;]<br>    return None</pre><p>This helps follow-up continuity:</p><ul><li>if user says “Can you explain that more?”, we bias toward last route.</li></ul><h3>Core router function</h3><pre><br>def route_query(user_query: str, chat_history: list[dict]) -&gt; RouteDecision:<br>    q = user_query.lower().strip()<br><br>    structured_hits = sum(1 for kw in STRUCTURED_KEYWORDS if kw in q)<br>    unstructured_hits = sum(1 for kw in UNSTRUCTURED_KEYWORDS if kw in q)<br><br>    # Bias follow-up pronouns toward the last assistant route.<br>    has_followup_pronoun = any(token in q.split() for token in {&quot;it&quot;, &quot;that&quot;, &quot;those&quot;, &quot;them&quot;, &quot;more&quot;})<br>    prev_route = _last_assistant_route(chat_history)<br>    if has_followup_pronoun and prev_route:<br>        return RouteDecision(route=prev_route, reason=&quot;Follow-up pronoun with prior route context.&quot;, confidence=0.72)<br><br>    if structured_hits &gt; unstructured_hits and structured_hits &gt; 0:<br>        return RouteDecision(route=&quot;structured&quot;, reason=&quot;Structured intent keywords detected.&quot;, confidence=0.9)<br><br>    if unstructured_hits &gt; structured_hits and unstructured_hits &gt; 0:<br>        return RouteDecision(route=&quot;unstructured&quot;, reason=&quot;Document-oriented keywords detected.&quot;, confidence=0.9)<br><br>    # Default fallback: keep unstructured as primary user experience for existing app.<br>    return RouteDecision(route=&quot;unstructured&quot;, reason=&quot;No strong structured signals; defaulting to unstructured.&quot;, confidence=0.55)</pre><p>This is the actual intent classification stage for Part 6.</p><p>We then have our orchestrator.py script next:</p><h4>Imports</h4><pre>import logging<br>import numpy as np<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>from agent_graph import run_langgraph_agent_query<br>from config import embeddings_model<br>from helper import get_last_qa_context, expand_followup_query, store_chat_history<br>from retrieval_and_generation_pipeline import rag_chain<br>from router import route_query</pre><p>The orchestrator connects everything:</p><ul><li>structured agent,</li><li>unstructured chain,</li><li>router,</li><li>follow-up helpers.</li></ul><h3>Unstructured follow-up classifier</h3><pre>def _is_unstructured_followup(user_query: str, chat_history: list[dict]) -&gt; bool:<br>    logging.info(&quot;1. Classifying the query as follow-up or not...&quot;)<br>    context = get_last_qa_context(chat_history)<br>    if context == &quot;&quot;:<br>        return False<br><br>    query_embedding = np.array(embeddings_model.embed_documents([user_query]))<br>    context_embedding = np.array(embeddings_model.embed_documents([context]))<br>    similarity = cosine_similarity(query_embedding, context_embedding)[0][0]<br>    logging.info(<br>        &quot;2. Follow-up Detection | Cosine Similarity: %s | Similarity: %s&quot;,<br>        &quot;True&quot; if similarity &gt;= 0.25 else &quot;False&quot;,<br>        similarity,<br>    )<br><br>    ambiguous_keywords = {&quot;it&quot;, &quot;more&quot;, &quot;that&quot;, &quot;this&quot;, &quot;they&quot;, &quot;them&quot;}<br>    rule_based_followup = any(word in user_query.lower().split() for word in ambiguous_keywords)<br>    logging.info(&quot;3. Follow-up Detection | Rule-based: %s&quot;, &quot;True&quot; if rule_based_followup else &quot;False&quot;)<br><br>    return similarity &gt;= 0.20 or rule_based_followup</pre><p>This preserves conversational unstructured behavior from earlier parts.</p><h3>Entry point for query execution</h3><p>This is the entry point, where we decide whether the user query needs answer from the structured langgraph agent? or the unstructured RAG pipeline.</p><pre><br>def execute_user_query(user_query: str, chat_history: list[dict], session_namespace: str) -&gt; dict:<br>    decision = route_query(user_query, chat_history)<br><br>    if decision.route == &quot;structured&quot;:<br>        result = run_langgraph_agent_query(user_query)<br>        return {<br>            &quot;answer&quot;: result[&quot;answer&quot;],<br>            &quot;route&quot;: &quot;structured&quot;,<br>            &quot;router_reason&quot;: decision.reason,<br>            &quot;router_confidence&quot;: decision.confidence,<br>        }<br><br>    context = get_last_qa_context(chat_history)<br>    expanded_user_query = &quot;&quot;<br>    if _is_unstructured_followup(user_query, chat_history):<br>        logging.info(&quot;CLASSIFICATION RESULT:This is a follow-up question.&quot;)<br>        expanded_user_query = expand_followup_query(user_query, context)<br><br>    if len(chat_history) &lt; 2 or expanded_user_query == &quot;&quot;:<br>        answer = rag_chain.invoke(<br>            {&quot;question&quot;: user_query, &quot;user_specific_namespace&quot;: &quot;&quot;, &quot;expanded_user_query&quot;: &quot;&quot;}<br>        )<br>    else:<br>        answer = rag_chain.invoke(<br>            {<br>                &quot;question&quot;: user_query,<br>                &quot;user_specific_namespace&quot;: session_namespace,<br>                &quot;expanded_user_query&quot;: expanded_user_query,<br>            }<br>        )<br><br>    store_chat_history(user_query, answer, session_namespace)<br>    return {<br>        &quot;answer&quot;: answer,<br>        &quot;route&quot;: &quot;unstructured&quot;,<br>        &quot;router_reason&quot;: decision.reason,<br>        &quot;router_confidence&quot;: decision.confidence,<br>    }</pre><p>This is the single point where routing and execution begins.</p><p>If routed to <strong>structured:</strong></p><ul><li>run LangGraph SQL agent,</li><li>return normalized output payload.</li></ul><p><strong>Only unstructured route uses conversational expansion logic.</strong></p><p>This keeps our existing conversation-memory behavior:(You can read Part 3 article <a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part3-344d89cb7b8e">here</a>, in order to revise the conversational RAG Implementation in our project)</p><ul><li>first/non-follow-up queries -&gt; direct</li><li>follow-ups -&gt; session namespace context</li><li>store latest Q&amp;A in conv_vector_*</li></ul><p>Unified output shape keeps UI code minimal.</p><p>Up next, we have the app.py , we already had this script since the beginning of our project. this is the basis for our streamlit application. We have slightly updated this script, in order to accommodate the new query routing aspect into this app.</p><h3>Updated imports</h3><pre>import streamlit as st<br>from config import index<br>from orchestrator import execute_user_query<br>import uuid</pre><p>app.py now imports orchestrator, instead of directly RAG invocation logic.</p><h3>Query submission block</h3><pre>import streamlit as st<br>from config import index<br>from orchestrator import execute_user_query<br>import uuid<br><br><br># Streamlit UI<br>st.title(&quot;Interactive RAG-powered Q&amp;A&quot;)<br>st.subheader(&quot;Please, Delete your chat history before exiting the app.&quot;, divider=&quot;rainbow&quot;)<br>st.write(&quot;Ask a question based on the indexed knowledge base.&quot;)<br><br># Session State for chat history display<br>if &quot;chat_history&quot; not in st.session_state:<br>    st.session_state.chat_history = []<br><br># Generate a unique session ID if not already created<br>if &quot;session_id&quot; not in st.session_state:<br>    st.session_state.session_id = str(uuid.uuid4())  # Generates a random UUID - this will be the name of this user&#39;s conv_vector namespace<br><br>session_namespace = f&quot;conv_vector_{st.session_state.session_id}&quot;<br># print(f&quot;Your session namespace: {session_namespace}&quot;) # Just for debugging purposes<br><br># Display chat history/chat messages<br>for message in st.session_state.chat_history:<br>    st.chat_message(message[&#39;role&#39;]).markdown(message[&#39;content&#39;])<br><br># chat_input field Allows &quot;Enter&quot; to submit<br>user_query = st.chat_input(&quot;Enter your question:&quot;)<br><br>if user_query is not None:  # Ensures it only runs if the user has actually entered something<br>    if user_query.strip() == &quot;&quot;:  # Show warning only if the input is explicitly empty<br>        st.warning(&quot;Please enter a question.&quot;)<br>    else:<br>        # 1. Display the user query as part of the chat history<br>        st.chat_message(&quot;user&quot;).markdown(user_query)<br><br>        # 2. Route and invoke either unstructured or structured path based on prior turns<br>        result = execute_user_query(user_query, st.session_state.chat_history, session_namespace)<br>        response = result[&quot;answer&quot;]<br>        route = result[&quot;route&quot;]<br><br>        # 3. Append user query to chat history/messages<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query})<br><br>        # 4. Display the output<br>        st.chat_message(&quot;assistant&quot;).markdown(response)<br>        st.caption(f&quot;Route: {route} | Reason: {result[&#39;router_reason&#39;]}&quot;)<br><br>        # 5. Append RAG response to chat history/messages<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response, &quot;route&quot;: route})</pre><p>What changed in app.py in Part 6?</p><ul><li>previously app directly executed unstructured rag_chain,</li><li>now app calls orchestrator for route-aware execution.</li></ul><h3>Clear session history</h3><pre># Delete chat history button<br>if st.button(&quot;Delete Chat History&quot;):<br>    print(f&quot;Deleting the chat history for session namespace: {session_namespace}&quot;)<br>    index.delete(namespace=session_namespace, delete_all=True)<br>    st.session_state.chat_history = []  # Clear UI history<br>    st.success(&quot;Chat history deleted successfully.&quot;)</pre><p>No major change, but still essential for session-level memory hygiene.</p><h3>Run your latest Streamlit unified interface</h3><p>python -m streamlit run app.py</p><h3>Suggested Test Queries</h3><h3>Structured route examples</h3><ul><li>“Which product generated the highest revenue?”</li><li>“How many orders did Alice Smith place?”</li><li>“Show users with more than 2 orders.”</li></ul><h3>Unstructured route examples</h3><ul><li>“What does BOFA disclosure mention about vault access?”</li><li>“Explain the locking and unlocking policy from the PDF.”</li></ul><h3>Follow-up behavior checks</h3><ul><li>Ask structured question, then: “Can you break that down further?”</li><li>Ask unstructured question, then: “Can you explain that section again?”</li></ul><p>I would suggest you try to challenge the application, in order to further understand its’ flaws and brainstorm how to fix those flaws. That would be a good exercise to take up!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPdOA__IWeBrvjEw2c_-0Q.png" /><figcaption>Final High level system diagram</figcaption></figure><h4>Congratulations!!You have successfully covered all the foundations that are important in order to understand and implement the RAG projects going forward.</h4><h3>What’s Next</h3><h4><strong>How Query Routing Is Implemented in Real-World Systems?</strong></h4><p>In production AI systems, query routing is usually not a single if/else block. Rather, It is a layered decision system optimized for quality, cost, and latency.</p><p>A common real-world patterns can be understood by reading the below articles. These are highly valuable and helpful in understand industry standard best practices when it comes to implementing RAGs and Agentic Systems. I highly recommend reading them, as they are easy to understand and makes your foundational concepts stronger:</p><p>1. <strong>Rule-based pre-router (cheap + fast) </strong><br> First pass catches obvious intents using deterministic rules (keywords, metadata, tenant/app context).</p><p>2. <strong>Semantic/LLM-based router for ambiguous cases </strong><br> If rule confidence is low, route decision is delegated to a classifier/router model. <br> References: <br> — [<a href="https://docs.langchain.com/oss/python/langchain/multi-agent/router">LangChain Router Pattern</a>]<br> — <a href="https://docs.llamaindex.ai/en/stable/api_reference/retrievers/router/">[LlamaIndex RouterRetriever</a>]</p><p>3. <strong>Planner/Decomposer for complex multi-intent queries</strong><br> Complex prompts are decomposed into sub-questions, each sent to the right tool/source. <br> Reference: [<a href="https://learn.microsoft.com/en-us/azure/search/agentic-retrieval-overview">Azure Agentic Retrieval Overview</a>]</p><p>4. <strong>Orchestrator + specialist agents/tools</strong><br> A coordinator handles dispatch and aggregates outputs from specialists. <br> References: <br> — [<a href="https://docs.cloud.google.com/architecture/choose-design-pattern-agentic-ai-system">Google Cloud Agentic Coordinator Pattern</a>]<br> — [<a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/agentic-ai-patterns/workflow-for-routing.html">AWS Routing Workflow Pattern</a>]</p><p>5. <strong>Safety/policy gates before execution</strong><br> Especially for structured systems (SQL/database): read-only checks, auth boundaries, and risk checks are applied before executing tools. <br> Reference: [<a href="https://learn.microsoft.com/en-us/azure/architecture/ai-ml/guide/rag/rag-solution-design-and-evaluation-guide">Azure RAG Design and Evaluation Guide</a>]</p><h4>Why We Chose the Simplest Query Router in This Project</h4><p>For this series, we intentionally approached with a deterministic keyword-based router because it gives learners:</p><p>- a transparent first mental model,<br>- low runtime cost,<br>- easy debugging,<br>- clear understanding of the concept and control over behavior.</p><p>This article is an <strong>entry point</strong>, <strong>not an endpoint. </strong><br>The goal is to make the concept practical first, then encourage deeper exploration.</p><p>You should think of this implementation as <strong>Phase 1 routing architecture.</strong></p><h4>How Learners Can Extend This Project on Their Own:</h4><p>If you want to evolve this into a more production-grade router, here is a practical progression path:</p><p>1. Keep the current rule-based router as first pass. <br>2. Add a confidence threshold and an `uncertain` class. <br>3. For uncertain cases, add an LLM classifier router. <br>4. Add fallback logic (try unstructured first, then structured if needed). <br>5. Track routing metrics: wrong-route rate, latency, and user corrections. <br>6. Add query decomposition for multi-intent prompts. <br>7. Add domain-specific routing policies (finance, HR, legal, support, etc.).</p><p>This is exactly how many teams mature routing systems over time.</p><h3>Good Practices</h3><ul><li>Modular architecture (router, orchestrator, app separation)</li><li>Deterministic and explainable first-stage routing</li><li>Unified output contract for UI simplicity</li><li>Re-indexing discipline when embedding model changes</li><li>Guardrailed structured path (read-only SQL in tool layer)</li><li>Route transparency for debugging and learning</li></ul><h3>Final Wrap-Up</h3><p>Our RAG Series has finally come to an end! Part 6 closes the complete journey:</p><ul><li>from basic RAG concepts, to unstructured conversational retrieval, structured agentic querying, and finally the <strong>query-routed unified RAG application.</strong></li></ul><p>This is where the system becomes a practical multi-data AI application instead of a single pipeline demo.</p><p>Hope you enjoyed my RAG series and support me with a clap/share to ensure my articles reach more learners.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579a0639c406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Series (Part 5) — Agentic RAG]]></title>
            <link>https://medium.com/@swetha.voora01/rag-series-part-5-097616caf0fb?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/097616caf0fb</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 03:38:23 GMT</pubDate>
            <atom:updated>2026-02-24T03:41:29.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back! If you’ve been following my series, you know we’ve already built a AI pipeline for querying unstructured PDFs (Parts 1–3) and established a basic pipeline for the Text-to-SQL concept with a single products table in Part 4.</p><p>But you are at the right place, if you want to understand how things work in the <em>real</em> world. And in the real world, enterprise data doesn’t live in a single table. It lives in complex, relational databases.</p><p>Today, we are upgrading our database and our RAG pipeline. We will add users, orders, and order_items tables, and try to ensure our model actually understands the intricate nuances and relationships between these different entities by officially converting our <strong>prompt based RAG for structured data into Agentic RAG</strong>. Eventually, this will lead us to query routing, but first, we have a major architectural hurdle to overcome.</p><p>Let’s dive in, break some things, and learn exactly <em>why</em> they break so we can build them better. You can fork or clone my <a href="https://github.com/SwethaVoora/RAG_Pipeline/tree/main">repo</a> and get started.</p><h3>1. Switching to Google’s Gemini API</h3><p>Before we write any code, we need to talk about access. While building this projct, my OpenAI free tier usage got expired. Since I want you to be able to experiment and learn free of cost, we are officially switching to Google’s Gemini API.</p><p><strong>NOTE: We will be using </strong><strong>gemini-2.5-flash model, but you can switch to a different model if you need to. However, use cautiously as we are in a free tier and might run into error 429(Rate limiting for model invocation)</strong></p><p><strong>How to set it up:</strong></p><ol><li>Navigate to this <a href="https://aistudio.google.com/api-keys">link</a> and Create a API Key for your project.</li><li>Add it to your .env file like this: GEMINI_API_KEY=your_key_here. LangChain will automatically pick this up!</li><li>Install all the required packages into your active virtual environment using my requirements.txt linked <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/requirements.txt">here</a>.(All these packages are compatible with python v3.13 or 3.12)</li></ol><p><em>(For a deeper dive on the quickstart, you can check out the </em><a href="https://ai.google.dev/gemini-api/docs/quickstart"><em>official Gemini docs</em></a><em>.)</em></p><h3>2. Building a Real Relational Database</h3><p>Now that our API key and package installations to use gemini is ready, let’s get our data imported into Supabase.</p><p>Go to your Supabase <strong>SQL Editor(If your Supabase database has been deleted/cannot be restored, you can follow the steps I detailed in </strong><a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-part-4-4bbf149020d1"><strong>RAG Series Part 4 </strong></a><strong>to set it up again for the products table) </strong>and run the following script to create our interconnected schema:</p><pre>-- 1. Create Users Table<br>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(100),<br>    email VARCHAR(100) UNIQUE,<br>    created_at TIMESTAMP DEFAULT NOW()<br>);<br>-- 2. Create Orders Table (Links to Users)<br>CREATE TABLE orders (<br>    id SERIAL PRIMARY KEY,<br>    user_id INTEGER REFERENCES users(id),<br>    order_date TIMESTAMP,<br>    status VARCHAR(20) CHECK (status IN (&#39;pending&#39;, &#39;shipped&#39;, &#39;delivered&#39;, &#39;cancelled&#39;)),<br>    total_amount NUMERIC(10, 2)<br>);<br>-- 3. Create Order Items Table (Links Orders to Products)<br>-- This is a many-to-many relationship table<br>CREATE TABLE order_items (<br>    id SERIAL PRIMARY KEY,<br>    order_id INTEGER REFERENCES orders(id),<br>    product_id INTEGER REFERENCES products(id),<br>    quantity INTEGER,<br>    price_at_purchase NUMERIC(10, 2) -- Good practice: price might change later!<br>);</pre><p>Once executed, head over to the Supabase <strong>Table Editor</strong>. Click on your newly created tables and select “Import data from CSV” (you can grab the dummy data CSVs linked in my GitHub repo and either upload them as CSV or paste them as text directly) to populate the database with dummy data.</p><ul><li>user data is linked <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/data/users.csv">here</a></li><li>orders data is linked <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/data/orders.csv">here</a></li><li>order_items data is linked <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/data/order_items.csv">here</a></li></ul><p><strong>A quick shoutout to Supabase here:</strong> Their UI lets you seamlessly visualize your database relations directly from the editor, instantly showing you exactly which foreign keys are referencing which tables. It’s a lifesaver when debugging or understanding the key structure visually.</p><h3>3. The “Context Bottleneck” (Why Part 4 is obsolete)</h3><p>Right now, our project uses a simple LangChain prompt-based approach. Under the hood, our prompt essentially says: <em>“Here is the schema for the PRODUCTS table. Answer the user query.”</em></p><p>This works as intended for a query like <em>“List all products under $50.” or “Name all the products that contain “ea” in the product name.” </em>But what happens when a user asks a complicated, insight-driven question like: <em>“Who bought the most expensive product?and what is the revenue it generated in the last 3 months?”</em></p><p>If we stick to our current approach, we have to paste the CREATE TABLE statements for all 4 of our tables into the prompt. This will likely fail or hallucinate for two major reasons:</p><ul><li><strong>Too many tokens:</strong> Pasting the schema for 4 tables into every single prompt is expensive. As databases scale to 50+ tables, this causes massive token bloat and confuses the model.</li><li><strong>Complex Joins:</strong> Drowning the model in irrelevant tables causes it to lose focus. It might try to guess column names for joining (e.g., hallucinating products.owner_id instead of correctly mapping orders.user_id).</li></ul><p>We need a system that can <em>lazy load</em> only the schemas it needs. We need to upgrade from a linear Chain to an <strong>Agent</strong>.</p><h3>3. Enter the ReAct Framework</h3><p>To understand agents, you need to understand <strong>ReAct</strong> (Reasoning + Acting). Think about how <em>you</em> solve a problem. If I ask you, “What is the weather in Tokyo?”, you don’t just magically know the answer. You:</p><ol><li><strong>Reason:</strong> “I don’t know the weather, so I need to check my phone.”</li><li><strong>Act:</strong> You open a weather app.</li><li><strong>Observe:</strong> You read “75 degrees.”</li><li><strong>Reason:</strong> “Okay, I have the answer.”</li><li><strong>Act:</strong> You tell me the weather.</li></ol><p>An Agent does the exact same thing. We give the LLM a “Brain” (Reasoning) and “Hands” (Tools it can act with). Let’s build this from scratch so you can see exactly how it works under the hood.</p><p>Create a file named agent.py in your root directory.</p><h4>Step A: Connect the Brain &amp; The Database</h4><p>First, we set up our imports and connect to our Supabase database.</p><pre>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain_core.messages import HumanMessage, ToolMessage, SystemMessage<br>from langchain_core.tools import tool<br>from langchain_community.utilities import SQLDatabase<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br># 1. Connect to Database<br>db = SQLDatabase.from_uri(f&quot;postgresql://{os.getenv(&#39;SUPABASE_USER&#39;)}:{os.getenv(&#39;SUPABASE_PASSWORD&#39;)}@{os.getenv(&#39;SUPABASE_HOST&#39;)}:{os.getenv(&#39;SUPABASE_PORT&#39;)}/{os.getenv(&#39;SUPABASE_DB&#39;)}&quot;)</pre><p><strong>What is </strong><strong>SQLDatabase in langchain_community.utilities?</strong> In simple terms, it&#39;s a wrapper package by LangChain. Instead of us having to write lines of psycopg2 boilerplate to open and close connections, read data from our database, we will be using SQLDatabase which handles all the heavy lifting of securely talking to our Postgres database and retrieving the necessary information using secure credentials.</p><h4>Step B: Giving the Agent “Hands” (The Tools)</h4><p>An LLM can only output text. To let it interact with our database, we give it functions decorated with @tool.</p><pre># 2. Define the Tools<br>@tool<br>def list_tables_tool():<br>    &quot;&quot;&quot;Returns a list of all tables in the database.&quot;&quot;&quot;<br>    return &quot;, &quot;.join(db.get_usable_table_names())<br><br>@tool<br>def get_schema_tool(table_names: str):<br>    &quot;&quot;&quot;Returns the schema (columns and types) for the specified tables.<br>    Input must be a comma-separated list of table names. <br>    Example: &#39;users, orders&#39;<br>    &quot;&quot;&quot;<br>    return db.get_table_info(table_names.split(&quot;, &quot;))<br><br>@tool<br>def execute_sql_tool(sql_query: str):<br>    &quot;&quot;&quot;Executes a SQL query and returns the results.<br>    Input must be a valid SQL string.<br>    &quot;&quot;&quot;<br>    try:<br>        return db.run(sql_query)<br>    except Exception as e:<br>        return f&quot;Error executing SQL: {e}&quot;<br><br><br># 3. Initialize the Model with Tools<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>llm_with_tools = llm.bind_tools([list_tables_tool, get_schema_tool, execute_sql_tool])</pre><p><strong>What is </strong><strong>@tool?</strong> This is a magic decorator. When you put @tool above a Python function, LangChain reads the function&#39;s name, its inputs, and its docstring (the text in the &quot;&quot;&quot; quotes), and translates all of that into a JSON format the LLM can understand. <strong>The docstring is crucial</strong>—it is literally the instructions the AI reads to know <em>when</em> and <em>how</em> to use the tool.</p><h4>Step C: The ReAct Loop (The “Brute Force” Agent)</h4><p>Now, we wire it all together in a while loop. This loop forces the model to Reason, Act, and Observe until it has a final answer and breaks.</p><pre># --- THE AGENT RUNTIME: The &quot;While&quot; Loop ---<br>def run_agent(user_query):<br>    # Start the conversation history<br>    messages = [<br>        SystemMessage(content=&quot;You are a helpful SQL assistant. Always check the schema before writing a query.&quot;),<br>        HumanMessage(content=user_query)<br>    ]<br>    <br>    print(f&quot;User: {user_query}&quot;)<br>    <br>    # LOOP: Keep going until the LLM stops calling tools<br>    while True:<br>        # 1. Ask the Brain (Reasoning)<br>        ai_msg = llm_with_tools.invoke(messages)<br>        messages.append(ai_msg) # Add AI thought to history<br>        <br>        # 2. Check: Did the AI want to use a tool?<br>        if not ai_msg.tool_calls:<br>            # If no tool call, the agent is done. It has the answer.<br>            print(f&quot;Agent Final Answer: {ai_msg.content}&quot;)<br>            break<br>        # 3. If yes, execute the tool (Acting)<br>        for tool_call in ai_msg.tool_calls:<br>            tool_name = tool_call[&quot;name&quot;]<br>            tool_args = tool_call[&quot;args&quot;]<br>            print(f&quot; -&gt; Agent is calling tool: {tool_name} with args: {tool_args}&quot;)<br>            <br>            # Map the NAME (string) to the FUNCTION (code).<br>            tool_output = &quot;Error: Tool not found&quot;<br>            if tool_name == &quot;list_tables_tool&quot;:<br>                tool_output = list_tables_tool.invoke(tool_args)<br>            elif tool_name == &quot;get_schema_tool&quot;:<br>                tool_output = get_schema_tool.invoke(tool_args)<br>            elif tool_name == &quot;execute_sql_tool&quot;:<br>                tool_output = execute_sql_tool.invoke(tool_args)<br>            <br>            # 4. Feed the observation back to the brain<br>            messages.append(ToolMessage(content=str(tool_output), tool_call_id=tool_call[&quot;id&quot;]))<br>if __name__ == &quot;__main__&quot;:<br>    run_agent(&quot;Who bought the most expensive product?&quot;)</pre><p>You can run the new script the agent.py using the below command in your active virtual environment:</p><pre>python3 agent.py</pre><h3>🚨 The “Gotcha”: The Ambiguity Trap</h3><p>This raw loop works, but it is fragile. When I ran agent.py twice with the exact same question (<em>&quot;Who bought the most expensive product?&quot;</em>), <strong>I got two completely different SQL queries and two different answers.</strong></p><p>Try 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dhCoDQy4RBHEq10hb99XNQ.png" /></figure><p><em>Try 2:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XZBhmNw00EecAodDnCVELA.png" /></figure><p>Why? Because I failed to account for two crucial details:</p><ol><li><strong>The Temperature Issue</strong> LLMs have a “creativity” dial called temperature. If you leave it at the default, the model might try a different logical path every time. For strictly deterministic tasks like writing SQL, you must enforce precision. <strong>The Fix:</strong> Initialize your model with temperature=0.</li></ol><p><strong>A low temperature makes the model pick the highest-probability tokens, reducing randomness and ensuring predictable, factual, and repetitive answers.</strong></p><p>To Understand more about Temperature, I would suggest you give a quick read in vellum.ai’s page linked <a href="https://www.vellum.ai/llm-parameters/temperature?utm_source=google&amp;utm_medium=organic">here</a>.</p><p><strong>2. The Prompt Ambiguity (Business Rules)</strong> Look at our schema. What does “most expensive” mean?</p><ul><li>Did the user mean the highest catalog price? (products.price)</li><li>Or did they mean the highest price someone actually paid on a receipt? (order_items.price_at_purchase)</li></ul><p>Both interpretations result in valid SQL! The LLM was forced to guess because it didn’t understand my company’s business logic.</p><p><strong>The Fix:</strong> We must explicitly guide the Agent in the System Prompt:</p><pre>SystemMessage(content=&quot;&quot;&quot;You are an expert PostgreSQL agent.<br>BUSINESS RULES:<br>- If asked about a product&#39;s catalog price, ALWAYS use products.price.<br>- If asked about how much a user paid, ALWAYS use order_items.price_at_purchase.&quot;&quot;&quot;)</pre><p>The while True: loop I just showed you is a great learning tool to understand the ReAct framework. But in production, managing that loop manually is dangerous.So, we are going to use the temperature fix, strict business logic and autonomous agentic approach to rebuild our Agent RAG.</p><p>In the second half of this article, we are going to throw away the while loop and rebuild this using <strong>LangGraph</strong>—the professional way to orchestrate State Machines.</p><p>Here is the second half of your Medium article. It breaks down the LangGraph implementation into easily digestible, copy-pasteable steps while heavily focusing on the <em>why</em> behind every concept.</p><h3>5. The Professional Way: Enter LangGraph</h3><p>To build resilient, production-ready AI, we use a <strong>State Machine</strong>.</p><p><strong>LangGraph</strong> is a library that allows us to build Agents as graphs. Instead of a messy loop, LangGraph thinks in:</p><ul><li><strong>State:</strong> The memory or “scratchpad” of the graph.</li><li><strong>Nodes:</strong> The steps or workers (e.g., The Brain, The Tools).</li><li><strong>Edges:</strong> The logic paths connecting the nodes (e.g., “If the Brain asks for a tool, go to the Tool Node”).</li></ul><p>You can use requirements.txt linked <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/requirements.txt">here</a> to install the required packages for version compatibility into your virtual env.(FYI, Im using python 3.13)</p><p>Create a new file called agent_graph.py and let&#39;s build this step-by-step.</p><h4>Step 1 &amp; 2: Setup Tools and Model (Fixing the Temperature!)</h4><p>First, we import our libraries, connect to the database, and define our tools exactly as we did before.</p><p>Before we give an AI access to our database, we need to set some ground rules.</p><p>So, Initially, we define our SYSTEM_PROMPT. Remember the “Ambiguity Trap” from earlier? We try to fix that here — by telling the Agent exactly how to calculate/generate insights for certain things.</p><p>Second, we define our tools. Look closely at the execute_sql_tool. I added a security guardrail to check if the query starts with select. If the AI ever hallucinates or a malicious user tries a prompt injection like <em>&quot;Update user id 1 to John Doe&quot;</em>, the tool intercepts it and blocks the execution.</p><p>But pay close attention to <strong>Step 2</strong>. Remember that “Ambiguity Trap” where the model gave us two different answers? We fix half of that problem right here by explicitly setting temperature=0. This removes the LLM&#39;s &quot;wide creativity&quot; and forces it to be a little more deterministic, logical SQL coder.</p><p>Copy and paste this into a newly created agent_graph.py:</p><pre>import os<br>from dotenv import load_dotenv<br>from typing import Annotated, TypedDict, Literal<br><br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain_core.messages import HumanMessage, SystemMessage, BaseMessage<br>from langchain_core.tools import tool<br>from langchain_community.utilities import SQLDatabase<br>from langgraph.graph.message import add_messages<br>from langgraph.graph import StateGraph, END<br>from langgraph.prebuilt import ToolNode<br><br>load_dotenv()<br><br># Our initial System Prompt<br>SYSTEM_PROMPT = &quot;&quot;&quot;You are an expert PostgreSQL agent.<br>BUSINESS RULES:<br>- If asked about a product&#39;s catalog price, ALWAYS use products.price.<br>- If asked about revenue or how much a user paid, ALWAYS use order_items.price_at_purchase.<br>- For any user-level analysis, user identity MUST be users.id (NOT users.name).<br>- users.name is only a display label and can have duplicates.<br>Always check schemas before querying.&quot;&quot;&quot;<br><br># --- 1. SETUP TOOLS ---<br>db = SQLDatabase.from_uri(f&quot;postgresql://{os.getenv(&#39;SUPABASE_USER&#39;)}:{os.getenv(&#39;SUPABASE_PASSWORD&#39;)}@{os.getenv(&#39;SUPABASE_HOST&#39;)}:{os.getenv(&#39;SUPABASE_PORT&#39;)}/{os.getenv(&#39;SUPABASE_DB&#39;)}&quot;)<br><br>@tool<br>def list_tables_tool():<br>    &quot;&quot;&quot;List all table names in the database.&quot;&quot;&quot;<br>    return &quot;, &quot;.join(db.get_usable_table_names())<br><br>@tool<br>def get_schema_tool(table_names: str):<br>    &quot;&quot;&quot;Get the schema for specific tables. Input: comma-separated list of tables.&quot;&quot;&quot;<br>    return db.get_table_info(table_names.split(&quot;, &quot;))<br><br>@tool<br>def execute_sql_tool(sql_query: str):<br>    &quot;&quot;&quot;Execute a SQL query. Input: valid SQL string.&quot;&quot;&quot;<br>    normalized = sql_query.strip().lower()<br>    # SECURITY GUARDRAIL: Block INSERT/UPDATE/DELETE/DROP<br>    if not normalized.startswith(&quot;select&quot;):<br>        return &quot;Error: only read-only SELECT queries are allowed.&quot;<br>    try:<br>        return db.run(sql_query)<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;<br><br>tools = [list_tables_tool, get_schema_tool, execute_sql_tool]<br><br># --- 2. SETUP MODEL ---<br># CRITICAL: temperature=0 ensures strict, deterministic SQL generation!<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;, temperature=0)<br>llm_with_tools = llm.bind_tools(tools)</pre><h4>Step 3: Define the State (Solving the Amnesia Bug)</h4><p>This is arguably the most important concept in LangGraph. The “State” is an object that gets passed from Node to Node. If a Node is a worker(LLM model, tool), the State is the clipboard/memory they pass around.</p><p>When I first built this and tried to invoke. my agent, it crashed with an error: ValueError: contents are required.</p><p>Why? Because <strong>my Agent had amnesia.</strong> Especially, Gemini API needs at least one non-empty Human message in the request, even if a system prompt is provided. Other models like OpenAI may handle a system-prompt-only request differently. By default, when a Node updates the State, it <em>overwrites</em> whatever was there before.</p><ul><li><strong>Turn 1:</strong> User asks a question. State = [HumanMessage]</li><li><strong>Turn 2:</strong> Agent outputs a tool call. State is overwritten = [AIMessage]</li><li><strong>Turn 3:</strong> Our Agent then gets the AIMessage, but because the original human question was deleted — It wont know what to generate a output for.</li></ul><p>To fix this, we use a built-in LangGraph reducer called add_messages. By wrapping our state list in Annotated[..., add_messages], we guarantee that every thought and action at each step of our state machine is appended to a running ledger, rather than overwriting it.</p><pre># --- 3. DEFINE STATE ---<br>class AgentState(TypedDict):<br>    # The add_messages reducer ensures we APPEND to the conversation history<br>    # instead of overwriting it at every node.<br>    messages: Annotated[list[BaseMessage], add_messages]</pre><h4>Step 4: Define the Nodes and Edges</h4><p>Next, we define our actual logic. We need one Node to act as the Brain, and one Edge (a routing function) to decide if we need to call a tool or if we are finished.</p><pre># --- 4. DEFINE NODES &amp; EDGES ---<br>def call_model(state: AgentState):<br>    &quot;&quot;&quot;The &#39;Brain&#39; Node: Just calls the LLM.&quot;&quot;&quot;<br>    messages = state[&#39;messages&#39;]<br>    response = llm_with_tools.invoke(messages)<br>    # Return a dictionary to append the AI&#39;s response to the State<br>    return {&quot;messages&quot;: [response]}<br><br>def should_continue(state: AgentState) -&gt; Literal[&quot;tools&quot;, END]:<br>    &quot;&quot;&quot;The &#39;Logic&#39; Edge: Decides where to go next.&quot;&quot;&quot;<br>    last_message = state[&#39;messages&#39;][-1]<br>    <br>    # If the LLM has made a tool call, route to the &#39;tools&#39; node<br>    if last_message.tool_calls:<br>        return &quot;tools&quot;<br>    <br>    # Otherwise, route to END (stop the graph)<br>    return END</pre><h4>Step 5: Build the Graph</h4><p>Now, we act like plumbers. We take our State, our Nodes, and our Edges, and connect the pipes.</p><p>Instead of a loop, LangGraph thinks in <strong>Nodes</strong> (steps) and <strong>Edges</strong> (paths).</p><ol><li><strong>Node 1: The Agent (Reasoning)</strong> -&gt; The LLM decides what to do.(<strong>This is our entry point)</strong></li><li><strong>Edge:</strong> Logic check.<br>- If LLM wants to use a tool -&gt; Go to <strong>Node 2</strong>.<br>- If LLM has the answer -&gt; <strong>END</strong>.</li><li><strong>Node 2: The Tools (Action)</strong> -&gt; Execute SQL, Get Schema, etc.</li><li><strong>Edge:</strong> Go back to <strong>Node 1</strong> — The Agent (The graph has a Loop).</li></ol><p><em>(Bonus: If you have LangSmith configured as per my instructions in </em><a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part-2-964dae6a8b73"><em>RAG Part 2</em></a><em>, then executing this graph automatically enables visual tracing of every single state transition in your LangSmith dashboard!)</em></p><pre># --- 5. BUILD THE GRAPH ---<br>workflow = StateGraph(AgentState)<br><br># Add the nodes<br>workflow.add_node(&quot;agent&quot;, call_model)<br># LangGraph gives us a pre-built node that automatically handles tool execution!<br>workflow.add_node(&quot;tools&quot;, ToolNode(tools)) <br><br># Set the entry point<br>workflow.set_entry_point(&quot;agent&quot;)<br><br># Add the conditional logic (Agent -&gt; Tools OR Agent -&gt; END)<br>workflow.add_conditional_edges(&quot;agent&quot;, should_continue, [&quot;tools&quot;, END])<br><br># Loop back: After tools finish, always go back to the Agent to observe results<br>workflow.add_edge(&quot;tools&quot;, &quot;agent&quot;) <br><br># Compile the graph<br>agent_app = workflow.compile()</pre><h4>Step 6: Run It</h4><p>Finally, we run our graph.</p><p>Because our ultimate goal is to serve this Agent to an application, I wrote a quick wrapper function called run_langgraph_agent_query. This function hides the messy streaming logic and just returns a clean JSON dictionary with our final answer, making it perfectly reusable for our server.</p><pre>def _extract_message_text(message: BaseMessage) -&gt; str:<br>    if isinstance(message.content, str):<br>        return message.content<br>    if isinstance(message.content, list):<br>        parts = [part.get(&quot;text&quot;, &quot;&quot;) for part in message.content if isinstance(part, dict)]<br>        return &quot;\n&quot;.join(p for p in parts if p)<br>    return str(message.content)<br><br>def run_langgraph_agent_query(question: str) -&gt; dict:<br>    initial_state = {<br>        &quot;messages&quot;: [<br>            SystemMessage(content=SYSTEM_PROMPT),<br>            HumanMessage(content=question),<br>        ]<br>    }<br>    final_answer = &quot;&quot;<br>    for event in agent_app.stream(initial_state, config={&quot;recursion_limit&quot;: 20}):<br>        for key, value in event.items():<br>            print(f&quot;--- Node: {key} ---&quot;)<br>            messages = value.get(&quot;messages&quot;, [])<br>            if not messages:<br>                continue<br>            if key == &quot;agent&quot;:<br>                ai_msg = messages[-1]<br>                tool_calls = getattr(ai_msg, &quot;tool_calls&quot;, []) or []<br>                if not tool_calls:<br>                    final_answer = _extract_message_text(ai_msg)<br>            if key == &quot;tools&quot;:<br>                for msg in messages:<br>                    tool_name = getattr(msg, &quot;name&quot;, None)<br>                    if tool_name:<br>                        print(f&quot;    [Action] Executed Tool: {tool_name}&quot;)<br>    return {&quot;answer&quot;: final_answer}<br><br><br><br># --- 6. RUN IT ---<br>if __name__ == &quot;__main__&quot;:<br>    query = &quot;Identify the product that has generated the highest total revenue. Then, analyze the users who bought it—are they one-time shoppers, or do they tend to buy multiple items?&quot;<br>    <br>    print(f&quot;User: {query}\n&quot;)<br>    output = run_langgraph_agent_query(query)<br>    print(&quot;\n&quot; + &quot;=&quot; * 50)<br>    print(&quot;FINAL BUSINESS INSIGHT:&quot;)<br>    print(&quot;=&quot; * 50)<br>    print(output[&quot;answer&quot;])</pre><p>Now that your agent_graph.py is complete, you can try to run it in your terminal after ensuring that your virtual environment is active. And all the necessary packages are installed.</p><h3>6. Wiring it up to FastAPI (main.py)</h3><p>Now, we proceeed to updating our API. In Part 4, our main.py was cluttered. We had to manually write database connection boilerplate and regex checks to ensure the LLM wasn&#39;t writing malicious SQL directly in our server file.</p><p>Take a look at how incredibly clean our main.py is now. Because our agent_graph.py completely encapsulates the tools, the SQLDatabase connection, and the security guardrails, our API server only has to do one thing: handle web requests.</p><p>Here is your updated main.py script:</p><pre># main.py<br>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>from agent_graph import run_langgraph_agent_query<br>import uvicorn<br><br>app = FastAPI()<br><br># Pydantic model for input validation<br>class QueryRequest(BaseModel):<br>    question: str<br><br>@app.post(&quot;/query&quot;)<br>async def query_db(request: QueryRequest):<br>    try:<br>        # We completely replaced our old nl2sql chain with the LangGraph wrapper!<br>        response = run_langgraph_agent_query(request.question)<br>        return {<br>            &quot;answer&quot;: response[&quot;answer&quot;],<br>            &quot;agent&quot;: &quot;langgraph&quot;,<br>        }<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=f&quot;LangGraph agent execution failed: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>Now run your API on using the below command in your terminal:</p><pre>uvicorn api.main:app --reload</pre><p>This would enable you to open the <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> url. Go to <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a>/docs and “Try it out” and enter your user query in the “question” key’s value string and click on “Execute”.</p><p>And additionally, You can view the entire agent flow in your LangSmith account, provided you followed my instructions on LangSmith setup in <a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part-2-964dae6a8b73">RAG Part 2</a> article of this series. Below is a example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3OpA_9Ua97afHEGJFvbpA.png" /></figure><h3>The Magic of Agentic Execution</h3><p>Considering you are using the same user query as mine, which is:<br>“Identify the product that has generated the highest total revenue. Then, analyze the users who bought it — are they one-time shoppers, or do they tend to buy multiple items?”</p><p>When you run this agent_graph.py in your python virtual env, IN THE TERMINAL, you aren’t just getting raw SQL rows back. Look at what happens in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlkW8Kcdyfzj7IszGKDB4w.png" /><figcaption>Final Output</figcaption></figure><ul><li><strong>list_tables_tool</strong>: The agent scopes out the database.</li><li><strong>get_schema_tool</strong>: It lazy-loads only the tables it needs.</li><li><strong>execute_sql_tool</strong>: It runs the first complex JOIN to find the top revenue product.</li><li><strong>execute_sql_tool (Again!)</strong>: It pauses, realizes it hasn&#39;t answered the second half of your question, dynamically writes a <em>second</em> SQL query to analyze user behavior, and executes it.</li></ul><p>And the final output? It isn’t a messy JSON or a raw table. It is a clean, synthesized paragraph:</p><blockquote>“The product that has generated the highest total revenue is <strong>Tripod</strong>, with a total revenue of $14,941.50. Analyzing the users who bought ‘Tripod’, it appears that all of them are one-time shoppers for this product…”</blockquote><h3>🚨 The Second Gotcha: The Data Integrity Trap Or Cost Trap</h3><p>This section is only to make you understand on how to further Improve the curent pipeline by adding more guardrails or validation steps. You can take these issues as challenges andtry to improve your pipeline by yourself, If interested.</p><p>Our Agent is built, our database is protected from UPDATE statements, and our memory amnesia is fixed. Everything looks production-ready, right?</p><h4>Data Integrity Issue:</h4><p>But what happens if a user asks the Agent: <em>“Calculate the total lifetime revenue for the user Charlie Williams.”</em></p><p>The Agent will happily write a SQL query like this: SELECT SUM(price_at_purchase) FROM order_items JOIN orders ... JOIN users ON ... WHERE users.name = &#39;Charlie Williams&#39; and returns a response like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxRTiw4lEloV3--STYBLbg.png" /></figure><p><strong>This is a massive data integrity failure.</strong> In a real enterprise database, you might have five different people named “John Doe”. If the Agent groups or filters by users.name, it just grouped five different people into one! Your User is now looking at completely skewed revenue analytics. users.name is just a display label; it is not a unique identifier.</p><p>Instead of returning such response, the agent needs to know that there could be multiple users with same user name, the Agent should automatically look up the unique users.id first, and send a response to the user to specify <em>which</em> unique Chaarllie Williams do they mean, before calculating any financial metrics. for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad7M9KGoxcXKEQRihrgjTQ.png" /></figure><p>May be you could solve it by a simple update in the SYSTEM_PROMPT of our pipeline Like below? would that alone solve the problem? Any other way of tackling this kind of issue?</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;You are an expert PostgreSQL agent.<br>BUSINESS RULES:<br>- If asked about a product&#39;s catalog price, ALWAYS use products.price.<br>- If asked about revenue or how much a user paid, ALWAYS use order_items.price_at_purchase.<br>- For any user-level analysis, user identity MUST be users.id (NOT users.name).<br>- users.name is only a display label and can have duplicates.<br>- If asked about details about a user&#39;s orders by specifying a name, ALWAYS check if there are multiple<br>    users with that same name. If yes, then send a response statingthat there are multiple users with the same name and hence cannot be used for analysis.<br>Always check schemas before querying.&quot;&quot;&quot;</pre><h4>Cost Issue:</h4><p>We successfully protected our database by adding a guardrail inside our execute_sql_tool that blocks anything other than a SELECT statement. But if we think about system architecture, there is a slight inefficiency here.</p><p>If a user sends the prompt: <em>“Update user id 1 to have the name John Doe”</em>, our current pipeline still sends the prompt to the Gemini API, waits for the LLM to reason and write the UPDATE SQL, and <em>then</em> our execute_sql_tool tool catches it and blocks it. We successfully stopped the attack, but <strong>we still paid for the LLM API call and made the user wait for the latency.</strong></p><p>In a true enterprise production environment, we want to practice <strong>“Shift-Left” security</strong> by catching bad intents as early as possible. We can improve this pipeline by adding a User Intent Classification step <em>before</em> the LangGraph agent is ever triggered.</p><p>By applying simple Regex or string matching at the FastAPI endpoint level (main.py), we can scan the request.question for red flags. If a user&#39;s prompt contains hardcoded keywords like change, update, remove, write, insert,…etc, we can instantly return an HTTP 400 Error. This multi-layered approach ensures that our expensive LangGraph agent is only triggered when we actually have a valid analytical question to answer!</p><p>Here is the overall picture of our agent for your understanding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgelIgHKZFbFWlzhpFIPgg.png" /><figcaption>Main flow diagram</figcaption></figure><h3>What’s Next?</h3><p>Great! You just built your RAG agent for structured data.</p><p>Furthermore, we now have two incredibly powerful systems: A Vector DB for unstructured PDFs (Parts 1–3) and a LangGraph Agent for structured SQL (Part 5).</p><p>In <strong>Part 6</strong>, we are going to combine them. We will build a <strong>Query Router Agent</strong> that sits at the front door to decide whether to search the PDFs or query the SQL database. and much more!</p><p>The architecture is finally coming together. See you in Part 6!</p><p>NOTE: Since we switched from openai to gemini API, I have updated the unstructured RAG scripts to use the gemini library as well. You can get the scripts from my github repo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=097616caf0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation(RAG): Part 4]]></title>
            <link>https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-part-4-4bbf149020d1?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbf149020d1</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[nl-2-sql]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[query-routing]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Wed, 07 May 2025 01:00:02 GMT</pubDate>
            <atom:updated>2025-12-10T00:55:20.753Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to my RAG Series.</p><p>In this part of the series, we take our RAG pipeline one step further — adding the ability to <strong>answer structured data queries from a relational database</strong>.<br>For simplicity, we start with <strong>a single table</strong> to demonstrate the core concepts of:</p><ul><li>Natural Language to SQL (NL2SQL) <strong>Query Construction</strong></li></ul><p>In future parts, we’ll extend this RAG to handle <strong>multi-table joins and more complex query generation.</strong></p><p>This staged approach ensures we build a <strong>practical, modular, and maintainable Conversational AI system</strong> — just like you would in a real-world project.</p><p>I was fascinated to read the below engineering blogs to understand the intricacies of NL2SQL. You can read them too, to understand this concept and how it is being leveraged in leading companies and their products.</p><ul><li>Uber’s — <a href="https://www.uber.com/blog/query-gpt/">Query GPT</a></li><li>Swiggy’s — <a href="https://bytes.swiggy.com/hermes-a-text-to-sql-solution-at-swiggy-81573fb4fb6e">Hermes</a></li><li>Amazon’s financial Automation GenAI Q&amp;A <a href="https://aws.amazon.com/blogs/machine-learning/how-amazon-finance-automation-built-a-generative-ai-qa-chat-assistant-using-amazon-bedrock/">chat assistant</a></li></ul><h3>DATABASE</h3><p>For your ease of implementation of this project, I have detailed the instructions on how to setup a simple cloud based database with a single table “products”. Which we will expand in the later articles in this series to accommodate joins in our SQL queries and handle complex relationships within the database.</p><p>I chose the products table as ecommerce is a setup that is well understood by everyone.</p><h3>Supabase Setup Documentation</h3><p>In this tutorial, I will tell you how to set up your own database , you can follow the steps below to create our db setup.</p><h4>Create a Supabase Project</h4><ol><li><strong>Log In / Sign Up:</strong><br> Visit <a href="https://app.supabase.com/">Supabase</a> and log in with your credentials, or sign up if you’re a new user.</li><li><strong>Create a New Organization</strong></li><li><strong>Create a New Project:</strong></li></ol><ul><li>Click the <strong>“New Project”</strong> button from your dashboard.</li></ul><p>Fill in the project details:</p><ul><li><strong>Project Name:</strong> For example, RAG_Series</li><li><strong>Database Password:</strong> Choose a secure password.</li><li><strong>Region:</strong> Select the region closest to your target audience.</li><li>Click <strong>“Create New Project”</strong> and wait for the project provisioning to complete.</li></ul><h3>Set Up the Products Table</h3><ol><li><strong>Access the Database:</strong><br> From the project dashboard, click on <strong>“Table Editor”</strong> in the left sidebar.</li><li><strong>Open the Table Editor:</strong><br> click <strong>“New Table”</strong>.</li><li><strong>Configure the Table:</strong></li></ol><ul><li><strong>Table Name:</strong> products</li><li><strong>Schema:</strong> Use the default schema.</li><li>Optionally, add a description like “Table for storing product details for NL2SQL demonstration.”</li></ul><h3><strong>Add Columns:</strong></h3><p>Create the following columns:</p><ul><li><strong>id:</strong></li><li>Data Type: integer</li><li>Options: Set as <strong>Primary Key</strong> and enable <strong>Auto-Increment</strong>.</li><li><strong>created_at:</strong></li><li>Data Type: timestamp</li><li>Options: Optionally, set a default value to the current timestamp.</li><li><strong>name:</strong></li><li>Data Type: text or varchar(255)</li><li>Options: Set as <strong>Required/Not Null</strong>.</li><li><strong>description:</strong></li><li>Data Type: text</li><li>Options: Optional.</li><li><strong>price:</strong></li><li>Data Type: numeric or decimal</li><li>Options: Set as <strong>Required/Not Null</strong>.</li><li><strong>stock:</strong></li><li>Data Type: integer</li><li>Options: Optional (for tracking inventory).</li></ul><ol><li><strong>Save the Table:</strong><br> Click <strong>“Save”</strong> or <strong>“Create Table”</strong> to finalize the schema.</li></ol><h4>Insert Sample Records (Optional)</h4><p>You can add sample data to test your queries. For example, use the <strong>SQL Editor</strong> to run an INSERT command:</p><pre>INSERT INTO products (name, description, price, stock, created_at)<br>VALUES (your values here)</pre><p>Repeat or modify the command to add additional sample records. An Alternative would be to import from a csv. You can find my sample products data <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/data/products.csv">here</a>.</p><h4>4. Configure Public Read Access with RLS</h4><p>Since the database is intended for public use (with read-only access), enabling Row-Level Security (RLS) is necessary:</p><p><strong>Enable RLS:</strong><br> In the table view for products, toggle the <strong>RLS</strong> option to enable it.</p><p><strong>Create a Public Read Policy:</strong></p><ul><li>Click <strong>“New Policy”</strong>.</li><li><strong>Policy Name:</strong> public read access</li><li><strong>Table:</strong> products</li><li><strong>Action:</strong> SELECT</li><li><strong>Using Expression:</strong> Set to ‘true’ to allow all users to read data.</li><li>Save the policy.</li></ul><p>With RLS enabled and the public read policy in place, any SELECT queries will return data as expected while write operations remain secure.</p><p>Now that our database is setup. Our next step is to implement the NL2SQL functionality. For this step, we have 2 ways:<br>1. Prompt way : We define a well-thought prompt for our LLM model, which gives all the schema details to the model, along with a couple sample queries, instructions to perform the NL2SQL functionality and then asks the model to write a SQL query based on the user query.</p><p>2. Fine-tune models: We can use one of the existing models, and then fine-tune this model, and then use it to particularly convert the NL to SQL.</p><p>For the sake of simplicity, lets stick to the Prompt Way for now.</p><p>NOTE: Make sure that your virtual environment is activated.</p><h3>NL2SQL Module Implementation</h3><p>In this section, we’ll walk through the implementation of our NL2SQL module, which is designed to convert natural language questions into SQL queries for our products table. The following code uses LangChain’s tools along with OpenAI’s GPT-3.5 Turbo model.</p><pre>import os<br>from config import OPENAI_API_KEY<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_openai.chat_models import ChatOpenAI<br>from langsmith import utils<br>import logging<br>from langchain_core.runnables import RunnableLambda, RunnablePassthrough, RunnableSequence<br><br>utils.tracing_is_enabled()<br><br># Creating the prompt to instruct the model on how/what to do to generate the SQL queries<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;You are a expert at generating SQL queries for the following table schema.<br><br>Table : products<br>Columns : id(auto increment, primary key, integer), created_at(timestamp), name(varchar), description(varchar), price(numeric), stock(integer)<br><br>And the following question: {question}<br><br>Some sample user queries and their corresponding SQL queries for your understanding:<br>1. What are the names of all the products?<br>SQL query: SELECT name FROM products<br><br>2. What are the names of all the products that cost more than $100?<br>SQL query: SELECT name FROM products WHERE price &gt; 100<br><br>3. What are the names of all the products that cost more than $100 and have a stock quantity of 10 or more?<br>SQL query: SELECT name FROM products WHERE price &gt; 100 AND stock &gt;= 10<br><br>Please keep in mind that, certain functions and methods can only be used on some columns, based on their datatype. <br>So, knowing the datatype of the columns is really important.<br><br>If you dont know the answer, just say you dont know.<br><br>Generate a SQL query to answer this question.<br>&quot;&quot;&quot;)<br><br># Defining the LLM that will be used to answer the user query<br>model = ChatOpenAI(openai_api_key = OPENAI_API_KEY, model=&quot;gpt-3.5-turbo&quot;)<br><br># Defining the output parser to parse the output of the LLM and exrtact the content out of the AIMessage object response<br>def outputParser(response):<br>    logging.info(&quot;NL2SQL RAG output: Parsing the response...&quot;)<br>    return response.content<br><br><br># Chain<br>nl2sql_chain = ({&quot;question&quot;: RunnablePassthrough()} | prompt | model | outputParser)<br><br># Invoking the chain with a sample question<br>response = nl2sql_chain.invoke(&quot;What are the names of all the products whose name contains &#39;ea&#39; and have a stock quantity of 10 or more?&quot;)<br>print(response)</pre><p>Now, If you run the below command. You should see a SQL query generated for the user query mentioned in the nl2sql_chain invocation, and printed in your terminal.</p><pre>python3 nl2sql.py</pre><p>You can even get a glimpse of the steps involved in this chain along with the input and output, using your LangSmith traces. Below is a screenshot of the simple invoke of our chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9AyBAeUZsS3k-qqOKJoWg.png" /></figure><p>Great!We now have our chain generating SQL queries.</p><p>But, we need these queries to actual run on our database and return the results to the end user. Some points to keep in mind:<br>- The Users can only run SELECT statements<br>- We should not allow users to perform any write(Create/Update/Delete) queries<br>- What/How do we update our RAG to accommodate multiple tables?<br>- How do we catch the user intent?</p><p>Our next major step is to execute these queries on your Supabase database and expose this functionality via an API.</p><ul><li>Lets create a FastAPI server:</li></ul><p>For this, Install the fastapi package by running the below command in your terminal</p><pre>pip install &quot;fastapi[standard]&quot;</pre><p>And then we create a new folder named “<strong>api”</strong> in our project’s root folder. And add a “main.py” file inside it. This is the file which will handle our connection to supabase database and API requests handlings(aka SQL queries to be run on our supabase database).</p><h4>SUPABASE CONNECTION PARAMETERS:</h4><p>Before going to api/main.py file. Lets, ensure we add the below env variables to our .env file:</p><pre>SUPABASE_HOST=<br>SUPABASE_PORT=<br>SUPABASE_DB=<br>SUPABASE_USER=<br>SUPABASE_PASSWORD=</pre><p>The corresponding for these values can be found in your supabase database. <br>- Go to your supabase account<br>- On the dashboard, click on your project under your organization<br>- And click on the “Connect” button on the top navbar<br>- A “Connect to your project” dialog box should open now<br>- Click on the “view parameters” button under the Direct Connection -section<br>- All the necessary env variables will be available here<br>- <strong>SUPABASE_PASSWORD</strong> is the password you setup during this project’s creation.</p><h4>QUERY RUNNING ON THE DATABASE/API HANDLING:</h4><p>Now that you have all the necessary env variables in your .env file. Lets proceed to api/main.py file:</p><pre># This will be used to connect to our supabase database<br># This will be used to create a connection to our database<br># This will be used to define the api endpoint, to which the end user&#39;s query will be passed<br># This will be used to define, what happens once the api endpoint is hit<br># The api endpoint will make a call to the nl2sql chain and generate the corresponding SQL query<br># The generated SQL query is then run on our database<br><br>from typing import Union<br><br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from fastapi import HTTPException<br>import psycopg2<br>from nl2sql import nl2sql_chain  # Import your NL2SQL chain<br>from config import OPENAI_API_KEY<br>import os<br>import uvicorn<br><br>app = FastAPI()<br><br># Pydantic model for input validation<br>class QueryRequest(BaseModel):<br>    question: str<br><br># Establish database connection<br>def get_db_connection():<br>    return psycopg2.connect(<br>        host=os.getenv(&quot;SUPABASE_HOST&quot;),<br>        dbname=os.getenv(&quot;SUPABASE_DB&quot;),<br>        user=os.getenv(&quot;SUPABASE_USER&quot;),<br>        password=os.getenv(&quot;SUPABASE_PASSWORD&quot;),<br>        port=os.getenv(&quot;SUPABASE_PORT&quot;, 5432)<br>    )<br><br>@app.post(&quot;/query&quot;)<br>async def query_db(request: QueryRequest):<br>    # Generate SQL query from the natural language input<br>    try:<br>        sql_query = nl2sql_chain.invoke(request.question)<br>        print(sql_query)<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=&quot;Error generating SQL query.&quot;)<br>    <br>    # Validate that the SQL query is read-only<br>    if not sql_query.strip().lower().startswith(&quot;select&quot;):<br>        raise HTTPException(status_code=400, detail=&quot;Only SELECT queries are allowed.&quot;)<br><br>    # Execute the SQL query on Supabase<br>    try:<br>        conn = get_db_connection()<br>        cur = conn.cursor()<br>        cur.execute(sql_query)<br>        records = cur.fetchall()<br>        # Optionally, get column names from cur.description<br>        columns = [desc[0] for desc in cur.description]<br>        result = [dict(zip(columns, row)) for row in records]<br>        cur.close()<br>        conn.close()<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=&quot;Error executing SQL query.&quot;)<br><br>    return {&quot;sql&quot;: sql_query, &quot;result&quot;: result}<br><br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>Now, In order to run the backend server, all you need to do is run the below command in your terminal</p><pre>fastapi dev path/to/your/main.py/file</pre><p>This should run the uvicorn server on the <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> endpoint.</p><p>If the above command doesnt work, then try running the below command:</p><pre>uvicorn api.main:app --reload</pre><p>Because, we wont be able to find the config, nl2sql modules from the api/main.py file. So, Its better we run our server directly from the root folder.</p><p>Now you can navigate to <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs/</a> and try out the ‘/query’ endpoint manually.</p><p>Once you click on the “Try it out” button, you should be able to modify the Request body JSON. Where you can replace the value of the question and execute it. You should see the Response body displaying the SQL query and the corresponding result.</p><p>Below is a screenshot of a sample request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouqPxBBhCUjHdiD9lHeLVA.png" /></figure><p>Below is a screenshot of a sample response(displaying both SQL query based on the user query, and the corresponding result(s)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J60azlvBoLhWkMuMGW-3Yw.png" /></figure><p>Nice!We now have the flow of generating SQL queries and running that SQL query on the database and getting the corresponding results.</p><p>🎉Congratulations! You now have a local script that is capable of constructing SQL queries based on user query, then queries SQL databases and retrieves the results from it.</p><p>But, We now need to integrate this functionality in to our existing streamlit RAG application.</p><p>As you have already noticed, we will have 2 knowledge bases in our case after integrating nl2sql module into our application:<br>1. The Vector store for the unstructured data(document embeddings)<br>2. The Supabase for the structure data(SQL database)</p><p>Here comes the point where we need our LLM application to actually decide on which knowledge base to leverage based on the current user query — <strong>Query Routing</strong>. So, lets discuss more on it in the next parts.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbf149020d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation(RAG) Series: Part3]]></title>
            <link>https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part3-344d89cb7b8e?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/344d89cb7b8e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langsmith]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 18:19:19 GMT</pubDate>
            <atom:updated>2025-02-10T18:44:25.763Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back! In this part of the series, We will focus on turning our RAG pipeline into a Conversational RAG Application.</p><h3>What will you learn in this Part?</h3><ul><li><strong>Implementing</strong> <strong>multi-turn conversation handling</strong> in RAG</li><li><strong>Managing</strong> <strong>chat history embeddings</strong> for context-aware responses</li><li><strong>Detecting</strong> <strong>and expanding follow-up queries</strong> dynamically</li><li><strong>Using</strong> <strong>Streamlit</strong> to build an interactive RAG-powered chat UI</li><li><strong>Storing and retrieving chat history</strong> using a vector database</li><li><strong>Building</strong> <strong>a</strong> <strong>fully functional Conversational RAG application</strong></li><li><strong>Best practices</strong> for implementing a modular and maintainable RAG project</li></ul><h3>Why Streamlit?</h3><p>Because, Streamlit is a light-weight framework used to develop python-based LLM, RAG pipelines as applications with minimal code, less time and easier deployments for end users. So, We might have our first RAG Application built in just a few minutes. So, Let’s get started.</p><p>Before that, I hope you went through <a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part1-9afbd2577df5">Part1</a> and <a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part-2-964dae6a8b73">Part2</a> of this series, as they are important to understand &amp; easily implement Part3.</p><h3>Installing Necessary Packages:</h3><p>First things first, <strong>make sure your virtual environment is activated</strong>.</p><p>Now, run the below command to install streamlit package in your environment.</p><pre>pip install streamlit</pre><p>Next run the below command to see streamlit sample application in your browser.</p><pre>streamlit hello</pre><p>Do you remember, we created a single notebook in Part2 to create 2 seperate chains — one for Indexing, the other one for Retrieval &amp; Generation?</p><p>Now, Lets separate the jupyter notebook into 2 seperate python scripts to ensure <strong>modularity</strong> among Indexing Phase and Retrieval-Generation Phases, as we are implementing Static Indexing. (I explained <strong>Static vs Dynamic Indexing</strong> in Part2.)</p><p>Create the below 2 new files in your project and populate them with applicable cells from your notebook <strong>OR</strong> copy the files from the links below:</p><ul><li><a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/scripts_v1/indexing_pipeline_basic.py">indexing_pipeline.py</a></li><li><a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/scripts_v1/retrieval_and_generation_pipeline_basic.py">retrieval_and_generation_pipeline.py</a></li></ul><p>In our case, we are not allowing our end-users to upload/Index their documents. Instead, We are going to Index our own set of curated document(s) and all the end users will query and share this same Index.</p><p><strong>NOTE : You dont need to run the indexing pipeline this time. Because, If you followed Part2, then you must already have your document indexed.</strong></p><p>Now create a <strong>app.py </strong>file in your project. This is the file which will be used to create our UI for the RAG application using streamlit.</p><p>This basic file is being created so that a user can ask a question, and the output generated by the LLM is displayed to the end user.</p><pre>import streamlit as st<br>import os<br>from langchain_openai import OpenAIEmbeddings<br>from pinecone import Pinecone<br>from retrieval_and_generation_pipeline import rag_chain  # Import the chain you built for retrieval<br>from dotenv import load_dotenv<br><br># Load API keys from environment<br>load_dotenv()<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br><br># Initialize Pinecone<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br>index_name = &quot;testprojectv1&quot;<br>index = pc.Index(index_name)<br><br># Streamlit UI<br>st.title(&quot;Interactive RAG-powered Q&amp;A&quot;)# Title of the Application<br>st.write(&quot;Ask a question based on the indexed knowledge base.&quot;)<br><br># User Input<br>user_query = st.text_input(&quot;Enter your question:&quot;)<br><br>if st.button(&quot;Get Answer&quot;):# If this button is clicked, then the below code is run<br>    if user_query.strip():# strip is method used to remove leading, trailing spaces<br>        # Run the RAG pipeline<br>        response = rag_chain.invoke(user_query)<br>        <br>        # Display the result<br>        st.subheader(&quot;Answer:&quot;)<br>        st.write(response)<br>    else:# If the user clicked on the button, without any question, then the below code is run<br>        st.warning(&quot;Please enter a valid question.&quot;)</pre><p>To run your RAG application, run the below command in your terminal:</p><pre>streamlit run app.py</pre><p>Once you run the above command, you see something like below on your browser. Where a user can ask a single question and get an answer right away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hij33gznnCFVLTzUSVU7qg.png" /><figcaption>The Streamlit UI generated for the above app.py</figcaption></figure><p>If your streamlit app is running, and you make a change to your app.py and save it. Then streamlit will ask you if you want to rerun your changes on the browser. At that time, you can select “<strong>Always re-run</strong>” option on the top-right corner of your browser, as this will make the developer experience much better as streamlit can now detect changes and apply them automatically on the browser.</p><h4>Great! You now have your streamlit Application running!!!</h4><h3>MULTI-TURN CONVERSATIONAL RAG:</h3><p>So, Right now, our rag_and_generation_pipeline.py is able to work for Single-turn Q&amp;A — users ask a question, get an answer and start over again.</p><p>But a more practical RAG would be the one facilitating Multi-turn conversational ability, where users can ask multiple questions to interact and continue the discussion without losing context, like a chat.(Yup!You guessed it right!Just like Chatgpt!)</p><p>The first thought that comes to our mind when we talk about conversational RAG is displaying/storing our conversation/chat history so far. Right!</p><p>When we think of saving the previous Q&amp;A messages of the conversation, a naive approach would be — We use a variable “chat_history” to store the previous Q&amp;As till the current query. And whenever a user asks a query, we take all of them and pass them as context to our prompt in the RAG chain and then send that to the LLM. That should give us context-aware results.</p><p>Yes, You are thinking in the right direction…The downside to this approach is that, as the user asks more and more questions, the context being sent to the LLM will become too large, meaning — lengthy context windows, and there by resulting in high costs and billings, and sometimes exceeding the context window permitted by the models themselves. So, It is imperative to come up with a more optimized way, both in terms of context window and choosing the right amount of content from the chat history.</p><p>There are various approaches to implementing a conversational RAG. Each use-case will need to weigh many factors and decide on a final approach, which basically comes down to the kind of business problem we are trying to solve.</p><p>Keeping simplicity in mind, I came up with a flow for implementing a basic conversational RAG. Let’s go over the naive approach discussed above and 1 other approach:</p><h3>1. Entire Chat history as context to the LLM.(Naive Approach):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xJrxrEYfjiCKACZ4c5yCw.png" /><figcaption>Naive Approach</figcaption></figure><h4>Pros:</h4><ul><li>Easiest &amp; Naive approach to implement.</li><li>All we will need is a list named “chat_history” to keep on saving new Q&amp;A as the conversation goes on.</li><li>Maintains full context awareness.</li></ul><h4>Cons:</h4><ul><li>The context window keeps increasing with the number of questions.</li><li>Lengthy contexts can result in more tokens.</li><li>High costs for the usage of LLM models.</li><li>Might exceed permitted context window lengths.</li></ul><h3>2. QUERY EXPANSION, ONLY RELEVANT CHAT HISTORY AS CONTEXT TO THE LLM:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJAQSIpsm12QgMHeveiS2g.png" /><figcaption>Our Approach</figcaption></figure><h4>Pros:</h4><ul><li>Able to classify follow-up and non follow-up queries.</li><li>Retains conversational context by dynamically expanding follow-up queries</li><li>Optimized token usage (only relevant Q&amp;A pairs are retrieved).</li><li>Context window reduces significantly when compared to the previous approach</li></ul><h4>Cons:</h4><ul><li>Additional steps for query expansion and double retrieval make the system more complexity.</li><li>We need to carefully curate the similarity score threshold for query classification and retrieving relevant Q&amp;A pairs from chat history vector store.</li></ul><p><strong>NOTE</strong> : We discussed <strong>Query-translation</strong> in <a href="https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part1-9afbd2577df5">Part 1 </a>of this series. In this case, our query expansion method is a way of performing query translation too.</p><h3>Let’s Implement the APPROACH 2:</h3><p>While we are going to implement our RAG based on the approach 2 discussed above. You need to understand that there is no “one solutions fits all” implementation. We need to come up with the solution that works the best for our problem.</p><h3>A. INDEXING PIPELINE:</h3><p>You can just combine all the cells related to Indexing pipeline from your RAG_pipeline.ipynb notebook and put them into indexing_pipeline.py file. or just copy the file from <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/scripts_v1/indexing_pipeline_basic.py">here</a>.</p><p>There are no additional changes needed in the indexing part for now. Because, the change we need is only for the retrieval part.</p><p>This <strong>indexing_pipeline.py</strong> file should look something like this:</p><pre>&#39;&#39;&#39;<br>- This file contains the code for the indexing pipeline only(does not include the retrieval and generation pipeline).<br>- The content of this file was part of the RAG_pipeline notebook file previously.<br>- All the methods in this file were seperate cells in the RAG_pipeline notebook.<br>- I just combined the indexing related methods and applicable methods into this file to ensure modularity and maintainability.<br>&#39;&#39;&#39;<br><br>import os<br>from dotenv import load_dotenv<br>from langsmith import utils<br>import time<br>import logging<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.runnables import RunnableLambda, RunnablePassthrough, RunnableSequence<br>from pinecone import Pinecone, ServerlessSpec<br><br><br>load_dotenv(dotenv_path=&quot;.env&quot;)<br><br># Load API Keys Safely<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br>LANGSMITH_API_KEY = os.getenv(&quot;LANGSMITH_API_KEY&quot;)<br>LANGSMITH_PROJECT = os.getenv(&quot;LANGSMITH_PROJECT&quot;)<br>LANGSMITH_TRACING_V2 = os.getenv(&quot;LANGSMITH_TRACING_V2&quot;)<br><br><br># Enabling tracing in LangSmith<br>utils.tracing_is_enabled()<br><br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br><br><br># Initialize Pinecone client<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br><br><br># Index Name<br>index_name = &quot;testprojectv1&quot;<br><br><br># Create index<br>index = pc.Index(index_name)<br><br><br># In this example, we&#39;ll create the index if it doesn&#39;t exist and then proceed with the indexing pipeline next<br>def ensure_index():<br>    existing_indexes = [index[&quot;name&quot;] for index in pc.list_indexes()]<br>    if index_name in existing_indexes:<br>        logging.info(f&quot;Index &#39;{index_name}&#39; already exists. Skipping creation.&quot;)<br>    else:<br>        logging.info(f&quot;Creating Pinecone index: {index_name}&quot;)<br>        pc.create_index(<br>            name=index_name,<br>            dimension=1536,<br>            metric=&#39;cosine&#39;,<br>            spec=ServerlessSpec(cloud=&#39;aws&#39;, region=&#39;us-east-1&#39;)<br>        )<br>        time.sleep(5)  # Ensure index is ready<br><br><br># This method is to load the document and split it into chunks<br>def load_and_split_documents(filepath):<br>    logging.info(&quot;Loading document...&quot;)<br>    loader = PyPDFLoader(filepath)<br>    docs = loader.load()<br><br>    logging.info(&quot;Splitting documents into chunks...&quot;)<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=1000,<br>        chunk_overlap=200,<br>        add_start_index=True<br>    )<br>    splits = text_splitter.split_documents(docs)<br>    return {&quot;all_splits&quot;: splits, &quot;total_Splits:&quot;: len(splits), &quot;message&quot;: &quot;Documents loaded and split successfully!&quot;}<br><br><br># This method is to generate embeddings for the chunks/splits created in the previous method<br>def embed_documents(inputs):<br>    splits = inputs[&quot;all_splits&quot;]<br>    logging.info(&quot;Generating embeddings...&quot;)<br>    embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, openai_api_key=OPENAI_API_KEY)<br>    embeddings = embeddings_model.embed_documents([split.page_content for split in splits])<br><br>    # Compute norms (to ensure embeddings aren&#39;t garbage)<br>    norms = [sum(e[:5]) for e in embeddings[:5]]  # Get first 5 embeddings&#39; norm<br>    <br>    return {&quot;all_embeddings&quot;: embeddings, &quot;norms&quot;: norms, &quot;message&quot;: &quot;Embeddings generated successfully!&quot;}<br><br><br># This method is to upsert the embeddings of the chunks/splits from the previous method into Pinecone Using Batch Upsert<br>def upsert_embeddings(data):  # This function expects a dictionary<br>    splits = data[&quot;splits&quot;][&quot;all_splits&quot;]<br>    embeddings = data[&quot;embeddings&quot;][&quot;all_embeddings&quot;]<br>    logging.info(f&quot;Upserting {len(embeddings)} documents into Pinecone...&quot;)<br>    index = pc.Index(index_name)<br><br>    vectors = [<br>        {<br>            &quot;id&quot;: f&quot;doc_{split.metadata.get(&#39;source&#39;)}_{i}_{split.metadata.get(&#39;page_label&#39;, &#39;no_label&#39;)}&quot;,  # Ensure ID is valid and unique(because vectors of same Id get overwritten by the latest vector)<br>            &quot;values&quot;: emb,<br>            &quot;metadata&quot;: {&quot;text&quot;: split.page_content}<br>        }<br>        for i, (split, emb) in enumerate(zip(splits, embeddings)) if len(emb) &gt; 0<br>    ]<br><br>    BATCH_SIZE = 100  # Recommended batch size<br>    for i in range(0, len(vectors), BATCH_SIZE):<br>        batch = vectors[i:i + BATCH_SIZE]<br>        index.upsert(vectors=batch, namespace=&#39;ns1&#39;)<br>        logging.info(f&quot;Upserted batch {i // BATCH_SIZE + 1} of {len(vectors) // BATCH_SIZE + 1}&quot;)<br>    <br>    logging.info(f&quot;Upserted {len(vectors)} vectors into the vector store.&quot;)<br>    return f&quot;Upserted {len(vectors)} vectors into the vector store.&quot;<br><br><br># Turn Functions into Runnables<br>load_split_runnable = RunnableLambda(load_and_split_documents)<br>embed_runnable = RunnableLambda(embed_documents)<br>upsert_runnable = RunnableLambda(upsert_embeddings)<br><br><br># Using LangChain&#39;s | Operator for an Indexing Chain<br>indexing_chain = (<br>    load_split_runnable <br>    | {<br>        &quot;splits&quot;: RunnablePassthrough(),<br>        &quot;embeddings&quot;: embed_runnable<br>    }<br>    | upsert_runnable<br>)<br><br><br># This method is to define the indexing pipeline and pre-requisites before upserting the chunks and embeddings<br>def run_indexing_pipeline(filepath):<br>    ensure_index()<br>    <br>    indexing_chain.invoke(filepath)<br>    <br>    logging.info(&quot;Indexing pipeline completed successfully!&quot;)<br><br><br># Run the indexing pipeline<br>run_indexing_pipeline(&quot;path/to/your/file&quot;)<br><br><br># Print index stats to verify index creation and upsertion<br>print(index.describe_index_stats())</pre><h3>B. RETRIEVAL &amp; GENERATION PIPELINE:</h3><ul><li>While most of our code is from our part 2 of this series. We will need some additional code in our retrieval_and_generation_pipeline.py file to accommodate the flow of follow-up questions and context-aware retrieval. Lets go over the flow to understand what needs adding.</li></ul><h4>1. ENTERING USER QUERY:</h4><ul><li>The user will enter a query in the chat_input field(user query input will be defined in app.py, a file used by streamlit to generate a UI for our RAG application), which should invoke our retrieval and generation pipeline. But, before the invocation, we are first going to classify our query.</li></ul><h4>2. CLASSIFY AS A FOLLOW-UP/NON-FOLLOW-UP QUESTION:</h4><ul><li>The reason we are implementing the classification of follow-up questions is, because the RAG might not understand a follow-up question directly. See the example below:</li></ul><pre>&quot;User&quot; : What is the locking/unlocking system?<br><br>&quot;AI&quot; : The locking system involves rental of a box with keys provided by the bank. Additional locks are prohibited. Its a key-based locking system.<br><br>&quot;User&quot; : Tell me more about it.<br><br>&quot;AI&quot; : Please specify which aspect of the Safe Deposit Box Account Rental Agreement you would <br>like to learn more about for a detailed explanation.</pre><p>Our current RAG pipeline <strong>does not track the specific entity</strong> of the user’s query when handling follow-ups. Let me explain where it went wrong:</p><ol><li><strong>User asks:</strong> <em>“What is the locking/unlocking system?”</em><br>- The RAG retrieves and answers correctly.</li><li><strong>User asks:</strong> <em>“Tell me more about it.”</em><br>- The LLM fails because <strong>“it” is ambiguous</strong> and the retriever does not expand the query with past context.</li></ol><h4>Now, how do we fix this?</h4><p>We need to <strong>detect follow-up questions</strong> and <strong>expand them into a fully contextualized query</strong> before proceeding to retrieval.</p><p>Our Approach will be to <strong>Detect if the user query is a follow-up:</strong></p><ul><li>Check similarity between the user query and the last <strong>RAG conversation(the last Q &amp; A pair in the chat history)</strong>.</li><li>If the similarity between them is <strong>≥ 0.20</strong>, then we treat it as a follow-up.</li><li>Additionally, we will include a rule-based check to see if the user query contains any of the words in (it, this, that, more).</li><li>We classify the question as a follow-up if it satisfies either similarity score check or rule-based check.</li><li>We will actually define this method in the STREAMLIT app.py file as we are only considering the last Q&amp;A pair from the chat history, which is readily available in the session_state of streamlit application.</li><li><strong>NOTE: We will discuss about session_state in the next section</strong></li></ul><h4>3. QUERY EXPANSION OF THE FOLLOW-UP QUESTION:</h4><ul><li>If the query is classified as a follow-up query, then we expand the original user query by appending it to the last Q&amp;A pair in the chat history. (this last Q&amp;A pair will be retrieved from <strong>session state</strong> in our streamlit application and not the user specific <strong>conv_vector</strong> vector store). See the below example to understand how we are expanding a follow-up query:</li></ul><pre>Original query: &quot;Tell me more about it.&quot;<br>Expanded query: &quot;Previous User Query: What is the locking/unlocking system?<br> <br>                 Previous Assistant Response: The locking system involves rental of a box with keys provided by the bank. <br>                 Additional locks are prohibited. Its a key-based locking system.<br>                 <br>                 Follow-up question: Tell me more about it.&quot;</pre><ul><li>Now, this expanded query is passed as input to our <strong>new retriever</strong>.</li><li>Now that the new retriever sees <strong>the new expanded question</strong>, it can fetch better context.</li></ul><h4>4. RETRIEVER FOR RELEVANT CONTEXT FROM CHAT HISTORY VECTOR STORE:</h4><ul><li>So, this new retriever will embed the expanded query and based on this embedding we will retrieve relevant Q&amp;A pairs from the user specific chat history vector database, which is stored in a separate namespace for each user’s session, within our index “testprojectv1”.</li></ul><p>- <strong>NOTE:</strong> Remember how we created a namespace “ns1” within our “testprojectv1” Index in Part2, to store our documents’ embeddings in vector representation? In a similar manner, we are going to create namespace “conv_vector_{session_namespace}” to store the each user session specific chat history Q&amp;A’s embeddings. All the namespaces “conv_vector_{session_namespace}” and “ns1” will belong to the same index “testprojectv1”.</p><p>- <strong>NOTE</strong>: We are creating a separate namespace for each user session because Im planning on deleting the namespace by providing the user with a “Delete Chat History” button to delete their chat history embeddings before they exit the application, to ensure Im not using too much memory of my vector store.(Additionally, we can add an automated script to delete user specific namespaces periodically.)</p><ul><li>After retrieving the relevant Q&amp;A pairs, we will only choose the Q&amp;A pairs with similarity score of atleast 0.25, to ensure we are not using too much/non-relevant context.</li><li>We will then format the original user query and the selected Q&amp;A pairs into a dictionary.</li></ul><pre>{<br>&quot;question&quot;:something, <br>&quot;selected_chat_history_context&quot;:something<br>}</pre><ul><li>This dictionary will be passed as input to our original retriever.</li></ul><h4>5. OUR ORIGINAL RETRIEVER</h4><ul><li>The original retriever will then combine the question &amp; selected_chat_history_context into a single string and embed it, followed by retrieving relevant document chunks based on the embedding.</li><li>And the retrieved chunks are used and are formatted into a context string, which is passed to the prompt.</li><li>The prompt takes both context, and the original user query and invokes the LLM model.</li></ul><h4>6. GENERATION</h4><ul><li>The LLM output is then parsed and the final response is displayed to the end user.</li><li>And keeping our billing costs in mind, I have set a limit of 150 characters for each LLM response. So you can edit your prompt to include any number of characters/additional instructions depending on your RAG usecase.</li></ul><h4>7. ADDITIONAL METHODS:</h4><ul><li>To format the last Q&amp;A in the session state’s chat history into a string.(<strong>get_last_qa_context</strong>)</li><li>To expand the user query using last Q&amp;A pair in the session_state chat history, incase the question was classified as a follow-up.(<strong>expand_followup_query</strong>)</li><li>To store each chat message pair (user query, LLM response) embeddings in a user session specific namespace within our Index after each user query is answered. So that, when a user asks a query, we can retrieve relevant Q&amp;A pairs from this vector store for better retrieval of doc chunks or getting a proper context of what is being asked by the user. The user session specific namespace will be prefixed with “conv_vector”.(<strong>store_chat_history</strong>)</li><li><strong>We will be adding these additional methods in a helper.py file</strong>. So that we can ensure that each pipeline file only has the methods which are part of its chain.</li></ul><p>So our retrieval_and_generation_pipeline.py file should be something like this:</p><pre>&#39;&#39;&#39;<br>- This file contains the code for the retrieval and generation pipeline only(does not include the indexing pipeline).<br>- The content of this file was part of the RAG_pipeline notebook file previously.<br>- All the methods in this file were seperate cells in the RAG_pipeline notebook.<br>- I just combined the retrieval and generation related methods and applicable cells into this file to ensure modularity and maintainability.<br><br><br>documenting the changes made for feature/streamlit in this file for my better understanding of the codebase.<br>- Added retrieve_chat_history method to retrieve the relevant chat history from user session&#39;sconv_vector<br>- Renamed retriever to retrieve_relevant_docs method for better understanding<br>- Added Logging for retrieve_chat_history and retrieve_relevant_docs to differentiate them for a better developer experience during debugging &amp; monitoring<br>- Updated retrieve_relevant_docs method to include the chat history context<br>- Added formatContext method as part of the 2 retrievers to format the retrieved elements(Q&amp;A pairs or Document chunks) into a single string(For simplicity)<br>- Updated the retriever_runnable to include the 2 retrievers sequentially<br>- limiting the LLM response to not be more than 150 characters<br>&#39;&#39;&#39;<br><br>import os<br>from dotenv import load_dotenv<br>from langsmith import utils<br>import time<br>import logging<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.runnables import RunnableLambda, RunnablePassthrough, RunnableSequence<br>from pinecone import Pinecone, ServerlessSpec<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain_openai.chat_models import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnableLambda<br><br>load_dotenv(dotenv_path=&quot;.env&quot;)<br><br># Load API Keys<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br>LANGSMITH_API_KEY = os.getenv(&quot;LANGSMITH_API_KEY&quot;)<br>LANGSMITH_PROJECT = os.getenv(&quot;LANGSMITH_PROJECT&quot;)<br>LANGSMITH_TRACING_V2 = os.getenv(&quot;LANGSMITH_TRACING_V2&quot;)<br><br># The Index we are going to interact with<br>index_name = &quot;testprojectv1&quot;<br><br># Initialize Pinecone client<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br>index = pc.Index(index_name)<br><br># Defining the Embedding model to be used for embedding the user query<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, openai_api_key=OPENAI_API_KEY)<br><br># creating the Index object, to interact with it<br>index = pc.Index(index_name)<br><br># Enabling tracing in LangSmith<br>utils.tracing_is_enabled()<br><br># Creating a method to embed the user query, and retrieve relevant past Q&amp;A pairs from `conv_vector`<br>def retrieve_chat_history(input):<br>    logging.info(&quot;RAG stage 1: Retrieving relevant Q&amp;A pairs from testprojectv1/conv_vector...for follow-up questions&quot;)<br>    question = input[&#39;question&#39;]<br>    user_specific_namespace = input[&#39;user_specific_namespace&#39;]<br>    expanded_query = input[&#39;expanded_user_query&#39;]<br><br>    if not user_specific_namespace:<br>        return {&quot;question&quot;: question, &quot;chat_history_context&quot;: &quot;&quot;}<br>    <br>    # logging.info(&quot;Retrieving relevant Q&amp;A pairs from testprojectv1/conv_vector...&quot;)<br>    embeddedQuestion = embeddings_model.embed_documents([expanded_query])<br>    chat_history_results = index.query(vector=embeddedQuestion, top_k=2, namespace=user_specific_namespace, include_metadata=True)<br><br>    # only selecting the Q&amp;A pairs with similarity threshold above 0.70<br>    if len(chat_history_results[&#39;matches&#39;]):<br>        selected_chat_history_results = [doc for doc in chat_history_results[&#39;matches&#39;] if doc.get(&#39;score&#39;,0) &gt; 0.25]<br>    else:<br>        selected_chat_history_results = []<br><br>    # formatting the question and retrieved Q&amp;A pairs into a dictionary<br>    # we are using a dictionary with matches key, because this is the format usually returned by a retriever, and this is format the formatContext method expects<br>    formatted_chat_history_results = formatContext({&#39;matches&#39;: selected_chat_history_results})<br>    return {&quot;question&quot;: question, &quot;chat_history_context&quot;: formatted_chat_history_results}<br><br><br># Creating a method to embed the (user query combined with the chat history context), and retrieve the relevant documents from `ns1`<br>def retrieve_relevant_docs(input):<br>    logging.info(&quot;RAG stage 2: Retrieving relevant document chunks from testprojectv1/ns1...&quot;)<br>    question = input[&quot;question&quot;]<br>    chat_history_context = input[&quot;chat_history_context&quot;]<br>    # logging.info(&quot;Retrieving relevant document chunks from testprojectv1/ns1...&quot;)<br>    # always include the question in []. because embed_documents expects a list. <br>    # If its not a list, then each character will be treated as a separate document that needs to be embedded seperately.<br>    embeddedQuestion = embeddings_model.embed_documents([question + &quot; &quot; + chat_history_context]) <br>    similar_docs = index.query(vector=embeddedQuestion, top_k=3, namespace=&quot;ns1&quot;, include_metadata=True)<br>    formatted_similar_docs = formatContext(similar_docs)<br>    return formatted_similar_docs<br><br><br># Creating a method to format the retrieved elements(Q&amp;A pairs or Document chunks) into a single string(For simplicity)<br>def formatContext(retrieved_elements):<br>    return &quot;\n&quot;.join(doc.metadata[&quot;text&quot;] for doc in retrieved_elements[&#39;matches&#39;])<br><br><br># Creating a prompt, which takes the context and question as inputs and passes them to the model<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>    Answer the user question based on the following chathistory-based and knowledge-base context in no more than 150 characters.<br>    If you dont know the answer, just say you dont know.<br>    If you think the user question is not related to the knowledge base context, just ask the user to query on the topic of the knowledge base Indexed.<br>                                          <br>    Context: {context}<br>                                          <br>    Question: {question}&quot;&quot;&quot;)<br><br><br># Defining the LLM that will be used to answer the user query<br>model = ChatOpenAI(openai_api_key = OPENAI_API_KEY, model=&quot;gpt-3.5-turbo&quot;)<br><br><br># Defining the output parser to parse the output of the LLM and exrtact the content out of the AIMessage object response<br>def outputParser(response):<br>    logging.info(&quot;RAG stage final: Parsing the response...&quot;)<br>    return response.content<br><br><br># Wrap the 2 retrievers as runnables and creating a retriever_runnable<br>retrieveChatHistory_runnable = RunnableLambda(retrieve_chat_history)<br>retrieveRelevantDocs_runnable = RunnableLambda(retrieve_relevant_docs)<br>retriever_runnable = RunnableSequence(retrieveChatHistory_runnable, retrieveRelevantDocs_runnable)<br><br><br># Chain for the retrieval and generation phases<br>rag_chain = (<br>    {&quot;context&quot;: retriever_runnable, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | model<br>    | outputParser<br>)</pre><h3>C. STREAMLIT UI(app.py):</h3><ul><li>Well, In our basic streamlit app.py file, we just displayed a Title, a Subtitle, text_input field where user can enter his question and click on the “Get Answer” button.</li><li>But, In order to turn it into a conversational RAG application. We will need to display all the messages being sent back and forth on the screen, to ensure our user has a chat like interactive experience.</li><li>So, first, we will need to change our input field from text_input to chat_input.<br>- Because,<strong> text_input</strong> field can only react to click of a button. In this case, our “Get Answer” button.<br>- Where as the <strong>chat_input</strong> field has a UI similar to that of chat box, where a user can either click on the button or press the “Enter” key to submit a query.</li><li>As soon as the user query is submitted, We will need to classify whether its a follow-up or a non follow-up question. So, we will define the <strong>is_followup_question</strong> method here, as we need direct access to the session_state’s chat history variable.</li></ul><h4><strong>SOME Q&amp;As FOR YOUR UNDERSTANDING:</strong></h4><pre>&quot;Q.What is session state?&quot;<br>- So, session state in Streamlit is a persistent storage mechanism (acts like a Python dictionary) that maintains information across reruns of your app.<br>- It allows you to store user-specific data such as chat history, unique session identifiers, preferences, or any other custom variable across reruns.<br>- A streamlit application reruns from top to bottom for every user interaction with the application.(Like, asking a user query)<br>- Hence, session state is critical to preserve context (like previous chat messages) between interactions.<br><br>&quot;Q.What is a session?&quot;<br>- A session is the period during which a user interacts with an application.<br>- Each browser tab typically gets its own session.<br>- It stores user-specific data (like chat history) while the tab is open.<br>- The session ends when the tab is closed or the app is refreshed.<br><br>&quot;Q.When does a Streamlit application rerun?&quot;<br>- Every time a user interacts (e.g., submits a form, clicks a button), causing the script to rerun.<br>- Streamlit is designed to manage rapid reruns.<br>- But, the work during reruns can be reduced by some caching annotations provided by streamlit.<br><br>&quot;Q.When does a session state get refreshed?&quot;<br>- It persists during a session and is refreshed only when a new session starts or the app is restarted.<br><br>&quot;Q.Why add chat history in session state when there’s a Pinecone namespace dedicated for each user session?&quot;<br>- Session state: Provides immediate, in-memory context for the current conversation.<br>- Pinecone namespace: Stores a persistent, indexed history for long-term retrieval.<br>- We are using the chat history stored in memory, for immediate processing during the current session and low-latency retrieval.<br>- And it is easier to manage without needing external API calls or queries, thereby not incurring extra costs for querying an external database.<br><br>&quot;Q.Why is our is_followup_question method in app.py instead of helper.py?&quot;<br>- It directly interacts with session state and UI logic, making it specific to the streamlit applicaiton flow rather than a generic utility function.</pre><ul><li>And right after the classification, we need to display the user query as part of the chat history messages. (using streamlit’s markdown)</li><li>And then add that message to our chat_history in the session_state.</li><li>And once the LLM response is received, we should display that as part of our chat history messages too.</li><li>And add this LLM response to our chat history in the session_state and so on.</li><li>Once the user is done interacting with our LLM, we need to ensure that the user related namespace is deleted. So, we will include a “delete chat history” button in the UI, which will delete the chat history in the session state, as well as delete the user specific namespace from our index.</li></ul><p>Our <strong>app.py</strong> file should be something like this:</p><pre>import streamlit as st<br>from langchain_openai import OpenAIEmbeddings<br>from pinecone import Pinecone<br>from retrieval_and_generation_pipeline import rag_chain<br>from helper import get_last_qa_context, store_chat_history, expand_followup_query  # Import the chain you built for retrieval<br>import uuid, logging<br>import numpy as np<br>from sklearn.metrics.pairwise import cosine_similarity<br>import os<br>from dotenv import load_dotenv<br><br># Load API keys from environment<br><br>load_dotenv()<br><br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br><br># Initialize Pinecone<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br>index_name = &quot;testprojectv1&quot;<br>index = pc.Index(index_name)<br><br><br># Created a method to classify if the user query is a follow-up by comparing its embedding with the combined embedding of the last Q&amp;A pair.<br>def is_followup_question(user_query, context):<br>    logging.info(&quot;1. Classifying the query as follow-up or not...&quot;)<br>    # If the last Q&amp;A pair is not available, return False<br>    context = get_last_qa_context(st.session_state.chat_history)<br>    if context == &quot;&quot;:<br>        return False<br><br>    # Embedding-based follow-up detection using cosine similarity<br>    # Since embeddings_model.embed_documents returns a list, we wrap them with np.array.<br>    query_embedding = np.array(embeddings_model.embed_documents([user_query]))<br>    context_embedding = np.array(embeddings_model.embed_documents([context]))<br><br>    # cosine_similarity returns a 2D array (1x1 in this case), so we extract the first element.<br>    similarity = cosine_similarity(query_embedding, context_embedding)[0][0]<br>    logging.info(f&quot;2. Follow-up Detection | Cosine Similarity: {&#39;True&#39; if similarity &gt;= 0.25 else &#39;False&#39;} | Similarity: {similarity}&quot;)<br><br>    # Rule-based follow-up detection<br>    ambiguous_keywords = {&quot;it&quot;, &quot;more&quot;, &quot;that&quot;, &quot;this&quot;, &quot;they&quot;, &quot;them&quot;}<br>    rule_based_followup = any(word in user_query.lower().split() for word in ambiguous_keywords)<br>    logging.info(f&quot;3. Follow-up Detection | Rule-based: {&#39;True&#39; if rule_based_followup else &#39;False&#39;}&quot;)<br>    <br>    # Return True if the similarity is above 0.25 or if the rule-based follow-up detection is True.<br>    return similarity &gt;= 0.20 or rule_based_followup<br><br><br># Streamlit UI<br>st.title(&quot;Interactive RAG-powered Q&amp;A&quot;)<br>st.subheader(&quot;Please, Delete your chat history before exiting the app.&quot;, divider=&quot;rainbow&quot;)<br>st.write(&quot;Ask a question based on the indexed knowledge base.&quot;)<br><br># Session State for chat history display<br>if &quot;chat_history&quot; not in st.session_state:<br>    st.session_state.chat_history = []<br><br># Generate a unique session ID if not already created<br>if &quot;session_id&quot; not in st.session_state:<br>    st.session_state.session_id = str(uuid.uuid4())  # Generates a random UUID - this will be the name of this user&#39;s conv_vector namespace<br><br>session_namespace = f&quot;conv_vector_{st.session_state.session_id}&quot;<br># print(f&quot;Your session namespace: {session_namespace}&quot;) # Just for debugging purposes<br><br># Display chat history/chat messages<br>for message in st.session_state.chat_history:<br>    st.chat_message(message[&#39;role&#39;]).markdown(message[&#39;content&#39;])<br><br># chat_input field Allows &quot;Enter&quot; to submit<br>user_query = st.chat_input(&quot;Enter your question:&quot;)<br><br>if user_query is not None:  # Ensures it only runs if the user has actually entered something<br>    if user_query.strip() == &quot;&quot;:  # Show warning only if the input is explicitly empty<br>        st.warning(&quot;Please enter a question.&quot;)<br>    else:<br><br>        # Compute the context from the chat history once.<br>        context = get_last_qa_context(st.session_state.chat_history)<br><br><br>        expanded_user_query = &quot;&quot;<br>        # Detect if it&#39;s a follow-up<br>        if is_followup_question(user_query, context):<br>            logging.info(&quot;CLASSIFICATION RESULT:This is a follow-up question.&quot;)<br>            # 3. Expand the follow-up question<br>            expanded_user_query = expand_followup_query(user_query, context)<br><br>        # 1. Display the user query as part of the chat history<br>        st.chat_message(&quot;user&quot;).markdown(user_query)<br><br>        # 2. Append user query to chat history/messages<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query})<br><br>        # 3. Invoke/Run the RAG pipeline<br>        # ##############################################################################################################<br>        if len(st.session_state.chat_history) &lt; 2 or expanded_user_query == &quot;&quot;: # If this is the first question or a non follow-up question<br>            response = rag_chain.invoke({&quot;question&quot;: user_query, &quot;user_specific_namespace&quot;: &quot;&quot;, &quot;expanded_user_query&quot;: &quot;&quot;})<br>        else:<br>            response = rag_chain.invoke({&quot;question&quot;: user_query, &quot;user_specific_namespace&quot;: session_namespace, &quot;expanded_user_query&quot;: expanded_user_query})<br>        # ############################################################################################################## <br>        <br>        # 4. Display the RAG output as part of the chat history<br>        st.chat_message(&quot;assistant&quot;).markdown(response)<br><br>        # 5. Append RAG response to chat history/messages<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response})<br><br>        # Store the latest Q&amp;A in the vector store<br>        store_chat_history(user_query, response, session_namespace)<br><br># Delete chat history button<br>if st.button(&quot;Delete Chat History&quot;):<br>    print(f&quot;Deleting the chat history for session namespace: {session_namespace}&quot;)<br>    index.delete(namespace=session_namespace, delete_all=True)<br>    st.session_state.chat_history = []  # Clear UI history<br>    st.success(&quot;Chat history deleted successfully.&quot;)<br></pre><p>To know all the namespaces currently present in your index. you can run the below code in a separate python file named <strong>namespaces.py</strong>:</p><pre>import os<br>from pinecone import Pinecone<br>from dotenv import load_dotenv<br><br># Load API keys<br>load_dotenv()<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br><br>index_name = &quot;testprojectv1&quot;<br><br># Initialize Pinecone client<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br>index = pc.Index(index_name)<br><br># Retrieve index statistics<br>index_stats = index.describe_index_stats()<br>print(index_stats)</pre><p>This should list all the namespaces currently present in your Index in the ‘namespaces’ key-value pair.</p><p>You can choose to include the code in the above file to automatically delete the namespaces prefixed with “conv_vector”, incase you feel the users forget to delete their chat history.</p><h3>DRY(DON’T REPEAT YOURSELF):</h3><p>Now, If we take a look at all 4 files — indexing_pipeline, retrieval_and_generation_pipeline, app, namespaces scripts. You should notice that we are loading the env variables, pinecone client, logging configuration in all these files. So, Lets separate these out into a <strong>config.py </strong>file and remove all these repetitions from your scripts.</p><p>Create a new file <strong>config.py</strong> in your project. And add the below code into it:</p><pre>&#39;&#39;&#39;<br>This file contains the configuration settings for the application. Made this file to ensure DRY. <br>Because most of these variables, settings and client were used in multiple files:<br>(indexing_pipeline, retrieval_and_generation_pipeline and app.py)<br><br>It includes the following variables:<br>- OPENAI_API_KEY<br>- PINECONE_API_KEY<br>- LANGSMITH_API_KEY<br>- LANGSMITH_PROJECT<br>- LANGSMITH_TRACING_V2<br>- embeddings_model<br>- pc(pinecone client)<br>- index<br>- index_name<br>- logging configuration<br>&#39;&#39;&#39;<br><br>import os<br>import logging<br>from dotenv import load_dotenv<br>from pinecone import Pinecone<br>from langchain_openai import OpenAIEmbeddings<br><br># Load environment variables from .env<br>load_dotenv(dotenv_path=&quot;.env&quot;)<br><br># Load API Keys safely<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br>LANGSMITH_API_KEY = os.getenv(&quot;LANGSMITH_API_KEY&quot;)<br>LANGSMITH_PROJECT = os.getenv(&quot;LANGSMITH_PROJECT&quot;)<br>LANGSMITH_TRACING_V2 = os.getenv(&quot;LANGSMITH_TRACING_V2&quot;)<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br><br># Set the logging level for httpx, pinecone, pincone_plugin_interface to WARNING to suppress INFO-level logs<br>logging.getLogger(&quot;httpx&quot;).setLevel(logging.WARNING)<br>logging.getLogger(&quot;pinecone&quot;).setLevel(logging.WARNING)<br>logging.getLogger(&quot;pinecone_plugin_interface&quot;).setLevel(logging.WARNING)<br><br># Defining the Embedding model to be used for embedding a user query<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, openai_api_key=OPENAI_API_KEY)<br><br># Initialize Pinecone client and index<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br>index_name = &quot;testprojectv1&quot;<br>index = pc.Index(index_name)</pre><p>Now, go ahead and remove the repeated code from those 4 files. And just <strong>import</strong> <strong>the necessary variables, configurations from</strong> <strong>config.py</strong> instead of writing the same code in multiple files.</p><h3>HELPER METHODS(helper.py):</h3><ul><li>Add a <strong>helper.py</strong> in your project and add the helper functions to it.(the helper functions which we discussed at the end of retrieval and generation pipeline section in this part)</li></ul><pre>import logging<br>from config import index, embeddings_model<br><br># Created a method to retrieve the last Q&amp;A pair from the chat history and format them into a single string.<br>def get_last_qa_context(chat_history):<br>    if len(chat_history) &lt; 2:<br>        return &quot;&quot;<br>    last_idx = len(chat_history)<br>    prev_message = chat_history[last_idx - 2]  # Last user query<br>    last_message = chat_history[last_idx - 1]  # Last assistant response<br>    if prev_message.get(&quot;role&quot;) == &quot;user&quot; and last_message.get(&quot;role&quot;) == &quot;assistant&quot;:<br>        return f&quot;Previous User Query: {prev_message[&#39;content&#39;]}\nPrevious Assistant Response: {last_message[&#39;content&#39;]}&quot;<br>    return &quot;&quot;<br><br># Cretaing a method to expand the user query if it is a follow-up question<br>def expand_followup_query(user_query, context):<br>    # Append the follow-up question to the context.<br>    expanded_query = f&quot;{context}\nFollow-up question: {user_query}&quot;<br>    # logging.info(&quot;Expanded follow-up query: &quot; + expanded_query)<br>    return expanded_query.strip()<br><br># Store latest Q&amp;A in user specific namespace prefixed with `conv_vector`<br>def store_chat_history(user_query, llm_response, user_specific_namespace):<br>    logging.info(&quot;Storing latest Q&amp;A into conv_vector...&quot;)<br>    embedding = embeddings_model.embed_documents([user_query + &quot; &quot; + llm_response])<br>    <br>    vector = {<br>        &quot;id&quot;: f&quot;chat_{hash(user_query)}&quot;,<br>        &quot;values&quot;: embedding[0],<br>        &quot;metadata&quot;: {&quot;text&quot;: f&quot;Q: {user_query}\nA: {llm_response}&quot;}<br>    }<br>    <br>    index.upsert(vectors=[vector], namespace=user_specific_namespace)<br>    logging.info(&quot;Chat history stored successfully.&quot;)</pre><p>Now, just run the below command in your terminal to run your RAG application on your browser:</p><pre>streamlit run app.py</pre><h3>BELOW IS A SCREENSHOT OF THE STREAMLIT APPLICATION :</h3><p>See how the RAG can now answer our follow-up questions? Power of context-awareness, I guess!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_nASsK8myoZFncXbc5RLw.png" /><figcaption>A screenshot displaying sample RAG chat</figcaption></figure><p>For easy understanding, I also included logging in our application. So, the below screenshot is to see and undertsand what is going on after each user query submission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUAnK5TLA5GwMJ8_VSR13A.png" /><figcaption>Logs in the console</figcaption></figure><h4>✨ Congratulations! You just built your own RAG application using streamlit, which supports multi-turn conversational RAG.</h4><h3>FINAL STEPS:</h3><p>Run the below command to add all the new packages to requirements.txt file.</p><pre>pip freeze &gt; requirements.txt</pre><p>Make sure to deactivate your virtual environment using:(on Mac)</p><pre>deactivate</pre><p>You can check out my github repo for the source code <a href="https://github.com/SwethaVoora/RAG_Pipeline">here</a>.</p><p>In the next parts, we will try and enhance our RAG application further. So, Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344d89cb7b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation (RAG) Series: Part 2]]></title>
            <link>https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part-2-964dae6a8b73?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/964dae6a8b73</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[langsmith]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 15:24:24 GMT</pubDate>
            <atom:updated>2025-02-03T15:24:24.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>STEP-BY-STEP IMPLEMENTATION OF A RAG PIPELINE</h3><p>Welcome to Part 2 of the RAG Series! In this part, I will walk you through a <strong>Step-by-step Implementation of a complete RAG pipeline</strong> using <strong>LangChain, LangSmith, Pinecone, and OpenAI LLMs</strong>. If you are looking to build a scalable <strong>Retrieval Augmented Generation (RAG) system</strong>, this guide is for you!</p><p>By the end of this article, you will have a <strong>fully functional RAG pipeline</strong> capable of retrieving, processing, and generating fact-based responses.</p><p><em>If you haven’t read Part 1 yet, I recommend checking it out first, as the terminology and the concept &amp; flow of RAG is explained in simple terms for your better understanding.</em></p><p>By the end of this article, you will have learnt:</p><ol><li><strong>Creating an Index in Pinecone</strong></li><li><strong>Embedding and Storing Data Efficiently</strong></li><li><strong>Retrieving Relevant Chunks from Pinecone</strong></li><li><strong>Formatting Context for LLMs</strong></li><li><strong>Building a Chain for Indexing Phase using LangChain</strong></li><li><strong>Building a Full RAG Chain Using LangChain</strong></li><li><strong>Integrating with LangSmith for Observability</strong></li><li><strong>Executing a Query(User Question)Through the Entire Pipeline</strong></li></ol><p>Let’s get started!</p><h3>Prerequisites/Project Setup</h3><p>I’m using Jupyter Notebook for this implementation. But you can use Jupyter Notebook(For easy debugging &amp; Interactive development) <strong>OR </strong>Python scripts(for modularity and production-ready application).</p><p><strong>Step 1</strong>: Create a new folder named “RAGProject”(or your choice of name)<br><strong>Step 2</strong>: Inside the folder, <strong>create a </strong><strong>.env file</strong> and add:</p><pre>OPENAI_API_KEY=&lt;Create_an_APIKey_in_your_openai_developer_platform_account&gt;<br>LANGSMITH_API_KEY=&lt;Create_an_API_Key_in_your_langsmith_account&gt;<br>LANGSMITH_PROJECT=&lt;your_choice_of_name&gt;<br>LANGSMITH_TRACING_V2=&quot;true&quot;<br>PINECONE_API_KEY=&lt;You_will_get_an_API_Key_right_after_you_sign_up&gt;<br>#DEEPSEEK_API_KEY=&lt;If_you_choose_deepseek_for_the_llm_model&gt;</pre><p><strong>Step 3: (Optional) Create a requirements.txt file inside the RAGProject folder and </strong>can copy the requirements.txt file from the link <a href="https://github.com/SwethaVoora/RAG_Pipeline/blob/main/requirements.txt">here</a>.<br><strong>Step 4</strong>: Create a jupyter notebook file(with your choice of name)<br><strong>Step 5</strong>: Add an empty data folder inside the RAGProject folder(This is where you will save all your documenst meant to be Indexed.)<br><strong>Step 6</strong>: Create a virtual python environment using the below command:</p><pre>python3 -m venv myenv</pre><p>This should add a myenv folder inside your project folder.<br><strong>Step 7</strong>: Activate the virtual environment using(on Mac):</p><pre>source myenv/bin/activate</pre><p><strong>Step 8</strong>: Populate the env variables in the .env file.<br><strong>Step 9</strong>: Make sure to select your virtual environment as the kernel when running the notebook cell for the first time.</p><h3>Setting Up Dependencies &amp; Environment Variables</h3><p>we begin by installing the dependencies needed for this part of the series:</p><p>If you did step3 from prerequisites, then run the below command:</p><pre>pip install -r requirements.txt</pre><p>Else,</p><p>We begin by installing and importing all the necessary packages in the notebook itself. Ensure you have the following installed in your environment:</p><pre>%pip install -qU pinecone python-dotenv langchain_community pypdf langchain-openai langchain-text-splitters langgraph langchain langsmith faiss-cpu</pre><p>These packages provide:</p><ul><li><strong>LangChain</strong>: To orchestrate different components of RAG.</li><li><strong>Pinecone</strong>: A vector database to store embeddings and perform similarity search.</li><li><strong>OpenAI</strong>: For embedding generation and answering queries.</li><li><strong>pypdf</strong>: To load and process PDFs.</li><li><strong>LangSmith</strong>: To enable observability and monitoring for the Indexing Chain and the RAG chain.</li></ul><p>Next, we set up environment variables using dotenv library in our next cell:</p><pre>import os<br>from dotenv import load_dotenv, find_dotenv<br><br>load_dotenv(dotenv_path=&quot;.env&quot;)<br><br># Load API Keys Safely<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>PINECONE_API_KEY = os.getenv(&quot;PINECONE_API_KEY&quot;)<br>LANGSMITH_API_KEY = os.getenv(&quot;LANGSMITH_API_KEY&quot;)<br>LANGSMITH_PROJECT = os.getenv(&quot;LANGSMITH_PROJECT&quot;)<br>LANGSMITH_TRACING_V2 = os.getenv(&quot;LANGSMITH_TRACING_V2&quot;)</pre><p>With our dependencies installed and environment variables set, let’s move on to the<strong> next steps</strong>.</p><h3>Implementing LangSmith for Observability in RAG Pipelines</h3><p><strong>Why Use LangSmith?<br></strong>LangSmith is an <strong>observability and monitoring tool</strong> designed specifically for <strong>LLM (Large Language Model) applications</strong>. When integrating <strong>Retrieval-Augmented Generation (RAG)</strong>, LangSmith provides detailed insights into the <strong>execution of each step</strong>, ensuring that we can debug, optimize, and refine the pipeline efficiently.</p><pre>from langsmith import utils<br>utils.tracing_is_enabled()</pre><p>To enable tracing, we already loaded our environmental variables namely:</p><ul><li><strong>LANGSMITH_API_KEY</strong> — This is the API Key you will use to connect to langsmith and check the logs/traces of the LLM calls.</li><li><strong>LANGSMITH_PROJECT</strong> — This is the project, in which you will see the triggered chains on langsmith account.</li><li><strong>LANGSMITH_TRACING_V2</strong> — The tracing_is_enabled() works based on the value of this variable. If its true, then the tracing for this project is turned on. Else, It is turned off.</li></ul><h3>Indexing the Documents(Static Indexing)</h3><p>Before we can retrieve and generate responses using RAG, we need to <strong>index</strong> our data. This involves <strong>storing document embeddings</strong> in a vector database so that we can efficiently retrieve relevant chunks when needed.</p><h4>What is an Index?</h4><p>An <strong>index</strong> is a structured store of embeddings that enables efficient similarity searches. It consists of:</p><ul><li><strong>A fixed dimensionality</strong> (depends on the embedding model, e.g., 1536 for OpenAI&#39;s text-embedding-3-small). This is the size/length of each vector within the index.</li><li><strong>A similarity metric</strong> (e.g., cosine similarity).</li></ul><h4>What is Static Indexing?</h4><p>Static indexing is the process of pre-indexing the curated set of documents prior to deploying the RAG. Typically, all end users will be retrieving from this shared index.</p><p>Going futher, depending on the type of application you are building. you can choose <strong>dynamic indexing</strong>(end users get to upload a document for indexing) or<strong> static indexing</strong>(companies do pre-indexing of the curated set of documents prior to deploying the RAG).</p><p>But, If you are using dynamic indexing, then It is also important that users have the option to either archive/delete their index once they are done using their particular embeddings for RAGs, for privacy and storage.</p><p>In short,<br><strong>⦿ Dynamic Indexing:</strong> Indexing happens per user and on demand.<br><strong>⦿</strong> <strong>Static Indexing:</strong> Indexing happens <strong>once before deployment(or periodically for updates) </strong>and serves all users.</p><p>We will be using Static Indexing for this project.</p><h4>Initializing Pinecone Client &amp; Logging:</h4><p>We’ll enable logging to track progress and initialize the Pinecone client for vector storage.</p><p>Let’s give our Index a name — “testprojectv1”</p><pre>import time<br>import logging<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.runnables import RunnableLambda, RunnablePassthrough, RunnableSequence<br>from pinecone import Pinecone, ServerlessSpec<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br><br># Initialize Pinecone client<br>pc = Pinecone(api_key=PINECONE_API_KEY)<br><br># Index Name<br>index_name = &quot;testprojectv1&quot;</pre><p>To Index our document, we first need to ensure that have a dedicated Index, where we can store our embeddings.</p><h4>Create a Function to check If our Index exists, If not, We create it:</h4><p>We check, if our index(“testprojectv1”) already exists using the client.</p><p>If it already existing, we proceed to next steps. Otherwise, We create this index and proceed from there.</p><pre>def ensure_index():<br>    existing_indexes = [index[&quot;name&quot;] for index in pc.list_indexes()]<br>    if index_name in existing_indexes:<br>        logging.info(f&quot;Index &#39;{index_name}&#39; already exists. Skipping creation.&quot;)<br>    else:<br>        logging.info(f&quot;Creating Pinecone index: {index_name}&quot;)<br>        pc.create_index(<br>            name=index_name,<br>            dimension=1536,<br>            metric=&#39;cosine&#39;,<br>            spec=ServerlessSpec(cloud=&#39;aws&#39;, region=&#39;us-east-1&#39;)<br>        )<br>        time.sleep(5)  # Ensure index is ready</pre><p>For creation of the Index, we provide:</p><ul><li><strong>index_name </strong>— In this case, it is “testprojectv1”. <strong>Note that index names should always contain lower case alphabets and ‘-(dash)’ only.</strong></li><li><strong>dimension</strong> — This number depends on the embedding model you are using to embed the chunks/user query.(both needs to be same). For example: OpenAI’s embedding model ‘<strong>text-embedding-3-small</strong>’ has a dimension of <strong>1536</strong>.<br> — — What does dimension refer to? This is the length of the vector, which is created for each piece of chunk, essentially signifying how many numerical values are used to capture a chunk’s features/semantic meaning in the embedding space.</li><li><strong>metric</strong> — This can be a similarity metric of your choice. Im choosing ‘cosine’. But you can use euclidean, dotproduct…etc. Refer Pinecone documentation for available similar metrics <a href="https://docs.pinecone.io/guides/indexes/understanding-indexes#distance-metrics">here</a>.</li><li><strong>spec</strong> — This indicates the settings for creating a serverless index(as we are using ServerlessSpec object), which means you don’t need to manage underlying infrastructure, only defining the cloud provider and region where the index should be deployed is enough.</li></ul><h3>Why Pinecone?</h3><p>Pinecone is one of the most <strong>popular vector databases</strong> for indexing and searching embeddings.</p><h4>Key Advantages of Pinecone:</h4><ol><li><strong>Fully Serverless</strong> — No need to manage infrastructure.</li><li><strong>Highly Scalable</strong> — Handles <strong>millions of vectors</strong> with ease and ensures low-latency.</li><li><strong>Fast Similarity Search</strong> — Uses <strong>various</strong> techniques for efficient retrieval.</li><li><strong>Supports Namespaces</strong> — Helps organize multiple sets of embeddings within the same index.</li><li><strong>Seamless Integration</strong> — Works with <strong>LangChain</strong>, <strong>Hugging Face</strong>, and <strong>OpenAI</strong>.</li></ol><p>So, we <strong>don’t have to worry about scaling, hosting, or optimizing</strong> the infrastructure. <strong>Pinecone handles it all for us!</strong></p><p>Now that our Index is ready. We can proceed to our Indexing Phase next.</p><p><strong>NOTE</strong> : I will be using the terms <strong>functions, components and runnables interchangeably </strong>as we will convert the functions we define into runnables using RunnableLambda from LangChain’s runnables. These are the components which are combined to form a Chain using LangChain’s ‘|’ pipe operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI1mWJmOP4DVkg85ZeLAeg.png" /><figcaption>Diagrammatic Representation of RAG Pipeline</figcaption></figure><h3>Indexing Phase:</h3><p>According to our diagrammatic representation. We follow the below steps and <strong>chain them in the same order of definition, to Index our document.</strong></p><p>When we invoke the chain, each step is traced on Langsmith. I will be discussing the structure of each step’s Input &amp; Output(on LangSmith) — under each function defined below.</p><h3><strong>1. Load and Split documents:</strong></h3><p>We use PyPDFLoader to load the document into memory</p><p>Most <strong>LLMs have a context window limit</strong>, so we must split documents into smaller pieces before embedding them.</p><p>And also, Chunks improve the retrieval accuracy without exceeding LLM’s input limits.</p><pre>def load_and_split_documents(filepath):<br>    logging.info(&quot;Loading document...&quot;)<br>    loader = PyPDFLoader(filepath)<br>    docs = loader.load()<br><br>    logging.info(&quot;Splitting documents into chunks...&quot;)<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=1000,<br>        chunk_overlap=200,<br>        add_start_index=True<br>    )<br>    splits = text_splitter.split_documents(docs)<br>    return {&quot;all_splits&quot;: splits, &quot;total_Splits:&quot;: len(splits), &quot;message&quot;: &quot;Documents loaded and split successfully!&quot;}</pre><p><strong>WHAT WILL LANGSMITH SHOW WHEN THE ABOVE COMPONENT IS RUN?</strong></p><pre>INPUT:<br>    file passed to the load_and_split_documents function<br>OUTPUT:<br>    {<br>    &quot;all_splits&quot;:splits, <br>    &quot;total_Splits&quot;:number, <br>    &quot;message&quot;:&quot;Documents loaded and split successfully!&quot;<br>    }</pre><p>- Where, <strong>all_splits</strong> is a list of Document objects created for each chunk within the document.</p><h3><strong>2. Embed documents:</strong></h3><p>Now that our text is chunked, we move to <strong>embedding the text</strong>.</p><p><strong>Embedding Model</strong>- We use OpenAI’s embedding model ‘<strong>text-embedding-3-small</strong>’ to convert text into vector representations which capture the content’s semantic meaning.</p><pre>def embed_documents(inputs):<br>    splits = inputs[&quot;all_splits&quot;]<br>    logging.info(&quot;Generating embeddings...&quot;)<br>    embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, openai_api_key=OPENAI_API_KEY)<br>    embeddings = embeddings_model.embed_documents([split.page_content for split in splits])<br><br>    # Compute norms (to ensure embeddings aren&#39;t garbage)<br>    norms = [sum(e[:5]) for e in embeddings[:5]]  # Get first 5 embeddings&#39; norm<br>    <br>    return {&quot;all_embeddings&quot;: embeddings, &quot;norms&quot;: norms, &quot;message&quot;: &quot;Embeddings generated successfully!&quot;}</pre><p><strong>WHAT WILL LANGSMITH SHOW WHEN THE ABOVE COMPONENT IS RUN?</strong></p><pre>INPUT : # This will be the output of load_and_split_documents function:<br>    {<br>    &quot;all_splits&quot;:splits, <br>    &quot;total_Splits&quot;:number, <br>    &quot;message&quot;:&quot;Documents loaded and split successfully!&quot;<br>    }<br>Output :<br>    {<br>    &quot;all_embeddings&quot;: embeddings, <br>    &quot;norms&quot;: norms, <br>    &quot;message&quot;: &quot;Embeddings generated successfully!&quot;<br>    }</pre><p>- Where, <strong>all_embeddings</strong> is a dictionary of vectors created for each chunk within the document.</p><h3><strong>3. Index Embeddings:</strong></h3><p>Now that we have embeddings, we store them in <strong>Pinecone</strong>.<br>In Pinecone, we use the <strong>upsert</strong> opertaion to write the records to our namespace present within our Index.</p><pre>def upsert_embeddings(data):  # This function expects a dictionary<br>    splits = data[&quot;splits&quot;][&quot;all_splits&quot;]<br>    embeddings = data[&quot;embeddings&quot;][&quot;all_embeddings&quot;]<br>    logging.info(f&quot;Upserting {len(embeddings)} documents into Pinecone...&quot;)<br>    index = pc.Index(index_name)<br><br>    vectors = [<br>        {<br>            # Ensure &quot;id&quot; is valid and unique(because vectors of same Id get overwritten by the latest vector)<br>            &quot;id&quot;: f&quot;doc_{split.metadata.get(&#39;source&#39;)}_{i}_{split.metadata.get(&#39;page_label&#39;, &#39;no_label&#39;)}&quot;,  <br>            &quot;values&quot;: emb,<br>            &quot;metadata&quot;: {&quot;text&quot;: split.page_content}<br>        }<br>        for i, (split, emb) in enumerate(zip(splits, embeddings)) if len(emb) &gt; 0<br>    ]<br><br>    BATCH_SIZE = 100  # Recommended batch size<br>    for i in range(0, len(vectors), BATCH_SIZE):<br>        batch = vectors[i:i + BATCH_SIZE]<br>        index.upsert(vectors=batch, namespace=&#39;ns1&#39;)<br>        logging.info(f&quot;Upserted batch {i // BATCH_SIZE + 1} of {len(vectors) // BATCH_SIZE + 1}&quot;)<br>    <br>    logging.info(f&quot;Upserted {len(vectors)} vectors into the vector store.&quot;)<br>    return f&quot;Upserted {len(vectors)} vectors into the vector store.&quot;</pre><p><strong>Why batch upsertion here? Because,</strong></p><ul><li><strong>Pinecone limits each request to 2MB or 1000 records.</strong></li><li><strong>Batching prevents API failures due to request size.</strong></li></ul><p><strong>WHAT WILL LANGSMITH SHOW WHEN THE ABOVE COMPONENT IS RUN?</strong></p><pre>Input: <br>    This will be a dictionary.<br>    {<br>    &quot;splits&quot;: output of load_and_split_documents function, <br>    &quot;embeddings&quot;: embed_documents function<br>    }<br>Output: <br>    &quot;Upserted {len(vectors)} vectors into the vector store&quot;</pre><h3><strong>4. Creating a Indexing Chain:</strong></h3><p>Using LangChain’s <strong>| operator</strong>, we define a runnablesequence(chain) of the above functions — for Indexing.</p><pre>from langchain_core.runnables import RunnableLambda, RunnableSequence<br><br># Turn Functions into Runnables<br>load_split_runnable = RunnableLambda(load_and_split_documents)<br>embed_runnable = RunnableLambda(embed_documents)<br>upsert_runnable = RunnableLambda(upsert_embeddings)<br><br># Using LangChain&#39;s | Operator for an Indexing Chain<br>indexing_chain = (<br>    load_split_runnable <br>    | {<br>        &quot;splits&quot;: RunnablePassthrough(),<br>        &quot;embeddings&quot;: embed_runnable<br>    }<br>    | upsert_runnable<br>)</pre><h3><strong>5. Defining the entire process of Indexing Chain:</strong></h3><p>As discussed above, We will first ensure we have our Index in place. Next, We will invoke the chain containing the runnables for the steps we detailed above.</p><pre><br>def run_indexing_pipeline(filepath):<br>    ensure_index()<br>    <br>    indexing_chain.invoke(filepath)<br>    <br>    logging.info(&quot;Indexing pipeline completed successfully!&quot;)</pre><h3><strong>6. Invoking the Chain:</strong></h3><pre>run_indexing_pipeline(&quot;/path/to/your/file/&quot;)</pre><p>After you run the above cell. You can go check out the tracing for this Indexing pipeline on your langsmith account.</p><ul><li>SignIn to your LangSmith account.</li><li>Go to <strong>Observability</strong> -&gt; <strong>Tracing Projects</strong> -&gt; Click on the project with the name “TestProjectv1”(or whatever name you provided for the <strong>LANGSMITH_PROJECT</strong> env variable.</li><li>You should see a RunnableSequence populated in the project.</li><li>If you click on it. You should see a detailed log containing input, output, latency, status and errors(if applicable) for each and every step executed as part of the Indexing Pipeline.</li></ul><p>The below screenshot gives you an idea of what all steps took place as part of the Indexing Pipeline we invoked, and their latency: (These are all the functions I defined above and converted into runnables for chaining)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*l-vgsS_Hoca9dijnFoJ-ww.png" /></figure><p><strong>NOTE</strong> : <strong>In order to write readable and maintainable code. We need to make sure that we understand the structure of Inputs/Outputs for each function and how are we chaining each of these functions(components). Because we will need to use one runnable’s output as the next runnable’s input in a chain.</strong></p><p><strong>NOTE: You should try not to display your splits or embeddings directly in the output. Because, this will increase the latency for each step of the chain, eventually increasing the latency for the entire Indexing pipeline.And also, This might result in privacy comprise and malicious attacks.</strong></p><p>This marks the <strong>completion of our Indexing Phase</strong>. We now have our Index in place.</p><pre>index = pc.Index(index_name)</pre><ul><li>This initializes an instance of the Pinecone index with the name stored in index_name and allows you to interact with the existing Pinecone vector database index for the stage of retrieval.</li></ul><p>We can verify that our documents were correctly indexed by running the below cell, as it fetches the metadata and statistics related to the index.</p><pre>print(index.describe_index_stats())</pre><p>This will give the name of the namespace(‘ns1’), which is part of our index(‘testprojectv1’). And the total number of vectors in it. <strong>The total number of vectors must be equal to the number of chunks we embedded before indexing.</strong></p><p><strong>NOTE</strong> : If you notice the <strong>total_vector_count</strong> being less than the number of chunks. Then chances are the ‘id’ you mentioned for each embedding might not be unique. <strong>If any two ‘id’s are same, then they get overwritten by the latest embedding information.</strong></p><h3><strong>Now, Lets proceed to Retrieval and Generation Phases:</strong></h3><p>Now that we’ve successfully indexed our documents, it’s time to build the <strong>Retrieval &amp; Generation Chain</strong>. This phase ensures that <strong>when a user asks a question, we retrieve the most relevant chunks and generate a factual, context-aware response</strong>.</p><h3>How this Works</h3><p>When the <strong>Retrieval &amp; Generation Chain</strong> is invoked:</p><ol><li>The <strong>retriever searches</strong> for relevant document chunks based on the <strong>user query.</strong></li><li>The retrieved chunks are <strong>formatted into context</strong> for the LLM.</li><li>A <strong>predefined prompt</strong> structures the query for the LLM.</li><li>The <strong>LLM generates a response</strong> using both the user question &amp; retrieved context.</li><li>Finally, <strong>the response is parsed and displayed</strong>.</li></ol><p>When executed, <strong>each step is logged in LangSmith</strong>, capturing:</p><ul><li>Input &amp; output per step</li><li>Tokens used &amp; latency</li><li>Errors (if any)</li><li>Trace &amp; Run IDs for debugging</li></ul><h3>1. Defining the Embedding Model:</h3><p>This needs to be the same embedding model, we used for embedding the chunks/splits during the Indexing Phase - for accurate similarity search.</p><pre>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, openai_api_key=OPENAI_API_KEY)</pre><h3>2. Creating the Retriever</h3><ul><li>This retriever will retrieve the relevant chunks or docs from the vector store index using ‘similarity search’.</li><li>We use <strong>include_metadata</strong> in the index.query(), because our page_content(text) is actually part of our metadata key in the embedded splits/chunks.</li><li>Include the question(user query) within a list, because embeddings_mode.embed_documents expects a list parameter.(<strong>If its not a list, then each character will be treated as a separate document that needs to be embedded seperately.</strong>)</li></ul><pre>def retriever(question):<br>    embeddedQuestion = embeddings_model.embed_documents([question]) <br>    similar_docs = index.query(vector=embeddedQuestion, top_k=3, namespace=&quot;ns1&quot;, include_metadata=True)<br>    return similar_docs</pre><h3>3. Format the Retrieved Context</h3><p>We need to format the retrieved chunks into a structured context string, which can later be passed to an LLM.</p><pre>def formatContext(retrieved_docs):<br>    return &quot;\n&quot;.join(doc[&quot;metadata&quot;][&quot;text&quot;] for doc in retrieved_docs[&#39;matches&#39;])</pre><h3>4. Converting the above two functions into runnables:</h3><p>Since <strong>LangChain Chains require runnables</strong>, we wrap our retrieval and format functions using RunnableLambda , to convert them into runnables.</p><pre>from langchain_core.runnables import RunnableLambda<br><br># Wrap retriever and formatContext as runnables<br>retriever_runnable = RunnableLambda(retriever)<br>formatContext_runnable = RunnableLambda(formatContext)</pre><h3>5. Prompt Templating:</h3><p>Here, we are formatting a prompt for the LLM Model.</p><ul><li>context = output of (<strong>retriever_runnable | formatContext_runnable</strong>) chain.</li><li>question = user query.</li></ul><pre>from langchain.prompts import ChatPromptTemplate<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>    Answer the user question based on the following context.<br>    If you dont know the answer, just say you dont know.<br>                                          <br>    Context: {context} <br>                                          <br>    Question: {question}&quot;&quot;&quot;)</pre><h3><strong>6. Defining the Model to be invoked for the final response:</strong></h3><p>The LLM can be swapped out easily for other models like DeepSeek, Claude, Mistral…etc.</p><pre>from langchain_openai.chat_models import ChatOpenAI<br><br>model = ChatOpenAI(openai_api_key = OPENAI_API_KEY, model=&quot;gpt-3.5-turbo&quot;)</pre><h3>7. Parse the LLM Response:</h3><p>Since LLM outputs are AIMessage objects, we will be using the below Parser to just extract the actual text out of it, for the end user.</p><pre>def outputParser(response):<br>    return response.content</pre><h3>8. Defining the Retrieval and Generation Chain:</h3><p>Her, we are chaing all the components together.</p><pre>from langchain_core.runnables import RunnablePassthrough<br># Chain<br>rag_chain = (<br>    {&quot;context&quot;: retriever_runnable | formatContext_runnable, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | model<br>    | outputParser<br>)</pre><h3>9. Invoking the chain:</h3><pre># Question<br>rag_chain.invoke(&quot;Ask a question here?&quot;)</pre><p><strong>How it Works?</strong></p><ol><li><strong>User query</strong> is passed to &quot;context&quot; and &quot;question&quot;.</li><li>&quot;context&quot;: <br>- User query is embedded &amp; is used by the <strong>retriever</strong>.<br>- Retriever returns <strong>relevant document chunks</strong>.<br>- These chunks are formatted by <strong>format_context_runnable</strong>.</li><li>&quot;question&quot;:<br>- User query input is passed along as output with no change using RunnablePassthrough().</li><li><strong>Final Steps</strong>:<br>- The prompt receives {context, question} which is then passed to the LLM.<br>- LLM <strong>processes the structured prompt</strong>.<br>- Output is parsed &amp; returned.</li></ol><p>When we run the above cell, we get a new RunnableSequence added to our traces list in Langsmith.</p><p>Below is a screenshot of the trace, displaying the steps executed according to the chain we have created and invoked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*nwYIo9xUKIrHIH2iCnSAAw.png" /></figure><p>🎉 <strong>Congratulations! You’ve built a full-fledged RAG pipeline!</strong></p><h3>OPTIONAL</h3><p><strong>Optionally</strong>, Now that you have your pipeline working. If you want to delete your index to save/make memory for more projects on pinecone. You can run the below cell:</p><pre>pc.delete_index(&#39;testprojectv1&#39;)</pre><p><strong>Finally, To deactivate the python environment, simply run(on Mac):</strong></p><pre>deactivate</pre><h3>What’s Next?</h3><p>Now that we’ve built a working RAG pipeline inside a Jupyter Notebook, it’s time to take it a step further.</p><p>In <strong>Part 3</strong>, I’ll turn this into an <strong>interactive RAG-powered AI app.</strong></p><p><strong>Stay tuned for the next parts.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964dae6a8b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation(RAG) Series : Part1]]></title>
            <link>https://medium.com/@swetha.voora01/retrieval-augmented-generation-rag-series-part1-9afbd2577df5?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/9afbd2577df5</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langsmith]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 02:13:51 GMT</pubDate>
            <atom:updated>2025-02-01T06:08:33.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retrieval Augmented Generation(RAG) Series : Part1</h3><p>Throughout this series, I’ll walk you through the concepts of how RAG works, why and when do we need them, what is a RAG pipeline, how to integrate it with tools like LangChain and LangSmith, how to store and retrieve data using vector databases, and finally, how to bring it all together into a full-stack application.</p><p>RAG! You have most definitely come across this term before.<br>In this part of the series, you will get a proper insight of what RAGs are? and how to leverage this concept to customize your models output!</p><p>By the end of part1, you’ll have the answers to questions like:</p><ul><li>What exactly is RAG, and how do you know if you need it?</li><li>What are embeddings, vector stores, and how does chunking help with retrieval?</li><li>What are LangChain and LangSmith, and how do they simplify building RAG pipelines?</li><li>What is a entire RAG pipeline like?</li></ul><p>I’m going to be detailing the implementations as part of my projects. Aiding me and my readers to enhance their AI skillset. So, let’s get started.</p><p><strong>What is RAG?</strong><br><strong>Retrieval Augmented Generation (RAG)</strong> is an approach in AI where <strong>Large Language Models (LLMs)</strong> — such as OpenAI’s ChatGPT, GPT-4, Claude, or Llama — are combined with external data sources to enhance the quality and accuracy of generated text. While LLMs can excel in understanding and producing human-like language, they often have notable limitations, like reliance on dated training data and the inability to handle highly domain-specific queries out of the box.</p><p>RAG helps overcome these hurdles by:</p><ol><li><strong>Retrieving</strong> relevant documents or information in real time from external sources (e.g., private databases, vector stores, or the internet).</li><li><strong>Augmenting</strong> the model’s response with this up-to-date or specialized context, thereby <strong>“grounding”</strong> the model’s output in facts and reducing hallucinations.</li></ol><p><strong>Why Do We Need RAG? What are the right use-cases to bring RAG into the picture?</strong></p><p>If you ever came across any one of the situations listed below, Then it is your cue to get to understand RAG:</p><p><strong>Wanted to build a custom AI assistant</strong> restricted to a specific subject domain for more accurate, domain-specific answers?</p><p><strong>Wanted ChatGPT’s training data to be current</strong> rather than limited to a historical cutoff?</p><p><strong>Needed ChatGPT to cite real references</strong> (websites/articles) instead of producing made-up or “hallucinated” citations?</p><p>Modern LLMs typically <strong>have a cut-off date for training data</strong> (e.g., ChatGPT’s publicly stated cutoff) and often <strong>lack real-time knowledge</strong> or <strong>deep domain expertise</strong> in certain areas. Moreover, they frequently <strong>provide references or citations that are incomplete or incorrect</strong> (“hallucinations”). RAG addresses these gaps by linking models to external, carefully curated sources like search engines(for real-time knowledge retrieval), vector stores(for relevant information retrieval), traditional databases(like SQL database) and many others.</p><p><strong>Overview of the RAG process:<br></strong>Retrieval-Augmented Generation (RAG) expands the capabilities of a Large Language Model (LLM) by augmenting its knowledge with <strong>external data</strong>. When the LLM alone cannot respond accurately — due to incomplete training data, outdated information, or specialized domain requirements — RAG brings in a <strong>retriever</strong> that fetches relevant information from external sources(<strong>particular database/dataset/google search engine)</strong> and then <strong>generates</strong> the output for the end user.</p><p>The full RAG pipeline typically involves three major steps: <strong>Indexing</strong>, <strong>Retrieval</strong>, and <strong>Generation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI1mWJmOP4DVkg85ZeLAeg.png" /><figcaption>Diagrammatic Representation of RAG pipeline</figcaption></figure><p>Let’s take a closer look at each phase.</p><h3>1. Indexing Phase</h3><ol><li><strong>Source of Documents</strong><br>Collect and organize the documents or data sources you want the model to reference (e.g., PDFs, webpages, internal databases, google search).</li><li><strong>Chunking / Splitting</strong><br>Because most embedding models have limits on the amount of text they can process at once, each document is <strong>split into smaller pieces</strong>, known as “chunks.”</li><li><strong>Decide on an Embedding Model</strong><br>Select an embedding model capable of converting text into <strong>numerical (vector) representations</strong>.</li><li><strong>Indexing Embedded chunks in vector stores</strong></li></ol><ul><li><strong>Embedding</strong>: Each text chunk is converted into a <strong>numerical vector</strong> that captures its semantic meaning.</li><li><strong>Vector Database</strong> (Vector Store): These vectors are then <strong>indexed</strong> and stored, allowing for efficient similarity searches.</li><li>In semantic space, chunks with similar content appear “closer” to each other.</li></ul><h3>2. Retrieval Phase</h3><ol><li><strong>User Question</strong><br>A user submits a query (e.g., “What are the latest updates in our company’s leave policy?”).</li><li><strong>Embed the User Query</strong><br>Using <strong>the same embedding model</strong> employed during indexing, the system transforms the user’s query into a numerical vector.</li><li><strong>Perform Similarity Search </strong><br>The embedded query is compared against the (already embedded) vectors in the <strong>vector store</strong> to find the <strong>most relevant chunks</strong>.<br>- Techniques like <strong>cosine similarity</strong> or <strong>dot-product similarity</strong> or <strong>similarity score threshold </strong>are typically used.</li><li><strong>Retrieve Relevant Chunks<br></strong>Based on the similarity algorithm used, relevant pieces of chunks from the vector store are retrieved.</li><li><strong>Context Creation</strong><br>The <strong>retrieved chunks</strong> are then formatted or combined into a context package (e.g., a text prompt) that will be passed to the LLM.</li><li><strong>Optional Query Handling</strong></li></ol><ul><li><strong>Query Translation / Construction</strong>: If the user’s query needs translation or reformatting (e.g., from natural language to structured query syntax).</li><li><strong>Query Routing</strong>: If multiple data sources or vector stores exist, the system routes the query to the appropriate one.</li></ul><h3>3. Generation Phase</h3><ol><li><strong>Final Prompt Preparation</strong><br>The user’s <strong>original query</strong> and the <strong>formatted context</strong>(based on the retrieved chunks)<strong> </strong>are integrated into a final prompt. This prompt is then sent to the LLM for a response.</li><li><strong>LLM Invocation</strong><br>The LLM (e.g., GPT-4, Claude, Llama) processes the prompt, leveraging the new context provided.</li><li><strong>Output Parsing</strong><br>The LLM generates a response (often referred to as an AIMessage object). If needed, additional parsing may be performed to extract content, citations, structured data, or other metadata from the AIMessage object.</li><li><strong>User-Facing Output</strong><br>The final output is presented to the user, reflecting <strong>up-to-date, context-relevant</strong> information that the LLM alone could not have reliably provided.</li></ol><h3><strong>SOME Q&amp;A:</strong></h3><p><strong>Why Do We Split (Chunk)?</strong><br>Large Language Models and Embedding models can only handle a certain amount of text at once — this limit is called their “context window (total length of the input and the output combined).”</p><p>By breaking documents into smaller sections, we make sure each piece of chunk fits within that limit. It also helps the model quickly find the right information for a given question, improving both <strong>accuracy</strong> and <strong>efficiency</strong>.</p><p><strong>What is an Embedding?<br></strong>An <strong>embedding</strong> is a process that converts text into a numerical representation(series of numbers) while capturing its semantic meaning, placing it in a “3D-like” space where similar pieces of text appear closer together. The “distance” between any two embeddings reflects how similar or different their meanings are. In practical terms, embeddings help us quickly find and compare relevant information — if two text snippets produce embeddings that are close together, they’re likely discussing similar topics.</p><p><strong>What is a Vector Store?</strong><br>A <strong>vector store</strong> (or vector database) is a specialized data structure designed to store and manage <strong>embeddings</strong> — the numerical representations of text or other unstructured data. By keeping these vectors in one place, a vector store makes it easy to <strong>quickly search</strong> for similarities among pieces of text. This comes in handy during RAG’s retrieval phase, where the model looks up relevant chunks of information based on how close their embeddings are in “vector space.”</p><p><strong>Why Do We Need an Output Parser?</strong><br>When a user submits a query to an LLM in a RAG pipeline, the model typically returns an <strong>AIMessage</strong> object. This object often contains additional metadata beyond just the text the user wants to read. An <strong>Output Parser</strong> — for example, StrOutputParser—extracts and returns only the <strong>content</strong> (the plain text answer) from the AIMessage. This makes it simpler for front-end applications or other parts of the system to display or use the model’s response.</p><h3><strong>Optional(Yet Important) Stages within a RAG pipeline:</strong></h3><p><strong>A. Query Translation : </strong>This is the stage where, once a user inputs a question to a llm, the question is translated in such a way that the retrieval process is ensured to perform better than usual. Some of the popular query translation methods are :</p><ul><li><strong>HyDE</strong>(where you produce a hypothetical document relating the question, which is then used to retrieve docs from the vector stores and then the relevant docs are also retrieved for the original question and then an output is provided to user combining the retrieval of both hypothetical document and the original question as the context to the llm)</li><li><strong>Multi-Query</strong>(A users question is translated into multiple differently worded questions, and relevant retrieval of documents are done for all these questions. And then all the retrievals are combined to provide an output to the user)</li><li><strong>RAG-Fusion</strong>(While this is almost similar to the Multi-query approach, it differs in the context provided to the llm model. Here, The retrieved docs for each of the multiple questions are ranked and then a new context is created and passed through the llm, which will then generate the output for the user)</li><li><strong>Step-back</strong>(This is a approach where, the user’s question is converted into a higher lever abstract question, for which the retrieval is done, alongisde the retrieval for the original question. And based on the relevant docs retrieved for both original and step-back question, a combined context is provided to the llm, which will then be used to provide a output to the user)</li></ul><p><strong>B. Query Routing: </strong>This is the stage where, when a user inputs a query/question. The query is routed to the Index or database which is most relevant for retrieval in the current scenario. This phase can be helpful to ensure that the llm model is enabled to use the right resource(s) to leverage and produce the output to the users.</p><p>Lets say we have multiple Indexes(a vector store of an embedded research article on AI, a vector store for embeddings of a Fantasy book series, a tool to use Google search engine). We provide these indexes or data sources as options from which the model can retrieve data from.</p><p>We need to enable our llm model to be able to retrieve from a single/more relevant data sources which are related to the user query, instead of retrieving from all the sources altogether.</p><p><strong>C. Query Construction: </strong>Once you’ve routed the query to the appropriate data store, the next step often involves <strong>Query Construction</strong>. This stage is about <strong>preparing</strong> or <strong>transforming</strong> the user’s natural language query into a format that best suits your retrieval engine or vector database. For example, you might:</p><ol><li><strong>Rephrase or Translate</strong> the user query if your database requires a specific syntax or language format. (Eg : Natural language to SQL)</li><li><strong>Add Filters</strong> or <strong>Parameters</strong> (e.g., search only recent documents, filter by author).</li></ol><p>The core goal of Query Construction is to <strong>maximize retrieval accuracy</strong> by ensuring the user’s question is framed in a way the database or search engine can <strong>optimally interpret</strong>. Once the constructed query is ready, the system will perform the <strong>actual retrieval</strong>, pulling back the most relevant chunks or documents to be fed into the LLM.</p><p><strong>In Summary</strong></p><ul><li><strong>Query Translation </strong>rewrites the user query to assure <strong>better</strong> retrieval.</li><li><strong>Query Routing</strong> helps you pick the <strong>right</strong> data source.</li><li><strong>Query Construction</strong> ensures you’re <strong>asking</strong> a data source in the <strong>best</strong> way possible.</li></ul><h3>Chaining</h3><p>In LangChain, <strong>chaining</strong> refers to the process of linking together multiple, distinct components in a pipeline so they run in a specific sequence.</p><p>All the stages we have seen in the RAG pipeline are individual components/runnables. For instance, you might have a component that <strong>translates</strong> a user query, one more that <strong>retrieves</strong> relevant documents, another that <strong>invokes</strong> <strong>an LLM</strong>, and yet another that <strong>parses</strong> the output. By “chaining” these components (using the ‘|’ pipe operator), the <strong>output</strong> of one step becomes the <strong>input</strong> to the next — ensuring the entire RAG process (<strong>from retrieval to generation</strong>) works smoothly.</p><p><strong>Why Use Chaining?</strong></p><ul><li><strong>Modularity</strong>: Each stage in your RAG pipeline — query translation, embedding, retrieval, parsing, etc. — exists as its own unit.</li><li><strong>Reusability</strong>: You can swap out components (e.g., switch to a different LLM or parser) without disrupting the rest of the pipeline.</li><li><strong>Clarity</strong>: It’s easier to understand and debug a sequence of smaller tasks rather than one large, monolithic script.</li></ul><h3>LangSmith</h3><p><strong>LangSmith</strong> is a tool that brings <strong>monitoring and observability</strong> to your LangChain pipelines. Each time your RAG chain runs, LangSmith logs the steps taken, the time each step takes, the inputs passed along, and the outputs generated. This detailed view helps you:</p><ol><li><strong>Debug Issues</strong>: Quickly pinpoint where a chain might be failing or producing unexpected results.</li><li><strong>Track Performance</strong>: Identify slow or costly components, especially important as your pipeline grows in size and complexity.</li><li><strong>Optimize Your Workflow</strong>: Fine-tune prompts, adjust your chain’s logic, or experiment with different LLMs — knowing you can always trace each step in real time.</li></ol><p>In short, <strong>LangSmith</strong> offers a clear window into the inner workings of your RAG pipeline, making it easier to build, maintain, and scale high-quality AI solutions.</p><p><strong>What’s Next?<br>In Part2, </strong>we’ll dive into a hands-on example showing <strong>how to implement a RAG pipeline</strong> using LangChain, LangSmith, Python, LLMs, Pinecone vector database and <strong>more…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9afbd2577df5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a CI/CD Pipeline using Jenkins, Amazon EC2, GitHub and Docker — Part 2]]></title>
            <link>https://medium.com/@swetha.voora01/creating-a-ci-cd-pipeline-using-jenkins-amazon-ec2-github-and-docker-part-2-2c8948e3f3e5?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8948e3f3e5</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[amazon-ec2]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 17:48:03 GMT</pubDate>
            <atom:updated>2024-02-27T18:29:28.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a CI/CD Pipeline using Jenkins, Amazon EC2, GitHub and Docker — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DObZtE6U2MzghAMAAAgrLg.png" /><figcaption>CI/CD pipeline</figcaption></figure><p>You can find <a href="https://medium.com/@swetha.voora01/creating-a-ci-cd-pipeline-using-jenkins-amazon-ec2-github-and-docker-part-1-72e0a9c30b37">Part 1</a> here.</p><p>Now that you have verified that pushes to your repo’s main branch trigger a build in the Jenkins Controller EC2 instance. Lets continue with the below steps for the further enhancing our CI/CD pipeline.</p><h3>Configuring a Slave Node in Jenkins</h3><p>Leveraging a Jenkins Slave node for building jobs is a strategic approach to distribute workload and optimize the utilization of resources within your CICD pipeline. This section guides you through setting up an EC2 instance as a Jenkins Slave node.</p><h3>Setting Up the Jenkins Slave Node</h3><ul><li>Install Java openjdk version 11 on the second ec2 instance(Jenkins Slave Instance): run the commands</li></ul><pre>sudo apt-get update<br>sudo apt-get install openjdk-11-jdk</pre><ul><li>Access Jenkins Controller Homepage: Navigate to http://&lt;ec2-Ipv4-DNS&gt;:8080 address of your Jenkins Controller on your web browser to access your Jenkins dashboard.</li><li>Navigate to Nodes Configuration:Click on “Manage Jenkins” in the main menu. Select “Nodes”.</li><li>Add a New Node:Click on “New Node”. Name the node, for example, “Slave-node-1”. Select “Permanent Agent” and proceed with “OK”.</li></ul><h3>Configure Node Details:</h3><ul><li>Executors: Set the number of executors based on your instance’s vCPUs and expected workload. It’s advisable to have less than or equal executors to the number of vCPUs on your Jenkins Slave instance.</li><li>Remote Root Directory: Connect to your Jenkins slave EC2 instance using SSH/EC2 Instance connect and run “cd ~” followed by “pwd” to print the root directory. Copy this path into the “Remote root directory” field.</li><li>Labels: Assign labels to your node to control job execution. Labels help in job segregation and routing.(example : you can use “dev” for your Slave-node-1)</li><li>Usage: Opt for “Only build jobs with label expressions matching this node” to ensure specific job execution.</li><li>Launch Method: Select “Launch agent via SSH”.</li><li>Host: On your second EC2 instance(Jenkins slave), use the below command to find the IP address of your slave instance and Enter this IP in the “Host” field.</li></ul><pre>hostname -i</pre><ul><li>Credentials: Generate an SSH key pair on your Jenkins Slave EC2 instance by running the below command</li></ul><pre>ssh-keygen</pre><ul><li>Navigate to the .ssh directory and use cat to display your public key and private key in your terminal.(Similar to jenkins job creation’s Source Code Management (SCM) Section)</li><li>Copy the public key and Enter the below command to list the keys and files in the .ssh folder</li></ul><pre>ll</pre><ul><li>Run the below command to edit authorized_keys file</li></ul><pre>vim authorized_keys</pre><ul><li>Press i on the keyboard to be able to insert into the file.</li><li>Paste the public key at the end of the authorized_keys file to authorize access from Jenkins Controller.</li><li>Press ‘esc’ key and type :wq and enter, You will come back to your terminal.</li><li>Private Key: Copy the private key from your Jenkins Slave ec2 instance, generated earlier. In Jenkins, under the node configuration’s “Credentials”, choose “Add”. Select “SSH Username with private key”, input the Jenkins Slave EC2 instance’s username(Example : root), and paste the private key.</li><li>Host Key Verification Strategy: Choose “Non verifying verification strategy” for simplicity and to avoid host key verification issues.</li></ul><p>Finalizing Node Setup:</p><p>After configuring the credentials and specifying the host details, save your node’s configuration.</p><p>By completing the above steps, you’ve successfully set up an additional node in Jenkins, designated for executing build jobs. This setup not only enhances the efficiency of your CICD pipeline by offloading build tasks from the Jenkins master (Controller) but also introduces flexibility in managing different types of jobs based on the labels assigned to them.</p><p>This slave node setup is part of an overarching strategy to optimize resource utilization, improve build times, and maintain a clean separation of duties within your Jenkins environment. As you progress with your CICD pipeline development, you can further customize and scale your Jenkins infrastructure by adding more slave nodes as required.</p><h3>Additional Configuration in the Job, for Optimal Resource Management</h3><p>After setting up your Jenkins Slave node, it’s crucial to revisit your job(Freestyle project job) configuration to ensure it runs on the designated slave node and to manage build artifacts efficiently. Here’s how to adjust your job settings for better resource management and to direct the job execution to the slave node.</p><h3>Configuring Job to Use the Slave Node</h3><ol><li>Access Your Job Configuration: Navigate back to the Jenkins homepage at http://&lt;ec2-Ipv4-DNS&gt;:8080. Find the job you created for your CICD pipeline and click on its name. Click “Configure” to edit the job settings.</li><li>Discard Old Builds: Within the job configuration, locate the “General” section. Check the option for “Discard old builds” to enable automatic cleanup of build records. Under “Strategy”, select “Log Rotation”. Set “Max # of builds to keep” to 1. This setting helps in conserving storage space by retaining only the most recent build.</li><li>Restrict Job to Specific Node: Scroll down to check the option “Restrict where this project can run”. In the label expression field that appears, enter the label you assigned to your slave node during its configuration (e.g., the label “dev” you used for “Slave-node-1”). Upon entering the label, Jenkins will indicate if the label correctly matches any of the available nodes with a note such as “Label is tied to 1 node” or “Label matches # of nodes”, ensuring that the job will only run on the specified node(s).</li></ol><h3>Finalizing the Job Configuration</h3><p>After making these adjustments, your job is now optimized to automatically manage build artifacts and specifically target the configured slave node for execution. This ensures that your builds are processed on the appropriate infrastructure, leveraging the distributed nature of Jenkins to enhance performance and manage resources effectively.</p><p>By directing the job to run on a slave node, you alleviate the workload on the Jenkins Controller, allowing it to manage job scheduling and orchestration more efficiently. Additionally, by keeping only the most recent build, you maintain a lean environment that is easier to manage and quicker to troubleshoot.</p><p>Remember to click “Save” at the bottom of the job configuration page to apply these changes.</p><h3>Checking the Repo Content Cloned into the Slave-Node EC2 Instance</h3><p>Once your Jenkins CICD pipeline triggers a build on the slave node (Slave-node-1) due to a push to the main branch of your GitHub repository, the repository’s content will be cloned into the /root/workspace folder of your Jenkins slave EC2 instance. To facilitate the execution of your project, especially if it requires Node.js, you may need to install Node Version Manager (NVM) and Node.js. Here’s how to manage this setup and verify that your project has been correctly cloned and set up.</p><h3>Installing NVM and Node.js</h3><ul><li>Install NVM:On your slave EC2 instance, install NVM by executing the following command:</li></ul><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash</pre><ul><li>After installation, you might need to close and reopen your terminal to start using NVM. This step ensures that the NVM commands are loaded into your shell session.</li><li>Install Node.js: Install the latest version of Node.js using NVM by running:</li></ul><pre>nvm install node</pre><ul><li>The command node is an alias for the latest version, ensuring you have the most current Node.js features and security updates.</li><li>Install NPM: Node.js comes with NPM (Node Package Manager), but if required, you can update NPM to its latest version with:</li></ul><pre>sudo apt install npm</pre><h3>Preparing and Running Your Project</h3><p>Assuming your GitHub repository includes a project utilizing Vite/React for the frontend, follow these steps to configure and run your application:</p><ul><li>Make sure to add port 3000 in your Jenkins slave EC2 instance’s security group.</li></ul><h3>NOTE: (For a React application, you can use package.json to modify the host and port for the application. It should be something like this: )</h3><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;HOST=0.0.0.0 PORT=3000 react-scripts start&quot;<br>}</pre><ul><li>Configure Vite for Development: Ensure your vite.config.js includes server configuration to listen on all network interfaces (0.0.0.0) and on a specified port (e.g., 3000). This configuration is crucial for accessing the application from outside the EC2 instance. Example vite.config.js setup:</li></ul><pre>import { defineConfig } from &#39;vite&#39;; <br>import react from &#39;@vitejs/plugin-react&#39;; <br>export default defineConfig({ <br>    server: { <br>        host: &#39;0.0.0.0&#39;, <br>        port: 3000 // Specify your desired port here.       },<br>    plugins: [react()],<br>});</pre><ul><li>Install Project Dependencies: Change directory to your project’s frontend folder in the Jenkins Slave EC2 instance(e.g., /path/from/root/to/frontend) and run the below command to fetch and install necessary dependencies.</li></ul><pre>npm install</pre><ul><li>Verify Installation: Check if the node_modules directory is successfully created within your frontend folder, indicating that dependencies have been installed correctly.</li><li>Run Your Application: Start your application by executing this command in your terminal.</li></ul><pre>npm run dev</pre><ul><li>This command will launch your application in development mode, making it accessible via the Jenkins Slave EC2 instance’s public DNS or IP address followed by the specified port (e.g., http://&lt;EC2-Public-IPv4-DNS&gt;:3000).</li></ul><p>By following similar steps you can run your backend too. Once these steps are done, you’ve ensured that your project is correctly cloned and set up on the Jenkins Slave node. Additionally, you’ve prepared your development environment to run a full-stack application using Node.js and Vite, making your project accessible for testing and further development.</p><h3>Configuring Docker for Deployment</h3><p>Integrating Docker into your development and deployment workflow offers numerous benefits, including consistent environments, scalability, and isolation for your applications. By containerizing your frontend/backend, you ensure that it can be deployed consistently across any environment. Here’s how to set up Docker for your frontend application.</p><h3>Installing Docker</h3><ul><li>Install Docker: Open your terminal on the Jenkins Slave EC2 Instance (or whichever instance you intend to deploy your application) and execute the following command to install Docker:</li></ul><pre>sudo apt install docker.io</pre><ul><li>Ensure Docker is installed and running by checking its status or version with</li></ul><pre>sudo systemctl status docker or docker --version.</pre><h3>Preparing the Dockerfile</h3><p>If you don’t already have a Dockerfile in your repository’s frontend/backend folder, follow these steps to create one:</p><p>***NOTE: Ensure that you are adding this Dockerfile to your frontend/backend repos***</p><p>Go to your Jenkins Slave EC2 instance.(Below is an Example for creating DockerFile for the frontend)</p><ul><li>Navigate to Your Frontend Directory: Change directory to your frontend folder where you want to create the Dockerfile. Run this command to create and open a new Dockerfile for editing.</li></ul><pre>sudo vim Dockerfile</pre><p>Writing the Dockerfile:</p><ul><li>Press i on your keyboard to enter insert mode in Vim.</li><li>Define the base image with the Node.js version you’re using, for example, FROM node:21.6.2-alpine.</li><li>Set the working directory inside the Docker container to match the path of your frontend directory using WORKDIR /path/to/frontend/directory.</li><li>Copy your project files into the Docker image with COPY . .</li><li>Install project dependencies using RUN npm install.</li><li>Expose the port your application runs on, which is 3000, with EXPOSE 3000.</li><li>Define the command to run your application using CMD [“npm”,”run”,”dev”].</li><li>Example Dockerfile:</li></ul><pre>FROM node:21.6.2-alpine <br>WORKDIR /path/to/frontend/directory<br>COPY . . <br>RUN npm install <br>EXPOSE 3000 <br>CMD [&quot;npm&quot;,&quot;run&quot;,&quot;dev&quot;]</pre><p>Updating Github Repo Structure: Make sure to Include this Dockerfile inside the frontend folder in your repo.</p><h3>Building and Running the Docker Container</h3><h4>***NOTE : If you are not the root user. Please add sudo before the below docker commands, when running them in your Jenkins Slave EC2 instance***</h4><ul><li>Build Your Docker Image: After saving your Dockerfile, make sure you are inside your frontend/backend folder and build your Docker image in your Jenkins Slave instance by running the below command in the terminal:</li></ul><pre>docker build . -t your-desired-image-name</pre><ul><li>This command creates a Docker image with the name you mentioned in the place of your-desired-image-name, based on the instructions in your Dockerfile.</li><li>Run Your Docker Container: To run your Docker container, use:</li></ul><pre>docker run -d --name your-desired-container-name -p 3000:3000 your-image-name</pre><ul><li>Replace your-desired-container-name with a name for your container. This command runs the container in detached mode, maps port 3000 inside the container to port 3000 on your host, and uses the image named your-image-name.</li></ul><h3>Verifying Deployment</h3><ul><li>After your container is up and running, using the public IP address of your Jenkins Slaves EC2 instance, visit http://&lt;EC2-Public-IPv4-DNS&gt;:3000 in your web browser. You should now see your application running, served directly from the Docker container instead of your git clone. This verifies that the Docker containerization and deployment process is working correctly.</li></ul><p>By following these steps, you’ve successfully integrated Docker into your project’s deployment process, allowing for consistent and scalable deployments. In the next steps, you’ll learn how to automate this process using Jenkins to build and deploy your Docker container upon code changes.</p><h3>Continuous Deployment using Docker and Jenkins</h3><p>To achieve Continuous Deployment (CD) using Docker and Jenkins, you will configure your Jenkins job to automatically build when commits are pushed to your main branch in GitHub, stop and remove an existing Docker container, and then run a new one with the latest code from your repository. This process ensures that your application is always up-to-date with the latest changes. Follow these steps to configure the CD process in your Jenkins job:</p><h3>Configuring Build Actions for Docker Deployment</h3><ul><li>Access Your Job Configuration: Go back to the Jenkins Controller instance’s Jenkins dashboard and open the job you’ve created for your CICD pipeline. Click “Configure” to modify the job settings.</li><li>Add Build Step for Container Management: Scroll down to the “Build Steps” section. Click “Add build step” and select “Execute shell”. In the command box that appears, enter the following script to check if a Docker container with your-container-name exists. If it does, the script stops and removes the container to prepare for deploying the latest version:</li></ul><pre># Check if the container exists <br>if docker ps -a | grep -q &quot;your-container-name-here&quot;; then <br>    # Stop the container <br>    docker stop your-container-name-here <br>    <br>    # Remove the container <br>    docker rm your-container-name-here <br>fi</pre><p>Replace “your-container-name-here” with the actual name of your Docker container in quotes.</p><ul><li>Add Build Step for Image Removal: Click “Add build step” again and choose “Execute shell”. Enter the following commands to remove the existing Docker image named your-image-name to ensure that you can rebuild the image from the latest code:</li></ul><pre># Remove the frontend image  <br>docker rmi your-desired-image-name</pre><p>***NOTE : Make sure to have a docker image (with the same name as “your-desired-image-name”) in your Jenkins Slave instance, before trying to execute these shell commands as part of the automated process. Because, I had issues when there was no image in the EC2 instance, even though i tried to remove it conditionally( i.e., if the image exists)***</p><ul><li>Add Build Step for Building and Running the Container: Add another “Execute shell” build step. This time, include the commands to build a new Docker image from your Dockerfile in the new git clone in the Jenkins Slave Instance and run a new container from this image:</li></ul><pre>docker build -f /path/from/root/to/frontend/Dockerfile -t your-image-name-here /path/from/root/to/frontend <br><br>docker run -d --name your-container-name-here -p 3000:3000 your-image-name-here</pre><ul><li>Replace /path/from/root/to/frontend/Dockerfile with the actual path to your Dockerfile, your-image-name-here with the name you wish to give your Docker image (it can be any name you prefer), and your-container-name-here with the name you want for your Docker container.</li><li>Save Your Configuration:After adding these build steps, click “Save” to apply the changes to your job.</li></ul><h3>Verifying Continuous Deployment</h3><p>Now, whenever you push changes to your repository’s main branch, Jenkins will trigger this job. The job will build a new Docker image with the latest code and deploy it by running a new container, ensuring your application is always up-to-date. Consequently, your application remains updated without the necessity to manually intervene or access the EC2 instances. Your updated application can always be easily accessed at http://&lt;Jenkins_Slave-Ipv4-DNS&gt;:3000.</p><p>This setup forms the core of a Continuous Deployment pipeline using Jenkins and Docker, automating the deployment process and significantly reducing the manual effort required to update your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8948e3f3e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a CI/CD Pipeline using Jenkins - Part1]]></title>
            <link>https://medium.com/@swetha.voora01/creating-a-ci-cd-pipeline-using-jenkins-amazon-ec2-github-and-docker-part-1-72e0a9c30b37?source=rss-6fe701a1f764------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e0a9c30b37</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Swetha Voora]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 02:07:15 GMT</pubDate>
            <atom:updated>2024-02-29T03:46:07.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a CI/CD Pipeline using Jenkins, Amazon EC2, GitHub and Docker — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DObZtE6U2MzghAMAAAgrLg.png" /><figcaption>CI/CD Pipeline</figcaption></figure><h3>Creating and Connecting to EC2 Instance via SSH/EC2 Instance Connect</h3><p>In this section, I’ll guide you through the process of creating and connecting to an Amazon EC2 instance, which is a crucial step in setting up a CICD pipeline with Jenkins, Github, Docker, and AWS EC2. This process involves two major steps: creating the instances and establishing a connection to manage them.</p><h3>Creating Instances</h3><ol><li>Navigate to AWS EC2 Service: Start by logging into your AWS Management Console and accessing the EC2 service dashboard.</li><li>Launch an Instance: Click on the “Launch Instance” button to start the creation process.</li><li>Select the Amazon Machine Image (AMI): Choose an AMI that suits your project requirements. For this guide, we’ll use Ubuntu.</li><li>Create a Key Pair: A key pair is essential for securely connecting to your instance. Create a new key pair, give it a name, and ensure you select RSA as the “key pair type” and .pem as the “private key file format.” Download and save this key pair.</li><li>Configure a Security Group: Security groups act as virtual firewalls. Create one for your instance and configure it to allow SSH (port 22), HTTPS (port 443), and HTTP (port 80) traffic from the internet.</li><li>Instance Specifications: For demonstration purposes, select the default or free tier eligible options for instance type, storage, and other configurations.</li><li>Launch the Instance: Finalize the creation by clicking “Launch Instance.” This instance will serve as our Jenkins Controller.</li><li>Create Another Instance: Repeat the steps to create a second instance, which will act as a Jenkins Slave node for deploying your application.</li></ol><h3>Connecting to Instances</h3><h3>a. SSH Connection</h3><p>To connect to the EC2 instance using SSH key pair:</p><p>Locate Your Key Pair: Find the .pem file you downloaded during the instance creation process.</p><p>Modify Permissions: Before connecting, go to the folder, where the .pem file was saved. Then, change the permissions of the .pem file to read-only using the below command in your terminal.</p><pre>chmod 400 &lt;filename.pem&gt;</pre><p>Establish SSH Connection: Use the SSH command to connect to your instance. Refer to the AWS documentation for AMI-specific default usernames: <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/managing-users.html">AWS EC2 User Guide</a>.</p><pre>ssh -i &lt;path/to/downloaded/.pem/file&gt; instance-user-name@&lt;ec2-public-IPv4-DNS&gt;</pre><h3>b. EC2 Instance Connect</h3><p>For a more straightforward connection:</p><ol><li>Select Your Instance: In the EC2 dashboard, choose the instance you wish to connect to.</li><li>Initiate Connection: Click on the “Connect” button located at the top right of the dashboard.</li><li>Choose Connection Method: You’ll be directed to a page with various connection options. Select the “EC2 Instance Connect” tab and then click “Connect.”</li></ol><p>The above steps walk you through the initial steps of setting up your AWS EC2 instances for a Jenkins CICD pipeline, ensuring you have a solid foundation for continuous integration and deployment tasks.</p><h3>Installation of Java and Jenkins on the Jenkins Controller</h3><p>After setting up your EC2 instances, the next step in creating a robust CICD pipeline is installing the necessary tools on the First EC2 Instance. This guide focuses on installing Java and Jenkins, essential components for running Jenkins and executing your build jobs.</p><p>***NOTE : We will consider the first EC2 Instance as our Jenkins Controller, and the second EC2 instance as our Jenkins Slave.***</p><ul><li>Update Your Package Lists: Once you are connected to your Jenkins Controller ec2-instance, ensure your package lists are up-to-date to avoid any compatibility issues during installation.</li></ul><pre>sudo apt-get update</pre><ul><li>Install Java Development Kit: Jenkins requires Java to run. Install OpenJDK 11 using the following command:</li></ul><pre>sudo apt-get install openjdk-11-jdk</pre><ul><li>Add Jenkins Repository Key: Before installing Jenkins, add its repository key to your system. This ensures authenticity and integrity of the Jenkins package.</li></ul><pre>sudo curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null</pre><ul><li>Add Jenkins Repository: With the key added, append the Jenkins repository to your system’s package source list.</li></ul><pre>sudo echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list &gt; /dev/null</pre><ul><li>Install Jenkins: Update your package list to reflect the new repository addition and install Jenkins.</li></ul><pre>sudo apt-get update <br>    sudo apt-get install jenkins</pre><ul><li>Start Jenkins Service: Once Jenkins is installed, start its service.</li></ul><pre>sudo systemctl start jenkins</pre><ul><li>Check Jenkins Status: Verify that Jenkins is running as expected.</li></ul><pre>sudo systemctl status jenkins</pre><ul><li>Enable Jenkins to Start at Boot: Ensure Jenkins starts automatically upon system boot.</li></ul><pre>sudo systemctl enable jenkins</pre><ul><li>Access Jenkins Setup Page: Navigate to your Jenkins setup page using the Jenkins Controller EC2 instance’s IPv4 DNS address on port 8080.</li></ul><pre>http://&lt;ec2-Ipv4-DNS&gt;:8080</pre><ul><li>Unlock Jenkins: Jenkins installation comes with a security measure requiring an initial admin password. Retrieve this password from the specified path.</li></ul><pre>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><ul><li>Proceed with Jenkins Setup: With the initial admin password, unlock Jenkins on the setup page, install suggested plugins, and create an admin user to start using Jenkins.</li></ul><p>This sequence of steps ensures that Java and Jenkins are correctly installed and configured on your Jenkins Controller, setting the stage for further CICD pipeline development.</p><h3>Troubleshooting: Accessing the Jenkins Interface</h3><p>If you’ve followed the installation steps for Jenkins on your Jenkins Controller EC2 instance but are unable to access the Jenkins interface via your web browser, the issue is likely related to network access configurations. Jenkins runs on port 8080 by default, and this port needs to be explicitly allowed through your instance’s security group to enable access from your local machine or the internet. Here’s how you can adjust your AWS EC2 instance’s security settings to resolve this:</p><ol><li>Navigate to AWS EC2 Dashboard: Log in to your AWS Management Console and go to the EC2 service section.</li><li>Select Your Instance: Identify and click on the instance running Jenkins to view its details.</li><li>Access the Security Tab: Within the instance detail view, locate and click on the “Security” tab to view security group settings.</li><li>Edit Security Group Rules: Click on the security group name to navigate to its configuration. You will be redirected to a page where you can view and edit the security group’s inbound and outbound rules.</li><li>Add a New Inbound Rule: To modify the inbound rules, look for the option to “Edit inbound rules” and click on it.</li><li>Configure the New Rule:</li></ol><pre>Type: Select &quot;Custom TCP&quot; from the dropdown menu.<br><br>Protocol: Ensure the protocol is set to TCP.<br><br>Port Range: Enter 8080 to specify the port used by Jenkins.<br><br>Source: Choose &quot;Custom&quot; and enter 0.0.0.0/0 to allow access from any IP address. <br><br>For a more secure setup, you might want to restrict access to specific IP addresses or ranges.</pre><ul><li>Save the Rule: After configuring the new rule, save your changes to apply them.</li></ul><p>By following these steps, you open port 8080 on your EC2 instance, allowing traffic to reach Jenkins. After adjusting these settings, try accessing the Jenkins interface again by navigating to http://&lt;ec2-Ipv4-DNS&gt;:8080 in your web browser. This should resolve the access issue, granting you the ability to proceed with Jenkins setup and configuration for your CICD pipeline.</p><h3>Integrating GitHub with Jenkins</h3><p>Integrating GitHub with your Jenkins CICD pipeline is a crucial step for automating your build and deployment processes. This integration allows Jenkins to react to code changes in your repository, triggering builds, tests, and deployments automatically. Follow these steps to integrate GitHub with Jenkins:</p><h3>Generating a GitHub Personal Access Token</h3><ol><li>Access GitHub Settings: Log into your GitHub account(This is the account, which owns the repository), click on your profile picture at the top right, and select “Settings” from the dropdown menu.</li><li>Navigate to Developer Settings: Scroll down the settings sidebar until you find “Developer settings” at the bottom. Click on it.</li><li>Personal Access Tokens: Within the developer settings, select “Personal Access Tokens — Tokens (classic)” from the menu.</li><li>Generate New Token: Click on the “Generate new token” button. You’ll be prompted to provide a token description/note and select the scopes or permissions you’d like the token to have. Ensure you choose the scopes that match the requirements for your Jenkins integration. I recommend repo-public_repo scope(if your repo is public), repo scope(if your repo is private).</li><li>Copy and Save Your Token: Click on Generate token. Once the token is generated, make sure to copy and save it securely. This token will act as a password, and you won’t be able to see it again after leaving the page.</li></ol><h3>Configuring GitHub in Jenkins</h3><ol><li>Open Jenkins Interface: Navigate to your Jenkins dashboard by accessing http://&lt;ec2-Ipv4-DNS&gt;:8080 in your web browser. Here, the address corresponds to the Jenkins Controller EC2 instance’s Ipv4 address.</li><li>Access System Configuration: Click on “Manage Jenkins” from the main menu, then click on “Configure System” or “System” depending on your Jenkins version.</li><li>Scroll to GitHub Section: In the system configuration page, scroll down until you find the “GitHub” section or “GitHub Servers” if you are configuring it for the first time.</li><li>Add GitHub Server: The API URL should already be populated with <a href="https://api.github.com./">https://api.github.com.</a> Assign a name to your GitHub server configuration, such as “GitHub”.</li><li>Configure Credentials: Click on the “Add” button next to the credentials dropdown and Select “Jenkins”. A dialog will appear. For the kind of credentials, select “Secret text”. In the “Secret” field, paste the personal access token you generated earlier. Give it an ID for easy identification, such as “github-personal-access-token”, and optionally provide a description. Click the “Add” button to save your credentials.</li><li>Select Your GitHub Credentials: Back in the GitHub server configuration, click on the Credentials dropdown and select the credential you just added by its ID.</li><li>Test the Connection: Click on the “Test connection” button to ensure Jenkins can communicate with GitHub using the provided credentials. This step verifies that Jenkins is correctly configured to interact with your GitHub repositories.</li><li>Disable Manage Hooks: If present, uncheck the “Manage hooks” option to manually manage webhooks in GitHub for triggering builds in Jenkins. This is recommended if you prefer to have control over webhook configurations.</li><li>Go to Dashboard and click “Manage Jenkins”, then click “Security” and Scroll down to the bottom and select “No Verification” option for the Git Host Key Verification Configuration section’s “Host key verification strategy” field.</li></ol><p>By completing these steps, you’ve successfully integrated GitHub with Jenkins, allowing for a seamless connection between your source code repository and your CI/CD pipeline. This integration is key to automating the process of building, testing, and deploying your application based on changes made to the repository.</p><h3>Creating a Jenkins Job to Initiate the CICD Process</h3><p>Creating a Jenkins job is the cornerstone of automating your Continuous Integration and Continuous Deployment (CICD) process. This job will listen for changes in your GitHub repository and trigger builds accordingly. Here’s how to set up a Jenkins job for your CICD pipeline:</p><h3>Setting Up a New Jenkins Job</h3><ol><li>Access Jenkins Homepage: Navigate to your Jenkins interface by visiting http://&lt;ec2-Ipv4-DNS&gt;:8080.</li><li>Create a New Job: Click on “New Item” or “Create a job” if you haven’t created any jobs yet.</li><li>Configure Job: Assign a name to your job and select “Freestyle project” as the type. Click “OK” to proceed to the job configuration.</li></ol><h3>Configuring Job Details</h3><h3>General Section</h3><ul><li>Provide a brief description of the job’s purpose or leave it blank.</li><li>Check the “GitHub project” box and enter the HTTP URL of your GitHub repository.</li></ul><h3>Source Code Management (SCM) Section</h3><ul><li>Choose “Git” as the SCM.</li><li>Provide the SSH URL of your GitHub repository.</li><li>Under “Credentials”, click on “Add” &gt; “Jenkins” to add a new credential. Choose “SSH username with private key”. Enter a meaningful ID.</li><li>Enter the username associated with your GitHub account where you created the personal access token.</li><li>Now go to your Jenkins controller instance’s terminal, generate a new SSH key pair by running :</li></ul><pre>ssh-keygen</pre><ul><li>Use the below command to display your private key, and copy it.</li></ul><pre>sudo cat path/to/id_rsa</pre><ul><li>Now, come back to the Jenkins credential modal, select “Private Key” &gt; “Enter directly” and paste your private key and click Add.</li><li>Back in credentials dropdown, select the ID of the Newly created credential.</li><li>Specify the “Branches to build” as the */main branch or any specific branch you intend to build from.</li><li>Now, Obtain your public key from your terminal, with the below command and copy it.</li></ul><pre>sudo cat path/to/id_rsa.pub</pre><h3>Integrating with GitHub</h3><ul><li>Go to your GitHub account’s settings, select the SSH and GPG Keys option from the Left hand menu.</li><li>Click on New SSH Key, Give it name(Example : Jenkins-Controller-Public-Key) , leave the Key type default (Authentication Key) and paste the copied public key here with no trailing/leading spaces.</li><li>Then, Go to your GitHub repository’s settings and select “Webhooks” from the left menu.</li><li>Click “Add webhook” and provide the payload URL as</li></ul><pre>http://&lt;ec2-Public-Ipv4-DNS&gt;:8080/github-webhook/</pre><ul><li>Set the content type to application/json.</li><li>Choose “Just the push event” for which events would trigger the webhook.</li><li>Save the webhook to integrate GitHub with your Jenkins job.</li><li>You should be able to see the recent deliveries tab next to webhooks tab, where you can check if the webhook URL is accessible from your github repo.</li></ul><h3>Build Triggers Section</h3><ul><li>Enable “GitHub hook trigger for GITScm polling” to allow commits to the main branch of your repository to automatically trigger builds.</li></ul><p>Save the Job Configuration. By following these steps, you’ve successfully created a Jenkins job configured to trigger builds based on changes to your GitHub repository. This setup is pivotal for implementing a CICD pipeline, allowing for automated testing and deployment processes. Further configurations, particularly for integrating Docker for deployment, will enhance this pipeline, enabling a fully automated flow from code commit to deployment.</p><p>Now, If you commit anything you will see that a build is triggered in the built-in node(Jenkins-Controller)</p><p>You can find <a href="https://medium.com/@swetha.voora01/creating-a-ci-cd-pipeline-using-jenkins-amazon-ec2-github-and-docker-part-2-2c8948e3f3e5">Part 2</a> here, explore the next steps to elevate your CI/CD pipeline to new heights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e0a9c30b37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>