Guide to How to code a basic Artificial Intelligence stress-relief companion
How to Code a Basic Artificial Intelligence Stress‑Relief Companion
A step‑by‑step tutorial that lets you build a friendly AI that listens, offers calming tips, and helps users unwind.
Introduction
Everyone needs a moment of calm during a hectic day. In this guide you create a lightweight AI companion that detects stress signals, replies with soothing language, and suggests simple relaxation techniques. The project uses Python, the transformers library for natural‑language understanding, and a tiny Flask web front‑end for an interactive experience.
What You Need
- Python 3.9 or newer
- Basic knowledge of
pipand virtual environments - A code editor (VS Code, PyCharm, etc.)
- Internet connection for model download
requirements.txt tidy. It makes future updates painless.
1. Set Up the Development Environment
Create an isolated environment to avoid dependency conflicts.
python -m venv ai‑companion
source ai‑companion/bin/activate # On Windows: ai‑companion\Scripts\activate
pip install --upgrade pip
pip install transformers torch flask
Save the package list for later reference:
pip freeze > requirements.txt
2. Design the Conversation Flow
The companion follows three simple states:
- Greeting – Warm hello and invitation to share feelings.
- Detection – Identify stress keywords or sentiment.
- Response – Offer calming suggestions or a brief meditation.
“You seem a bit tense today. Would you like a 30‑second breathing exercise?”
3. Build the NLP Core
We use a distilled BERT model for sentiment analysis because it’s fast and accurate enough for short user inputs.
# nlp_core.py
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
class StressDetector:
def __init__(self):
self.tokenizer = AutoTokenizer.from_pretrained(
"distilbert-base-uncased-finetuned-sst-2-english"
)
self.model = AutoModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased-finetuned-sst-2-english"
)
def is_stressed(self, text: str) -> bool:
inputs = self.tokenizer(text, return_tensors="pt", truncation=True)
with torch.no_grad():
logits = self.model(**inputs).logits
prob = torch.softmax(logits, dim=1)[0][1].item() # probability of "positive" (stress) sentiment
return prob > 0.6 # adjust threshold as needed
The detector returns True when the sentiment leans toward stress, allowing the companion to trigger a soothing response.
4. Create the Companion Logic
This module combines greeting, detection, and response.
# companion.py
from nlp_core import StressDetector
import random
import time
detector = StressDetector()
greetings = [
"Hey there! How are you feeling today?",
"Hello! I'm here to listen. What's on your mind?"
]
relax_tips = [
"Take a slow, deep breath… In… Hold… Out… Repeat three times.",
"Try a quick stretch: raise your arms, roll your shoulders, and release.",
"Listen to a calming sound for 30 seconds. Close your eyes if you can."
]
def get_response(user_input: str) -> str:
if detector.is_stressed(user_input):
return random.choice(relax_tips)
return "I hear you. Let me know if you’d like a relaxation tip."
The function get_response() can be called from a web route, a CLI, or a chatbot platform.
5. Add a Simple Flask Front‑End
Flask gives us a clean, interactive web card where users type their feelings and receive instant feedback.
# app.py
from flask import Flask, render_template_string, request
from companion import get_response, greetings
app = Flask(__name__)
HTML = """
AI Stress‑Relief Companion
AI Companion
{{ greeting }}
{% if reply %}
You: {{ user_msg }}
Companion: {{ reply }}
{% endif %}
"""
@app.route("/", methods=["GET", "POST"])
def index():
reply = None
user_msg = ""
if request.method == "POST":
user_msg = request.form["msg"]
reply = get_response(user_msg)
return render_template_string(HTML, greeting=random.choice(greetings), reply=reply, user_msg=user_msg)
if __name__ == "__main__":
app.run(debug=True)
Run the app with python app.py. Open http://127.0.0.1:5000 to start chatting.
6. Test and Refine
Effective AI companions need real‑world feedback. Follow these steps:
| Step | Action |
|---|---|
| 1️⃣ | Gather 10‑15 sample sentences that express stress, calm, or neutral moods. |
| 2️⃣ | Run each through detector.is_stressed() and note false positives/negatives. |
| 3️⃣ | Adjust the probability threshold in is_stressed() until accuracy feels acceptable. |
| 4️⃣ | Add or replace tips in relax_tips to match your audience. |
7. Extend the Companion (Optional)
- Voice Input/Output: Integrate
SpeechRecognitionandpyttsx3for hands‑free interaction. - Personalization: Store user preferences in a lightweight SQLite DB and adapt tips over time.
- Advanced Emotion Detection: Swap the SST‑2 model for
facebook/blenderbot-400M-distilland add intent classification. - Progressive Web App: Wrap the Flask front‑end with
Flask‑PWAto make it installable on mobile.
Conclusion
You now have a fully functional AI stress‑relief companion built with Python, a compact BERT model, and a clean Flask UI. The project demonstrates how natural‑language sentiment detection can power simple, empathetic interactions without heavy infrastructure.
Keep the experience gentle, iterate based on feedback, and watch your companion become a trusted calm‑corner for anyone who needs a quick mental reset.
Comments
Post a Comment