DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building Library Assistant using Lyzr SDK

In a world inundated with distractions, finding time to sit down with a good book may seem like a luxury. However, the act of reading goes far beyond mere entertainment; it is a powerful tool for personal development and growth. In this blog post, we’ll explore the transformative impact that reading can have on our lives and why it’s essential to make it a regular habit.

Image description

One of the most significant benefits of reading is its ability to expand our perspective. Through books, we can immerse ourselves in different cultures, time periods, and viewpoints, gaining insights that we might never encounter otherwise. Whether it’s a work of fiction that transports us to a fantastical realm or a non-fiction book that delves into a new field of study, each reading experience broadens our understanding of the world and the people in it.

Why use Lyzr SDK’s?

With Lyzr SDKs, crafting your own GenAI application is a breeze, requiring only a few lines of code to get up and running swiftly.

Checkout the Lyzr SDK’s

Lets get Started!

Create a new file app.py and use that

import os
import shutil
import streamlit as st
from lyzr import ChatBot
Enter fullscreen mode Exit fullscreen mode

This code snippet imports essential libraries for file handling, user interface creation, and Lyzr’s ChatBot functionality. The os module facilitates interactions with the operating system, shutil aids in high-level file operations, and streamlit provides tools for building interactive web applications. Lastly, the ChatBot module from Lyzr suggests the integration of conversational AI features into the Streamlit application.

Subsequently, it initializes the OpenAI API key using Streamlit’s secrets management. By accessing the specific key stored securely in Streamlit’s secrets, where the OpenAI API key is securely stored, it replaces the placeholder “OPENAI_API_KEY”. This ensures secure access to the OpenAI API within the Streamlit application.


# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
# Function to remove existing files in the directory
def remove_existing_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            st.error(f"Error while removing existing files: {e}")
Enter fullscreen mode Exit fullscreen mode

This function removes existing files from a specified directory. It iterates through the files in the directory using os.listdir(), constructs the full file path using os.path.join(), and attempts to remove each file using os.unlink() for files or shutil.rmtree() for directories. If an error occurs during the removal process, it displays an error message using Streamlit's st.error().

# Set the local directory
data_directory = "data"

# Create the data directory if it doesn't exist
os.makedirs(data_directory, exist_ok=True)

# Remove existing files in the data directory
remove_existing_files(data_directory)
Enter fullscreen mode Exit fullscreen mode

This code snippet first sets a variable data_directory to "data", representing the directory where data files will be stored. Then, it ensures that this directory exists by creating it if it doesn't already exist using os.makedirs(data_directory, exist_ok=True). Finally, it calls the remove_existing_files() function to clear any existing files in the data directory, preparing it for new data.

# Function to implement RAG Lyzr Chatbot
def rag_implementation(file_path):
    # Check the file extension
    _, file_extension = os.path.splitext(file_path)

    if file_extension.lower() == ".pdf":
        # Initialize the PDF Lyzr ChatBot
        rag = ChatBot.pdf_chat(
            input_files=[file_path],
            llm_params={"model": "gpt-4"},
        )
    elif file_extension.lower() == ".docx":
        # Initialize the DOCX Lyzr ChatBot
        rag = ChatBot.docx_chat(
            input_files=[file_path],
            llm_params={"model": "gpt-4"},
        )
    else:
        # Handle unsupported file types
        raise ValueError("Unsupported file type. Only PDF and DOCX files are supported.")

    return rag
Enter fullscreen mode Exit fullscreen mode

This function, rag_implementation(file_path), facilitates the implementation of the RAG Lyzr Chatbot based on the file type provided. It begins by extracting the file extension from the given file_path.

If the file is a PDF (file_extension.lower() == ".pdf"), the function initializes the RAG Lyzr Chatbot for PDF files using the specified input file(s) and parameters.

If the file is a DOCX (file_extension.lower() == ".docx"), the function initializes the RAG Lyzr Chatbot for DOCX files with the specified input file(s) and parameters.

In case the file type is not supported, it raises a ValueError indicating that only PDF and DOCX files are supported.

