# Response Generation Pipeline
```mermaid
flowchart LR
A[User Message] --> B[Preprocess Input
trim text, detect follow-up,
enrich with history]
B --> C{Empty or
Self-harm Risk?}
C -->|Empty| D[Return supportive default reply]
C -->|Self-harm risk| E[Return crisis-support reply]
C -->|No| F[Intent Detection
detect_intent()]
F --> G[Topic Detection
detect_topic()]
G --> H{Fast-path
known menstrual topic?}
H -->|Yes| I[Template Reply
build_specific_topic_reply()]
I --> Z[Safety Constraints + Cleanup
apply_safety_constraints()
cleanup_reply()]
H -->|No| J{Run Emotion Model?}
J -->|Yes| K[Emotion Classification
GoEmotions RoBERTa
emotion bucket + prefix]
J -->|No| L[Skip emotion inference]
K --> M{Run KB Retrieval?}
L --> M
M -->|Yes| N[Knowledge Base Search
top-k chunk retrieval]
N --> O[Build Context
KB answer or RAG context]
M -->|No| P[No external context]
O --> Q{Response Composition Logic}
P --> Q
Q -->|Calming intent| R[Calming steps reply]
Q -->|Out of scope| S[Scope-limited reply]
Q -->|Follow-up + previous topic| T[Follow-up reply]
Q -->|Known topic template| U[Template-based reply]
Q -->|KB only, no RAG| V[KB grounded reply]
Q -->|Support / affirmation / unknown topic| W[LLM Response
EmpatheticResponder]
Q -->|Info question / symptom + RAG context| X[LLM + RAG Response
Flan-T5 + retrieved context]
Q -->|No strong match| Y[Clarifying / fallback reply]
R --> Z
S --> Z
T --> Z
U --> Z
V --> Z
W --> Z
X --> Z
Y --> Z
Z --> AA[Final Chat Reply
reply + emotions + topic + intent + kb_sources]
KB[(KB Documents)] --> N
EM[(Emotion Model
SamLowe/roberta-base-go_emotions)] --> K
LLM[(Response Generator
google/flan-t5-base)] --> W
LLM --> X
```
Source alignment:
- [services/chat_service.py](d:\FYP IMPLEMENTATION\EmpowerHer_Chatbot\services\chat_service.py)
- [models/response_generator.py](d:\FYP IMPLEMENTATION\EmpowerHer_Chatbot\models\response_generator.py)
- [services/kb_retriever.py](d:\FYP IMPLEMENTATION\EmpowerHer_Chatbot\services\kb_retriever.py)