[go: up one dir, main page]

DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building Budget Planner app with Lyzr SDK

In the realm of personal finance, navigating the intricate web of budget planning can often feel like deciphering a complex puzzle. From tracking expenses to allocating funds across various categories, the process can be overwhelming, to say the least. However, with the advent of innovative solutions like the Lyzr SDK, mastering budget planning has never been more attainable.

Image description

In today’s dynamic economic landscape, effective budget planning serves as the cornerstone of financial stability and success. Whether you’re striving to build an emergency fund, save for a dream vacation, or invest in your future, having a well-defined budget lays the groundwork for achieving your financial aspirations.

At the heart of this revolution lies the Lyzr SDK — a powerful tool designed to streamline and optimize the budget planning process. By harnessing the capabilities of artificial intelligence and machine learning, Lyzr SDK empowers individuals and businesses alike to take control of their finances with confidence and ease.

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 streamlit as st
import shutil
from lyzr import ChatBot
Enter fullscreen mode Exit fullscreen mode

The provided Python script imports essential modules for file management (os, shutil) and web application development (streamlit). Additionally, it imports the ChatBot class from the lyzr module, suggesting integration with a chatbot functionality, likely leveraging natural language processing capabilities.

Next Set Up OpenAI API Key and using Streamlit’s secrets management, set up the OpenAI API key within your Streamlit application. Replace "OPENAI_API_KEY" with the actual key name defined in your Streamlit secrets where your OpenAI API key is stored.

os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
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

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)
Enter fullscreen mode Exit fullscreen mode

These lines of code are responsible for managing a local directory named “data” within the file system. Initially, it sets the variable data_directory to the string "data", representing the name of the directory to be used. Next, it 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, it calls the remove_existing_files(data_directory) function to clear out any existing files or subdirectories within the "data" directory, ensuring it's empty and ready for use.

# File upload widget
uploaded_file = st.file_uploader("Choose Word file", type=["docx"])

if uploaded_file is not None:
    # Save the uploaded Word 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(f"File successfully saved")
Enter fullscreen mode Exit fullscreen mode

This code snippet creates a file upload widget using Streamlit, allowing users to select Word files (“docx” format). Upon file selection, it saves the uploaded Word file to a local directory named “data”. The code then displays a success message confirming the file’s successful saving.

def get_files_in_directory(directory="data"):
    # This function helps us get the file path along with the filename.
    files_list = []

    # Ensure the directory exists
    if os.path.exists(directory) and os.path.isdir(directory):
        # Iterate through all files in the directory
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)

            # Check if the path points to a file (not a directory)
            if os.path.isfile(file_path):
                files_list.append(file_path)

    return files_list
Enter fullscreen mode Exit fullscreen mode

This function, get_files_in_directory(directory="data"), retrieves a list of file paths from the specified directory. It checks if the directory exists and is valid, then iterates through its contents. For each file found, it appends the file path to a list. Finally, it returns the list of file paths, excluding directories.

def rag_implementation():
    # This function will implement RAG Lyzr Chatbot
    path = get_files_in_directory()
    path = path[0]

    rag = ChatBot.docx_chat(
        input_files=[str(path)],
        llm_params={"model": "gpt-3.5-turbo"},
        # vector_store_params=vector_store_params
    )

    return rag
Enter fullscreen mode Exit fullscreen mode

The function rag_implementation() is responsible for implementing the RAG Lyzr Chatbot. Initially, it retrieves the file path using the get_files_in_directory() function. It then selects the first file from the list of files obtained. Subsequently, it initializes the RAG Chatbot instance named rag using the ChatBot.docx_chat() method. This method takes the path to the input file containing the conversation history, along with parameters specifying the language model to be used, in this case, GPT-3.5 Turbo. Finally, the function returns the initialized chatbot instance rag.

def resume_response():
    rag = rag_implementation()
    prompt = """  Please follow the instructions below to determine the ideal allocation of expenses based on the provided total budget for the month,
                    - From the total budget given for a month , take that amount and use it to allocate for these expenses.
                    - Calculate the expense for these below using the formula given and after calculation not display it.
                    - Housing : To calculate housing expenses it is 31.91% the total budget, later describe how to spend the amount for better living.
                    - Utilities: To calculate Utilities expense it is 4.21% the total budget, later describe how to spend the amount for better living.
                    - Transportation: To calculate Transportation expense it is 6.38% the total budget, later describe how to spend the amount for better living.
                    - Groceries: To calculate Groceries expense it is 8.51% the total budget, later describe how to spend the amount for better living.
                    - Insurance: To calculate Insurance expense it is 3.19% the total budget, later describe how to spend the amount for better living.
                    - Entertainment: To calculate Entertainment expense it is 3.19% the total budget, later describe how to spend the amount for better living.
                    - Personal Care: To calculate Personal Care expense it is 2.13% the total budget, later describe how to spend the amount for better living.
                    - Savings: To calculate Savings expense it is 10.36% the total budget, later describe how to spend the amount for better living.
                    - Miscellaneous: To calculate Miscellaneous expense it is 4.26% the total budget, later describe how to spend the amount for better living.
                    - Just show the amount not the calculation part. """

    response = rag.chat(prompt)
    return response.response

Enter fullscreen mode Exit fullscreen mode

The resume_response() function orchestrates the response generation process based on the provided budget allocation instructions. First, it calls the rag_implementation() function to initialize the RAG Lyzr Chatbot. Then, it constructs a prompt containing detailed instructions for determining expense allocations based on the total budget for the month.

The prompt outlines specific percentages of the total budget allocated for various expense categories, such as housing, utilities, transportation, groceries, insurance, entertainment, personal care, savings, and miscellaneous expenses. It emphasizes calculating expenses without displaying the calculation part. Subsequently, the function passes this prompt to the chatbot instance rag using the rag.chat() method to generate a response.

Finally, it returns the response generated by the chatbot, which presumably provides recommendations for allocating expenses as per the given instructions.Ultimately, the true measure of success lies in realizing your financial goals. Whether you’re aiming to eliminate debt, build wealth, or achieve financial freedom, Lyzr SDK serves as your trusted companion on the path to prosperity.

In conclusion, the journey to financial wellness begins with a single step — and with Lyzr SDK by your side, that step has never been more attainable. By simplifying the budget planning process and empowering users with actionable insights, Lyzr SDK paves the way for a brighter and more prosperous future. So why wait? Take the plunge today and embark on your journey to financial freedom with Lyzr SDK as your trusted guide.

Youtube Link: https://www.youtube.com/watch?v=kg1Tn_jaf-M

App link: https://budget-planner-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Budget-Planner

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)