Simplify model selection for both embeddings and LLM. Editing capabilities for new tenant columns...

This commit is contained in:
Josako
2024-05-13 14:58:21 +02:00
parent 011bdce38d
commit adee283d7a
10 changed files with 98 additions and 119 deletions

View File

@@ -3,6 +3,7 @@ import uuid
from datetime import datetime as dt, timezone as tz
from flask import request, redirect, url_for, flash, render_template, Blueprint, session, current_app
from flask_security import hash_password, roles_required, roles_accepted
from sqlalchemy.exc import SQLAlchemyError
from common.models.user import User, Tenant, Role
from common.extensions import db
@@ -15,82 +16,46 @@ user_bp = Blueprint('user_bp', __name__, url_prefix='/user')
@user_bp.route('/tenant', methods=['GET', 'POST'])
@roles_required('Super User')
def tenant():
if request.method == 'POST':
# Handle the required attributes
name = request.form.get('name')
website = request.form.get('website')
error = None
if not name:
error = 'Tenant name is required.'
elif not website:
error = 'Tenant website is required.'
# Create new tenant if there is no error
if error is None:
new_tenant = Tenant(name=name, website=website)
# Handle optional attributes
lic_start = request.form.get('license_start_date')
lic_end = request.form.get('license_end_date')
monthly = request.form.get('allowed_monthly_interactions')
# language fields
default_language = request.form.get('default_language')
allowed_languages = request.form.getlist('allowed_languages')
if default_language != '':
new_tenant.default_language = default_language
if allowed_languages != '':
new_tenant.allowed_languages = allowed_languages
# LLM fields
default_embedding = request.form.get('default_embedding')
allowed_embeddings = request.form.getlist('allowed_embeddings')
if default_embedding != '':
new_tenant.default_embedding = default_embedding
if allowed_embeddings != '':
new_tenant.allowed_embeddings = allowed_embeddings
default_llm_model = request.form.get('default_llm_model')
allowed_llm_models = request.form.getlist('allowed_llm_models')
if default_llm_model != '':
new_tenant.default_llm_model = default_llm_model
if allowed_llm_models != '':
new_tenant.allowed_llm_models = allowed_llm_models
# license data
if lic_start != '':
new_tenant.license_start_date = dt.strptime(lic_start, '%Y-%m-%d')
if lic_end != '':
new_tenant.license_end_date = dt.strptime(lic_end, '%Y-%m-%d')
if monthly != '':
new_tenant.allowed_monthly_interactions = int(monthly)
# Handle Timestamps
timestamp = dt.now(tz.utc)
new_tenant.created_at = timestamp
new_tenant.updated_at = timestamp
# Add the new tenant to the database and commit the changes
try:
db.session.add(new_tenant)
db.session.commit()
except Exception as e:
error = e.args
# Create schema for new tenant
if error is None:
current_app.logger.info(f"Successfully created tenant {new_tenant.id} in Database")
current_app.logger.info(f"Creating schema for tenant {new_tenant.id}")
Database(new_tenant.id).create_tenant_schema()
else:
current_app.logger.error(f"Error creating tenant: {error}")
flash(error) if error else flash('Tenant added successfully.')
form = TenantForm()
if form.validate_on_submit():
# Handle the required attributes
new_tenant = Tenant(name=form.name.data,
website=form.website.data,
default_language=form.default_language.data,
allowed_languages=form.allowed_languages.data,
embedding_model=form.embedding_model.data,
llm_model=form.llm_model.data,
licence_start_date=form.license_start_date.data,
lic_end_date=form.license_end_date.data,
allowed_monthly_interactions=form.allowed_monthly_interactions.data)
# Handle Embedding Variables
new_tenant.html_tags = form.html_tags.data.split(',') if form.html_tags.data else [],
new_tenant.html_end_tags = form.html_end_tags.data.split(',') if form.html_end_tags.data else [],
new_tenant.html_included_elements = form.html_included_elements.data.split(',') if form.html_included_elements.data else [],
new_tenant.html_excluded_elements = form.html_excluded_elements.data.split(',') if form.html_excluded_elements.data else []
# Handle Timestamps
timestamp = dt.now(tz.utc)
new_tenant.created_at = timestamp
new_tenant.updated_at = timestamp
# Add the new tenant to the database and commit the changes
try:
db.session.add(new_tenant)
db.session.commit()
except SQLAlchemyError as e:
current_app.logger.error(f'Failed to add tenant to database. Error: {str(e)}')
flash(f'Failed to add tenant to database. Error: {str(e)}')
return render_template('user/tenant.html', form=form)
# Create schema for new tenant
current_app.logger.info(f"Successfully created tenant {new_tenant.id} in Database")
flash(f"Successfully created tenant {new_tenant.id} in Database")
current_app.logger.info(f"Creating schema for tenant {new_tenant.id}")
Database(new_tenant.id).create_tenant_schema()
return redirect(url_for('basic_bp.index'))
return render_template('user/tenant.html', form=form)
@@ -100,11 +65,30 @@ def edit_tenant(tenant_id):
tenant = Tenant.query.get_or_404(tenant_id) # This will return a 404 if no tenant is found
form = TenantForm(obj=tenant)
if request.method == 'GET':
# Populate the form with tenant data
form.populate_obj(tenant)
if tenant.html_tags:
form.html_tags.data = ', '.join(tenant.html_tags)
if tenant.html_end_tags:
form.html_end_tags.data = ', '.join(tenant.html_end_tags)
if tenant.html_included_elements:
form.html_included_elements.data = ', '.join(tenant.html_included_elements)
if tenant.html_excluded_elements:
form.html_excluded_elements.data = ', '.join(tenant.html_excluded_elements)
if request.method == 'POST' and form.validate_on_submit():
# Populate the tenant with form data
form.populate_obj(tenant)
# Then handle the special fields manually
tenant.html_tags = [tag.strip() for tag in form.html_tags.data.split(',') if tag.strip()]
tenant.html_end_tags = [tag.strip() for tag in form.html_end_tags.data.split(',') if tag.strip()]
tenant.html_included_elements = [elem.strip() for elem in form.html_included_elements.data.split(',') if
elem.strip()]
tenant.html_excluded_elements = [elem.strip() for elem in form.html_excluded_elements.data.split(',') if
elem.strip()]
db.session.commit()
print(session)
flash('Tenant updated successfully.', 'success')
if session.get('tenant'):
if session['tenant'].get('id') == tenant_id:
@@ -215,14 +199,17 @@ def handle_tenant_selection():
the_tenant = Tenant.query.get(tenant_id)
session['tenant'] = the_tenant.to_dict()
session['default_language'] = the_tenant.default_language
session['default_embedding_model'] = the_tenant.default_embedding_model
session['default_llm_model'] = the_tenant.default_llm_model
session['embedding_model'] = the_tenant.embedding_model
session['llm_model'] = the_tenant.llm_model
action = request.form['action']
if action == 'view_users':
return redirect(url_for('user_bp.view_users', tenant_id=tenant_id))
elif action == 'edit_tenant':
return redirect(url_for('user_bp.edit_tenant', tenant_id=tenant_id))
match action:
case 'view_users':
return redirect(url_for('user_bp.view_users', tenant_id=tenant_id))
case 'edit_tenant':
return redirect(url_for('user_bp.edit_tenant', tenant_id=tenant_id))
case 'select_tenant':
return redirect(url_for('basic_bp.session_defaults'))
# Add more conditions for other actions
return redirect(url_for('select_tenant'))