<?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 Vamsidhar Venkataraman on Medium]]></title>
        <description><![CDATA[Stories by Vamsidhar Venkataraman on Medium]]></description>
        <link>https://medium.com/@vamsidhar.venkataraman?source=rss-87a5f2e5798d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NqsIOpk2XHZI4MXX</url>
            <title>Stories by Vamsidhar Venkataraman on Medium</title>
            <link>https://medium.com/@vamsidhar.venkataraman?source=rss-87a5f2e5798d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:52:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vamsidhar.venkataraman/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[Getting Started with RAG: LangChain, FAISS, StreamLit, and Ollama for Local LLMs]]></title>
            <link>https://medium.com/@vamsidhar.venkataraman/getting-started-with-rag-langchain-faiss-streamlit-and-ollama-for-local-llms-bf621b3a9202?source=rss-87a5f2e5798d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf621b3a9202</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Vamsidhar Venkataraman]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 10:54:49 GMT</pubDate>
            <atom:updated>2025-01-11T10:54:49.737Z</atom:updated>
            <content:encoded><![CDATA[<p>This article assumes a basic understanding of Retrieval-Augmented Generation (RAG). Here, we focus on the tech stack and the code involved in implementing RAG. Let’s dive into the details.</p><h3>What is Ollama ?</h3><p>Ollama is a cutting-edge platform designed to run open-source large language models locally on your machine. It simplifies the process by bundling model weights, configuration, and data into a single package defined by a Model file. This eliminates the need for intricate setup and configuration details, including leveraging your GPU for better performance.</p><p>To get started with setting up the Ollama environment, check out the repository:</p><p><a href="https://github.com/ollama/ollama">GitHub — ollama/ollama</a>:</p><p>Get up and running with Llama 3.3, Phi 4, Gemma 2, and other large language models.</p><h3>Model Used</h3><p>In this project, we have used the <strong>Llama 3.1 8B parameter model</strong> due to its relatively small size (4.7GB). It strikes a balance between performance and resource requirements, making it ideal for local deployment.</p><h3>Vector Embeddings</h3><p>For the vector embeddings, I utilized the <strong>BERT embedding model</strong>. Among the numerous BERT-based models available, I chose the popular ‘all-MiniLM-L12-v2’ model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNldBGssH7L3R-EGThhPag.png" /><figcaption>Different pre-trained embedding models available in Sentence Transformers</figcaption></figure><p>If you’re interested in exploring other pre-trained models, refer to the documentation below:</p><p><a href="https://sbert.net/">SentenceTransformers Documentation</a></p><h3>Vector Database</h3><p><strong>FAISS</strong> (Facebook AI Similarity Search) is an open-source library developed by Meta AI (formerly Facebook AI) for efficient similarity search and clustering of dense vectors. It’s widely used in machine learning and information retrieval applications due to its:</p><ul><li><strong>Speed</strong></li><li><strong>Scalability</strong></li><li><strong>Flexibility</strong></li></ul><p>FAISS allows you to handle large-scale vector data with ease, making it an ideal choice for embedding-based search tasks.</p><h3>Tech Stack Summary</h3><p>Here’s the technology stack used for this RAG implementation:</p><ol><li><strong>LLM</strong>: Llama 3.1 (8B parameters) powered by Ollama for local deployment.</li><li><strong>Embedding Model</strong>: BERT-based ‘all-MiniLM-L12-v2’ for vector embeddings.</li><li><strong>Vector Database</strong>: FAISS for fast and efficient similarity search.</li><li><strong>Integration Framework</strong>: LangChain to build and manage the RAG pipeline.</li><li><strong>Frontend</strong>: StreamLit for an interactive user interface.</li></ol><p>This combination ensures a robust, efficient, and locally deployable RAG system.</p><h3>Code :</h3><pre>import streamlit as st<br>import os<br>from langchain.chains import LLMChain<br>from langchain_community.document_loaders import PyPDFDirectoryLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain.chains import create_retrieval_chain<br>from langchain_community.vectorstores import FAISS<br>from langchain_ollama import OllamaLLM<br>from sentence_transformers import SentenceTransformer<br>from langchain.embeddings.base import Embeddings<br>import numpy as np<br><br>llm = OllamaLLM(base_url=&quot;http://localhost:11434&quot;, model=&quot;llama3.1&quot;)</pre><p>This initializes the key libraries and sets up the Llama model using the OllamaLLM module to interact with local LLMs. The base URL specifies the running Ollama server, and the model being used is llama3.1.</p><pre>class CustomEmbeddings(Embeddings):<br>    def __init__(self, model):<br>        self.model = model<br><br>    def embed_documents(self, texts):<br>        embeddings = self.model.encode(texts)<br>        return embeddings.tolist()<br><br>    def embed_query(self, text):<br>        embedding = self.model.encode([text])[0]<br>        return embedding.tolist()<br><br>    def __call__(self, text):<br>        if isinstance(text, str):<br>            return self.embed_query(text)<br>        elif isinstance(text, list):<br>            return self.embed_documents(text)<br>        else:<br>            raise ValueError(&quot;Input must be a string or list of strings&quot;)</pre><p>This class wraps the embedding model (here, SentenceTransformer) to embed documents and queries. It supports both single text inputs and lists of texts and ensures flexibility in generating vector representations.</p><pre>if &quot;embeddings_model&quot; not in st.session_state:<br>    model = SentenceTransformer(&#39;all-MiniLM-L12-v2&#39;)<br>    st.session_state.embeddings_model = CustomEmbeddings(model)<br><br>if &quot;vectors&quot; not in st.session_state:<br>    st.session_state.vectors = None<br><br>if &quot;loader&quot; not in st.session_state:<br>    st.session_state.loader = None<br><br>if &quot;docs&quot; not in st.session_state:<br>    st.session_state.docs = None<br><br>if &quot;text_splitter&quot; not in st.session_state:<br>    st.session_state.text_splitter = None<br><br>if &quot;final_documents&quot; not in st.session_state:<br>    st.session_state.final_documents = None<br><br>if &quot;chat_history&quot; not in st.session_state:<br>    st.session_state.chat_history = []</pre><p>This initializes various session state variables required for the application, including embeddings, vectors, document loaders, text splitters, and chat history. The use of st.session_state ensures persistence across user interactions.</p><pre>def vector_embedding(uploaded_file=None):<br>    if uploaded_file:<br>        with open(os.path.join(&quot;pdfs&quot;, uploaded_file.name), &quot;wb&quot;) as f:<br>            f.write(uploaded_file.getbuffer())<br>        st.session_state.loader = PyPDFDirectoryLoader(&quot;pdfs&quot;)<br>    else:<br>        st.session_state.loader = PyPDFDirectoryLoader(&quot;pdfs&quot;)<br>    <br>    st.session_state.docs = st.session_state.loader.load()<br>    st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=50)<br>    st.session_state.final_documents = st.session_state.text_splitter.split_documents(st.session_state.docs[:30])<br>    <br>    st.session_state.vectors = FAISS.from_documents(<br>        st.session_state.final_documents,<br>        st.session_state.embeddings_model<br>    )</pre><p>This function handles PDF uploads and embedding. It processes the uploaded PDFs, splits the text into chunks, and embeds the resulting chunks into a FAISS vector store for similarity search.</p><pre>def summarize_document():<br>    if &quot;final_documents&quot; not in st.session_state or not st.session_state.final_documents:<br>        return &quot;Please upload a document first.&quot;<br>    <br>    try:<br>        full_text = &quot; &quot;.join([doc.page_content for doc in st.session_state.final_documents])<br>        summary_prompt = ChatPromptTemplate.from_template(<br>            &quot;&quot;&quot;<br>            Please provide a concise summary of the following document:<br>            {text}<br>            <br>            Summary:<br>            &quot;&quot;&quot;<br>        )<br>        summary_chain = LLMChain(llm=llm, prompt=summary_prompt)<br>        summary = summary_chain.run(text=full_text[:4000])<br>        return summary<br>    except Exception as e:<br>        return f&quot;Error: {str(e)}&quot;</pre><p>This function generates a summary of the uploaded document by concatenating the text, creating a summary prompt, and passing it to the LLM using a LangChain LLMChain.</p><pre>st.title(&quot;Chat with PDF&quot;)<br><br>st.sidebar.header(&quot;Upload PDF&quot;)<br>uploaded_file = st.sidebar.file_uploader(&quot;Choose a PDF&quot;, type=[&quot;pdf&quot;])<br><br>if uploaded_file and st.sidebar.button(&quot;Upload &amp; Embed&quot;):<br>    vector_embedding(uploaded_file)<br>    st.sidebar.success(&quot;Document uploaded and embedded!&quot;)<br><br>if st.sidebar.button(&quot;Summarize Document&quot;):<br>    with st.spinner(&quot;Generating summary...&quot;):<br>        summary = summarize_document()<br>        st.write(&quot;### Document Summary&quot;)<br>        st.write(summary)<br><br>prompt1 = st.text_input(&quot;Ask a question from the document&quot;)<br><br>if st.button(&quot;Ask&quot;):<br>    if prompt1:<br>        if &quot;vectors&quot; not in st.session_state or not st.session_state.vectors:<br>            vector_embedding()<br>        prompt = ChatPromptTemplate.from_template(<br>            &quot;&quot;&quot;<br>            Answer the questions based on the provided context only.<br>            Please provide the most accurate response based on the question:<br>            &lt;context&gt;<br>            {context}<br>            &lt;/context&gt;<br>            Questions: {input}<br>            &quot;&quot;&quot;<br>        )<br>        document_chain = create_stuff_documents_chain(llm, prompt)<br>        retriever = st.session_state.vectors.as_retriever()<br>        retrieval_chain = create_retrieval_chain(retriever, document_chain)<br>        response = retrieval_chain.invoke({&#39;input&#39;: prompt1})<br>        answer = response[&#39;answer&#39;]<br>        st.session_state.chat_history.append({&quot;question&quot;: prompt1, &quot;answer&quot;: answer})<br><br>        st.write(&quot;### Answer&quot;)<br>        st.write(answer)<br><br>        with st.expander(&quot;Chat History&quot;):<br>            for i, chat in enumerate(st.session_state.chat_history):<br>                st.write(f&quot;**Q{i+1}:** {chat[&#39;question&#39;]}&quot;)<br>                st.write(f&quot;**A{i+1}:** {chat[&#39;answer&#39;]}&quot;)<br>                st.write(&quot;-----------------------------------&quot;)</pre><p>This is the main user interface where users can upload PDFs, generate summaries, and ask questions. The application handles embedding, retrieves relevant vectors, and uses the LLM to provide answers while maintaining chat history for better user interaction.</p><h3>Demo :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7BdLK9EUbggNneOkwffPJw.gif" /></figure><p>With the power of Retrieval-Augmented Generation (RAG), LangChain, FAISS, StreamLit, and Ollama, we’ve created an efficient and interactive system to query PDFs using local Large Language Models (LLMs). This article demonstrated how these tools work together to handle document embeddings, vector storage, and retrieval, culminating in a seamless user interface.</p><p>By leveraging custom embeddings and cutting-edge technologies like SentenceTransformers and Ollama, you can achieve a robust solution for managing and interacting with unstructured text data locally — without relying on cloud-based LLMs.</p><p>Feel free to experiment further with different embedding models, larger LLMs, or additional features like multi-document querying or advanced summarization. The possibilities are vast, and this implementation serves as a foundation to build your own intelligent RAG-based applications.</p><p>Code : <a href="https://github.com/vamsid07/LocalRAG">https://github.com/vamsid07/LocalRAG</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf621b3a9202" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>