# Function to get Lyzr response
def advisor_response(file_path, preferred_genre):
    rag = rag_implementation(file_path)
    prompt = f""" You are an Expert LIBRARY ASSISTANT BOT. Always introduce yourself. Your task is to ANALYZE an uploaded document and USER INPUT concerning their preferred genres. 

                  Based on this information, you MUST RECOMMEND relevant books to the user.

                  Here's your step-by-step guide:

                  1. First, EXAMINE the uploaded documents CAREFULLY, categorize and recheck for any missing details. DO NOT DISPLAY the book list to the user.

                  2. Next, After the user enters their (genre{preferred_genre}).Use this information in the next step.

                  3. Then, COMPARE the user's preferred genre with your categorized list to IDENTIFY potential book matches.

                  4. After that, SELECT a variety of titles from the matched list that you believe will best suit the user's genre taste. 
                     If the preferred genre cannot be matched with the book list, state that the books are currently not available and kindly suggest the user to select an another genre or explore different genres.

                  5. Now, PRESENT these recommendations to the user in an organized manner, perhaps by ranking them or grouping similar titles together.

                  FOLLOW these steps thoroughly and make sure to DISPLAY the recommendations.
                   """
    response = rag.chat(prompt)
    return response.response
Enter fullscreen mode Exit fullscreen mode

This advisor_response(file_path, preferred_genre) function is responsible for generating a response from the Lyzr Chatbot based on the uploaded file and the user's preferred genre. Here's how it works:

It first initializes the RAG Lyzr Chatbot using the rag_implementation(file_path) function, which determines the type of file and initializes the appropriate Lyzr Chatbot instance.

Next, it creates a prompt message that instructs the Chatbot on how to analyze the uploaded document and respond to the user’s preferred genre. This prompt outlines a step-by-step guide for the Chatbot, including examining the document, identifying potential book matches based on the user’s genre preference, and presenting recommendations to the user.

Then, it uses the initialized Chatbot instance to generate a response based on the prompt message.

# File upload widget
uploaded_file = st.file_uploader("Upload your book list here⬇️", type=["pdf", "docx"])

# If a file is uploaded
if uploaded_file is not None:
    # Save the uploaded file to the data directory
    file_path = os.path.join(data_directory, uploaded_file.name)
    with open(file_path, "wb") as file:
        file.write(uploaded_file.getvalue())

    # Display the path of the stored file
    st.success("File successfully saved")

    # Get preferred genre after file upload
    preferred_genre = st.text_input("Enter your preferred genre")

    # Generate advice button
    if st.button("Get Recommendation"):
        automatic_response = advisor_response(file_path, preferred_genre)
        st.markdown(automatic_response)
Enter fullscreen mode Exit fullscreen mode

This code segment presents a file uploader widget using Streamlit’s st.file_uploader() function, allowing users to upload their book lists. If a file is uploaded, it saves the file to the designated data directory and displays a success message.

After uploading the file, users can input their preferred genre via a text input widget. Upon clicking the “Get Recommendation” button, the advisor_response() function is invoked to generate recommendations based on the uploaded file and the user's preferred genre. The resulting recommendation is then displayed to the user in Markdown format.

Overall, this setup enables users to upload their book lists, specify their preferred genre, and receive tailored recommendations from the Lyzr Chatbot based on the uploaded content and user input.

In conclusion, reading is not just a pastime; it’s a powerful tool for personal growth, learning, and self-discovery. By making reading a priority in our lives, we can expand our horizons, deepen our understanding of the world, and cultivate essential skills for success and fulfillment. So, the next time you find yourself with a free moment, pick up a book and embark on a journey of personal development. Your mind and soul will thank you for it.

App link: https://library-assistant-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Library-Assistant

Connect with Lyzr
To learn more about Lyzr and its SDK’s, visit our website or get in touch with our team:

Website: Lyzr.ai
Book a Demo: Book a Demo
Discord: Join our Discord community
Slack: Join our Slack channel

Top comments (0)