<?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 Kumar Vaibhav on Medium]]></title>
        <description><![CDATA[Stories by Kumar Vaibhav on Medium]]></description>
        <link>https://medium.com/@kv742000?source=rss-ecf6acba6ea4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_eFF88GxtLXALVEr</url>
            <title>Stories by Kumar Vaibhav on Medium</title>
            <link>https://medium.com/@kv742000?source=rss-ecf6acba6ea4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:25:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kv742000/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[Creating a Python server for Document Q&A using LangChain]]></title>
            <link>https://medium.com/@kv742000/creating-a-python-server-for-document-q-a-using-langchain-31a123b67935?source=rss-ecf6acba6ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a123b67935</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Kumar Vaibhav]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 10:24:18 GMT</pubDate>
            <atom:updated>2023-07-12T10:24:18.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Generative AI is powered by very large machine learning models that are pre-trained on vast amounts of data, commonly referred to as foundation models (FMs). A subset of FMs called large language models (LLMs) are trained on trillions of words across many natural-language tasks. These LLMs can understand, learn, and generate text that’s nearly indistinguishable from text produced by humans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*sDJXmc6U_bXqbQHrNG2evQ.png" /></figure><p>LangChain is a framework for developing applications powered by language models. It allows you to connect a language model to other sources of data and let it interact with its environment. You can use it for various purposes such as chatbots, document analysis, code generation, and more. LangChain has components for different tasks and use cases, and you can also customize them to suit your needs. LangChain supports multiple languages such as Python and JavaScript. You can learn more about LangChain from its <a href="https://python.langchain.com/docs/get_started/introduction.html">official documentation</a>. In this article we will use OpenAI GPT3.5 with LangChain.</p><p>Flask is a lightweight WSGI web application framework written in Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It is classified as a microframework because it does not require particular tools or libraries and has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.</p><p>In a business context, a backend server is crucial for Document Question and Answer (Q&amp;A) systems utilizing LangChain. By offloading these resource-intensive operations to the backend server, the frontend client can focus on providing a seamless user experience and presenting the results in a user-friendly manner. These systems aim to extract meaningful information from various documents and provide accurate responses to user queries. A backend server acts as the central hub that orchestrates the entire process, managing data storage, document retrieval, language processing, and response generation. It enables efficient document indexing and retrieval, allowing quick access to relevant information. The server interacts with LangChain, a language processing platform, to analyze and understand the documents’ content, extract key insights, and generate intelligent responses. The backend server plays a pivotal role in ensuring scalability, reliability, and security, as it handles the computational and storage requirements of the Document Q&amp;A system. It serves as the backbone that enables seamless integration with other business applications, ensuring a smooth and robust user experience.</p><h3>Pre-requisites</h3><p>The following are the prerequisites for the tutorial:<br>1. A python IDE with pip and python installed.<br>2. A OpenAPI key — sk.xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>3. Postman or ThunderClient for testing.<br>4. Langchain library.</p><pre>pip install langchain</pre><p>3. Flask library</p><pre>pip install Flask</pre><h3>Creating Embeddings of the Documents</h3><p>In practise, users will need to query numerous documents at the same time. However, all LLM models have a token limit, which limits the amount of context we can supply to the model. To overcome this problem, we will break our documents into multiple chunks and store it in vector store with its embedding. Embeddings are vector representations of words and sentences that help computers understand the relationships between concepts. For this demo, we will be using two book pdfs with total 470 pages.</p><ol><li>Import required langchain components.</li></ol><pre>from langchain.document_loaders import DirectoryLoader<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>import os<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings.openai import OpenAIEmbeddings</pre><p>2. Specify OpenAI key.</p><pre>os.environ[&#39;OPENAI_API_KEY&#39;]=&lt;your-openai-key&gt;</pre><p>3. Make a directory called &quot;docs&quot; and place all of your pdf files inside of it. Utilise the DirectoryLoader function to load the files from your directory.</p><pre>loader = DirectoryLoader(f&#39;docs&#39;, glob=&quot;./*.pdf&quot;, loader_cls=PyPDFLoader)<br>documents = loader.load()</pre><p>4. Use <strong>RecursiveCharacterTextSplitter</strong><em> </em>function to split the documents into chunks. The attribute <strong>chunk_size</strong><em> </em>will define the size of window on documents and <strong>chunk_overlap</strong><em> </em>will specify window overlap.</p><pre>chunk_size_value = 1000<br>chunk_overlap=100<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size_value, chunk_overlap=chunk_overlap,length_function=len)<br>texts = text_splitter.split_documents(documents)</pre><p>5. Create a Vector Store. For this example we will use FAISS. Use <strong>OpenAIEmbeddings</strong><em> </em>functions to create embeddings of the chunks and save it to FAISS. By using <strong>save_local</strong><em> </em>function we can save the created embeddings to local system for later use. Similarly, use <strong>load_local</strong><em> </em>to load a locally saved index.</p><pre>docembeddings = FAISS.from_documents(texts, OpenAIEmbeddings())<br>docembeddings.save_local(&quot;llm_faiss_index&quot;)<br>docembeddings = FAISS.load_local(&quot;llm_faiss_index&quot;, OpenAIEmbeddings())</pre><h3>Creating a Document Q&amp;A Chain using LangChain</h3><p>We will be using a pre-defined chain from langchain, called <strong>qa_chain</strong>.</p><ol><li>Import necessary library and functions.</li></ol><pre>from langchain.prompts import PromptTemplate<br>from langchain.chains.question_answering import load_qa_chain<br>from langchain.llms import OpenAI<br>from langchain.output_parsers import RegexParser</pre><p>2. Write a prompt template for LLM model. This template should define how the LLM should respond based on user input. Use <strong>PromptTemplate</strong><em> </em>function for creating final prompt with input variables.</p><pre>prompt_template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end.<br>If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>This should be in the following format:<br><br>Question: [question here]<br>Helpful Answer: [answer here]<br>Score: [score between 0 and 100]<br><br>Begin!<br><br>Context:<br>---------<br>{context}<br>---------<br>Question: {question}<br>Helpful Answer:&quot;&quot;&quot;<br><br>output_parser = RegexParser(<br>    regex=r&quot;(.*?)\nScore: (.*)&quot;,<br>    output_keys=[&quot;answer&quot;, &quot;score&quot;],<br>)<br><br>PROMPT = PromptTemplate(<br>    template=prompt_template,<br>    input_variables=[&quot;context&quot;, &quot;question&quot;],<br>    output_parser=output_parser<br>)</pre><p>3. Load the qa_chain by defining parameters like LLM, chain_type and prompt. Note that LangChain offers four chain types for question-answering with sources, namely <strong>stuff</strong>, <strong>map_reduce</strong>, <strong>refine</strong>, and <strong>map-rerank</strong>. You can find more about these chain types <a href="https://python.langchain.com/docs/modules/chains/document/">here</a>.</p><pre>chain = load_qa_chain(OpenAI(temperature=0), chain_type=&quot;map_rerank&quot;, return_intermediate_steps=True, prompt=PROMPT)</pre><h3>Invoking the Chain and Formatting the Output</h3><p>We’ll write a function that searches the saved embeddings for chunks related to the supplied query and returns <strong>k</strong> pieces. In the function, we can specify the value of <strong>k</strong>. The chain will then be called using the extracted pieces and the user’s query. The chain will return the response as well as the user-supplied input documents. We can then format it and return it as required.</p><pre>def getanswer(query):<br>    relevant_chunks = docembeddings.similarity_search_with_score(query,k=2)<br>    chunk_docs=[]<br>    for chunk in relevant_chunks:<br>        chunk_docs.append(chunk[0])<br>    results = chain({&quot;input_documents&quot;: chunk_docs, &quot;question&quot;: query})<br>    text_reference=&quot;&quot;<br>    for i in range(len(results[&quot;input_documents&quot;])):<br>        text_reference+=results[&quot;input_documents&quot;][i].page_content<br>    output={&quot;Answer&quot;:results[&quot;output_text&quot;],&quot;Reference&quot;:text_reference}<br>    return output</pre><h3>Creating a Simple Python Flask Backend</h3><ol><li>Import Flask and required functions.</li></ol><pre>from flask import Flask, request, jsonify</pre><p>2. Create the main function and assign a port number.</p><pre>app = Flask(__name__)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=8095, debug=False)</pre><p>3. Create a demo function and assign a route to it. Specify the allowed methods. The method should allow post method and extract query key from body payload and return it to the user.</p><pre>@app.route(&#39;/docqna&#39;,methods = [&quot;POST&quot;])<br>def processclaim():<br>    try:<br>        input_json = request.get_json(force=True)<br>        query = input_json[&quot;query&quot;]<br>        return &quot;you sent &quot;+query<br>    except:<br>        return jsonify({&quot;Status&quot;:&quot;Failure --- some error occured&quot;})</pre><p>4. Run the app and Test the sample app using Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YSUH6s5xe3OSqQOAU8hHg.png" /></figure><p>5. Now, we will connect this function to our <strong>getanswer()</strong> function by calling it. The new function will look like:</p><pre>@app.route(&#39;/docqna&#39;,methods = [&quot;POST&quot;])<br>def processclaim():<br>    try:<br>        input_json = request.get_json(force=True)<br>        query = input_json[&quot;query&quot;]<br>        output=getanswer(query)<br>        return output<br>    except:<br>        return jsonify({&quot;Status&quot;:&quot;Failure --- some error occured&quot;})</pre><p>6. For testing the app, we will ask a simple question to the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDLreNLPkbKRUuTXhl59VA.png" /></figure><p>The function will produce a json file including the Answer provided by QAChain as well as the Chunk to which Chain referred.</p><h3>Compiled Code</h3><pre>from flask import Flask, request, jsonify<br><br>from langchain.document_loaders import DirectoryLoader<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>import os<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings.openai import OpenAIEmbeddings<br><br>from langchain.prompts import PromptTemplate<br>from langchain.chains.question_answering import load_qa_chain<br>from langchain.llms import OpenAI<br>from langchain.output_parsers import RegexParser<br><br><br>app = Flask(__name__)<br>os.environ[&#39;OPENAI_API_KEY&#39;]=&#39;sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&#39;<br><br>loader = DirectoryLoader(f&#39;docs&#39;, glob=&quot;./*.pdf&quot;, loader_cls=PyPDFLoader)<br>documents = loader.load()<br>chunk_size_value = 1000<br>chunk_overlap=100<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size_value, chunk_overlap=chunk_overlap,length_function=len)<br>texts = text_splitter.split_documents(documents)<br>docembeddings = FAISS.from_documents(texts, OpenAIEmbeddings())<br>docembeddings.save_local(&quot;llm_faiss_index&quot;)<br>docembeddings = FAISS.load_local(&quot;llm_faiss_index&quot;,OpenAIEmbeddings())<br><br><br><br><br>prompt_template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end. If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>This should be in the following format:<br><br>Question: [question here]<br>Helpful Answer: [answer here]<br>Score: [score between 0 and 100]<br><br>Begin!<br><br>Context:<br>---------<br>{context}<br>---------<br>Question: {question}<br>Helpful Answer:&quot;&quot;&quot;<br>output_parser = RegexParser(<br>    regex=r&quot;(.*?)\nScore: (.*)&quot;,<br>    output_keys=[&quot;answer&quot;, &quot;score&quot;],<br>)<br>PROMPT = PromptTemplate(<br>    template=prompt_template,<br>    input_variables=[&quot;context&quot;, &quot;question&quot;],<br>    output_parser=output_parser<br>)<br>chain = load_qa_chain(OpenAI(temperature=0), chain_type=&quot;map_rerank&quot;, return_intermediate_steps=True, prompt=PROMPT)<br><br><br>def getanswer(query):<br>    relevant_chunks = docembeddings.similarity_search_with_score(query,k=2)<br>    chunk_docs=[]<br>    for chunk in relevant_chunks:<br>        chunk_docs.append(chunk[0])<br>    results = chain({&quot;input_documents&quot;: chunk_docs, &quot;question&quot;: query})<br>    text_reference=&quot;&quot;<br>    for i in range(len(results[&quot;input_documents&quot;])):<br>        text_reference+=results[&quot;input_documents&quot;][i].page_content<br>    output={&quot;Answer&quot;:results[&quot;output_text&quot;],&quot;Reference&quot;:text_reference}<br>    return output<br><br><br><br>@app.route(&#39;/docqna&#39;,methods = [&quot;POST&quot;])<br>def processclaim():<br>    try:<br>        input_json = request.get_json(force=True)<br>        query = input_json[&quot;query&quot;]<br>        output=getanswer(query)<br>        return output<br>    except:<br>        return jsonify({&quot;Status&quot;:&quot;Failure --- some error occured&quot;})<br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=8095, debug=False)</pre><h4>Hopefully following these steps works for you! Feel free to reach out if you have any queries.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a123b67935" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>