iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💬

Adding a Simple Web Interface to a LangChain Chatbot

に公開
2023/09/01

I added a simple web interface that can be tested locally to one of the LangChain chatbot use case sample codes.

https://python.langchain.com/docs/use_cases/chatbots.html#chat-retrieval

The sample code for "Chat with document retrieval" on the above page has hard-coded questions and runs in the command line. Therefore, I modified it to allow interactive question-and-answering by adding a simple web interface that can be tested locally, as shown in the image below.

It is designed so that when you enter a question in the text form at the top of the screen and press the Submit button, the question and answer are added to the bottom of the screen.

The file structure is as follows:

/your_directory
|-- app.py
|-- .env
|-- templates/
|   |-- index.html
|-- html_data/
|   |-- Equinox_EN.html
|-- pdf_data/
|   |-- Equinox_JP.pdf

You can issue an OPENAI_API_KEY on the OpenAI site and embed it in the .env file as follows (the string below is a dummy). Also, in my case, I had to add credits since I didn't have any available.

.env
OPENAI_API_KEY=D7f9G2uMEK1lvaoA8eB0xjXVNyR5rFQ63LhtSgZWmPc

The LangChain Python code (app.js) is turned into a web server using Flask. Please install any missing packages as needed, such as pip install bs4.

In this example, I am loading information from Wikipedia about the racehorse Equinox, which was the JRA Horse of the Year last year, to provide answers. While Document Loader supports various document types, I chose to load locally saved HTML and PDF files instead of using the WebBaseLoader from the sample code, as the information didn't need to be the absolute latest.

By the way, when I asked ChatGPT (GPT-4) right before testing this, it didn't seem to know much about Equinox. Although the horse had already debuted in September 2021, those paying attention back then were likely only die-hard Japanese horse racing fans.

app.js
# Flask imports
from flask import Flask, request, jsonify, render_template

# Langchain imports
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationalRetrievalChain, LLMChain
from langchain.embeddings import OpenAIEmbeddings
from langchain.memory import ConversationSummaryMemory
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma

# Other imports
import os
from dotenv import load_dotenv

app = Flask(__name__)

# Load environment variables
load_dotenv()

# Initialize Langchain model
llm = ChatOpenAI()

data = []

'''
# Load web article
from langchain.document_loaders import WebBaseLoader
urls = [
     "https://en.wikipedia.org/wiki/Equinox_(horse)"
]
for url in urls:
    loader = WebBaseLoader(url)
    partial_data = loader.load()
    data.extend(partial_data)
'''

# get data from HTML files
from langchain.document_loaders import BSHTMLLoader
pages = ["html_data/" + f for f in os.listdir("html_data") if f.endswith('.html')]
for page in pages:
    loader = BSHTMLLoader(page, open_encoding='utf-8')
    partial_data = loader.load()
    data.extend(partial_data)

# get data from PDF files
from langchain.document_loaders import PyPDFLoader
pdfs = ["pdf_data/" + f for f in os.listdir("pdf_data") if f.endswith('.pdf')]
for pdf in pdfs:
    loader = PyPDFLoader(pdf)
    partial_data = loader.load_and_split()
    data.extend(partial_data)

# Split and vectorize text
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
all_splits = text_splitter.split_documents(data)

# Create vector store
vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())

# Initialize memory and retriever
memory = ConversationSummaryMemory(llm=llm, memory_key="chat_history", return_messages=True)
retriever = vectorstore.as_retriever()
qa = ConversationalRetrievalChain.from_llm(llm, retriever=retriever, memory=memory,verbose=True)

# Flask routes
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/ask', methods=['POST'])
def ask():
    question = request.json['question']
    answer = qa(question)['answer']
    return jsonify({"answer": answer})

# Run application
if __name__ == '__main__':
    app.run()

This is the web page templates/index.html. I styled it to look like a chat using CSS, but the UI quality is quite low.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>LangChain ChatBot</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body, html {
            height: 100%;
            margin: 0;
            display: flex;
            flex-direction: column;
        }
        #chat {
            max-width: 100%;
            flex-grow: 1;
            overflow: auto;
        }
        .question,
        .answer {
            max-width: 80%;
            padding: 10px;
            margin: 5px;
            border-radius: 10px;
        }
        .question {
            background-color: #f1f1f1;
            float: right;
            clear: both;
        }
        .answer {
            background-color: #e6ffe6;
            float: left;
            clear: both;
        }
        .error {
            color: red;
            font-weight: bold;
        }
        #input-area {
            text-align: center;
            padding: 10px;
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
    <div id="chat">
        <!-- Chat history will go here -->
    </div>
    <div id="input-area">
        <input type="text" id="question" placeholder="Type your question here..." minlength="2" maxlength="200" size="100">
        <button id="submit">Submit</button>
    </div>
    <script>
        $(document).ready(function() {
            $("#submit").click(function() {
                const question = $("#question").val();
                $("#chat").append("<p class='question'>Q: " + question + "</p>");
                $('#chat').scrollTop($('#chat')[0].scrollHeight); // Scroll to the bottom of #chat

                // Clear the text input field
                $("#question").val('');
                
                $.ajax({
                    url: '/ask',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ "question": question }),
                    success: function(data) {
                        const answer = data.answer;
                        $("#chat").append("<p class='answer'>A: " + answer + "</p>");
                        $('#chat').scrollTop($('#chat')[0].scrollHeight); // Scroll to the bottom of #chat

                        // Re-enable the submit button
                        $("#submit").prop("disabled", false);
                    },
                    error: function() {
                        $("#chat").append("<p class='answer error'>An error occurred. I'm sorry. Please ask your question again.</p>");
                        
                    }
                });
            });
        });
    </script>
</body>
</html>

After preparing the files above, run python app.js. Once you confirm that the web server is in a listening state, simply open http://127.0.0.1:5000/ in your browser to interact with it.

The operational results are as shown in the first image of this post. Since verbose=True is enabled, you can see more detailed behavior on the command line side. However, there are cases where the vector store search fails to pick up relevant information correctly, leading to an inability to answer, so the accuracy of information retrieval seems to be a key consideration.

In any case, I think it's a good thing that it can provide answers by combining the latest information. Also, unlike conventional bot frameworks, it works as a chatbot to some extent without having to define Intents and Entities or design conversation flows, so I felt that the barrier to entry is quite low in terms of making it easily.

Update History
  • 2023/8/31: Changed the Document Loader. Improved the web page UI.
  • 2023/9/1: Removed unnecessary code. Added a link to the next entry.

Discussion