Building Student Advisor using Lyzr SDK
Tags: ai, students, edtech, lyzr
Published: 2024-04-14 09:08:45

Are you a student navigating the complexities of academia, seeking **personalized guidance tailored** to your ambitions and coursework? Look no further! We’re thrilled to introduce the **Lyzr Student Advisor App**, an innovative solution leveraging the power of AI to revolutionize **student advising**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5m7iz68jqukhfbbomud.png)

At its core, the **Lyzr Student Advisor App** is designed to empower students on their academic journey. By harnessing the capabilities of **Lyzr’s ChatBot**, this application offers tailored insights and recommendations to help students excel in their coursework, develop career trajectories, and foster personal growth.

**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
](https://docs.lyzr.ai/homepage)
Lets get Started!
Create a new file app.py and use that

```
import os
import shutil
import streamlit as st
from lyzr import ChatBot
```
The code starts by importing essential modules for file handling, such as **os** and **shutil**, as well as for creating web applications, like **streamlit**. Furthermore, it imports the **ChatBot class** from the **lyzr module**, suggesting a potential integration of a chatbot feature, likely leveraging natural language processing capabilities.

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"]
```

```
# Function to remove existing files
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}")
```
The function **remove_existing_files(directory)** serves to erase all files and directories within a designated directory. It traverses through each item within the specified directory using **os.listdir(directory)**. For every item encountered, it forms the complete file path by combining the directory path with the item's filename. Subsequently, it tries to eliminate the item utilizing **os.unlink()** for files or **shutil.rmtree()** for directories. In case of any errors during this removal procedure, it handles them and presents an error notification using Streamlit's **st.error()** function.

```
# 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)
```
These lines of code handle a local directory named “**data**” within the file system. First, the variable data_directory is set to the string "data", indicating the name of the directory to be managed. Then, the code creates the "data" directory using **os.makedirs(data_directory, exist_ok=True)**. 

The **exist_ok=True** parameter ensures that the directory is created only if it doesn't already exist. Following this, the function **remove_existing_files(data_directory)** is invoked to clear any pre-existing files or subdirectories within the "data" directory, ensuring it is empty and prepared for usage.

```
# 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
```
This function, **rag_implementation**, serves to implement 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, it initializes the **Lyzr ChatBot** specifically designed for PDF files using the **pdf_chat method** from the ChatBot class. Similarly, if the file is a DOCX document, it initializes the ChatBot for DOCX files using the **docx_chat method**.

Both initialization processes include specifying the input file(s) and setting the language model parameters, here defined as {**"model": "gpt-4"**}. If the file extension doesn't match ".pdf" or ".docx", the function raises a ValueError indicating that only PDF and DOCX files are supported.

```
# Function to get Lyzr response
def advisor_response(file_path, ambition):
    rag = rag_implementation(file_path)
    prompt = f"""Your name is Isha, always remember that, and you are a student advisor at a university. Always introduce yourself.
                 
                 To generate advice for the uploaded document, please follow the instructions below:
                    
                      - Course work and grades: Being a Student Advisor, look into the uploaded marksheet and give important insights about where the student performance lies.
                     
                      - Ambition: Informed by the student's ambition (replace {ambition}), advise them on the steps required to excel in their chosen path.
                     
                      - Academic advice: Being a Student Advisor, look into the uploaded document and give important insights about where the student's strength and weaknesses lie and how to improve them.
                     
                      - Career guidance: Being a student Advisor utilize the student's ambition, coursework, and grades, offer pertinent suggestions for their career trajectory.
                     
                      - Personal development: Being a student Advisor offer guidance on fostering high productivity through effective time management techniques and engaging in relevant extracurricular activities.
                     
                      - Please ensure adherence to these steps and provide responses akin to a student advisor. """

    response = rag.chat(prompt)
    return response.response
```
This **advisor_response** function utilizes the rag_implementation function to initialize the **Lyzr ChatBot**. It then generates a prompt containing instructions and placeholders for various aspects of advising, such as **coursework**, **ambition**, **academic advice**, **career guidance**, and **personal development**. The placeholder {ambition} is used to incorporate the student's ambition dynamically into the prompt.

The function prompts the **Lyzr ChatBot** with this message, instructing it to provide advice based on the uploaded document and the provided prompt. The ChatBot processes the prompt and generates a response, which is then returned by the function. This response is expected to contain advice and insights tailored to the student’s academic journey and ambitions.

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

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")

    # User input for student's ambition
    ambition = st.text_input("What is your Ambition?")

    # Generate advice button
    if st.button("Get Advice"):
        if not ambition:
            st.warning("Please enter your ambition.")
        else:
            automatic_response = advisor_response(file_path, ambition)
            st.markdown(automatic_response)
```
This section of code creates a file upload widget using Streamlit’s **file_uploader** function. Users are prompted to upload their marksheet file, with supported file types restricted to PDF and DOCX formats.

Upon file upload, the code saves the uploaded file to the specified **data_directory**, ensuring it is stored locally for further processing. A success message is displayed to confirm the successful saving of the file.

Next, users are prompted to input their ambition through a text input field. This information is crucial for generating **personalized advice tailored** to the user’s career aspirations.

Finally, a button labeled “**Get Advice**” allows users to trigger the advice generation process. Before proceeding, the code checks if the ambition field is empty and prompts the user to enter their ambition if necessary. If the ambition is provided, the **advisor_response** function is called with the file path and ambition as arguments. The generated advice is then displayed to the user using Streamlit's markdown function.

As we continue to refine and enhance the **Lyzr Student Advisor App**, our vision is to empower students worldwide with AI-driven guidance that adapts to their unique needs and aspirations. Whether you’re a freshman exploring academic possibilities or a senior fine-tuning your career path, the Lyzr Student Advisor App is your trusted companion every step of the way.

Youtube: https://www.youtube.com/watch?v=sPo667YXmlw

App link: https://student-advisor-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Student-Advisor

**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](https://www.lyzr.ai/)
**Book a Demo**: [Book a Demo](https://www.lyzr.ai/book-demo/)
**Discord**: [Join our Discord community](https://discord.com/invite/nm7zSyEFA2)
**Slack**: [Join our Slack channel](https://anybodycanai.slack.com/join/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw#/shared-invite/email)