Building an University Advisor App with Lyzr SDK
Tags: ai, opensource, university, advice
Published: 2024-04-24 13:32:42

In today’s competitive academic landscape, finding the **right university** that aligns with your aspirations, academic achievements, and financial considerations can be daunting. However, with advancements in artificial intelligence and natural language processing, creating personalized university recommendation systems has become more accessible than ever.

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

In this blog post, we’ll explore how to leverage the **Lyzr SDK** to build a **University Advisor app** tailored to Ivy League aspirants.

**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 PIL import Image
from lyzr import ChatBot
```
This code snippet sets up a **Streamlit application** with various functionalities. First, the **os** module is imported for interacting with the operating system, followed by the **shutil** module for file operations. Streamlit is imported as **st** to facilitate the creation of the web application. Additionally, the Image class from the PIL library is imported for handling images. Lastly, the Lyzr library's **ChatBot** module is imported, indicating that this application may incorporate a chatbot feature powered by Lyzr.

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 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}")
```
This function, **remove_existing_files(directory)**, serves to remove any existing files within a specified directory. It iterates over each file within the directory using os.listdir(directory), then constructs the full file path using os.path.join(directory, filename).

For each file, it attempts to determine if it’s a regular file or a directory using **os.path.isfile()** and **os.path.isdir()** respectively. If it's a file or a symbolic link (os.path.islink()), it removes the file using os.unlink(file_path). If it's a directory, it recursively removes it along with its contents using shutil.rmtree(file_path).

In case an error occurs during the removal process, it displays an error message using Streamlit’s **st.error()** function, indicating the nature of the error. This function ensures that the specified directory is clean from any existing files before further operations.

```
# 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)
```
This code snippet initializes a variable data_directory to store the path of a directory named "data". It then creates the "data" directory using **os.makedirs(data_directory, exist_ok=True)**, ensuring that the directory is created if it doesn't exist.

Next, it calls the **remove_existing_files()** function with the data_directory as an argument to remove any existing files within the "data" directory, ensuring a clean slate for further operations. This sequence of steps ensures that the "data" directory is ready for use, with any previous data removed to avoid conflicts or clutter.

```
# Function to implement RAG Lyzr Chatbot
def rag_implementation(file_path):
    _, file_extension = os.path.splitext(file_path)
    supported_extensions = [".pdf", ".docx"]

    if file_extension.lower() in supported_extensions:
        model = "gpt-4"
        if file_extension.lower() == ".pdf":
            return ChatBot.pdf_chat(input_files=[file_path], llm_params={"model": model})
        else:
            return ChatBot.docx_chat(input_files=[file_path], llm_params={"model": model})
    else:
        raise ValueError("Unsupported file type. Only PDF and DOCX files are supported.")
```
This rag_implementation(file_path) function is designed to implement RAG functionality for a Lyzr Chatbot, allowing it to interact with documents in PDF or DOCX format.

Firstly, it extracts the file extension from the provided file_path using os.path.splitext(file_path). It then checks if the file extension is one of the supported types, namely ".pdf" or ".docx".

If the file extension matches one of the supported types, it determines the appropriate Lyzr model to use based on the file format. For PDF files, it sets the model to “**gpt-4**” and invokes the **pdf_chat()** method of the ChatBot module, passing the PDF file path as input. Similarly, for DOCX files, it sets the model to "**gpt-4**" and invokes the docx_chat() method, passing the **DOCX** file path.

If the file extension doesn’t match any of the supported types, it raises a ValueError indicating that only **PDF and DOCX files** are supported.

```
# Function to get Lyzr response
def advisor_response(file_path, gre, gmat, ielts, expense, ambition, location):
    rag = rag_implementation(file_path)
    prompt = f""" 
You are an expert university student advisor. Always Introduce yourself. Your task is to provide university recommendations by analyzing the provided GRE scores {gre}, IELTS scores {ielts}, the user's ambition {ambition}, and budget {expense}, and suggest the most suitable universities from the uploaded document.

Here's your step-by-step guide:

1. Begin by examining the uploaded document with detailed information on various universities to understand the options available.

2. Next, evaluate the user's GRE {gre} and gmat {gmat} scores to gauge their academic standing.

3. Consider the user's ambition{ambition} and assess their financial constraints by looking at their budget {expense}.

4. Compare and match the user's qualifications, goals, and financial capacity with appropriate universities from your initial analysis.

5. Compile a shortlist of universities that best align with all of the user's criteria, focusing on those that closely match their profile.

6. After shortlisting based on expense fees{expense}, GRE {gre}, and GMAT{gmat} scores, LOCATE universities either in or near the specified user preferred location{location} for additional suitability.

7. Present your recommendations to the user in a clear manner, explaining why each university is a strong match based on their individual needs and aspirations.

You must undertake this task with diligence as it will have a profound effect on a student's future education path.

Keep in mind that you should only display universities that closely match the user's profile in markdown format , rather than showing the entire list from the uploaded document. Your recommendations should be customized to fit both academic standards and financial capabilities while supporting long-term objectives.
"""
    response = rag.chat(prompt)
    return response.response
```
The **advisor_response()** function orchestrates Lyzr Chatbot's university recommendations based on various criteria. It first invokes the RAG functionality, then constructs a task prompt for the advisor, including analyzing academic scores, ambition, budget, and location preferences. Finally, it initiates a conversation with the chatbot using the constructed prompt, generating markdown-formatted recommendations tailored to the user's profile.

```
# File path input field
file_path = "top_200_USA.pdf"

# Check if file path is not empty and exists
if file_path and os.path.exists(file_path):
     
    # User input 
    gre = st.number_input("What's your GRE score?", step=10, min_value=260, max_value=340)
    gmat = st.number_input("What's your Gmat score?", step=10, min_value=200, max_value=800)
    ambition = st.text_input("What is your ambition?")
    expense = st.text_input("What is your expected average fees?",placeholder="$")
    location = st.text_input("Whats your preferred location?")

    # Generate advice button
    if st.button("Get Advice"):
        if not gre or not ielts or not ambition or not expense:
            st.warning("Please fill out all fields.")
        else:
            automatic_response = advisor_response(file_path, gre, gmat, ielts, expense, ambition,location)
            st.markdown(automatic_response)
else:
    st.info("Please enter a valid file path.")
```
This code snippet presents a Streamlit interface for users to input their GRE score, GMAT score, ambition, expected average fees, and preferred location. If a file path is provided and it exists, the “**Get Advice**” button triggers the advisor_response() function to generate university recommendations based on the user's input. However, if any of the input fields are empty, a warning message is displayed prompting the user to fill out all fields.

Building a **University Advisor app** empowered by Lyzr SDK opens up new possibilities for students seeking tailored recommendations for their academic journey. By harnessing the power of AI and Streamlit, developers can create intuitive and user-friendly applications that simplify complex decision-making processes.

**App link**: https://universityadvisor-lyzr.streamlit.app/

**Source Code**: https://github.com/isakshay007/University_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)