Jul 9 - Chat - Add knowledge base for AI training
This commit is contained in:
+199
-25
@@ -7,12 +7,13 @@ from flask_login import login_required, current_user
|
||||
|
||||
from app import db
|
||||
from app.models.support import (SupportTicket, SupportTicketReply,
|
||||
SupportChatSession, SupportChatMessage)
|
||||
SupportChatSession, SupportChatMessage,
|
||||
SupportKnowledge)
|
||||
from app.models.user import User
|
||||
from app.models.facility import Facility
|
||||
from app.utils.decorators import supervisor_required
|
||||
from app.utils.scope import get_customer_scope
|
||||
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE
|
||||
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE
|
||||
from app.utils.time_utils import now_eastern
|
||||
from app.utils.notifications import notify
|
||||
|
||||
@@ -22,37 +23,132 @@ logger = logging.getLogger(__name__)
|
||||
# ── Groq system prompt ────────────────────────────────────────────────────────
|
||||
|
||||
_SYSTEM_PROMPT = """\
|
||||
You are JQC Support, a friendly assistant for customers of JQC (Janitorial Quality Control), \
|
||||
a commercial cleaning quality management platform.
|
||||
You are JQC Support, a friendly assistant for CUSTOMERS of JQC (Janitorial Quality \
|
||||
Control), a commercial cleaning quality-management platform used by a janitorial \
|
||||
service provider and its clients. You help the client (customer) understand and use \
|
||||
their portal. Only describe what a CUSTOMER can do — do not tell customers they can \
|
||||
perform staff-only actions (assigning issues, running inspections, editing templates, \
|
||||
managing users, notification matrix, etc.).
|
||||
|
||||
Help customers with:
|
||||
- Navigating the portal: Dashboard, Inspections, Issues, Reports pages
|
||||
- Inspection scores: 90%+ = Excellent, 70-89% = Satisfactory, below 70% = Needs Improvement
|
||||
- SLA timelines: Critical issues = 4 h, High = 24 h, Medium = 72 h, Low = 168 h
|
||||
- Issue statuses: Open → In Progress → Pending Verification → Resolved
|
||||
- Following issues to receive email/in-app update notifications
|
||||
- Reporting new cleaning concerns via the Issues > Log Issue page
|
||||
- Understanding facility scorecards and trend charts in Reports
|
||||
=== WHAT JQC DOES ===
|
||||
The janitorial provider performs quality inspections of the customer's facilities \
|
||||
against checklist templates, tracks any problems ("issues"), and shares scores and \
|
||||
reports. Work is organized as: Contracts → Facilities → Areas. A customer only sees \
|
||||
the facilities they are assigned to.
|
||||
|
||||
Rules:
|
||||
- Keep answers concise (3-5 sentences max) and friendly.
|
||||
- Never invent specific staff names, contract prices, schedules, or contact numbers.
|
||||
- If the customer has an access problem, billing question, or a concern you genuinely \
|
||||
cannot resolve through guidance, say so clearly and suggest they click \
|
||||
"Submit to Support" to reach the admin team directly.\
|
||||
=== CUSTOMER PORTAL NAVIGATION ===
|
||||
- Dashboard: at-a-glance cards — open issues (split by who handles them), issues \
|
||||
opened/resolved today, recent inspections, and a "Your Facilities" panel with search.
|
||||
- Facilities: the customer's assigned facilities; open one to see its details, areas, \
|
||||
scorecard, and QR code.
|
||||
- Inspections: completed and in-progress inspections at their facilities, with scores; \
|
||||
open one to see the checklist results and any flagged issues.
|
||||
- Issues: all cleaning issues at their facilities; filter by status, severity, facility, \
|
||||
date. Customers can log a new issue here.
|
||||
- Reports: facility scorecards, score trends, "Avg Score by Facility" (filterable by \
|
||||
Contract), and downloadable PDF summaries.
|
||||
- Support: this AI chat (Ask a Question), My Conversations (saved chats), and \
|
||||
My Requests (support tickets they submitted).
|
||||
|
||||
=== INSPECTION SCORES ===
|
||||
Each completed inspection has an overall score (0–100%). Interpretation:
|
||||
- 90%+ = Excellent, 80–89% = Good, 70–79% = Fair/Satisfactory, below 70% = Needs Improvement.
|
||||
Scorecards and the Reports page show a facility's average score and its trend over time. \
|
||||
Note: checklist items left unanswered (score 0) are excluded from the average.
|
||||
|
||||
=== ISSUES ===
|
||||
- Lifecycle (status): Open → In Progress → Pending Verification → Resolved.
|
||||
- Severity: Critical, High, Medium, Low — this drives the SLA (resolution target).
|
||||
- "Handled By" tells you who is resolving it:
|
||||
* Janitorial Staff — the cleaning provider's own crew.
|
||||
* Facility Staff — the facility's own on-site staff are handling it.
|
||||
* External Vendor — an outside contractor was engaged.
|
||||
In every case a member of the provider's team stays responsible for following up and \
|
||||
verifying the fix.
|
||||
- A customer can LOG a new issue (Issues → Log Issue / "Report a cleaning concern"): \
|
||||
pick the facility, describe the problem, set severity, optionally attach a photo. \
|
||||
Customers cannot assign issues to staff — the provider triages them.
|
||||
- FOLLOW an issue (the Follow button on the issue page) to get email + in-app \
|
||||
notifications whenever its status changes. Customers can also comment on issues they \
|
||||
reported or follow.
|
||||
|
||||
=== SLA (resolution targets by severity) ===
|
||||
Critical = 4 hours, High = 24 hours, Medium = 72 hours, Low = 168 hours (7 days). \
|
||||
These are targets measured from when the issue was reported; the system flags issues \
|
||||
that are at risk of, or have passed, their SLA.
|
||||
|
||||
=== FACILITY QR CODES ===
|
||||
Every facility has a printable QR code (from the facility's page, or "Print All QR \
|
||||
Codes" on the Facilities page). Anyone can scan it — no login — to see the facility's \
|
||||
recent cleaning quality and to "Report a Problem" (which files an issue). Customers can \
|
||||
view, print, and regenerate their facilities' QR codes; regenerating invalidates any \
|
||||
previously printed code, so it must be reprinted.
|
||||
|
||||
=== NOTIFICATIONS ===
|
||||
Customers get in-app (bell icon) and email notifications for relevant events — e.g. an \
|
||||
inspection completed at their facility, or updates on issues they follow/reported. \
|
||||
Notification Preferences let a customer turn specific email types off or switch to a \
|
||||
digest.
|
||||
|
||||
=== GETTING HUMAN HELP ===
|
||||
If the customer needs something this chat can't resolve — an access/login problem, a \
|
||||
billing question, a specific scheduling request, or a concern that needs a person — tell \
|
||||
them clearly and point them to the "Submit to Support" button (top of the chat), which \
|
||||
opens a request that the provider's admin team answers by email and in "My Requests".
|
||||
|
||||
=== STYLE & RULES ===
|
||||
- Be concise, warm, and practical. Prefer short paragraphs or numbered steps.
|
||||
- Ground answers in the features above. If you are not sure or the app may differ, say \
|
||||
so honestly rather than guessing — and suggest "Submit to Support".
|
||||
- NEVER invent specific staff names, contract prices, cleaning schedules, phone numbers, \
|
||||
facility data, or scores. You do not have access to the customer's live data — guide \
|
||||
them to where to find it in the portal instead.
|
||||
- Do not claim to perform actions yourself; explain where in the portal the customer does it.\
|
||||
"""
|
||||
|
||||
# Preset FAQ questions shown as quick-reply chips on first load
|
||||
FAQS = [
|
||||
{'icon': 'bi-clipboard-check', 'text': 'How do I view my inspection reports?'},
|
||||
{'icon': 'bi-graph-up', 'text': 'What do inspection scores mean?'},
|
||||
{'icon': 'bi-exclamation-circle','text': 'How do I track an open issue?'},
|
||||
{'icon': 'bi-megaphone', 'text': 'How do I report a cleaning concern?'},
|
||||
{'icon': 'bi-alarm', 'text': 'What is SLA and how does it work?'},
|
||||
{'icon': 'bi-bell', 'text': 'How do I get notified on issue updates?'},
|
||||
{'icon': 'bi-clipboard-check', 'text': 'How do I view my inspection reports?'},
|
||||
{'icon': 'bi-graph-up', 'text': 'What do inspection scores mean?'},
|
||||
{'icon': 'bi-exclamation-circle','text': 'How do I track or follow an issue?'},
|
||||
{'icon': 'bi-megaphone', 'text': 'How do I report a cleaning concern?'},
|
||||
{'icon': 'bi-alarm', 'text': 'What is SLA and how does it work?'},
|
||||
{'icon': 'bi-people', 'text': 'What does "Handled By" mean on an issue?'},
|
||||
{'icon': 'bi-qr-code', 'text': "How do I print my facility's QR code?"},
|
||||
{'icon': 'bi-bell', 'text': 'How do I get notified on issue updates?'},
|
||||
]
|
||||
|
||||
|
||||
# Soft cap on injected knowledge to keep prompt size (and token cost) reasonable.
|
||||
_KB_MAX_CHARS = 6000
|
||||
|
||||
|
||||
def _system_prompt_with_kb():
|
||||
"""Return the base system prompt plus all ACTIVE admin knowledge entries
|
||||
(phase38), so staff can curate the chatbot's knowledge without code changes.
|
||||
Best-effort — a KB failure never breaks the chat."""
|
||||
prompt = _SYSTEM_PROMPT
|
||||
try:
|
||||
entries = (SupportKnowledge.query
|
||||
.filter_by(active=True)
|
||||
.order_by(SupportKnowledge.sort_order.asc(), SupportKnowledge.id.asc())
|
||||
.all())
|
||||
if entries:
|
||||
parts = ["\n\n=== ADDITIONAL KNOWLEDGE (curated by the JQC team; "
|
||||
"treat as authoritative and prefer it over general guesses) ==="]
|
||||
total = 0
|
||||
for e in entries:
|
||||
block = f"\n\nTopic: {e.title}\n{e.content.strip()}"
|
||||
if total + len(block) > _KB_MAX_CHARS:
|
||||
break
|
||||
parts.append(block)
|
||||
total += len(block)
|
||||
prompt += ''.join(parts)
|
||||
except Exception as exc:
|
||||
logger.warning('SUPPORT | knowledge-base load failed: %s', exc)
|
||||
return prompt
|
||||
|
||||
|
||||
# ── Customer chat page ────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/chat')
|
||||
@@ -117,7 +213,7 @@ def chat_message():
|
||||
from groq import Groq
|
||||
client = Groq(api_key=api_key)
|
||||
|
||||
messages = [{'role': 'system', 'content': _SYSTEM_PROMPT}]
|
||||
messages = [{'role': 'system', 'content': _system_prompt_with_kb()}]
|
||||
# Append prior conversation (cap at last 20 turns to control token usage)
|
||||
for m in history[-20:]:
|
||||
if m.get('role') in ('user', 'assistant') and m.get('content'):
|
||||
@@ -416,6 +512,84 @@ def admin_conversation_detail(session_id):
|
||||
session=session, messages=messages)
|
||||
|
||||
|
||||
# ── Admin: AI chatbot Knowledge Base ──────────────────────────────────────────
|
||||
|
||||
@bp.route('/admin/knowledge')
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def admin_knowledge():
|
||||
entries = (SupportKnowledge.query
|
||||
.order_by(SupportKnowledge.sort_order.asc(), SupportKnowledge.id.asc())
|
||||
.all())
|
||||
groq_ready = bool(os.environ.get('GROQ_API_KEY'))
|
||||
return render_template('support/admin_knowledge.html',
|
||||
entries=entries, groq_ready=groq_ready)
|
||||
|
||||
|
||||
@bp.route('/admin/knowledge/new', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def admin_knowledge_new():
|
||||
from app.utils.forms import SupportKnowledgeForm
|
||||
form = SupportKnowledgeForm()
|
||||
if form.validate_on_submit():
|
||||
entry = SupportKnowledge(
|
||||
title = form.title.data.strip(),
|
||||
content = form.content.data.strip(),
|
||||
sort_order = form.sort_order.data or 0,
|
||||
active = form.active.data,
|
||||
created_by = current_user.id,
|
||||
created_at = now_eastern(),
|
||||
updated_at = now_eastern(),
|
||||
)
|
||||
db.session.add(entry)
|
||||
db.session.commit()
|
||||
log_action(ACTION_CREATE, 'SupportKnowledge', entry.id, entry.title[:60])
|
||||
flash('Knowledge entry added. The chatbot will use it immediately.', 'success')
|
||||
return redirect(url_for('support.admin_knowledge'))
|
||||
return render_template('support/admin_knowledge_form.html',
|
||||
form=form, title='New Knowledge Entry')
|
||||
|
||||
|
||||
@bp.route('/admin/knowledge/<int:entry_id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def admin_knowledge_edit(entry_id):
|
||||
from app.utils.forms import SupportKnowledgeForm
|
||||
entry = db.session.get(SupportKnowledge, entry_id)
|
||||
if entry is None:
|
||||
abort(404)
|
||||
form = SupportKnowledgeForm(obj=entry)
|
||||
if form.validate_on_submit():
|
||||
entry.title = form.title.data.strip()
|
||||
entry.content = form.content.data.strip()
|
||||
entry.sort_order = form.sort_order.data or 0
|
||||
entry.active = form.active.data
|
||||
entry.updated_at = now_eastern()
|
||||
db.session.commit()
|
||||
log_action(ACTION_UPDATE, 'SupportKnowledge', entry.id, entry.title[:60])
|
||||
flash('Knowledge entry updated.', 'success')
|
||||
return redirect(url_for('support.admin_knowledge'))
|
||||
return render_template('support/admin_knowledge_form.html',
|
||||
form=form, title='Edit Knowledge Entry', entry=entry)
|
||||
|
||||
|
||||
@bp.route('/admin/knowledge/<int:entry_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def admin_knowledge_delete(entry_id):
|
||||
entry = db.session.get(SupportKnowledge, entry_id)
|
||||
if entry is None:
|
||||
abort(404)
|
||||
label = entry.title[:60]
|
||||
eid = entry.id
|
||||
db.session.delete(entry)
|
||||
db.session.commit()
|
||||
log_action(ACTION_DELETE, 'SupportKnowledge', eid, label)
|
||||
flash('Knowledge entry deleted.', 'success')
|
||||
return redirect(url_for('support.admin_knowledge'))
|
||||
|
||||
|
||||
def _notify_customer_reply(ticket, reply):
|
||||
"""Create an in-app notification and send an email to the customer."""
|
||||
if not ticket.customer:
|
||||
|
||||
Reference in New Issue
Block a user