“Kaggle Notebook: Building an AI Stress Management Assistant from Scratch

StressLess: Building an AI Assistant for Workplace Stress Management

StressLess: Building an AI Assistant for Workplace Stress Management

Welcome to this educational guide on creating an artificial intelligence assistant dedicated to workplace stress management. This project, called StressLess, leverages advanced generative AI technologies to help individuals better understand and manage their professional stress.

Kaggle Notebook: StressLess v1 2025Q1

Understanding Workplace Stress

Stress is a physiological and psychological reaction to pressures or challenges. In a professional context, stress can originate from multiple sources: excessive workload, tight deadlines, interpersonal conflicts, or imbalance between professional and personal life.

According to the World Health Organization, over 300 million people worldwide suffer from work-related stress. This phenomenon leads to considerable economic costs, estimated at more than 1 trillion dollars annually in lost productivity.

Introduction to the StressLess Project

StressLess is an AI assistant designed to:

  • Identify stress factors specific to each user
  • Propose adapted stress management techniques
  • Provide personalized advice based on scientific data
  • Offer visualizations to better understand one’s stress state

This project integrates three advanced generative artificial intelligence capabilities that work together to create a comprehensive assistance experience.

The Three Generative AI Capabilities Used

1. Retrieval Augmented Generation (RAG)

This technology allows the assistant to access a specialized knowledge base on stress management and retrieve the most relevant information to answer users’ questions. It functions like an intelligent library that precisely selects resources adapted to each situation.

2. Function Calling

This capability enables the assistant to trigger specific actions based on detected needs. For example, when a user expresses anxiety, the assistant can automatically suggest a guided breathing exercise or schedule a break.

3. Structured Output/JSON Mode

This functionality analyzes users’ messages to extract structured information about their stress factors, symptoms, and intensity. This data is then organized in a format that allows for the generation of visualizations and precise recommendations.

Step-by-Step Guide to Creating StressLess

Here’s how to reproduce this project in a Kaggle environment. Each step is explained to be accessible even to programming beginners.

Step 1: Environment Configuration

Let’s start by installing the necessary libraries:

# Installing required libraries
!pip install -q google-generativeai langchain langchain-google-genai langchain-community faiss-cpu pandas numpy matplotlib seaborn ipywidgets

Next, let’s configure access to Google’s Gemini API:

# Configuring the Gemini API with a secret key
from kaggle_secrets import UserSecretsClient
secret_label = "GOOGLE_API_KEY"
api_key = UserSecretsClient().get_secret(secret_label)

# Configuring the Gemini API
import google.generativeai as genai
genai.configure(api_key=api_key)

Step 2: Creating the Knowledge Base

For our assistant to provide relevant advice, we create a knowledge base on stress management:

# Creating our stress management knowledge base
import pandas as pd

stress_management_data = [
    {
        "title": "Deep Breathing",
        "category": "Relaxation Technique",
        "content": "Deep breathing is a simple yet effective technique to quickly reduce stress..."
    },
    # Several other techniques and advice
]

# Creating a pandas DataFrame
stress_df = pd.DataFrame(stress_management_data)

This database contains relaxation techniques, time management methods, and other strategies to deal with professional stress.

Step 3: Implementing the RAG System

The RAG (Retrieval Augmented Generation) system allows retrieving the most relevant information from our knowledge base:

# Configuring embeddings
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=api_key)

# Preparing documents
documents = []
for _, row in stress_df.iterrows():
    doc_content = f"Title: {row['title']}\nCategory: {row['category']}\nContent: {row['content']}"
    documents.append(doc_content)

# Creating the vector database
vector_db = FAISS.from_documents(chunks, embeddings)

When a user asks a question, our system searches for the most relevant information:

def generate_rag_response(query):
    # Retrieving relevant documents
    relevant_docs = retrieve_relevant_docs(query)
    context = "\n\n".join([doc.page_content for doc in relevant_docs])
    
    # Creating the prompt with context
    prompt = f"""
    You are StressLess, an AI assistant specialized in workplace stress management.
    Use the following context to answer the user's question in an empathetic and helpful way.
    
    Context:
    {context}
    
    User question: {query}
    
    Response:
    """
    
    # Generating the response
    response = model.generate_content(prompt)
    
    return response.text, relevant_docs

Step 4: Implementing Function Calling

“Function Calling” allows our assistant to trigger specific actions:

def breathing_exercise(duration=60, technique="4-7-8"):
    """Function to guide a breathing exercise."""
    techniques = {
        "4-7-8": {
            "description": "Inhale for 4 seconds, hold for 7 seconds, exhale for 8 seconds",
            "benefits": "Reduces anxiety and helps with falling asleep"
        },
        # Other techniques...
    }
    
    return {
        "status": "success",
        "message": f"Started {technique} breathing exercise for {duration} seconds",
        "instructions": techniques[technique]["description"],
        "benefits": techniques[technique]["benefits"]
    }

We have also created functions to schedule breaks and analyze work habits. When the assistant detects that the user could benefit from one of these actions, it can automatically call the appropriate function.

