by It’s Fred
AI Narrative Therapy
import logging
from gunicorn.app.base import BaseApplication
from app_init import create_initialized_flask_app
# Flask app creation should be done by create_initialized_flask_app to avoid circular dependency problems.
app = create_initialized_flask_app()
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class StandaloneApplication(BaseApplication):
def __init__(self, app, options=None):
self.application = app
self.options = options or {}
super().__init__()
def load_config(self):
# Apply configuration to Gunicorn
for key, value in self.options.items():
if key in self.cfg.settings and value is not None:
self.cfg.set(key.lower(), value)
def load(self):
Created: | Last Updated:
Introduction to the Template
The "AI Narrative Therapy" template allows you to create a web application where users can engage in narrative therapy via chat. This template includes a mobile and desktop header, a chat interface, and backend logic to handle user messages and generate AI responses.
Clicking Start with this Template
To get started with the "AI Narrative Therapy" template, click Start with this Template in the Lazy Builder interface.
Test
After starting with the template, press the Test button to deploy the app. This will launch the Lazy CLI, which will handle the deployment process.
Entering Input
The app requires user input through the chat interface. Users will type their messages, and the AI will respond based on narrative therapy principles. No additional user input is required through the CLI.
Using the App
Once the app is deployed, you can interact with it through the chat interface. Here’s how to use the app:
- Open the App: Navigate to the provided link after deployment.
- Chat Interface: You will see a chat interface where you can type your messages.
- Send Messages: Type your message in the input box and click the Send button. The AI will respond to your message in the chat window.
Integrating the App
If you need to integrate the app with other tools or services, follow these steps:
-
API Integration: The app provides an endpoint for chat interactions. You can use this endpoint to send and receive messages programmatically.
- Sample Request:
json POST /chat { "message": "Hello, I need help with my anxiety." }
- Sample Response:
json { "response": "Hello, I'm here to help. Can you tell me more about what you're experiencing?" }
- Sample Request:
-
External Tools: If you need to integrate the app with external tools, such as a frontend framework or another backend service, use the provided API endpoint. Ensure you handle the API responses appropriately in your integration.
Code Overview
Here’s a brief overview of the key components in the template:
_mobile_header.html
```html
```
_desktop_header.html
```html
```
_header.html
```html
```
home.html
```html
```
script.js
```javascript document.addEventListener('DOMContentLoaded', () => { const mobileMenuButton = document.getElementById('mobile-menu-button'); const mobileMenu = document.getElementById('mobile-menu'); const chatForm = document.getElementById('chat-form'); const userInput = document.getElementById('user-input'); const chatMessages = document.getElementById('chat-messages');
mobileMenuButton.addEventListener('click', () => {
mobileMenu.classList.toggle('hidden');
});
// Close mobile menu when clicking outside
document.addEventListener('click', (event) => {
if (!mobileMenu.contains(event.target) && !mobileMenuButton.contains(event.target)) {
mobileMenu.classList.add('hidden');
}
});
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
const message = userInput.value.trim();
if (message) {
addMessageToChat('user', message);
userInput.value = '';
const response = await sendMessageToServer(message);
addMessageToChat('ai', response);
}
});
function addMessageToChat(sender, message) {
const messageElement = document.createElement('div');
messageElement.classList.add('mb-2', 'p-2', 'rounded');
messageElement.classList.add(sender === 'user' ? 'bg-blue-100' : 'bg-gray-100');
messageElement.textContent = message;
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
async function sendMessageToServer(message) {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});
const data = await response.json();
return data.response;
} catch (error) {
console.error('Error:', error);
return 'Sorry, there was an error processing your request.';
}
}
}); ```
main.py
```python import logging from gunicorn.app.base import BaseApplication from app_init import create_initialized_flask_app
Flask app creation should be done by create_initialized_flask_app to avoid circular dependency problems.
app = create_initialized_flask_app()
Setup logging
logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name)
class StandaloneApplication(BaseApplication): def init(self, app, options=None): self.application = app self.options = options or {} super().init()
def load_config(self):
# Apply configuration to Gunicorn
for key, value in self.options.items():
if key in self.cfg.settings and value is not None:
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if name == "main": options = { "bind": "0.0.0.0:8080", "workers": 4, "loglevel": "info", "accesslog": "-" } StandaloneApplication(app, options).run() ```
routes.py
```python from flask import render_template, request, jsonify from flask import current_app as app
def register_routes(app): @app.route("/") def home_route(): return render_template("home.html")
@app.route("/chat", methods=["POST"])
def chat():
data = request.json
user_message = data.get("message")
ai_response = generate_ai_response(user_message)
return jsonify({"response": ai_response})
from abilities import llm_prompt
def generate_ai_response(user_message): prompt = f"""You are a professional therapist specializing in narrative psychotherapy. Respond to the following message from a client in a way that aligns with narrative therapy principles:
Client: {user_message}
Therapist:"""
response = llm_prompt(prompt=prompt, model="gpt-4o", temperature=0.7)
return response
```
app_init.py
```python from flask import Flask from routes import register_routes
The app initialization must be done in this module to avoid circular dependency problems.
def create_initialized_flask_app(): # DO NOT INSTANTIATE THE FLASK APP IN ANOTHER MODULE. app = Flask(name, static_folder='static')
# Initialize database
# from models import db
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
# db.init_app(app)
# DO NOT INITIALIZE db IN ANOTHER MODULE.
# Initialize migrations
# Just write SQL queries for example to add a column to an existing table if missing
register_routes(app)
return app
```
requirements.txt
Flask
Flask-Static-Compress
flask-static-compress
flask==3.0.1
gunicorn
werkzeug==3.0.1
By following these steps, you can successfully deploy and use the "AI Narrative Therapy" template on the Lazy platform.