Building User Story & Use Case Generator using Lyzr SDK
Tags: ai, opensource, api, development
Published: 2024-04-08 07:05:21

Are you tired of spending countless hours crafting **user stories and use cases** for your projects? Do you wish there was a more efficient way to streamline your development process? Look no further, because **Lyzr’s User Story & Use Case Generator** is here to revolutionize the way you approach project management.

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

**Lyzr’s User Story & Use Case Generator** is an intuitive tool that harnesses the power of **artificial intelligence** to automate the tedious task of creating user stories and use cases. Powered by **Lyzr’s cutting-edge SDK**, this tool empowers your team with unmatched precision and efficiency, allowing you to focus on what truly matters — bringing your vision to life.

**How It Works**
Using **Lyzr’s User Story & Use Case Generator** is as simple as uploading your **project document**. Whether it’s a product requirement document, a business proposal, or any other project-related material, our tool can analyze it with ease. Once uploaded, Lyzr’s AI gets to work, extracting key information and crafting **tailored user stories and use cases** in seconds.

**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 handling files (**os, shutil**) and for web application development (**streamlit**). Furthermore, it brings in 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** by utilizing Streamlit’s secrets management. The specific key name stored in Streamlit secrets, where the OpenAI API key resides, is used to replace “OPENAI_API_KEY”. This approach 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 the management of a local directory named “**data**” in the file system. Firstly, it assigns the variable `**data_directory**` to the string “data”, which represents the name of the directory to be utilized. Then, it creates the “data” directory using `**os.makedirs(data_directory, exist_ok=True)**`. The `exist_ok=True` parameter guarantees that the directory is created only if it doesn’t already exist. Subsequently, it invokes the function to clear any existing files or subdirectories within the “data” directory, ensuring it’s empty and prepared for usage.

```
# 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")
```
This code snippet implements a file upload feature in a **Streamlit application**, enabling users to select and upload a Word file. Once a file is uploaded, it’s saved to a predefined directory within the file system. The file’s path is constructed by combining the directory path (**data_directory**) with the name of the uploaded file. Subsequently, the file content is written to this path in binary write mode. Finally, a success message is displayed to inform the user that the file has been successfully saved.

```
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
```
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.

```
# Function to implement RAG Lyzr Chatbot
def rag_implementation():
    # Get the file path
    file_path = get_files_in_directory()[0]

    # Initialize the RAG Lyzr ChatBot
    rag = ChatBot.docx_chat(
        input_files=[file_path],
        llm_params={"model": "gpt-3.5-turbo"},
    )

    return rag
```
The `**rag_implementation()**` function manages the integration of the RAG Lyzr Chatbot. Initially, it retrieves the file path by utilizing the `**get_files_in_directory()**` function, which gathers a list of files within the directory. Then, it selects the first file from the obtained list. Subsequently, it instantiates an instance of the **RAG Chatbot**, denoted as `rag`, employing the `**ChatBot.docx_chat()**` method. This method necessitates the file path containing the conversation history and additional parameters specifying the language model, such as **GPT-3.5 Turbo** in this instance. Ultimately, the function returns the initialized chatbot instance `**rag**`.

```
# Function to get Lyzr response
def resume_response():
    file_path = get_files_in_directory()[0]
    rag = rag_implementation()
    prompt = f"""To generate user stories and use cases for your project/product based on the uploaded document, please follow the instructions below:
                     - Product Vision and Goals: Identify and describe the overarching vision and goals of the product. What specific problem is the product aiming to solve?
                     - Target Audience and User Personas: Identify the primary users of the product and describe their demographics, behaviors, and needs to create user personas.
                     - Functional Requirements: Identify and specify the functionalities and features the product should have, highlighting both primary features and any additional capabilities required.
                     - Non-functional Requirements: Identify and specify non-functional requirements such as performance, scalability, security, and usability.
                     - User Flows and Workflows: Identify and illustrate typical user flows and workflows within the product.
                     - Acceptance Criteria: Identify and clarify the conditions that must be met for a user story to be considered complete and accepted by stakeholders.
                     - Constraints and Limitations: Identify any constraints or limitations that may impact feature development and implementation.
                     - Use Cases: Based on above information give multiple use cases that can used for by the user.
                     - User Stories: Based on the provided information, craft multiple user stories that represent specific user needs and actions within the product.
                     - Ensure that the information provided for Product Vision and Goals, Target Audience and User Personas, Functional Requirements, Non-Functional Requirements, User Flows and Workflows, Acceptance Criteria, and Constraints and Limitations is precise and comprehensive not more than 3 bullet points.
                     - The generated Use Cases and User Stories should be clearly explained individually with relevance to the product's context and objectives."""

    response = rag.chat(prompt)
    return response.response
if uploaded_file is not None:
    automatice_response = resume_response()
    st.markdown(f"""{automatice_response}""")
```
This code snippet defines the **resume_response()** function, which orchestrates the process of generating responses from the **Lyzr Chatbot** based on a predefined prompt. Initially, it obtains the file path of the document to be analyzed by calling the **get_files_in_directory()** function and selecting the first file from the list. Then, it initializes an instance of the Lyzr Chatbot by invoking the **rag_implementation()** function.

Next, a detailed prompt is constructed, outlining instructions for generating user stories and use cases for a given project or product. This prompt covers various aspects such as **product vision, target audience, functional and non-functional requirements, user flows, acceptance criteria, constraints, use cases, and user stories**.

Subsequently, the **Lyzr Chatbot** is prompted with this detailed instruction set, and it generates a response accordingly. Finally, the generated response is returned, which is then displayed in the **Streamlit application** using st.markdown() to render the response in Markdown format. This comprehensive process ensures the generation of tailored user stories and use cases based on the provided project information.

**Why Choose Lyzr?**

**Time-Saving:** Say goodbye to hours spent manually crafting user stories and use cases. With Lyzr, you can generate high-quality content in a fraction of the time.

**Accuracy:** Trust in the accuracy and reliability of Lyzr’s AI-powered analysis. Rest assured that the generated user stories and use cases are based on a comprehensive understanding of your project.

**Efficiency:** Free up valuable resources and allocate them to more strategic tasks. Lyzr’s User Story & Use Case Generator streamlines your project development process, allowing you to focus on innovation and growth.

**Get Started Today!**
Ready to revolutionize your project development process? Experience the power of **Lyzr’s User Story & Use Case Generator** today!

**Youtube Link**: https://www.youtube.com/watch?v=XxQAEv7zoos

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

**Source Code**:https://github.com/isakshay007/user_story_generator

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

Transform your projects with Lyzr and unleash the full potential of your team.