<?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 Najam Us Saqib on Medium]]></title>
        <description><![CDATA[Stories by Najam Us Saqib on Medium]]></description>
        <link>https://medium.com/@najamussaqib?source=rss-ccc4a099e1a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0QXV6NANnewhh6vz-Auy1Q.jpeg</url>
            <title>Stories by Najam Us Saqib on Medium</title>
            <link>https://medium.com/@najamussaqib?source=rss-ccc4a099e1a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:10:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@najamussaqib/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[Learning RAG with LangChain’s LangGraph: A Beginner’s Journey]]></title>
            <link>https://medium.com/@najamussaqib/learning-rag-with-langchains-langgraph-a-beginner-s-journey-4b9a2a5fbc08?source=rss-ccc4a099e1a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9a2a5fbc08</guid>
            <category><![CDATA[langgraph-tutorial]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Najam Us Saqib]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 13:19:58 GMT</pubDate>
            <atom:updated>2025-02-05T13:19:58.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting started with AI can be overwhelming. This guide simplifies the process by focusing on RAG and LangChain’s LangGraph. We’ll explore how these tools connect and empower you to build AI that learns from your data.</p><p>Let start with some key concept that we need to learn before going deeper in this post.</p><h4>What is retrieval-augmented generation?</h4><p>Retrieval-augmented generation (RAG) is an AI framework for retrieving facts from an external knowledge base to ground large language models (LLMs) on the most accurate, up-to-date information and to give users insight into LLMs’ generative process. <a href="https://research.ibm.com/blog/retrieval-augmented-generation-RAG">(check the complete blog here)</a>.</p><h4>What is LangChain?</h4><p>For developing applications powered by large language models (LLMs), LangChain offers a streamlined experience, much like Laravel and Django do for web development. It simplifies every stage of the LLM application lifecycle. <a href="https://www.langchain.com/">(click here to visit official website)</a>.</p><h4>Lets get started…</h4><p>A Retrieval Augmented Generation (RAG) system typically involves three key stages:</p><blockquote>Parsing<br>Embeddings &amp; Vector Store<br>Retrieval</blockquote><p>Now explore all of these above steps one by one.</p><h4>Parsing:</h4><p>This stage involves extracting text from your source documents. Several Python libraries are available for this, including PyMuPDF, unstructured.io, and LlamaParser. For this post, I used LlamaParser to process the DeepSeek research paper on the R1 model.</p><pre>from llama_parse import LlamaParse<br>parser = LlamaParse(api_key=userdata.get(&#39;LLAMA_CLOUD_API_KEY&#39;), result_type=&quot;markdown&quot;, target_pages=&quot;0,2,4,5,6,7,8,9,10,11,12,13,14,15&quot;)<br><br>async def load_document(document_path):<br>    data = await parser.aload_data(document_path)<br>    return data<br><br>docs = await load_document(&#39;/content/sample_data/DeepSeek_R1.pdf&#39;)</pre><p>LlamaParser’s API allows for granular control over page parsing. You can specify a set of page indices or a series of page ranges (e.g., 0–10, 20–25). The document’s first page corresponds to index 0.</p><h4>Embeddings &amp; Vector Store</h4><p>To create embeddings, the parsed document is divided into smaller chunks. Several chunking strategies exist (I’ll detail these in a future post), including:</p><blockquote>CharacterTextSplitter<br>RecursiveCharacterTextSplitter<br>Semantic Chunking</blockquote><p>For this post, I used semantic chunking, which groups text into semantically related units. Once the document is chunked, each chunk needs to be converted into a vector representation using an embedding model. I used OpenAI’s text-embedding-3-small model for this purpose. These embeddings are then stored in a vector database. Chroma DB is a popular choice, and setting it up is straightforward. You simply provide a collection name, the embedding model, and the directory where the vectors should be stored.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_chroma import Chroma<br><br>langchain_documents = [doc.to_langchain_format() for doc in docs]<br>text_splitter = SemanticChunker(OpenAIEmbeddings(api_key=userdata.get(&#39;OPENAI_API_KEY&#39;)))<br><br>splits = text_splitter.split_documents(documents=langchain_documents)<br><br>embedding_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;, api_key=userdata.get(&#39;OPENAI_API_KEY&#39;))<br><br>vector_store = Chroma(<br>  collection_name=&quot;deepseek_2_collection&quot;,<br>  embedding_function=embedding_model,<br>  persist_directory=&quot;./chroma_langchain_db&quot;,  # Where to save data locally, remove if not necessary<br>)<br><br>vector_store.add_documents(splits)</pre><h4>Retrieval</h4><p>We’ve now reached the exciting part: seeing LangChain, LangGraph, and the LLM in action. With parsing, embeddings, and our vector store set up, we need a way to retrieve relevant information from the database. This is where LangChain’s LangGraph comes in. Before diving into the implementation, let’s briefly overview LangGraph’s core components.<br>LangGraph is built on three fundamental elements:</p><blockquote>State<br>Nodes<br>Edges</blockquote><p>State is the heart of LangGraph. It acts as a dynamic record of the agent’s current status and evolves as the agent interacts with the environment. Think of it as the agent’s memory.</p><p>Nodes are the active components that perform specific tasks within the LangGraph. Each node represents a distinct step in the agent’s workflow, such as retrieving information from the vector store or interacting with the LLM.</p><p>Edges define the connections and flow of information between Nodes. They dictate the sequence of operations. Edges can be simple, directing the flow from one node to the next, or conditional, branching the workflow based on specific criteria or the State.</p><pre>llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;, api_key=userdata.get(&#39;OPENAI_API_KEY&#39;))<br><br>class State(TypedDict): #<br>  question: str<br>  answer: str<br>  context: str<br><br>def retriever(state: State):<br><br>  results = vector_store.as_retriever(search_type=&quot;similarity&quot;, k=2)<br>  similar_chunks = results.invoke(question)<br><br>  context = &quot;\n&quot;.join([chunk.page_content for chunk in similar_chunks])<br>  <br>  return {&quot;context&quot;: context}<br><br><br>def llm_process(state: State):<br><br>  prompt = PromptTemplate.from_template(<br>      &quot;&quot;&quot;<br>        You are a document reader and you need to answer user question based on the context.<br>        Context: {context}<br>        Question:  {question}<br>      &quot;&quot;&quot;<br>  )<br><br>  chain = (prompt | llm | StrOutputParser())<br>  response = chain.invoke({&quot;context&quot;: state[&quot;context&quot;], &quot;question&quot;: state[&quot;question&quot;]})<br>  <br>  return {&quot;answer&quot;: response}<br><br><br>graph_builder = StateGraph(State) #defining builder<br><br># defining nodes<br>graph_builder.add_node(&quot;retriever&quot;, retriever)<br>graph_builder.add_node(&quot;llm_process&quot;, llm_process)<br><br># defining edges, connection between nodes<br>graph_builder.add_edge(START, &quot;retriever&quot;)<br>graph_builder.add_edge(&quot;retriever&quot;, &quot;llm_process&quot;)<br>graph_builder.add_edge(&quot;llm_process&quot;, END)<br><br>graph = graph_builder.compile() # compiling builder<br><br><br>question = &quot;What is the Aha Moment of DeepSeek-R1-Zero?&quot;<br>result = graph.invoke({&quot;question&quot;: question})<br><br>print(result[&quot;answer&quot;])</pre><p>The code above demonstrates how the graph is constructed. We initialise the graph with a State object and add two nodes: retriever and llm_process. Finally, we define the flow of execution by connecting the nodes with edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Y_ik6EAIrt7BE7L52pfnBg.png" /></figure><p># Explanation:<br>The graph execution starts with the user’s question.</p><p># 1. Retriever Node: The retriever_node receives the user’s question and queries the vector database to retrieve the most relevant chunks of information. These chunks are then passed along with the original question to the llm_process node.</p><p># 2. LLM Processing Node: The llm_process node receives the question and the retrieved context. It uses the llm_chain to format a prompt, inserting the question and context into the appropriate placeholders. This formatted prompt is then sent to the LLM.</p><p># 3. LLM and Output Parsing: The LLM processes the prompt and generates a response. Finally, the StrOutputParser() extracts the string output from the LLM’s response, which is then stored in the ‘answer’ attribute of the graph’s state.</p><h4>Answer:</h4><pre>The &quot;aha moment&quot; of DeepSeek-R1-Zero occurs during an intermediate phase of the model&#39;s training, where it learns to allocate more thinking time to a problem by reevaluating its initial approach. This behavior reflects the model&#39;s growing reasoning abilities and exemplifies how reinforcement learning can lead to unexpected and sophisticated outcomes. It highlights the model&#39;s capacity to autonomously develop advanced problem-solving strategies simply by receiving the right incentives, rather than being explicitly taught how to solve problems. This moment serves as a significant revelation for both the model and the researchers, showcasing the potential of reinforcement learning to enhance intelligence and adaptability in artificial systems.</pre><h4>Conclusion:</h4><p>In this post, we’ve explored the key stages of building a RAG system, from parsing and embedding documents to leveraging LangChain and LangGraph for retrieval and LLM interaction. We’ve seen how LangGraph’s State, Nodes, and Edges provide a powerful framework for orchestrating complex LLM workflows. In future posts, I’ll dive deeper into specific implementation details and explore advanced techniques for optimizing RAG performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9a2a5fbc08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>