<?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 Jeel Gandhi on Medium]]></title>
        <description><![CDATA[Stories by Jeel Gandhi on Medium]]></description>
        <link>https://medium.com/@jeel21?source=rss-2d62bdb6ed5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*56dFKLj-SUL_TMKcfI85MA.jpeg</url>
            <title>Stories by Jeel Gandhi on Medium</title>
            <link>https://medium.com/@jeel21?source=rss-2d62bdb6ed5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:01:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeel21/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[Building an Agentic RAG System with LangGraph: A Complete Guide]]></title>
            <link>https://medium.com/@jeel21/building-an-agentic-rag-system-with-langgraph-a-complete-guide-f07ad69861b1?source=rss-2d62bdb6ed5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07ad69861b1</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph-tutorial]]></category>
            <dc:creator><![CDATA[Jeel Gandhi]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 16:14:24 GMT</pubDate>
            <atom:updated>2025-09-18T03:50:16.854Z</atom:updated>
            <content:encoded><![CDATA[<p>LangGraph has been gaining a lot of attention as a framework for building <strong>stateful, multi-step AI workflows</strong>. Curious about its potential, I wanted to get some hands-on experience with it — beginning with constructing an <strong>Agentic RAG system</strong> and how LangGraph simplifies orchestration and structures it better.</p><p><strong>Difference between Basic RAG and Agentic RAG :</strong></p><p><strong>Basic RAG</strong> : A retrieval-augmented generation system where an LLM retrieves relevant information from a database or document store and generates a response in a single-pass workflow.</p><p><strong>Agentic RAG</strong> : An extension of RAG in which the LLM functions as an autonomous agent, dynamically deciding whether additional steps — such as invoking tools or performing further retrieval are necessary before producing a final response.</p><p><strong>What is LangGraph?</strong></p><p><a href="https://langchain-ai.github.io/langgraph/concepts/why-langgraph/">LangGraph</a> is a framework (built on top of <a href="https://python.langchain.com/docs/introduction/?_gl=1*1rvwq87*_gcl_au*OTA0MTMwMTEzLjE3NTc2NTY3MDY.*_ga*NzQ4Njg0MDkwLjE3NDMyMzg1MzU.*_ga_47WX3HKKY2*czE3NTgxMDQ5NDckbzI5JGcwJHQxNzU4MTA0OTQ3JGo2MCRsMCRoMA..">LangChain</a>) for creating stateful, multi-step AI workflows using a graph-based structure.</p><p>Instead of writing “step 1 → step 2 → step 3” in plain Python, you define a graph of nodes (functions, LLMs, tools, etc.) and LangGraph handles:</p><blockquote>-&gt; how state flows between them<br>-&gt; when branches or loops happen<br>-&gt; how to pause/resume executions<br>-&gt; how to run multi-agent systems.</blockquote><p><strong>LangGraph Workflow Components:</strong></p><ol><li><strong>State :</strong> Shared memory that flows through your LangGraph graph, carrying context, inputs, outputs, and memory.</li><li><strong>Node :</strong> A step (function) in the LangGraph workflow that reads state, does some work, and returns updates to state.</li><li><strong>Edges :</strong> Edges in LangGraph are the connections (arrows) that define how the workflow moves from one node to another.<br>→ <strong>Types of Edges</strong> : <strong>Normal</strong> (Straight connection), <strong>Conditional</strong> (Branching, depends on State) and <strong>Loop</strong> (Connect a node back to itself)</li><li><strong>Tools : </strong>Functions your model can call, LangGraph lets you bind and execute them as part of your workflows.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTyJ5_6gnBUPsImv0-YSyw.jpeg" /></figure><p><strong>What we’re building…<br></strong>We will build a workflow here :</p><ol><li>User asks a question.</li><li><strong>Agent Node :</strong> Decides whether to use a tool or answer directly</li><li><strong>Retriever :</strong> Fetches relevant documents from the vector database (FAISS).</li><li><strong>Grade Node :</strong> Evaluates if the retrieved documents are relevant to query. If yes, go to generate otherwise rewrite</li><li><strong>Rewrite Node :</strong> Rephrases the question into a clearer query. Then sends it back to Agent for a fresh decision.</li><li><strong>Generate Node : </strong>Produces the final answer using the LLM with the retrieved (and graded) documents.</li><li>Returns the answer to the user.</li></ol><p><strong>Code Breakdown :<br></strong>Here’s the detailed explanation of each part of the code.</p><p><strong>Step 1 : Document Ingestion &amp; Indexing</strong></p><pre>from dotenv import load_dotenv<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain_community.vectorstores import FAISS<br>from langchain_huggingface.embeddings import HuggingFaceEmbeddings<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>load_dotenv()<br><br>urls=[<br>    &quot;https://langchain-ai.github.io/langgraph/tutorials/introduction/&quot;,<br>    &quot;https://langchain-ai.github.io/langgraph/tutorials/workflows/&quot;,<br>    &quot;https://langchain-ai.github.io/langgraph/how-tos/map-reduce/&quot;<br>]<br><br># Load raw documents from the web using WebBaseLoader<br>docs=[WebBaseLoader(url).load() for url in urls]<br><br># Flatten the nested list of documents<br>doc_list = [item for sublist in docs for item in sublist]<br><br># Split the documents into the smaller chunks<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=1000,<br>    chunk_overlap=100<br>)<br>doc_splits = text_splitter.split_documents(doc_list)<br><br># Create a vector store and generate embeddings of chunks and stores them in <br># FAISS for fast retrieval<br>vectorstore = FAISS.from_documents(<br>    documents=doc_splits,<br>    embedding=HuggingFaceEmbeddings()<br>)<br><br># Turn FAISS into a retriever object<br>retriever = vectorstore.as_retriever()<br>retriever.invoke(&quot;What is langgraph?&quot;)</pre><p><strong>Step 2 : Create a Retriever Tool</strong></p><pre>from langchain.tools.retriever import create_retriever_tool<br><br>retriever_tool=create_retriever_tool(<br>    retriever, # the retriever we built on top of FAISS<br>    name=&quot;retriever_vector_db_blog&quot;,<br>    description=&quot;Search and run information about Langgraph&quot;<br>)<br><br>tools = [retriever_tool]</pre><p><strong>Step 3 : Create an Agent</strong></p><pre>from typing import Annotated, Sequence<br>from typing_extensions import TypedDict<br>from langchain_core.messages import BaseMessage<br>from langgraph.graph.message import add_messages<br>from langchain_openai import ChatOpenAI<br><br># define the state of the graph and keep tracks of the all the messages exchanged<br>class AgentState(TypedDict):<br>     messages: Annotated[Sequence[BaseMessage], add_messages]<br><br># Create an Agent<br>def agent(state):<br>    &quot;&quot;&quot;<br>    Invokes the agent model to generate a response based on the current state. Given<br>    the question, it will decide to retrieve using the retriever tool, or simply end.<br><br>    Args:<br>        state (messages): The current state<br><br>    Returns:<br>        dict: The updated state with the agent response appended to messages<br>    &quot;&quot;&quot;<br>    print(&quot;---CALL AGENT---&quot;)<br>    messages = state[&quot;messages&quot;]<br><br>    # Initialize the LLM<br>    model = ChatOpenAI(<br>        model=&quot;openai/gpt-oss-20b&quot;,<br>        base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>    )<br>    <br>    # Bind the tool with Agent<br>    model = model.bind_tools(tools)<br>    <br>    # Call the model with current conversation history<br>    response = model.invoke(messages)<br>    return {&quot;messages&quot;: [response]}</pre><ul><li><strong>LLM setup</strong> : used <a href="https://python.langchain.com/docs/integrations/chat/openai/"><strong>ChatOpenAI</strong> </a>with gpt-oss-20b (Through <a href="https://openrouter.ai/"><strong>OpenRouter</strong></a>)</li></ul><pre>.env example<br><br>GOOGLE_API_KEY=<br>HUGGINGFACEHUB_API_TOKEN=<br>OPENAI_API_KEY=</pre><p><strong>Step : 4 Create a Grade Node</strong></p><pre>from typing import Annotated, Literal, Sequence<br>from typing_extensions import TypedDict<br><br>from langchain import hub<br>from langchain_core.messages import BaseMessage, HumanMessage<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br><br>from pydantic import BaseModel, Field<br><br># Create a condition<br>def grade_documents(state) -&gt; Literal[&quot;generate&quot;, &quot;rewrite&quot;]:<br>    &quot;&quot;&quot;<br>    Determines whether the retrieved documents are relevant to the question.<br><br>    Args:<br>        state (messages): The current state<br><br>    Returns:<br>        str: A decision for whether the documents are relevant or not<br>    &quot;&quot;&quot;<br><br>    print(&quot;---CHECK RELEVANCE---&quot;)<br>    <br>    # Relevance score in the form of yes or no -- binary score<br>    class grade(BaseModel):<br>        &quot;&quot;&quot;Binary score for relevance check.&quot;&quot;&quot;<br><br>        binary_score: str = Field(description=&quot;Relevance score &#39;yes&#39; or &#39;no&#39;&quot;)<br><br><br>    model = ChatOpenAI(<br>        model=&quot;openai/gpt-oss-20b&quot;,<br>        base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>    )<br>    <br>    # Wraps the model so its output is forced into the grade schema.<br>    llm_with_tool = model.with_structured_output(grade)<br><br>    prompt = PromptTemplate(<br>        template=&quot;&quot;&quot;You are a grader assessing relevance of a retrieved document to a user question. \n <br>        Here is the retrieved document: \n\n {context} \n\n<br>        Here is the user question: {question} \n<br>        If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n<br>        Give a binary score &#39;yes&#39; or &#39;no&#39; score to indicate whether the document is relevant to the question.&quot;&quot;&quot;,<br>        input_variables=[&quot;context&quot;, &quot;question&quot;],<br>    )<br>    <br>    # Prompt -&gt; LLM pipeline<br>    chain = prompt | llm_with_tool<br><br>    messages = state[&quot;messages&quot;]<br>    last_message = messages[-1]<br><br>    question = messages[0].content<br>    docs = last_message.content<br><br>    scored_result = chain.invoke({&quot;question&quot;: question, &quot;context&quot;: docs})<br><br>    score = scored_result.binary_score<br><br>    if score == &quot;yes&quot;:<br>        print(&quot;---DECISION: DOCS RELEVANT---&quot;)<br>        return &quot;generate&quot;<br><br>    else:<br>        print(&quot;---DECISION: DOCS NOT RELEVANT---&quot;)<br>        print(score)<br>        return &quot;rewrite&quot;</pre><p><strong>Step 5 : Create a Generate Node</strong></p><pre>def generate(state):<br>    &quot;&quot;&quot;<br>    Generate answer<br><br>    Args:<br>        state (messages): The current state<br><br>    Returns:<br>         dict: The updated message<br>    &quot;&quot;&quot;<br>    print(&quot;---GENERATE---&quot;)<br>    messages = state[&quot;messages&quot;]<br>    question = messages[0].content<br>    last_message = messages[-1]<br><br>    docs = last_message.content<br>    <br>    # Loads a prebuilt RAG prompt from LangChain Hub (rlm/rag-prompt).<br>    prompt = hub.pull(&quot;rlm/rag-prompt&quot;)<br><br>    model = ChatOpenAI(<br>        model=&quot;openai/gpt-oss-20b&quot;,<br>        base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>    )<br><br>    def format_docs(docs):<br>        return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br>    rag_chain = prompt | model | StrOutputParser()<br><br>    response = rag_chain.invoke({&quot;context&quot;: docs, &quot;question&quot;: question})<br>    return {&quot;messages&quot;: [response]}</pre><pre>You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don&#39;t know the answer, just say that you don&#39;t know. Use three sentences maximum and keep the answer concise.<br>Question: {question} <br>Context: {context} <br>Answer:<br><br>Prompt[rlm/rag-prompt]</pre><p><strong>Step 6 : Create a Rewrite Node</strong></p><pre>def rewrite(state):<br>    &quot;&quot;&quot;<br>    Transform the query to produce a better question.<br><br>    Args:<br>        state (messages): The current state<br><br>    Returns:<br>        dict: The updated state with re-phrased question<br>    &quot;&quot;&quot;<br><br>    print(&quot;---TRANSFORM QUERY---&quot;)<br>    messages = state[&quot;messages&quot;]<br>    question = messages[0].content<br><br>    msg = [<br>        HumanMessage(<br>            content=f&quot;&quot;&quot; \n <br>    Look at the input and try to reason about the underlying semantic intent / meaning. \n <br>    Here is the initial question:<br>    \n ------- \n<br>    {question} <br>    \n ------- \n<br>    Formulate an improved question: &quot;&quot;&quot;,<br>        )<br>    ]<br>    model = ChatOpenAI(<br>        model=&quot;openai/gpt-oss-20b&quot;,<br>        base_url=&quot;https://openrouter.ai/api/v1&quot;,<br>    )<br>    response = model.invoke(msg)<br>    return {&quot;messages&quot;: [response]}</pre><p><strong>Step 7 : Create a Graph</strong></p><pre>from langgraph.graph import START, END, StateGraph<br>from langgraph.prebuilt import ToolNode<br>from langgraph.prebuilt import tools_condition<br><br># Graph<br>builder = StateGraph(AgentState)<br><br># Nodes<br>builder.add_node(&quot;agent&quot;,agent)<br>retrieve = ToolNode([retriever_tool])<br>builder.add_node(&quot;retrieve&quot;,retrieve)<br>builder.add_node(&quot;rewrite&quot;,rewrite)<br>builder.add_node(&quot;generate&quot;,generate)<br><br>#Edges<br>builder.add_edge(START,&quot;agent&quot;)<br>builder.add_conditional_edges(<br>    &quot;agent&quot;,<br>    tools_condition,<br>    {<br>        &quot;tools&quot;: &quot;retrieve&quot;,<br>        END: END,<br>    },<br>)<br>builder.add_conditional_edges(<br>    &quot;retrieve&quot;,<br>    grade_documents,<br>)<br>builder.add_edge(&quot;generate&quot;, END)<br>builder.add_edge(&quot;rewrite&quot;, &quot;agent&quot;)<br><br>#Compile<br>graph = builder.compile()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*LpA_o-OrKlXdKNxfW2JmlQ.png" /><figcaption>Flow Graph</figcaption></figure><p><strong>Final Step : Generate a response</strong></p><pre># Runs an entire RAG pipeline at once<br>inputs = {<br>    &quot;messages&quot;: [<br>        (&quot;user&quot;, &quot;What is Machine Learning?&quot;),<br>    ]<br>}<br><br>result = graph.invoke(inputs)<br>final_answer = result[&quot;messages&quot;][-1].content # Pick the last message<br>print(final_answer)<br><br><br>#OR<br><br><br># Streams each step of the workflow.<br>inputs = {<br>    &quot;messages&quot;: [<br>        (&quot;user&quot;, &quot;What is LangGraph?&quot;),<br>    ]<br>}<br><br>for step in graph.stream(inputs):<br>    print(step)</pre><p><strong>Output :</strong></p><pre>---CALL AGENT---<br>**Machine Learning (ML)** is a field of computer science that gives computers the ability to learn from data and improve their performance on tasks without being explicitly programmed for each step. In other words, instead of writing a set of rules that a computer must follow, we provide it with examples and let it discover patterns and rules on its own.<br><br>---<br><br>### How It Works (in a nutshell)<br><br>1. **Collect data** – Gather examples of the problem you want to solve (images, text, sensor readings, etc.).  <br>2. **Choose a model** – Pick a mathematical function (e.g., a neural network, decision tree, support vector machine) that can map input data to an output.  <br>3. **Train the model** – Feed the data to the model and adjust its internal parameters so that its predictions get closer to the known correct answers.  <br>4. **Validate &amp; test** – Evaluate the trained model on new data it hasn&#39;t seen before to see how well it generalizes.  <br>5. **Deploy** – Put the model into an application where it can make real‑world predictions or decisions.<br><br>---<br><br>### When Does Machine Learning Make Sense?<br><br>- **Big Data:** When you have lots of information that’s too complex or huge for simple rule‑based programming.  <br>- **Patterns are hidden:** When the relationships in the data are subtle, nonlinear, or dynamic.  <br>- **Rapidly changing environments:** When rules or conditions may evolve over time, letting the model adapt through retraining is valuable.  <br><br>---<br><br>### Core Types (Taxonomy)<br><br>| Type | Key Idea | Typical Use |<br>|------|----------|-------------|<br>| **Supervised Learning** | Learn a mapping from input to output using labeled examples. | Image classification, spam detection, house‑price prediction. |<br>| **Unsupervised Learning** | Extract structure from unlabeled data. | Clustering customers, anomaly detection. |<br>| **Semi‑Supervised Learning** | Combine a small set of labeled data with a larger unlabeled set. | Text classification when labels are scarce. |<br>| **Reinforcement Learning** | Learn to choose actions that maximize cumulative reward through trial‑and‑error. | Robotics, game playing, autonomous navigation. |<br>| **Self‑Supervised / Contrastive Learning** | Create auxiliary tasks to exploit unlabeled data (e.g., predicting missing parts of an image). | Pretraining language models, vision transformers. |<br><br>---<br><br>### Common Algorithms<br><br>- **Linear/Logistic Regression** – Simple but powerful for many tabular problems.  <br>- **Decision Trees &amp; Random Forests** – Easy to interpret; good for mixed data types.  <br>- **Support Vector Machines (SVM)** – Effective for high‑dimensional data.  <br>- **K‑Nearest Neighbors (k‑NN)** – Non‑parametric and memory‑intensive.  <br>- **Neural Networks &amp; Deep Learning** – Hierarchical models that learn representations automatically, used in image, speech, and NLP.  <br>- **Gradient Boosting Machines (XGBoost, LightGBM)** – High‑performance tabular models.  <br><br>---<br><br>### Why It Matters<br><br>- **Automation** of tedious or impossible-to‑program tasks.  <br>- **Accurate predictions**** on complex inputs.**  <br>- **Insights** into data (e.g., important features, clusters).  <br>- **Adaptability** – Models can improve over time as more data becomes available.  <br><br>---<br><br>### Typical Workflow Example<br><br>1. *Problem:* Predict next-day stock price.  <br>2. *Data:* Historical prices, volume, news sentiment.  <br>3. *Model:* Recurrent Neural Network or Transformer.  <br>4. *Training:* Feed past sequences, minimize prediction error.  <br>5. *Evaluation:* Use time‑split validation to test future‑looking performance.  <br>6. *Deployment:* Predict price on new data, provide trade signals, monitor drift.<br><br>---<br><br>### Key Takeaway<br><br>**Machine learning is not magic; it’s a systematic and data‑driven approach to building software that can make intelligent decisions or predictions.** Its power comes from the combination of vast amounts of data, sophisticated mathematical models, and efficient computational resources that allow it to uncover patterns humans can’t manually write into rules.</pre><p><strong>Conclusion :</strong></p><p>In this guide, we built an Agentic RAG system with LangGraph — step by step. Unlike basic RAG, which only retrieves once and answers, Agentic RAG makes the LLM behave like an autonomous problem solver: it can retrieve, grade, rewrite, and then generate the final answer.</p><p>With LangGraph, we defined this workflow as a <strong>graph of nodes</strong> (Agent → Retrieve → Grade → Rewrite → Generate), giving us flexibility, debuggability, and the ability to scale into <strong>multi-agent systems</strong> in the future.</p><p><strong>Explore the Code :</strong></p><p>You can find the complete implementation, example notebooks, and resources here: <br><a href="https://github.com/JEELGANDHI21/AgenticAI-Learning/blob/main/LangGraph/AgenticRAG.ipynb">GitHub — Agentic RAG with LangGraph</a></p><blockquote><em>Now it’s your turn to experiment and expand this workflow. Try integrating external APIs, adding domain-specific tools, or swapping FAISS for a managed vector DB. Tinker with prompts, add more graders, or scale it into multi-agent setups then share your findings and improvements.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07ad69861b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>