Step 5: Implementing Structured Output

This capability allows for detailed analysis of users’ messages to extract structured information:

# Defining the JSON schema for stress analysis
stress_analysis_schema = {
    "type": "object",
    "properties": {
        "stress_factors": {
            "type": "array",
            "items": {
                # Definition of stress factors
            }
        },
        "symptoms": {
            # Definition of symptoms
        },
        "recommendations": {
            # Definition of recommendations
        },
        # Other properties...
    }
}

# Function to generate structured stress analysis
def generate_structured_analysis(query):
    model = genai.GenerativeModel('gemini-1.5-flash')
    
    prompt = f"""
    You are StressLess, an AI assistant specialized in workplace stress analysis.
    Analyze the user's message and identify stress factors, symptoms, and generate personalized recommendations.
    
    User message: {query}
    
    Respond with a structured JSON object according to the following schema:
    {json.dumps(stress_analysis_schema, indent=2, ensure_ascii=False)}
    """
    
    response = model.generate_content(prompt, generation_config={"response_mime_type": "application/json"})
    
    # Parsing the JSON
    json_response = json.loads(response.text)
    return json_response

Step 6: Creating Visualizations

To make information more accessible, we created visualizations that graphically represent stress analysis:

def visualize_stress_analysis(analysis):
    # Style configuration
    sns.set(style="whitegrid")
    plt.figure(figsize=(15, 10))
    
    # 1. Stress factors visualization
    plt.subplot(2, 2, 1)
    factors = [f["factor"] for f in analysis["stress_factors"]]
    severities = [f["severity"] for f in analysis["stress_factors"]]
    # Code to create a bar chart
    
    # 2. Symptoms visualization
    # 3. Overall stress level visualization
    # 4. Recommendations visualization
    
    plt.tight_layout()
    plt.show()

Step 7: Creating the User Interface

Finally, we developed a user-friendly interface to interact with our assistant:

def create_chat_ui():
    # Initializing StressLess
    stressless = StressLess()
    
    # Creating widgets for the interface
    output = widgets.Output()
    input_box = widgets.Text(placeholder="Type your message here...")
    send_button = widgets.Button(description="Send")
    # Other interface elements
    
    # Welcome message
    with output:
        display(HTML("""<div style='background-color: #f0f0f0; padding: 10px; border-radius: 10px;'>
        <b>StressLess:</b> Hello! I am StressLess, your AI workplace stress management assistant. How can I help you today?
        </div>"""))
    
    # Assembling the interface
    ui = widgets.VBox([output, input_area, button_area])
    return ui

Detailed Explanation of How It Works

How the RAG System Works

  1. Transformation of documents into numerical vectors (embeddings)
  2. Conversion of user questions into similar vectors
  3. Search for the semantically closest documents
  4. Use of these documents as context to generate a precise response

This approach allows the assistant to provide responses based on reliable information, rather than simply generating text without reference.

How Function Calling Works

  1. Analysis of the user message to detect specific intentions or needs
  2. Identification of the appropriate function to call
  3. Execution of this function with relevant parameters
  4. Presentation of the result to the user in a conversational manner

For example, if the user mentions feeling anxious, the assistant can trigger a guided breathing exercise to help them calm down.

How Structured Output Works

  1. In-depth analysis of the message to identify stress factors and their severity
  2. Detection of physical, emotional, and cognitive symptoms
  3. Organization of data in a structured format
  4. Generation of personalized recommendations based on this analysis
  5. Creation of visualizations to represent data intuitively

This capability allows for a detailed understanding of the user’s stress situation.

Result: A Personalized Assistant for Stress Management

The integration of these three AI capabilities allows StressLess to:

  1. Provide accurate and relevant information on stress management
  2. Offer practical interventions such as breathing exercises
  3. Analyze individual stress factors in depth
  4. Visualize data for better understanding
  5. Provide personalized recommendations adapted to each situation

Usage Examples

Here are some examples of interactions with StressLess:

  • “How can I manage stress related to tight deadlines at work?”
  • “I need an exercise to calm down quickly during a meeting.”
  • “Can you analyze my stress level? I feel overwhelmed by my projects and I’m not sleeping well.”
  • “Schedule an effective break for me this afternoon.”

Potential Future Improvements

This project could be enriched in several ways:

  • Integration with biometric sensors for objective stress detection
  • Development of a mobile application for permanent access
  • Expansion of the knowledge base with recent scientific research
  • Addition of longitudinal tracking features to observe stress evolution over time
  • Integration with calendars and productivity tools

Conclusion

StressLess illustrates how generative AI technologies can be applied to create concrete solutions to real problems. By combining RAG, Function Calling, and Structured Output, we have developed an assistant capable of providing personalized support for workplace stress management.

This project also demonstrates the potential of AI to improve well-being and mental health in a professional context. The technical skills you have acquired by creating this project can be applied to many other areas where AI can have a positive impact on society.

Feel free to explore the complete Kaggle notebook to see all implementation details and perhaps even develop your own improved version of StressLess!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *