Girish Jeswani commited on
Commit
759a72f
·
unverified ·
2 Parent(s): 0ba69dbeff2f84

Merge pull request #76 from sohank-17/girish-database-feature

Browse files
Files changed (38) hide show
  1. README.md +348 -127
  2. multi_llm_chatbot_backend/README.md +178 -0
  3. multi_llm_chatbot_backend/app/api/README.md +175 -0
  4. multi_llm_chatbot_backend/app/api/routes/auth.py +130 -0
  5. multi_llm_chatbot_backend/app/api/routes/chat.py +276 -128
  6. multi_llm_chatbot_backend/app/api/routes/chat_sessions.py +258 -0
  7. multi_llm_chatbot_backend/app/api/routes/debug.py +2 -1
  8. multi_llm_chatbot_backend/app/api/routes/documents.py +334 -49
  9. multi_llm_chatbot_backend/app/api/routes/sessions.py +231 -20
  10. multi_llm_chatbot_backend/app/api/utils.py +115 -9
  11. multi_llm_chatbot_backend/app/core/README.md +200 -0
  12. multi_llm_chatbot_backend/app/core/auth.py +116 -0
  13. multi_llm_chatbot_backend/app/core/database.py +66 -0
  14. multi_llm_chatbot_backend/app/core/improved_orchestrator.py +121 -15
  15. multi_llm_chatbot_backend/app/llm/README.md +173 -0
  16. multi_llm_chatbot_backend/app/main.py +29 -10
  17. multi_llm_chatbot_backend/app/models/README.md +140 -0
  18. multi_llm_chatbot_backend/app/models/default_personas.py +882 -16
  19. multi_llm_chatbot_backend/app/models/user.py +89 -0
  20. multi_llm_chatbot_backend/app/utils/README.md +142 -0
  21. multi_llm_chatbot_backend/requirements.txt +27 -2
  22. phd-advisor-frontend/package-lock.json +1190 -13
  23. phd-advisor-frontend/package.json +1 -0
  24. phd-advisor-frontend/src/App.js +68 -33
  25. phd-advisor-frontend/src/components/AdvisorStatusDropdown.js +339 -0
  26. phd-advisor-frontend/src/components/EnhancedChatInput.js +5 -1
  27. phd-advisor-frontend/src/components/ExportButton.js +92 -71
  28. phd-advisor-frontend/src/components/FileUpload.js +47 -2
  29. phd-advisor-frontend/src/components/Login.js +21 -7
  30. phd-advisor-frontend/src/components/MessageBubble.js +186 -17
  31. phd-advisor-frontend/src/components/Sidebar.js +330 -0
  32. phd-advisor-frontend/src/components/Signup.js +26 -8
  33. phd-advisor-frontend/src/data/advisors.js +427 -10
  34. phd-advisor-frontend/src/pages/ChatPage.js +648 -294
  35. phd-advisor-frontend/src/styles/ChatPage.css +433 -40
  36. phd-advisor-frontend/src/styles/ExportButton.css +12 -3
  37. phd-advisor-frontend/src/styles/Sidebar.css +660 -0
  38. phd-advisor-frontend/src/styles/components.css +35 -1
README.md CHANGED
@@ -4,204 +4,419 @@ An AI-powered academic guidance system that provides personalized advice through
4
 
5
  ## Features
6
 
7
- - **Multiple AI Advisor Personas**: Chat with specialized advisors including Methodologist (methodology expert), Theorist (conceptual frameworks), and Pragmatist (action-focused guidance)
8
- - **Document Upload Support**: Upload PDFs, Word documents, and text files to provide context for your questions
9
- - **Multi-LLM Backend**: Supports both Gemini API and Ollama models with seamless provider switching
10
- - **Real-time Chat Interface**: Modern, responsive chat interface with advisor-specific styling
11
- - **Context-Aware Responses**: Maintains conversation history and document context across the session
12
- - **Sequential Advisor Responses**: Get input from all advisors in a structured sequence
13
- - **Individual Advisor Chat**: Have focused conversations with specific advisors
 
14
 
15
  ## Architecture
16
 
17
  ### Frontend (React)
18
  - **Technology**: React 18 with modern hooks and functional components
19
  - **Styling**: CSS custom properties with dark/light theme support
20
- - **Components**: Modular component architecture with reusable UI elements
21
- - **State Management**: React hooks for local state management
22
- - **Icons**: Lucide React for consistent iconography
23
 
24
  ### Backend (FastAPI)
25
  - **Framework**: FastAPI with automatic API documentation
26
- - **LLM Integration**: Support for multiple providers (Gemini, Ollama)
27
- - **Document Processing**: PDF, DOCX, and text file extraction
28
- - **Session Management**: Global session context with file upload tracking
29
- - **CORS Support**: Configured for React development server
 
30
 
31
- ## Quick Start
32
 
33
- ### Prerequisites
34
- - Node.js 16+ and npm
35
- - Python 3.8+
36
- - (Optional) Gemini API key for Google's models
37
- - (Optional) Ollama installation for local models
38
 
39
- ### Backend Setup
 
 
 
40
 
41
- 1. **Clone and navigate to backend directory**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ```bash
43
  cd multi_llm_chatbot_backend
44
  ```
45
 
46
- 2. **Install dependencies**
 
 
 
 
 
 
 
 
 
 
 
 
47
  ```bash
48
  pip install -r requirements.txt
49
  ```
50
 
51
- 3. **Set up environment variables**
52
- Create a `.env` file:
 
53
  ```env
 
 
 
 
 
 
 
 
54
  GEMINI_API_KEY=your_gemini_api_key_here
55
  GEMINI_MODEL=gemini-2.0-flash
 
 
 
 
 
 
56
  ```
57
 
58
- 4. **Start the backend server**
 
 
 
 
 
59
  ```bash
60
  uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
61
  ```
62
 
63
  The API will be available at `http://localhost:8000` with interactive docs at `http://localhost:8000/docs`
64
 
65
- ### Frontend Setup
66
 
67
- 1. **Navigate to frontend directory**
68
  ```bash
69
- cd phd-advisor-frontend
70
  ```
71
 
72
- 2. **Install dependencies**
73
  ```bash
74
  npm install
75
  ```
76
 
77
- 3. **Start the development server**
78
  ```bash
79
  npm start
80
  ```
81
 
82
  The application will open at `http://localhost:3000`
83
 
84
- ## Advisor Personas
85
 
86
- ### Methodologist - Research Methodology Expert
87
- - **Focus**: Research design, validity, sampling, methodological rigor
88
- - **Style**: Precise, analytical, methodology-focused
89
- - **Best for**: Research design questions, data collection methods, validity concerns
90
 
91
- ### Theorist - Conceptual Frameworks Expert
92
- - **Focus**: Theoretical positioning, epistemological assumptions, conceptual clarity
93
- - **Style**: Thoughtful, intellectually rigorous, theory-oriented
94
- - **Best for**: Literature review, theoretical frameworks, conceptual development
 
95
 
96
- ### Pragmatist - Action-Focused Advisor
97
- - **Focus**: Practical next steps, immediate actions, progress over perfection
98
- - **Style**: Warm, motivational, results-oriented
99
- - **Best for**: Getting unstuck, prioritizing tasks, actionable advice
100
 
101
- ## API Endpoints
 
 
 
102
 
103
- ### Core Chat Endpoints
104
- - `POST /chat-sequential` - Get responses from all advisors in sequence
105
- - `POST /chat/{persona_id}` - Chat with a specific advisor
106
- - `POST /reply-to-advisor` - Reply to a specific advisor's message
107
 
108
- ### Document Management
109
- - `POST /upload-document` - Upload documents (PDF, DOCX, TXT)
110
- - `GET /uploaded-files` - List uploaded filenames
111
- - `GET /context` - View current session context
112
 
113
- ### Provider Management
114
- - `GET /current-provider` - Get current LLM provider info
115
- - `POST /switch-provider` - Switch between Gemini and Ollama
 
116
 
117
- ### System
118
- - `GET /debug/personas` - Debug persona configurations
119
- - `GET /` - API health check
120
 
121
- ## Configuration
122
 
123
- ### Supported LLM Providers
 
 
 
 
 
 
 
124
 
125
- **Gemini (Default)**
126
- - Requires GEMINI_API_KEY environment variable
127
- - Uses gemini-2.0-flash model by default
128
- - Cloud-based, requires internet connection
129
 
130
- **Ollama (Local)**
131
- - Requires Ollama installation
132
- - Uses llama3.2:1b model by default
133
- - Runs locally, no internet required
134
 
135
- ### File Upload Limits
136
- - Maximum file size: 10MB per file
137
- - Total session limit: 50MB
138
- - Supported formats: PDF, DOCX, TXT
139
 
140
- ### Environment Variables
141
- ```env
142
- # Required for Gemini
143
- GEMINI_API_KEY=your_api_key
144
 
145
- # Optional configurations
146
- GEMINI_MODEL=gemini-2.0-flash
147
- OLLAMA_BASE_URL=http://localhost:11434
 
 
148
  ```
149
 
150
- ## Development
151
 
152
- ### Project Structure
153
- ```
154
- phd-advisor-frontend/
155
- ├── public/
156
- ├── src/
157
- │ ├── components/ # Reusable UI components
158
- │ ├── data/ # Advisor configurations
159
- │ ├── pages/ # Main page components
160
- │ ├── styles/ # CSS stylesheets
161
- │ └── utils/ # Helper functions
 
 
 
 
162
 
163
- multi_llm_chatbot_backend/
164
- ├── app/
165
- │ ├── api/ # API routes
166
- │ ├── core/ # Business logic
167
- │ ├── llm/ # LLM client implementations
168
- │ ├── models/ # Data models
169
- │ ├── tests/ # Test files
170
- │ └── utils/ # Utility functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  ```
172
 
173
- ### Adding New Advisors
174
- 1. Create persona in `app/api/routes.py` with system prompt
175
- 2. Add advisor configuration in frontend `src/data/advisors.js`
176
- 3. Update advisor styling in `src/styles/`
 
 
 
 
 
 
177
 
178
- ### Testing Document Upload
179
- Use the test script:
180
  ```bash
181
- cd multi_llm_chatbot_backend/app/tests
182
- python test_document_upload.py
 
 
 
 
 
 
183
  ```
184
 
185
- ## Usage Examples
 
 
 
 
 
 
 
 
 
 
186
 
187
- ### Starting a Conversation
188
- 1. Navigate to the home page
189
- 2. Click "Start Conversation"
190
- 3. Type your PhD-related question
191
- 4. Receive responses from all three advisors
 
 
 
 
 
 
 
192
 
193
- ### Uploading Documents
194
- 1. In the chat interface, click the upload button
195
- 2. Select your PDF, DOCX, or TXT file
196
- 3. The document content will be added to the conversation context
197
- 4. Ask questions about your uploaded documents
198
 
199
- ### Switching LLM Providers
200
  ```bash
201
- curl -X POST "http://localhost:8000/switch-provider" \
202
- -H "Content-Type: application/json" \
203
- -d '{"provider": "ollama"}'
 
 
 
 
 
 
 
 
204
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  ## Contributing
207
 
@@ -211,10 +426,16 @@ curl -X POST "http://localhost:8000/switch-provider" \
211
  4. Push to the branch (`git push origin feature/amazing-feature`)
212
  5. Open a Pull Request
213
 
214
-
215
  ## Support
216
 
217
- - Check the API documentation at `http://localhost:8000/docs`
218
- - Review the debug endpoints for troubleshooting
219
- - Ensure all environment variables are properly configured
220
- - Verify that your LLM provider (Gemini/Ollama) is accessible
 
 
 
 
 
 
 
 
4
 
5
  ## Features
6
 
7
+ - **Multiple AI Advisor Personas**: Chat with 10+ specialized advisors including Methodologist, Theorist, Pragmatist, and more
8
+ - **Document Upload & Analysis**: Upload PDFs, Word documents, and text files for context-aware advice
9
+ - **Intelligent Document Retrieval (RAG)**: Advanced semantic search through your uploaded documents
10
+ - **Multi-LLM Backend**: Supports both Gemini API and local Ollama models
11
+ - **User Authentication**: Secure user accounts with persistent chat sessions
12
+ - **Chat Session Management**: Save, load, and manage multiple conversation threads
13
+ - **Export Capabilities**: Export chats and summaries in TXT, PDF, and DOCX formats
14
+ - **Real-time Chat Interface**: Modern, responsive UI with advisor-specific styling
15
 
16
  ## Architecture
17
 
18
  ### Frontend (React)
19
  - **Technology**: React 18 with modern hooks and functional components
20
  - **Styling**: CSS custom properties with dark/light theme support
21
+ - **State Management**: React Context and hooks
22
+ - **Authentication**: JWT-based authentication with persistent sessions
 
23
 
24
  ### Backend (FastAPI)
25
  - **Framework**: FastAPI with automatic API documentation
26
+ - **Database**: MongoDB for user data and chat sessions
27
+ - **Vector Database**: ChromaDB for document storage and semantic search
28
+ - **LLM Integration**: Support for Gemini API and Ollama models
29
+ - **Document Processing**: PDF, DOCX, and text file extraction with intelligent chunking
30
+ - **Authentication**: JWT tokens with bcrypt password hashing
31
 
32
+ ## Prerequisites
33
 
34
+ Before you begin, ensure you have the following installed:
 
 
 
 
35
 
36
+ - **Python 3.8+** (3.9+ recommended)
37
+ - **Node.js 16+** and npm
38
+ - **MongoDB** (Community Edition)
39
+ - **Git**
40
 
41
+ ## Installation Guide
42
+
43
+ ### Step 1: Clone the Repository
44
+
45
+ ```bash
46
+ git clone https://github.com/sohank-17/Neon-AI-Project.git
47
+ cd Neon-AI-Project
48
+ ```
49
+
50
+ ### Step 2: MongoDB Setup
51
+
52
+ #### Option A: Local MongoDB Installation
53
+
54
+ **On Windows:**
55
+ 1. Download MongoDB Community Server from [mongodb.com](https://www.mongodb.com/try/download/community)
56
+ 2. Install with default settings
57
+ 3. MongoDB will run as a Windows Service automatically
58
+
59
+ **On macOS:**
60
+ ```bash
61
+ # Using Homebrew
62
+ brew tap mongodb/brew
63
+ brew install mongodb-community
64
+ brew services start mongodb/brew/mongodb-community
65
+ ```
66
+
67
+ **On Linux (Ubuntu/Debian):**
68
+ ```bash
69
+ # Import MongoDB public GPG key
70
+ wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
71
+
72
+ # Create list file
73
+ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
74
+
75
+ # Install MongoDB
76
+ sudo apt-get update
77
+ sudo apt-get install -y mongodb-org
78
+
79
+ # Start MongoDB
80
+ sudo systemctl start mongod
81
+ sudo systemctl enable mongod
82
+ ```
83
+
84
+ #### Option B: MongoDB Atlas (Cloud)
85
+ 1. Create a free account at [MongoDB Atlas](https://www.mongodb.com/atlas)
86
+ 2. Create a new cluster
87
+ 3. Get your connection string
88
+ 4. Skip the local MongoDB setup
89
+
90
+ ### Step 3: Ollama Installation (for Local LLM Support)
91
+
92
+ #### Install Ollama
93
+
94
+ **On Windows:**
95
+ 1. Download Ollama from [ollama.ai](https://ollama.ai)
96
+ 2. Run the installer
97
+ 3. Ollama will start automatically
98
+
99
+ **On macOS:**
100
+ ```bash
101
+ # Using Homebrew
102
+ brew install ollama
103
+
104
+ # Or download from ollama.ai
105
+ ```
106
+
107
+ **On Linux:**
108
+ ```bash
109
+ # Install Ollama
110
+ curl -fsSL https://ollama.ai/install.sh | sh
111
+
112
+ # Start Ollama service
113
+ sudo systemctl start ollama
114
+ sudo systemctl enable ollama
115
+ ```
116
+
117
+ #### Download Required Models
118
+
119
+ Once Ollama is installed, download the recommended models:
120
+
121
+ ```bash
122
+ # Download the default model (recommended for development)
123
+ ollama pull llama3.2:1b
124
+
125
+ # Optional: Download larger, more capable models
126
+ ollama pull llama3.2:3b
127
+ ollama pull mistral:7b
128
+
129
+ # Verify installation
130
+ ollama list
131
+ ```
132
+
133
+ **Note**: The `llama3.2:1b` model is small (~1.3GB) and fast, perfect for development. For production, consider larger models for better quality.
134
+
135
+ ### Step 4: Backend Setup
136
+
137
+ 1. **Navigate to the backend directory:**
138
  ```bash
139
  cd multi_llm_chatbot_backend
140
  ```
141
 
142
+ 2. **Create a Python virtual environment:**
143
+ ```bash
144
+ # Create virtual environment
145
+ python -m venv venv
146
+
147
+ # Activate virtual environment
148
+ # On Windows:
149
+ venv\Scripts\activate
150
+ # On macOS/Linux:
151
+ source venv/bin/activate
152
+ ```
153
+
154
+ 3. **Install Python dependencies:**
155
  ```bash
156
  pip install -r requirements.txt
157
  ```
158
 
159
+ 4. **Set up environment variables:**
160
+ Create a `.env` file in the `multi_llm_chatbot_backend` directory:
161
+
162
  ```env
163
+ # MongoDB Configuration
164
+ MONGODB_CONNECTION_STRING=mongodb://localhost:27017
165
+ MONGODB_DATABASE_NAME=phd_advisor
166
+
167
+ # JWT Configuration
168
+ JWT_SECRET_KEY=your-super-secret-jwt-key-change-this-in-production-please-make-it-long-and-random
169
+
170
+ # Gemini API Configuration (Optional - for cloud LLM)
171
  GEMINI_API_KEY=your_gemini_api_key_here
172
  GEMINI_MODEL=gemini-2.0-flash
173
+
174
+ # Ollama Configuration (for local LLM)
175
+ OLLAMA_BASE_URL=http://localhost:11434
176
+
177
+ # Application Settings
178
+ CORS_ORIGINS=http://localhost:3000
179
  ```
180
 
181
+ **Getting a Gemini API Key (Optional):**
182
+ 1. Go to [Google AI Studio](https://makersuite.google.com/app/apikey)
183
+ 2. Create a new API key
184
+ 3. Add it to your `.env` file
185
+
186
+ 5. **Start the backend server:**
187
  ```bash
188
  uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
189
  ```
190
 
191
  The API will be available at `http://localhost:8000` with interactive docs at `http://localhost:8000/docs`
192
 
193
+ ### Step 5: Frontend Setup
194
 
195
+ 1. **Navigate to the frontend directory:**
196
  ```bash
197
+ cd ../phd-advisor-frontend
198
  ```
199
 
200
+ 2. **Install dependencies:**
201
  ```bash
202
  npm install
203
  ```
204
 
205
+ 3. **Start the development server:**
206
  ```bash
207
  npm start
208
  ```
209
 
210
  The application will open at `http://localhost:3000`
211
 
212
+ ## Quick Start Guide
213
 
214
+ ### First Time Setup Checklist
 
 
 
215
 
216
+ 1. MongoDB is running (check with `mongosh` or MongoDB Compass)
217
+ 2. Ollama is running with models downloaded (`ollama list`)
218
+ 3. Backend is running on port 8000
219
+ 4. Frontend is running on port 3000
220
+ 5. Create your first user account
221
 
222
+ ### Basic Usage
 
 
 
223
 
224
+ 1. **Create an Account:**
225
+ - Open `http://localhost:3000`
226
+ - Click "Sign Up"
227
+ - Fill in your details
228
 
229
+ 2. **Start Your First Chat:**
230
+ - Click "New Chat"
231
+ - Ask a question like "I need help with my research methodology"
232
+ - Get responses from multiple advisor personas
233
 
234
+ 3. **Upload Documents:**
235
+ - Click the upload button in the chat
236
+ - Upload a PDF, DOCX, or TXT file
237
+ - Ask questions about your document
238
 
239
+ 4. **Manage Chats:**
240
+ - Save important conversations
241
+ - Switch between different chat sessions
242
+ - Export chats in various formats
243
 
244
+ ## 🔧 Configuration
 
 
245
 
246
+ ### Environment Variables Reference
247
 
248
+ | Variable | Description | Default | Required |
249
+ |----------|-------------|---------|----------|
250
+ | `MONGODB_CONNECTION_STRING` | MongoDB connection URL | `mongodb://localhost:27017` | Yes |
251
+ | `MONGODB_DATABASE_NAME` | Database name | `phd_advisor` | Yes |
252
+ | `JWT_SECRET_KEY` | Secret key for JWT tokens | - | Yes |
253
+ | `GEMINI_API_KEY` | Google Gemini API key | - | No |
254
+ | `GEMINI_MODEL` | Gemini model to use | `gemini-2.0-flash` | No |
255
+ | `OLLAMA_BASE_URL` | Ollama server URL | `http://localhost:11434` | No |
256
 
257
+ ### Switching Between LLM Providers
 
 
 
258
 
259
+ The application supports two LLM providers:
 
 
 
260
 
261
+ 1. **Ollama (Local, Free):**
262
+ - Ensure Ollama is running
263
+ - Models run locally on your machine
264
+ - No API costs, complete privacy
265
 
266
+ 2. **Gemini (Cloud, Paid):**
267
+ - Requires API key
268
+ - Higher quality responses
269
+ - Faster response times
270
 
271
+ Switch providers using the API:
272
+ ```bash
273
+ curl -X POST "http://localhost:8000/switch-provider" \
274
+ -H "Content-Type: application/json" \
275
+ -d '{"provider": "ollama"}'
276
  ```
277
 
278
+ ## API Documentation
279
 
280
+ ### Authentication Endpoints
281
+ - `POST /auth/signup` - Create new user account
282
+ - `POST /auth/login` - Login with email/password
283
+ - `GET /auth/me` - Get current user profile
284
+
285
+ ### Chat Endpoints
286
+ - `POST /chat-sequential` - Get responses from all advisors
287
+ - `POST /chat/{persona_id}` - Chat with specific advisor
288
+ - `POST /reply-to-advisor` - Reply to specific advisor message
289
+
290
+ ### Document Management
291
+ - `POST /upload-document` - Upload PDF, DOCX, or TXT files
292
+ - `GET /uploaded-files` - List uploaded files
293
+ - `GET /document-stats` - Get document statistics
294
 
295
+ ### Session Management
296
+ - `GET /context` - Get current session context
297
+ - `POST /reset-session` - Reset current session
298
+ - `GET /session-stats` - Get session statistics
299
+
300
+ ### Export & Summary
301
+ - `GET /export-chat` - Export chat (txt, pdf, docx)
302
+ - `GET /chat-summary` - Generate chat summary
303
+
304
+ Full API documentation is available at `http://localhost:8000/docs` when the server is running.
305
+
306
+ ## Troubleshooting
307
+
308
+ ### Common Issues
309
+
310
+ **Backend won't start:**
311
+ ```bash
312
+ # Check if port 8000 is already in use
313
+ netstat -an | grep :8000
314
+
315
+ # Check Python virtual environment is activated
316
+ which python # Should point to your venv
317
+
318
+ # Check all dependencies are installed
319
+ pip list
320
  ```
321
 
322
+ **MongoDB connection issues:**
323
+ ```bash
324
+ # Test MongoDB connection
325
+ mongosh
326
+
327
+ # Check if MongoDB service is running
328
+ # Windows: Check Services app
329
+ # macOS: brew services list | grep mongodb
330
+ # Linux: systemctl status mongod
331
+ ```
332
 
333
+ **Ollama not working:**
 
334
  ```bash
335
+ # Check if Ollama is running
336
+ curl http://localhost:11434/api/tags
337
+
338
+ # Check downloaded models
339
+ ollama list
340
+
341
+ # Test model directly
342
+ ollama run llama3.2:1b "Hello"
343
  ```
344
 
345
+ **Frontend won't connect to backend:**
346
+ - Verify backend is running on port 8000
347
+ - Check CORS settings in backend `.env`
348
+ - Check browser developer console for errors
349
+
350
+ ### Performance Tips
351
+
352
+ 1. **For faster local LLM responses:**
353
+ - Use smaller models like `llama3.2:1b` for development
354
+ - Ensure sufficient RAM (8GB+ recommended)
355
+ - Use SSD storage for better model loading
356
 
357
+ 2. **For better document search:**
358
+ - Upload focused, relevant documents
359
+ - Use clear, descriptive filenames
360
+ - Break large documents into smaller sections
361
+
362
+ 3. **For production deployment:**
363
+ - Use larger, more capable models
364
+ - Consider GPU acceleration for Ollama
365
+ - Use MongoDB Atlas for cloud database
366
+ - Set up proper authentication and HTTPS
367
+
368
+ ## Development
369
 
370
+ ### Running Tests
 
 
 
 
371
 
 
372
  ```bash
373
+ # Backend tests
374
+ cd multi_llm_chatbot_backend
375
+ python -m pytest app/tests/
376
+
377
+ # Test specific functionality
378
+ python app/tests/test_rag_system.py
379
+ python app/tests/debug_rag.py
380
+ ```
381
+
382
+ ### Project Structure
383
+
384
  ```
385
+ phd-advisor-panel/
386
+ ├── multi_llm_chatbot_backend/
387
+ │ ├── app/
388
+ │ │ ├── api/routes/ # API route handlers
389
+ │ │ ├── core/ # Core business logic
390
+ │ │ ├── llm/ # LLM client implementations
391
+ │ │ ├── models/ # Data models and schemas
392
+ │ │ ├── utils/ # Utility functions
393
+ │ │ └── tests/ # Test files
394
+ │ ├── requirements.txt
395
+ │ └── .env
396
+ ├── phd-advisor-frontend/
397
+ │ ├── src/
398
+ │ │ ├── components/ # React components
399
+ │ │ ├── pages/ # Page components
400
+ │ │ ├── styles/ # CSS files
401
+ │ │ └── utils/ # Frontend utilities
402
+ │ ├── package.json
403
+ │ └── public/
404
+ └── README.md
405
+ ```
406
+
407
+ ### Adding New Advisor Personas
408
+
409
+ 1. Edit `app/models/default_personas.py`
410
+ 2. Add your persona configuration
411
+ 3. Restart the backend server
412
+ 4. The new persona will be available in chat
413
+
414
+ ### Extending Document Support
415
+
416
+ 1. Add new file type to `app/utils/document_extractor.py`
417
+ 2. Update the upload endpoint in `app/api/routes/documents.py`
418
+ 3. Test with sample files
419
+
420
 
421
  ## Contributing
422
 
 
426
  4. Push to the branch (`git push origin feature/amazing-feature`)
427
  5. Open a Pull Request
428
 
 
429
  ## Support
430
 
431
+ - Check the [API Documentation](http://localhost:8000/docs)
432
+ - Report bugs by opening an issue
433
+ - Request features by opening an issue
434
+ - Contact the development team
435
+
436
+ ## Acknowledgments
437
+
438
+ - Built with [FastAPI](https://fastapi.tiangolo.com/) and [React](https://reactjs.org/)
439
+ - Powered by [Ollama](https://ollama.ai/) for local LLM support
440
+ - Uses [ChromaDB](https://www.trychroma.com/) for vector storage
441
+ - Document processing with [PyPDF2](https://pypdf2.readthedocs.io/) and [python-docx](https://python-docx.readthedocs.io/)
multi_llm_chatbot_backend/README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-LLM Chatbot Backend
2
+
3
+ A modular, extensible FastAPI backend for building an AI-powered research advisor chatbot that supports:
4
+ - Multiple AI personas with configurable tone and behavior
5
+ - Dynamic switching between Gemini (cloud) and Ollama (local) LLMs
6
+ - Chat session persistence and context memory
7
+ - Document upload, chunking, and retrieval using RAG
8
+ - Rich export features (PDF, DOCX, TXT)
9
+ - User authentication and JWT-based access control
10
+
11
+ ---
12
+
13
+ ## Backend Architecture
14
+
15
+ ```text
16
+ User Input
17
+ ↓
18
+ /chat-sequential → Orchestrator
19
+ ↓ ↙ ↘
20
+ SessionManager ContextManager RAGManager
21
+ ↓ ↓ ↓
22
+ MongoDB Token Trimming ChromaDB
23
+ ↓ ↓ ↓
24
+ Persisted Chat & Doc Context → LLM (Gemini/Ollama)
25
+ ```
26
+
27
+ ---
28
+
29
+ ## Features
30
+
31
+ - Persona-based multi-agent conversation (`Theorist`, `Pragmatist`, etc.)
32
+ - Provider switching (Gemini ↔ Ollama)
33
+ - Context-aware response routing + top-K advisor selection
34
+ - PDF, DOCX, and TXT file upload and semantic retrieval
35
+ - Developer tools: debug personas, test RAG, export sessions
36
+ - Secure authentication and session scoping
37
+
38
+ ---
39
+
40
+ ## Setup Instructions
41
+
42
+ ### 1. Clone and Configure Environment
43
+
44
+ ```bash
45
+ git clone https://github.com/yourorg/multi-llm-chatbot-backend
46
+ cd multi-llm-chatbot-backend
47
+ cp .env.example .env # already provided
48
+ ```
49
+
50
+ ### 2. Python Environment Setup
51
+
52
+ ```bash
53
+ python -m venv venv
54
+ source venv/bin/activate # or venv\Scripts\activate on Windows
55
+
56
+ pip install -r requirements.txt
57
+ ```
58
+
59
+ ### 3. Run the Server
60
+
61
+ ```bash
62
+ uvicorn app.main:app --reload
63
+ ```
64
+
65
+ > Server will be available at: `http://localhost:8000`
66
+
67
+ ---
68
+
69
+ ## FastAPI Routing & Modules
70
+
71
+ | Folder | Description |
72
+ |--------|-------------|
73
+ | [`app/api`](./api_README.md) | REST API endpoints for chat, auth, RAG, exports |
74
+ | [`app/core`](./core_README.md) | Main orchestration, context windows, database logic |
75
+ | [`app/llm`](./llm_README.md) | Gemini + Ollama LLM wrappers |
76
+ | [`app/models`](./models_README.md) | Persona and user schemas |
77
+ | [`app/utils`](./utils_README.md) | File parsing, summaries, exports, vector helpers |
78
+
79
+ ---
80
+
81
+ ## Key Files
82
+
83
+ ### `main.py`
84
+
85
+ - Loads env vars, sets up FastAPI instance with CORS and routers
86
+ - Calls `connect_to_mongo()` on startup and `close_mongo_connection()` on shutdown
87
+ - Imports and registers all routers (`auth`, `chat_sessions`, etc.)
88
+
89
+ ### `.env` (Sample Vars)
90
+
91
+ ```ini
92
+ # MongoDB
93
+ MONGODB_CONNECTION_STRING=mongodb://localhost:27017
94
+ MONGODB_DATABASE_NAME=neon_ai_backend
95
+
96
+ # Gemini API Key and model
97
+ GEMINI_API_KEY=... # Replace with real key
98
+ GEMINI_MODEL=gemini-2.0-flash
99
+
100
+ # Default provider
101
+ DEFAULT_PROVIDER=gemini
102
+ ```
103
+
104
+ ### `requirements.txt`
105
+
106
+ Includes:
107
+ - **FastAPI**, **Uvicorn**: API framework and server
108
+ - **httpx**: Async LLM request handler
109
+ - **motor**, **pymongo**: MongoDB async access
110
+ - **chromadb**, **sentence-transformers**: Vector database + embeddings
111
+ - **PyPDF2**, **docx2txt**, **reportlab**: Document parsing and PDF generation
112
+ - **passlib**, **python-jose**: Auth and security
113
+
114
+ ---
115
+
116
+ ## Persona Design & Context Handling
117
+
118
+ - Personas defined in `app/models/default_personas.py`
119
+ - Rich system prompts, styles, and epistemologies
120
+ - Responses routed through `ImprovedChatOrchestrator`
121
+ - Context trimmed and weighted via `ContextManager`
122
+
123
+ ---
124
+
125
+ ## Switching LLM Providers
126
+
127
+ You can hot-swap models via API:
128
+
129
+ ```http
130
+ POST /switch-provider
131
+ { "provider": "gemini" } | { "provider": "ollama" }
132
+ ```
133
+
134
+ > Also supported: `/switch-model`, `/current-model`, `/current-provider`
135
+
136
+ ---
137
+
138
+ ## Document Upload + RAG
139
+
140
+ - Upload PDFs, DOCX, or TXT to sessions
141
+ - Text is extracted → chunked → embedded → stored in ChromaDB
142
+ - Queried during conversation by persona-aware `EnhancedRAGManager`
143
+
144
+ ---
145
+
146
+ ## Export Options
147
+
148
+ | Format | Export Endpoint |
149
+ |--------|------------------|
150
+ | PDF | `/export-chat?format=pdf` |
151
+ | DOCX | `/export-chat?format=docx` |
152
+ | TXT | `/export-chat?format=txt` |
153
+ | Summary | `/chat-summary?format=pdf` |
154
+
155
+ ---
156
+
157
+ ## Developer & Debug Endpoints
158
+
159
+ | Endpoint | Purpose |
160
+ |----------|---------|
161
+ | `/debug/personas` | See registered advisors and prompts |
162
+ | `/debug/ranked-personas` | View top-K advisors for context |
163
+ | `/debug/rag-status` | Run sample search to test document index |
164
+
165
+ ---
166
+
167
+ ## Status & Roadmap
168
+
169
+ - [x] Multi-LLM backend ready (Gemini + Ollama)
170
+ - [x] Document RAG + export system
171
+ - [x] Session-aware persona routing
172
+ - [x] JWT Auth + MongoDB user handling
173
+ - [ ] UI enhancements and persona memory
174
+ - [ ] Persona fine-tuning support (future)
175
+
176
+ ---
177
+
178
+ For questions, contributions, or deployment help — feel free to reach out!
multi_llm_chatbot_backend/app/api/README.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `app/api` – REST API Layer for Multi-LLM Chatbot
2
+
3
+ This module defines the complete FastAPI-based HTTP interface for all backend features, including chat, session management, RAG operations, provider switching, and document interaction.
4
+
5
+ Each file in this directory defines route groups (`APIRouter`) to modularize functionality.
6
+
7
+ ---
8
+
9
+ ## API Directory Layout
10
+
11
+ | File | Purpose |
12
+ |------|---------|
13
+ | `auth.py` | Handles user authentication (login, signup, token validation) |
14
+ | `chat.py` | Core routes for LLM-backed chat, reply-to-advisor, and multi-turn flow |
15
+ | `chat_sessions.py` | Stores user conversations and provides access to saved history |
16
+ | `debug.py` | Developer tools: debug personas, RAG tests, ranking advisor responses |
17
+ | `documents.py` | Upload, parse, index, and query documents via RAG |
18
+ | `provider.py` | Switch between Gemini and Ollama providers |
19
+ | `root.py` | Root `/` endpoint for heartbeat and versioning |
20
+ | `sessions.py` | Tracks and resets session-specific in-memory context |
21
+ | `utils.py` | Helpers used by multiple routers (e.g. session ID management) |
22
+
23
+ ---
24
+
25
+ ## `auth.py` – User Authentication API
26
+
27
+ | Endpoint | Method | Description |
28
+ |----------|--------|-------------|
29
+ | `/signup` | `POST` | Register a new user |
30
+ | `/login` | `POST` | Authenticate user and return access token |
31
+ | `/me` | `GET` | Return current logged-in user |
32
+ | `/healthcheck` | `GET` | Ping endpoint to check login status |
33
+
34
+ Uses JWT-based Bearer token auth via FastAPI dependencies.
35
+
36
+ ---
37
+
38
+ ## `chat.py` – Chat Interaction
39
+
40
+ | Endpoint | Method | Description |
41
+ |----------|--------|-------------|
42
+ | `/chat-sequential` | `POST` | Run a full advisor loop and return all persona responses |
43
+ | `/reply-to-advisor` | `POST` | Ask a question to a specific advisor/persona |
44
+
45
+ These routes handle:
46
+ - Message routing via `ImprovedChatOrchestrator`
47
+ - Persona-wise response generation
48
+ - Embedding document-aware context
49
+ - Returning consistent message structure
50
+
51
+ ---
52
+
53
+ ## `chat_sessions.py` – Persistent Storage of Conversations
54
+
55
+ | Endpoint | Method | Description |
56
+ |----------|--------|-------------|
57
+ | `/chat-sessions` | `GET` | List all saved chat sessions |
58
+ | `/chat-sessions/{id}` | `GET` | Retrieve specific chat session |
59
+ | `/chat-sessions/{id}` | `DELETE` | Soft-delete a chat session |
60
+ | `/chat-sessions/save` | `POST` | Save in-memory session to MongoDB |
61
+
62
+ Saves message history, metadata, and uploaded files.
63
+
64
+ ---
65
+
66
+ ## `debug.py` – Developer Tools
67
+
68
+ | Endpoint | Method | Description |
69
+ |----------|--------|-------------|
70
+ | `/debug/personas` | `GET` | List current personas, prompts, keywords |
71
+ | `/debug/ranked-personas` | `GET` | Return top advisors for current session |
72
+ | `/debug/rag-status` | `GET` | Run sample RAG query + return health info |
73
+
74
+ Provides insight into:
75
+ - Persona prompt preview
76
+ - RAG test queries and indexed documents
77
+ - Session size + truncation status
78
+
79
+ ---
80
+
81
+ ## `documents.py` – Document Upload and RAG
82
+
83
+ | Endpoint | Method | Description |
84
+ |----------|--------|-------------|
85
+ | `/upload-document` | `POST` | Upload and parse a document for semantic search |
86
+ | `/search-documents` | `POST` | RAG search using text query and persona context |
87
+ | `/document-stats` | `GET` | Overview of documents uploaded to session |
88
+ | `/uploaded-files` | `GET` | Return list of uploaded file names |
89
+ | `/document-insights/{filename}` | `GET` | Get detailed metadata for a document |
90
+ | `/export-chat` | `GET` | Export current or stored chat session (PDF, TXT, DOCX) |
91
+ | `/chat-summary` | `GET` | Export summary generated by LLM (multi-format) |
92
+
93
+ Supports file parsing (`PDF`, `DOCX`, `TXT`), chunking, embedding, and export.
94
+
95
+ ---
96
+
97
+ ## `provider.py` – LLM Provider Control
98
+
99
+ | Endpoint | Method | Description |
100
+ |----------|--------|-------------|
101
+ | `/current-provider` | `GET` | Return currently active provider and model |
102
+ | `/switch-provider` | `POST` | Dynamically switch between `gemini` and `ollama` |
103
+ | `/current-model` | `GET` | Get currently loaded model name |
104
+ | `/switch-model` | `POST` | Alias for switching based on model name |
105
+
106
+ Changes are propagated by:
107
+ - Creating new LLM client
108
+ - Re-registering all personas
109
+
110
+ ---
111
+
112
+ ## `sessions.py` – In-Memory Session Management
113
+
114
+ | Endpoint | Method | Description |
115
+ |----------|--------|-------------|
116
+ | `/context` | `GET` | Return current session context (messages, documents, stats) |
117
+ | `/reset-session` | `POST` | Reset in-memory session or specific chat context |
118
+ | `/session-stats` | `GET` | Return stats like message count, file size, timestamps |
119
+ | `/active-sessions` | `GET` | Return list of all active in-memory sessions |
120
+ | `/cleanup-sessions` | `POST` | Manually trigger expired session cleanup |
121
+
122
+ Supports ephemeral sessions and reusable chat contexts (e.g. for documents).
123
+
124
+ ---
125
+
126
+ ## `utils.py` – Route-Level Utilities
127
+
128
+ Defines shared helper:
129
+
130
+ - `get_or_create_session_for_request(request)`
131
+ - `get_or_create_session_for_request_async(request)`
132
+
133
+ These parse session cookies or generate new session IDs, crucial for maintaining separation across:
134
+ - In-memory ephemeral sessions
135
+ - Document-linked long-term sessions
136
+
137
+ ---
138
+
139
+ ## `root.py` – API Healthcheck
140
+
141
+ | Endpoint | Method | Description |
142
+ |----------|--------|-------------|
143
+ | `/` | `GET` | Return version + feature list |
144
+
145
+ Simple heartbeat endpoint used for readiness probes and sanity checks.
146
+
147
+ ---
148
+
149
+ ## Auth Flow Integration
150
+
151
+ Most routes use:
152
+
153
+ ```python
154
+ Depends(get_current_active_user)
155
+ ```
156
+
157
+ This ensures only logged-in users can:
158
+ - Upload and retrieve files
159
+ - Export summaries
160
+ - Save or delete chat sessions
161
+
162
+ JWT tokens are passed via the `Authorization: Bearer ...` header.
163
+
164
+ ---
165
+
166
+ ## High-Level Flow
167
+
168
+ ```text
169
+ Frontend → /chat-sequential → orchestrator → personas → RAG + LLM → response[]
170
+ ↘ /upload-document → extractor → RAG chunks → indexed
171
+ ↘ /context or /reset-session → session_manager
172
+ ↘ /export-chat or /chat-summary → utils + formatter
173
+ ```
174
+
175
+ ---
multi_llm_chatbot_backend/app/api/routes/auth.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends, status
2
+ from datetime import datetime, timedelta
3
+ from bson import ObjectId
4
+ from app.models.user import UserCreate, UserLogin, User, Token, UserResponse
5
+ from app.core.auth import (
6
+ get_password_hash,
7
+ authenticate_user,
8
+ create_access_token,
9
+ get_user_by_email,
10
+ get_current_active_user,
11
+ create_user_response,
12
+ ACCESS_TOKEN_EXPIRE_MINUTES
13
+ )
14
+ from app.core.database import get_database
15
+ import logging
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ router = APIRouter()
20
+
21
+ @router.post("/signup", response_model=Token)
22
+ async def signup(user_data: UserCreate):
23
+ """Create a new user account"""
24
+ try:
25
+ db = get_database()
26
+
27
+ # Check if user already exists
28
+ existing_user = await get_user_by_email(user_data.email)
29
+ if existing_user:
30
+ raise HTTPException(
31
+ status_code=status.HTTP_400_BAD_REQUEST,
32
+ detail="Email already registered"
33
+ )
34
+
35
+ # Create new user
36
+ hashed_password = get_password_hash(user_data.password)
37
+ user = User(
38
+ firstName=user_data.firstName,
39
+ lastName=user_data.lastName,
40
+ email=user_data.email,
41
+ hashed_password=hashed_password,
42
+ academicStage=user_data.academicStage,
43
+ researchArea=user_data.researchArea,
44
+ created_at=datetime.utcnow(),
45
+ is_active=True
46
+ )
47
+
48
+ # Insert user into database
49
+ result = await db.users.insert_one(user.dict(by_alias=True))
50
+ user.id = result.inserted_id
51
+
52
+ # Create access token
53
+ access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
54
+ access_token = create_access_token(
55
+ data={"sub": str(user.id)},
56
+ expires_delta=access_token_expires
57
+ )
58
+
59
+ return Token(
60
+ access_token=access_token,
61
+ token_type="bearer",
62
+ user=create_user_response(user)
63
+ )
64
+
65
+ except HTTPException:
66
+ raise
67
+ except Exception as e:
68
+ logger.error(f"Error during signup: {e}")
69
+ raise HTTPException(
70
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
71
+ detail="Could not create user account"
72
+ )
73
+
74
+ @router.post("/login", response_model=Token)
75
+ async def login(user_credentials: UserLogin):
76
+ """Login with email and password"""
77
+ try:
78
+ # Authenticate user
79
+ user = await authenticate_user(user_credentials.email, user_credentials.password)
80
+ if not user:
81
+ raise HTTPException(
82
+ status_code=status.HTTP_401_UNAUTHORIZED,
83
+ detail="Incorrect email or password",
84
+ headers={"WWW-Authenticate": "Bearer"},
85
+ )
86
+
87
+ # Update last login time
88
+ db = get_database()
89
+ await db.users.update_one(
90
+ {"_id": user.id},
91
+ {"$set": {"last_login": datetime.utcnow()}}
92
+ )
93
+ user.last_login = datetime.utcnow()
94
+
95
+ # Create access token
96
+ access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
97
+ access_token = create_access_token(
98
+ data={"sub": str(user.id)},
99
+ expires_delta=access_token_expires
100
+ )
101
+
102
+ return Token(
103
+ access_token=access_token,
104
+ token_type="bearer",
105
+ user=create_user_response(user)
106
+ )
107
+
108
+ except HTTPException:
109
+ raise
110
+ except Exception as e:
111
+ logger.error(f"Error during login: {e}")
112
+ raise HTTPException(
113
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
114
+ detail="Login failed"
115
+ )
116
+
117
+ @router.get("/me", response_model=UserResponse)
118
+ async def get_current_user_profile(current_user: User = Depends(get_current_active_user)):
119
+ """Get current user profile"""
120
+ return create_user_response(current_user)
121
+
122
+ @router.post("/logout")
123
+ async def logout():
124
+ """Logout (client should discard token)"""
125
+ return {"message": "Successfully logged out"}
126
+
127
+ @router.post("/verify-token", response_model=UserResponse)
128
+ async def verify_token(current_user: User = Depends(get_current_active_user)):
129
+ """Verify token and return user info"""
130
+ return create_user_response(current_user)
multi_llm_chatbot_backend/app/api/routes/chat.py CHANGED
@@ -1,138 +1,322 @@
1
- from fastapi import APIRouter, Request, HTTPException, Body
2
  from app.models.persona import Persona
3
  from app.core.session_manager import get_session_manager
4
- from app.api.utils import get_or_create_session_for_request
5
  from app.core.bootstrap import chat_orchestrator
 
 
6
  from pydantic import BaseModel
 
7
  import logging
 
 
8
 
9
  logger = logging.getLogger(__name__)
10
 
11
  router = APIRouter()
12
-
13
  session_manager = get_session_manager()
14
 
15
- # Keep all the same data models as before
16
  class UserInput(BaseModel):
17
  user_input: str
18
 
19
  class ChatMessage(BaseModel):
20
  user_input: str
21
- session_id: str = None
 
22
  response_length: str = "medium"
23
 
24
  class ReplyToAdvisor(BaseModel):
25
  user_input: str
26
  advisor_id: str
27
  original_message_id: str = None
 
28
 
29
  class PersonaQuery(BaseModel):
30
  question: str
31
  persona: str
32
 
 
 
33
 
34
- @router.post("/chat-sequential")
35
- async def chat_sequential_enhanced(message: ChatMessage, request: Request):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  """
37
- Enhanced sequential chat with intelligent persona ordering.
38
- Returns responses in the order determined by LLM-based relevance ranking.
39
  """
40
  try:
41
- # Get or create session
42
- session_id = get_or_create_session_for_request(request, message.session_id)
 
 
 
 
43
 
44
- # Add user message to session first (needed for persona ranking)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  session = session_manager.get_session(session_id)
 
 
 
 
 
 
46
  session.append_message("user", message.user_input)
47
 
48
- # Get intelligently ordered personas based on context
49
  top_personas = await chat_orchestrator.get_top_personas(
50
  session_id=session_id,
51
- k=3 # Get top 3 most relevant personas
52
  )
53
 
54
  logger.info(f"Intelligent persona order for session {session_id}: {top_personas}")
55
 
56
- # Generate responses from personas in the intelligent order
57
  responses = []
58
 
59
  for persona_id in top_personas:
60
  try:
61
- # Generate response from this persona
 
 
62
  persona_result = await chat_orchestrator.chat_with_persona(
63
  user_input=message.user_input,
64
  persona_id=persona_id,
65
- session_id=session_id,
66
  response_length=message.response_length or "medium"
67
  )
68
 
69
-
70
- if "persona_name" in persona_result and "response" in persona_result:
71
- responses.append({
72
- "persona": persona_result["persona_name"],
73
- "persona_id": persona_result["persona_id"],
74
- "response": persona_result["response"]
75
- })
76
- elif persona_result.get("type") == "single_persona_response" and "persona" in persona_result:
77
- persona_data = persona_result["persona"]
78
- responses.append({
79
- "persona": persona_data["persona_name"],
80
- "persona_id": persona_data["persona_id"],
81
- "response": persona_data["response"]
82
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  else:
84
- # Fallback response
85
  responses.append({
86
- "persona": chat_orchestrator.personas[persona_id].name,
87
  "persona_id": persona_id,
88
- "response": "I'm having trouble processing your question right now. Please try again."
 
 
 
89
  })
90
 
91
  except Exception as e:
92
  logger.error(f"Error generating response for persona {persona_id}: {str(e)}")
93
- # Error fallback
94
  responses.append({
95
- "persona": chat_orchestrator.personas[persona_id].name,
96
  "persona_id": persona_id,
97
- "response": "I encountered an error while processing your question. Please try again."
 
 
 
98
  })
99
 
100
- # response format
101
  return {
102
- "type": "sequential_responses",
103
- "responses": responses
 
 
 
 
 
 
 
104
  }
105
-
106
  except Exception as e:
107
- logger.error(f"Error in enhanced sequential chat: {str(e)}")
108
- return {
109
- "type": "error",
110
- "responses": [{
111
- "persona": "System",
112
- "response": "I'm having trouble processing your request. Could you please try again?"
113
- }]
114
- }
115
-
116
  @router.post("/chat/{persona_id}")
117
  async def chat_with_specific_advisor(persona_id: str, input: UserInput, request: Request):
118
- """Chat with a specific advisor - SAME INTERFACE"""
119
  try:
120
  if persona_id not in chat_orchestrator.personas:
121
  raise HTTPException(status_code=404, detail=f"Persona '{persona_id}' not found")
122
 
123
- # Get session using compatibility layer
124
- session_id = get_or_create_session_for_request(request)
125
 
126
- # Use new orchestrator
127
  result = await chat_orchestrator.chat_with_persona(
128
  user_input=input.user_input,
129
  persona_id=persona_id,
130
  session_id=session_id
131
  )
132
 
133
- # FIX: Handle the actual response structure from orchestrator
134
  if result.get("type") == "single_persona_response" and "persona" in result:
135
- # New expected structure
136
  persona_data = result["persona"]
137
  return {
138
  "persona": persona_data["persona_name"],
@@ -140,20 +324,12 @@ async def chat_with_specific_advisor(persona_id: str, input: UserInput, request:
140
  "response": persona_data["response"]
141
  }
142
  elif "persona_id" in result and "response" in result:
143
- # Current actual structure from orchestrator
144
  return {
145
  "persona": result["persona_name"],
146
  "persona_id": result["persona_id"],
147
  "response": result["response"]
148
  }
149
- elif result.get("type") == "error" or "error" in result:
150
- # Error handling
151
- return {
152
- "persona": "System",
153
- "response": result.get("error", "I'm having trouble generating a response right now. Please try again.")
154
- }
155
  else:
156
- # Fallback
157
  return {
158
  "persona": "System",
159
  "response": "I'm having trouble generating a response right now. Please try again."
@@ -168,25 +344,42 @@ async def chat_with_specific_advisor(persona_id: str, input: UserInput, request:
168
  "response": "I'm having trouble generating a response right now. Please try again."
169
  }
170
 
171
- # Reply to advisor endpoint (SAME INTERFACE)
172
  @router.post("/reply-to-advisor")
173
  async def reply_to_advisor(reply: ReplyToAdvisor, request: Request):
174
- """Reply to a specific advisor - SAME INTERFACE"""
175
  try:
176
  if reply.advisor_id not in chat_orchestrator.personas:
177
  raise HTTPException(status_code=404, detail=f"Advisor '{reply.advisor_id}' not found")
178
 
179
- # Get session using compatibility layer
180
- session_id = get_or_create_session_for_request(request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
- # Use new orchestrator
183
  result = await chat_orchestrator.chat_with_persona(
184
- user_input=reply.user_input,
185
  persona_id=reply.advisor_id,
186
  session_id=session_id
187
  )
188
 
189
- if result["type"] == "single_persona_response":
 
190
  persona_data = result["persona"]
191
  return {
192
  "type": "advisor_reply",
@@ -195,11 +388,19 @@ async def reply_to_advisor(reply: ReplyToAdvisor, request: Request):
195
  "response": persona_data["response"],
196
  "original_message_id": reply.original_message_id
197
  }
 
 
 
 
 
 
 
 
198
  else:
199
  return {
200
  "type": "error",
201
  "persona": "System",
202
- "response": result.get("message", "I'm having trouble generating a reply right now. Please try again.")
203
  }
204
 
205
  except HTTPException:
@@ -211,66 +412,13 @@ async def reply_to_advisor(reply: ReplyToAdvisor, request: Request):
211
  "persona": "System",
212
  "response": "I'm having trouble generating a reply right now. Please try again."
213
  }
214
-
215
- @router.post("/chat/{persona_id}")
216
- async def chat_with_specific_persona(persona_id: str, message: ChatMessage, request: Request):
217
- """
218
- Chat with a specific persona - Enhanced with RAG debugging
219
-
220
- This endpoint helps debug RAG integration by testing individual personas
221
- """
222
- try:
223
- session_id = get_or_create_session_for_request(request, message.session_id)
224
-
225
- # Validate persona exists
226
- if persona_id not in chat_orchestrator.personas:
227
- available_personas = list(chat_orchestrator.personas.keys())
228
- raise HTTPException(
229
- status_code=400,
230
- detail=f"Persona '{persona_id}' not found. Available: {available_personas}"
231
- )
232
-
233
- # Use the enhanced orchestrator method
234
- result = await chat_orchestrator.chat_with_persona(
235
- user_input=message.user_input,
236
- persona_id=persona_id,
237
- session_id=session_id,
238
- response_length=message.response_length or "medium"
239
- )
240
-
241
- # Fix: Handle the response structure properly
242
- if result.get("type") == "single_persona_response" and "persona" in result:
243
- persona_data = result["persona"]
244
-
245
- # Add debugging information
246
- result["debug_info"] = {
247
- "persona_id": persona_id,
248
- "session_id": session_id,
249
- "query_length": len(message.user_input),
250
- "rag_manager_available": True,
251
- "used_documents": persona_data.get("used_documents", False),
252
- "chunks_used": persona_data.get("document_chunks_used", 0)
253
- }
254
-
255
- return result
256
-
257
- except HTTPException:
258
- raise
259
- except Exception as e:
260
- logger.error(f"Error in individual persona chat: {str(e)}")
261
- return {
262
- "type": "error",
263
- "message": f"Error chatting with {persona_id}: {str(e)}",
264
- "persona_id": persona_id
265
- }
266
-
267
  @router.post("/ask/")
268
  async def ask_question(query: PersonaQuery, request: Request):
269
- """Ask question - SAME INTERFACE"""
270
  try:
271
- session_id = get_or_create_session_for_request(request)
272
 
273
- # Use the new orchestrator
274
  result = await chat_orchestrator.chat_with_persona(
275
  user_input=query.question,
276
  persona_id=query.persona,
 
1
+ from fastapi import APIRouter, Request, HTTPException, Body, Depends
2
  from app.models.persona import Persona
3
  from app.core.session_manager import get_session_manager
4
+ from app.api.utils import get_or_create_session_for_request_async
5
  from app.core.bootstrap import chat_orchestrator
6
+ from app.core.auth import get_current_active_user
7
+ from app.models.user import User
8
  from pydantic import BaseModel
9
+ from typing import Optional
10
  import logging
11
+ from app.core.database import get_database
12
+ from bson import ObjectId
13
 
14
  logger = logging.getLogger(__name__)
15
 
16
  router = APIRouter()
 
17
  session_manager = get_session_manager()
18
 
19
+ # Enhanced data models
20
  class UserInput(BaseModel):
21
  user_input: str
22
 
23
  class ChatMessage(BaseModel):
24
  user_input: str
25
+ session_id: Optional[str] = None
26
+ chat_session_id: Optional[str] = None # MongoDB chat session ID
27
  response_length: str = "medium"
28
 
29
  class ReplyToAdvisor(BaseModel):
30
  user_input: str
31
  advisor_id: str
32
  original_message_id: str = None
33
+ chat_session_id: Optional[str] = None
34
 
35
  class PersonaQuery(BaseModel):
36
  question: str
37
  persona: str
38
 
39
+ class SwitchChatRequest(BaseModel):
40
+ chat_session_id: str
41
 
42
+ class NewChatRequest(BaseModel):
43
+ title: Optional[str] = "New Chat"
44
+
45
+ @router.post("/switch-chat")
46
+ async def switch_to_chat(
47
+ request: SwitchChatRequest,
48
+ req: Request,
49
+ current_user: User = Depends(get_current_active_user)
50
+ ):
51
+ """
52
+ Switch to an existing chat session and load its context - FIXED VERSION
53
+ Ensures documents are accessible after switching
54
+ """
55
+ try:
56
+ logger.info(f"Switching to chat session: {request.chat_session_id}")
57
+
58
+ # Load the chat session into memory context with consistent session ID
59
+ memory_session_id = await get_or_create_session_for_request_async(
60
+ req,
61
+ chat_session_id=request.chat_session_id,
62
+ user_id=str(current_user.id)
63
+ )
64
+
65
+ if not memory_session_id:
66
+ raise HTTPException(status_code=404, detail="Chat session not found")
67
+
68
+ logger.info(f"Loaded chat into memory session: {memory_session_id}")
69
+
70
+ # Get the loaded session
71
+ session = session_manager.get_session(memory_session_id)
72
+
73
+ # Verify document access after loading
74
+ rag_stats = session.get_rag_stats()
75
+ logger.info(f"After switch - Session {memory_session_id} has {rag_stats.get('total_documents', 0)} documents")
76
+
77
+ # Get the original MongoDB chat session to retrieve messages in proper format
78
+ db = get_database()
79
+ chat_session = await db.chat_sessions.find_one({
80
+ "_id": ObjectId(request.chat_session_id),
81
+ "user_id": current_user.id,
82
+ "is_active": True
83
+ })
84
+
85
+ if not chat_session:
86
+ raise HTTPException(status_code=404, detail="Chat session not found in database")
87
+
88
+ # Return the messages in the original frontend format from MongoDB
89
+ original_messages = chat_session.get("messages", [])
90
+
91
+ logger.info(f"Switch successful - {len(original_messages)} messages, {rag_stats.get('total_documents', 0)} documents")
92
+
93
+ return {
94
+ "status": "success",
95
+ "memory_session_id": memory_session_id,
96
+ "chat_session_id": request.chat_session_id,
97
+ "message_count": len(original_messages),
98
+ "context": {
99
+ "messages": original_messages, # Return original format messages
100
+ "rag_info": rag_stats
101
+ },
102
+ # Include document access verification
103
+ "document_access": {
104
+ "total_documents": rag_stats.get('total_documents', 0),
105
+ "total_chunks": rag_stats.get('total_chunks', 0),
106
+ "documents": rag_stats.get('documents', []),
107
+ "uploaded_files": session.uploaded_files
108
+ },
109
+ "debug_info": {
110
+ "memory_session_format": memory_session_id,
111
+ "documents_accessible": rag_stats.get('total_documents', 0) > 0,
112
+ "session_loaded": memory_session_id in session_manager.sessions
113
+ }
114
+ }
115
+
116
+ except HTTPException:
117
+ raise
118
+ except Exception as e:
119
+ logger.error(f"Error switching to chat {request.chat_session_id}: {e}")
120
+ import traceback
121
+ logger.error(f"Full traceback: {traceback.format_exc()}")
122
+ raise HTTPException(status_code=500, detail="Failed to switch to chat")
123
+
124
+ @router.post("/new-chat")
125
+ async def create_new_chat(
126
+ request: NewChatRequest,
127
+ req: Request,
128
+ current_user: User = Depends(get_current_active_user)
129
+ ):
130
  """
131
+ Create a new chat with fresh context
 
132
  """
133
  try:
134
+ # Create a completely new session (no chat_session_id means fresh context)
135
+ memory_session_id = await get_or_create_session_for_request_async(req)
136
+
137
+ # Ensure the session is completely clean
138
+ session = session_manager.get_session(memory_session_id)
139
+ session.clear_all_data() # This clears both messages and documents
140
 
141
+ return {
142
+ "status": "success",
143
+ "memory_session_id": memory_session_id,
144
+ "message": "New chat created with fresh context",
145
+ "context": {
146
+ "messages": [],
147
+ "rag_info": {"total_documents": 0, "total_chunks": 0}
148
+ }
149
+ }
150
+
151
+ except Exception as e:
152
+ logger.error(f"Error creating new chat: {e}")
153
+ raise HTTPException(status_code=500, detail="Failed to create new chat")
154
+
155
+ @router.post("/chat-sequential")
156
+ async def chat_sequential_enhanced(
157
+ message: ChatMessage,
158
+ request: Request,
159
+ current_user: User = Depends(get_current_active_user)
160
+ ):
161
+ """
162
+ Enhanced sequential chat with proper session management, document access, and intelligent persona ordering
163
+ """
164
+ try:
165
+ # Ensure consistent session ID for document retrieval
166
+ if message.chat_session_id:
167
+ # Use the memory session format that matches document storage
168
+ session_id = f"chat_{message.chat_session_id}"
169
+ logger.info(f"Using chat session: {session_id}")
170
+
171
+ # FIXED: Ensure session exists in memory (load if needed)
172
+ if session_id not in session_manager.sessions:
173
+ logger.warning(f"Chat session {message.chat_session_id} not in memory, loading now")
174
+
175
+ # FIXED: Pass the user_id parameter to properly load existing session
176
+ loaded_session_id = await get_or_create_session_for_request_async(
177
+ request,
178
+ chat_session_id=message.chat_session_id,
179
+ user_id=str(current_user.id)
180
+ )
181
+
182
+ # Use the loaded session ID
183
+ session_id = loaded_session_id
184
+ logger.info(f"Loaded session from database: {session_id}")
185
+ else:
186
+ # No specific chat session, create/use ephemeral session
187
+ session_id = await get_or_create_session_for_request_async(request)
188
+ logger.info(f"Using ephemeral session: {session_id}")
189
+
190
+ # Get session from memory
191
  session = session_manager.get_session(session_id)
192
+
193
+ # Log session debugging info
194
+ rag_stats = session.get_rag_stats()
195
+ logger.info(f"Session {session_id} has {rag_stats.get('total_documents', 0)} documents available")
196
+
197
+ # Add user message to session (needed for persona ranking)
198
  session.append_message("user", message.user_input)
199
 
200
+ # RESTORED: Get intelligently ordered personas based on context
201
  top_personas = await chat_orchestrator.get_top_personas(
202
  session_id=session_id,
203
+ k=3 # Limit to top 3 most relevant personas
204
  )
205
 
206
  logger.info(f"Intelligent persona order for session {session_id}: {top_personas}")
207
 
208
+ # Generate responses from ONLY the top personas
209
  responses = []
210
 
211
  for persona_id in top_personas:
212
  try:
213
+ logger.info(f"Generating response for {persona_id} with session {session_id}")
214
+
215
+ # Generate response from this specific persona
216
  persona_result = await chat_orchestrator.chat_with_persona(
217
  user_input=message.user_input,
218
  persona_id=persona_id,
219
+ session_id=session_id, # This ensures document access
220
  response_length=message.response_length or "medium"
221
  )
222
 
223
+ # FIXED: Safe response processing with proper error handling
224
+ if isinstance(persona_result, dict):
225
+ # Handle different response formats
226
+ if "persona_name" in persona_result and "response" in persona_result:
227
+ responses.append({
228
+ "persona_id": persona_result["persona_id"],
229
+ "persona_name": persona_result["persona_name"],
230
+ "content": persona_result["response"],
231
+ "used_documents": persona_result.get("used_documents", False),
232
+ "document_chunks_used": persona_result.get("document_chunks_used", 0)
233
+ })
234
+ elif persona_result.get("type") == "single_persona_response" and "persona" in persona_result:
235
+ persona_data = persona_result["persona"]
236
+ responses.append({
237
+ "persona_id": persona_data["persona_id"],
238
+ "persona_name": persona_data["persona_name"],
239
+ "content": persona_data["response"],
240
+ "used_documents": persona_data.get("used_documents", False),
241
+ "document_chunks_used": persona_data.get("document_chunks_used", 0)
242
+ })
243
+ elif "error" in persona_result:
244
+ # Handle error responses
245
+ responses.append({
246
+ "persona_id": persona_id,
247
+ "persona_name": chat_orchestrator.personas[persona_id].name,
248
+ "content": persona_result["response"],
249
+ "used_documents": False,
250
+ "document_chunks_used": 0
251
+ })
252
+ else:
253
+ # Generic dict response
254
+ content = persona_result.get("response") or persona_result.get("content", "")
255
+ if content.strip():
256
+ responses.append({
257
+ "persona_id": persona_id,
258
+ "persona_name": chat_orchestrator.personas[persona_id].name,
259
+ "content": content,
260
+ "used_documents": persona_result.get("used_documents", False),
261
+ "document_chunks_used": persona_result.get("document_chunks_used", 0)
262
+ })
263
  else:
264
+ # Fallback for non-dict responses
265
  responses.append({
 
266
  "persona_id": persona_id,
267
+ "persona_name": chat_orchestrator.personas[persona_id].name,
268
+ "content": "I'm having trouble processing your question right now. Please try again.",
269
+ "used_documents": False,
270
+ "document_chunks_used": 0
271
  })
272
 
273
  except Exception as e:
274
  logger.error(f"Error generating response for persona {persona_id}: {str(e)}")
 
275
  responses.append({
 
276
  "persona_id": persona_id,
277
+ "persona_name": chat_orchestrator.personas[persona_id].name,
278
+ "content": "I encountered an error while processing your question. Please try again.",
279
+ "used_documents": False,
280
+ "document_chunks_used": 0
281
  })
282
 
 
283
  return {
284
+ "responses": responses,
285
+ "session_debug": {
286
+ "session_id": session_id,
287
+ "documents_available": rag_stats.get('total_documents', 0),
288
+ "chunks_available": rag_stats.get('total_chunks', 0),
289
+ "valid_responses": len(responses),
290
+ "selected_personas": top_personas,
291
+ "total_personas_available": len(chat_orchestrator.personas)
292
+ }
293
  }
294
+
295
  except Exception as e:
296
+ logger.error(f"Error in chat_sequential_enhanced: {e}")
297
+ import traceback
298
+ logger.error(f"Full traceback: {traceback.format_exc()}")
299
+ raise HTTPException(status_code=500, detail=f"Chat processing failed: {str(e)}")
300
+
301
+
 
 
 
302
  @router.post("/chat/{persona_id}")
303
  async def chat_with_specific_advisor(persona_id: str, input: UserInput, request: Request):
304
+ """Chat with a specific advisor - UPDATED"""
305
  try:
306
  if persona_id not in chat_orchestrator.personas:
307
  raise HTTPException(status_code=404, detail=f"Persona '{persona_id}' not found")
308
 
309
+ # Use async session management
310
+ session_id = await get_or_create_session_for_request_async(request)
311
 
 
312
  result = await chat_orchestrator.chat_with_persona(
313
  user_input=input.user_input,
314
  persona_id=persona_id,
315
  session_id=session_id
316
  )
317
 
318
+ # Handle response structure
319
  if result.get("type") == "single_persona_response" and "persona" in result:
 
320
  persona_data = result["persona"]
321
  return {
322
  "persona": persona_data["persona_name"],
 
324
  "response": persona_data["response"]
325
  }
326
  elif "persona_id" in result and "response" in result:
 
327
  return {
328
  "persona": result["persona_name"],
329
  "persona_id": result["persona_id"],
330
  "response": result["response"]
331
  }
 
 
 
 
 
 
332
  else:
 
333
  return {
334
  "persona": "System",
335
  "response": "I'm having trouble generating a response right now. Please try again."
 
344
  "response": "I'm having trouble generating a response right now. Please try again."
345
  }
346
 
 
347
  @router.post("/reply-to-advisor")
348
  async def reply_to_advisor(reply: ReplyToAdvisor, request: Request):
349
+ """Reply to a specific advisor with proper context - UPDATED"""
350
  try:
351
  if reply.advisor_id not in chat_orchestrator.personas:
352
  raise HTTPException(status_code=404, detail=f"Advisor '{reply.advisor_id}' not found")
353
 
354
+ # Handle session management for existing chats
355
+ if reply.chat_session_id:
356
+ session_id = f"chat_{reply.chat_session_id}"
357
+ else:
358
+ session_id = await get_or_create_session_for_request_async(request)
359
+
360
+ session = session_manager.get_session(session_id)
361
+
362
+ # Find the original message being replied to for context
363
+ original_message = None
364
+ if reply.original_message_id:
365
+ for msg in session.messages:
366
+ if getattr(msg, 'id', None) == reply.original_message_id:
367
+ original_message = msg.content
368
+ break
369
+
370
+ # Create context-aware input
371
+ contextual_input = reply.user_input
372
+ if original_message:
373
+ contextual_input = f"[Replying to your previous message: '{original_message[:100]}...'] {reply.user_input}"
374
 
 
375
  result = await chat_orchestrator.chat_with_persona(
376
+ user_input=contextual_input,
377
  persona_id=reply.advisor_id,
378
  session_id=session_id
379
  )
380
 
381
+ # Handle response structure
382
+ if result.get("type") == "single_persona_response" and "persona" in result:
383
  persona_data = result["persona"]
384
  return {
385
  "type": "advisor_reply",
 
388
  "response": persona_data["response"],
389
  "original_message_id": reply.original_message_id
390
  }
391
+ elif "persona_id" in result and "response" in result:
392
+ return {
393
+ "type": "advisor_reply",
394
+ "persona": result["persona_name"],
395
+ "persona_id": result["persona_id"],
396
+ "response": result["response"],
397
+ "original_message_id": reply.original_message_id
398
+ }
399
  else:
400
  return {
401
  "type": "error",
402
  "persona": "System",
403
+ "response": "I'm having trouble generating a reply right now. Please try again."
404
  }
405
 
406
  except HTTPException:
 
412
  "persona": "System",
413
  "response": "I'm having trouble generating a reply right now. Please try again."
414
  }
415
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  @router.post("/ask/")
417
  async def ask_question(query: PersonaQuery, request: Request):
418
+ """Ask question - UPDATED"""
419
  try:
420
+ session_id = await get_or_create_session_for_request_async(request)
421
 
 
422
  result = await chat_orchestrator.chat_with_persona(
423
  user_input=query.question,
424
  persona_id=query.persona,
multi_llm_chatbot_backend/app/api/routes/chat_sessions.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends, status
2
+ from typing import List, Optional
3
+ from datetime import datetime
4
+ from bson import ObjectId
5
+ from app.models.user import User, ChatSession, ChatSessionResponse
6
+ from app.core.auth import get_current_active_user
7
+ from app.core.database import get_database
8
+ from pydantic import BaseModel
9
+ import logging
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ router = APIRouter()
14
+
15
+ class CreateChatSessionRequest(BaseModel):
16
+ title: str
17
+
18
+ class UpdateChatSessionRequest(BaseModel):
19
+ title: Optional[str] = None
20
+ messages: Optional[List[dict]] = None
21
+
22
+ class SaveMessageRequest(BaseModel):
23
+ session_id: str
24
+ message: dict
25
+
26
+ @router.post("/chat-sessions", response_model=dict)
27
+ async def create_chat_session(
28
+ request: CreateChatSessionRequest,
29
+ current_user: User = Depends(get_current_active_user)
30
+ ):
31
+ """Create a new chat session for the user"""
32
+ try:
33
+ db = get_database()
34
+
35
+ session = ChatSession(
36
+ user_id=current_user.id,
37
+ title=request.title,
38
+ messages=[],
39
+ created_at=datetime.utcnow(),
40
+ updated_at=datetime.utcnow()
41
+ )
42
+
43
+ result = await db.chat_sessions.insert_one(session.dict(by_alias=True))
44
+ session.id = result.inserted_id
45
+
46
+ return {
47
+ "id": str(session.id),
48
+ "title": session.title,
49
+ "created_at": session.created_at,
50
+ "updated_at": session.updated_at,
51
+ "message_count": 0
52
+ }
53
+
54
+ except Exception as e:
55
+ logger.error(f"Error creating chat session: {e}")
56
+ raise HTTPException(
57
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
58
+ detail="Could not create chat session"
59
+ )
60
+
61
+ @router.get("/chat-sessions", response_model=List[ChatSessionResponse])
62
+ async def get_user_chat_sessions(
63
+ current_user: User = Depends(get_current_active_user),
64
+ limit: int = 50,
65
+ skip: int = 0
66
+ ):
67
+ """Get all chat sessions for the current user"""
68
+ try:
69
+ db = get_database()
70
+
71
+ cursor = db.chat_sessions.find(
72
+ {"user_id": current_user.id, "is_active": True}
73
+ ).sort("updated_at", -1).skip(skip).limit(limit)
74
+
75
+ sessions = []
76
+ async for session_data in cursor:
77
+ sessions.append(ChatSessionResponse(
78
+ id=str(session_data["_id"]),
79
+ title=session_data["title"],
80
+ created_at=session_data["created_at"],
81
+ updated_at=session_data["updated_at"],
82
+ message_count=len(session_data.get("messages", []))
83
+ ))
84
+
85
+ return sessions
86
+
87
+ except Exception as e:
88
+ logger.error(f"Error fetching chat sessions: {e}")
89
+ raise HTTPException(
90
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
91
+ detail="Could not fetch chat sessions"
92
+ )
93
+
94
+ @router.get("/chat-sessions/{session_id}")
95
+ async def get_chat_session(
96
+ session_id: str,
97
+ current_user: User = Depends(get_current_active_user)
98
+ ):
99
+ """Get a specific chat session with all messages"""
100
+ try:
101
+ db = get_database()
102
+
103
+ session_data = await db.chat_sessions.find_one({
104
+ "_id": ObjectId(session_id),
105
+ "user_id": current_user.id,
106
+ "is_active": True
107
+ })
108
+
109
+ if not session_data:
110
+ raise HTTPException(
111
+ status_code=status.HTTP_404_NOT_FOUND,
112
+ detail="Chat session not found"
113
+ )
114
+
115
+ return {
116
+ "id": str(session_data["_id"]),
117
+ "title": session_data["title"],
118
+ "messages": session_data.get("messages", []),
119
+ "created_at": session_data["created_at"],
120
+ "updated_at": session_data["updated_at"]
121
+ }
122
+
123
+ except HTTPException:
124
+ raise
125
+ except Exception as e:
126
+ logger.error(f"Error fetching chat session: {e}")
127
+ raise HTTPException(
128
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
129
+ detail="Could not fetch chat session"
130
+ )
131
+
132
+ @router.put("/chat-sessions/{session_id}")
133
+ async def update_chat_session(
134
+ session_id: str,
135
+ request: UpdateChatSessionRequest,
136
+ current_user: User = Depends(get_current_active_user)
137
+ ):
138
+ """Update a chat session (title or messages)"""
139
+ try:
140
+ db = get_database()
141
+
142
+ # Verify session belongs to user
143
+ session_data = await db.chat_sessions.find_one({
144
+ "_id": ObjectId(session_id),
145
+ "user_id": current_user.id,
146
+ "is_active": True
147
+ })
148
+
149
+ if not session_data:
150
+ raise HTTPException(
151
+ status_code=status.HTTP_404_NOT_FOUND,
152
+ detail="Chat session not found"
153
+ )
154
+
155
+ update_data = {"updated_at": datetime.utcnow()}
156
+
157
+ if request.title is not None:
158
+ update_data["title"] = request.title
159
+
160
+ if request.messages is not None:
161
+ update_data["messages"] = request.messages
162
+
163
+ await db.chat_sessions.update_one(
164
+ {"_id": ObjectId(session_id)},
165
+ {"$set": update_data}
166
+ )
167
+
168
+ return {"message": "Chat session updated successfully"}
169
+
170
+ except HTTPException:
171
+ raise
172
+ except Exception as e:
173
+ logger.error(f"Error updating chat session: {e}")
174
+ raise HTTPException(
175
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
176
+ detail="Could not update chat session"
177
+ )
178
+
179
+ @router.post("/chat-sessions/{session_id}/messages")
180
+ async def save_message_to_session(
181
+ session_id: str,
182
+ request: SaveMessageRequest,
183
+ current_user: User = Depends(get_current_active_user)
184
+ ):
185
+ """Add a message to a chat session"""
186
+ try:
187
+ db = get_database()
188
+
189
+ # Verify session belongs to user
190
+ session_data = await db.chat_sessions.find_one({
191
+ "_id": ObjectId(session_id),
192
+ "user_id": current_user.id,
193
+ "is_active": True
194
+ })
195
+
196
+ if not session_data:
197
+ raise HTTPException(
198
+ status_code=status.HTTP_404_NOT_FOUND,
199
+ detail="Chat session not found"
200
+ )
201
+
202
+ # Add timestamp to message if not present
203
+ message = request.message.copy()
204
+ if "timestamp" not in message:
205
+ message["timestamp"] = datetime.utcnow().isoformat()
206
+
207
+ await db.chat_sessions.update_one(
208
+ {"_id": ObjectId(session_id)},
209
+ {
210
+ "$push": {"messages": message},
211
+ "$set": {"updated_at": datetime.utcnow()}
212
+ }
213
+ )
214
+
215
+ return {"message": "Message saved successfully"}
216
+
217
+ except HTTPException:
218
+ raise
219
+ except Exception as e:
220
+ logger.error(f"Error saving message: {e}")
221
+ raise HTTPException(
222
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
223
+ detail="Could not save message"
224
+ )
225
+
226
+ @router.delete("/chat-sessions/{session_id}")
227
+ async def delete_chat_session(
228
+ session_id: str,
229
+ current_user: User = Depends(get_current_active_user)
230
+ ):
231
+ """Delete a chat session (soft delete)"""
232
+ try:
233
+ db = get_database()
234
+
235
+ result = await db.chat_sessions.update_one(
236
+ {
237
+ "_id": ObjectId(session_id),
238
+ "user_id": current_user.id
239
+ },
240
+ {"$set": {"is_active": False, "updated_at": datetime.utcnow()}}
241
+ )
242
+
243
+ if result.matched_count == 0:
244
+ raise HTTPException(
245
+ status_code=status.HTTP_404_NOT_FOUND,
246
+ detail="Chat session not found"
247
+ )
248
+
249
+ return {"message": "Chat session deleted successfully"}
250
+
251
+ except HTTPException:
252
+ raise
253
+ except Exception as e:
254
+ logger.error(f"Error deleting chat session: {e}")
255
+ raise HTTPException(
256
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
257
+ detail="Could not delete chat session"
258
+ )
multi_llm_chatbot_backend/app/api/routes/debug.py CHANGED
@@ -1,10 +1,11 @@
1
  from fastapi import APIRouter, Request, Query
2
  from app.core.session_manager import get_session_manager
3
  from app.core.rag_manager import get_rag_manager
4
- from app.api.utils import get_or_create_session_for_request
5
  from app.core.bootstrap import chat_orchestrator
6
  import logging
7
 
 
 
8
  logger = logging.getLogger(__name__)
9
 
10
  router = APIRouter()
 
1
  from fastapi import APIRouter, Request, Query
2
  from app.core.session_manager import get_session_manager
3
  from app.core.rag_manager import get_rag_manager
 
4
  from app.core.bootstrap import chat_orchestrator
5
  import logging
6
 
7
+ from app.api.old_routes import get_or_create_session_for_request
8
+
9
  logger = logging.getLogger(__name__)
10
 
11
  router = APIRouter()
multi_llm_chatbot_backend/app/api/routes/documents.py CHANGED
@@ -1,29 +1,180 @@
1
- from fastapi import APIRouter, Request, HTTPException, UploadFile, File, Body
2
  from fastapi import Query
3
  from app.utils.document_extractor import extract_text_from_file
4
  from app.core.session_manager import get_session_manager
5
  from app.core.rag_manager import get_rag_manager
6
- from app.api.utils import get_or_create_session_for_request
7
  from fastapi.responses import StreamingResponse
8
  from app.utils.chat_summary import generate_summary_from_messages, parse_summary_to_blocks, format_summary_for_text_export
9
  from app.utils.file_export import prepare_export_response, generate_pdf_file_from_blocks
10
  from app.core.session_manager import get_session_manager
11
- from app.api.utils import get_or_create_session_for_request
12
  from app.core.bootstrap import chat_orchestrator
 
 
 
 
13
  import logging
 
 
 
14
 
15
  logger = logging.getLogger(__name__)
16
 
17
  router = APIRouter()
18
 
19
  session_manager = get_session_manager()
20
- get_rag_manager = get_rag_manager # avoid circular import issues
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
  @router.post("/upload-document")
24
- async def upload_document(file: UploadFile = File(...), request: Request = None):
 
 
 
 
 
25
  try:
26
- session_id = get_or_create_session_for_request(request)
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  session = session_manager.get_session(session_id)
28
 
29
  MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
@@ -43,6 +194,8 @@ async def upload_document(file: UploadFile = File(...), request: Request = None)
43
  }
44
  file_type = file_type_map.get(file.content_type, "unknown")
45
 
 
 
46
  rag_result = rag_manager.add_document(
47
  content=content,
48
  filename=file.filename,
@@ -64,6 +217,7 @@ async def upload_document(file: UploadFile = File(...), request: Request = None)
64
  f"Document uploaded: '{doc_title}' ({file.filename}) - {rag_result['chunks_created']} sections processed, ~{rag_result['total_tokens']} tokens analyzed. You can now ask questions about this document by referencing it by name."
65
  )
66
 
 
67
  return {
68
  "message": f"Document '{file.filename}' uploaded and processed successfully.",
69
  "filename": file.filename,
@@ -71,7 +225,10 @@ async def upload_document(file: UploadFile = File(...), request: Request = None)
71
  "chunks_created": rag_result['chunks_created'],
72
  "total_tokens": rag_result['total_tokens'],
73
  "file_type": file_type,
74
- "can_reference_by_name": True
 
 
 
75
  }
76
 
77
  except HTTPException:
@@ -84,7 +241,7 @@ async def upload_document(file: UploadFile = File(...), request: Request = None)
84
  @router.post("/search-documents")
85
  async def search_documents(request: Request, query: str = Body(..., embed=True), persona: str = Body("", embed=True)):
86
  try:
87
- session_id = get_or_create_session_for_request(request)
88
  rag_manager = get_rag_manager()
89
 
90
  persona_contexts = {
@@ -116,7 +273,7 @@ async def search_documents(request: Request, query: str = Body(..., embed=True),
116
  @router.get("/document-stats")
117
  async def get_document_stats(request: Request):
118
  try:
119
- session_id = get_or_create_session_for_request(request)
120
  rag_manager = get_rag_manager()
121
  return rag_manager.get_document_stats(session_id)
122
  except Exception as e:
@@ -127,7 +284,7 @@ async def get_document_stats(request: Request):
127
  @router.get("/uploaded-files")
128
  async def get_uploaded_filenames(request: Request):
129
  try:
130
- session_id = get_or_create_session_for_request(request)
131
  session = session_manager.get_session(session_id)
132
  return {"files": session.uploaded_files}
133
  except Exception as e:
@@ -138,7 +295,7 @@ async def get_uploaded_filenames(request: Request):
138
  @router.get("/document-insights/{filename}")
139
  async def get_document_insights(filename: str, request: Request):
140
  try:
141
- session_id = get_or_create_session_for_request(request)
142
  rag_manager = get_rag_manager()
143
  stats = rag_manager.get_document_stats(session_id)
144
  document_info = next((doc for doc in stats.get("documents", []) if doc["filename"] == filename), None)
@@ -185,61 +342,189 @@ async def get_document_insights(filename: str, request: Request):
185
  raise HTTPException(status_code=500, detail=f"Error analyzing document: {str(e)}")
186
 
187
  @router.get("/export-chat")
188
- async def export_chat(request: Request, format: str = Query(..., regex="^(txt|pdf|docx)$")):
 
 
 
 
 
 
 
 
 
 
189
  try:
190
- session_id = get_or_create_session_for_request(request)
191
- session = session_manager.get_session(session_id)
192
-
193
- if not session.messages:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  return {"error": "No messages in this session."}
195
 
196
- return prepare_export_response(session.messages, format)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
 
 
198
  except Exception as e:
199
  logger.error(f"Error exporting chat: {str(e)}")
200
- return {"error": "Failed to export chat.", "detail": str(e)}
 
 
 
201
 
202
  @router.get("/chat-summary")
203
  async def chat_summary(
204
  request: Request,
205
- format: str = Query("text", regex="^(txt|pdf|docx)$")
 
 
206
  ):
207
  """
208
- Generate and return a summary of the current session chat.
 
 
209
  Can return as plain txt, PDF, or DOCX.
210
  """
211
  try:
212
- session_id = get_or_create_session_for_request(request)
213
- session = session_manager.get_session(session_id)
214
-
215
- if not session.messages:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  return {"error": "No messages in this session."}
217
 
218
- llm = next(iter(chat_orchestrator.personas.values())).llm
219
- summary_text = await generate_summary_from_messages(session.messages, llm)
220
-
221
- if format == "txt":
222
- # Use improved formatting for text export
223
- formatted_summary = format_summary_for_text_export(summary_text)
224
- return prepare_export_response(formatted_summary, "txt", filename_prefix="chat_summary")
225
-
226
- elif format == "docx":
227
- # Use improved formatting for DOCX export
228
- formatted_summary = format_summary_for_text_export(summary_text)
229
- return prepare_export_response(formatted_summary, "docx", filename_prefix="chat_summary")
230
-
231
- elif format == "pdf":
232
- # Parse and render using block formatting
233
- blocks = [{"type": "heading", "text": "Chat Summary"}] + parse_summary_to_blocks(summary_text)
234
-
235
- file_stream = generate_pdf_file_from_blocks(blocks)
236
- return StreamingResponse(
237
- file_stream,
238
- media_type="application/pdf",
239
- headers={"Content-Disposition": "attachment; filename=chat_summary.pdf"}
240
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
 
 
242
  except Exception as e:
243
  logger.error(f"Error in chat-summary endpoint: {str(e)}")
244
- return {"error": "Summary generation failed", "detail": str(e)}
245
-
 
 
 
1
+ from fastapi import APIRouter, Request, HTTPException, UploadFile, File, Body, Depends
2
  from fastapi import Query
3
  from app.utils.document_extractor import extract_text_from_file
4
  from app.core.session_manager import get_session_manager
5
  from app.core.rag_manager import get_rag_manager
6
+ from app.api.utils import get_or_create_session_for_request_async
7
  from fastapi.responses import StreamingResponse
8
  from app.utils.chat_summary import generate_summary_from_messages, parse_summary_to_blocks, format_summary_for_text_export
9
  from app.utils.file_export import prepare_export_response, generate_pdf_file_from_blocks
10
  from app.core.session_manager import get_session_manager
 
11
  from app.core.bootstrap import chat_orchestrator
12
+ from app.core.auth import get_current_active_user
13
+ from app.core.database import get_database
14
+ from app.models.user import User
15
+ from bson import ObjectId
16
  import logging
17
+ import re
18
+ from html import unescape
19
+
20
 
21
  logger = logging.getLogger(__name__)
22
 
23
  router = APIRouter()
24
 
25
  session_manager = get_session_manager()
26
+ get_rag_manager = get_rag_manager
27
+
28
+
29
+ def sanitize_html_content(content):
30
+ """
31
+ Clean up HTML content by removing or fixing malformed tags.
32
+ This prevents PDF export errors caused by invalid HTML structure.
33
+ """
34
+ if not content:
35
+ return content
36
+
37
+ try:
38
+ logger.debug(f"Sanitizing content (first 200 chars): {content[:200]}")
39
+
40
+ # First, unescape HTML entities
41
+ content = unescape(content)
42
+
43
+ # More aggressive approach: Strip ALL HTML tags first, then apply simple formatting
44
+ # This prevents malformed HTML from causing issues
45
+
46
+ # Remove all HTML tags completely (most aggressive approach)
47
+ content = re.sub(r'<[^>]*>', '', content)
48
+
49
+ # Clean up multiple spaces and normalize whitespace
50
+ content = re.sub(r'\s+', ' ', content)
51
+ content = content.strip()
52
+
53
+ # Remove any remaining HTML entities that might have been missed
54
+ content = re.sub(r'&[a-zA-Z0-9#]+;', '', content)
55
+
56
+ # Remove any remaining angle brackets that might cause issues
57
+ content = content.replace('<', '').replace('>', '')
58
+
59
+ logger.debug(f"Sanitized content (first 200 chars): {content[:200]}")
60
+ return content
61
+
62
+ except Exception as e:
63
+ logger.error(f"Error sanitizing HTML content: {str(e)}")
64
+ # Ultra-fallback: return only alphanumeric and basic punctuation
65
+ try:
66
+ import string
67
+ allowed_chars = string.ascii_letters + string.digits + string.punctuation + ' \n\r\t'
68
+ cleaned = ''.join(c for c in content if c in allowed_chars)
69
+ return re.sub(r'\s+', ' ', cleaned).strip()
70
+ except:
71
+ return "Content could not be sanitized for export"
72
+
73
+ def convert_messages_for_export(messages):
74
+ """
75
+ Convert stored message format to export-compatible format.
76
+ Stored format uses 'type', export functions expect 'role' and specific structure.
77
+ """
78
+ converted_messages = []
79
+
80
+ for i, msg in enumerate(messages):
81
+ try:
82
+ # Get and sanitize content
83
+ raw_content = msg.get('content', '')
84
+ sanitized_content = sanitize_html_content(raw_content)
85
+
86
+ # Debug logging for problematic content
87
+ if i < 5 or '<' in raw_content or '>' in raw_content: # Log first few messages and any with HTML
88
+ logger.debug(f"Message {i}: Original length: {len(raw_content)}, Sanitized length: {len(sanitized_content)}")
89
+ if raw_content != sanitized_content:
90
+ logger.debug(f"Content changed during sanitization for message {msg.get('id', 'unknown')}")
91
+
92
+ # Create base converted message
93
+ converted_msg = {
94
+ 'id': msg.get('id', 'unknown'),
95
+ 'timestamp': msg.get('timestamp', ''),
96
+ 'content': sanitized_content,
97
+ }
98
+
99
+ # Convert type to role and handle different message types
100
+ msg_type = msg.get('type', 'unknown')
101
+
102
+ if msg_type == 'user':
103
+ converted_msg['role'] = 'user'
104
+ # Add reply context if present
105
+ if 'replyTo' in msg:
106
+ reply_to = msg['replyTo']
107
+ converted_msg['content'] = f"[Reply to {reply_to.get('advisorName', 'advisor')}] {converted_msg['content']}"
108
+
109
+ elif msg_type == 'advisor':
110
+ converted_msg['role'] = 'assistant'
111
+ # Include advisor information
112
+ advisor_name = msg.get('advisorName', msg.get('persona', 'Advisor'))
113
+ converted_msg['advisor_name'] = advisor_name
114
+ converted_msg['advisor_id'] = msg.get('advisorId', msg.get('persona_id', 'unknown'))
115
+
116
+ # Mark special response types
117
+ if msg.get('isReply'):
118
+ converted_msg['content'] = f"[{advisor_name} replies] {converted_msg['content']}"
119
+ elif msg.get('isExpansion'):
120
+ converted_msg['content'] = f"[{advisor_name} expands] {converted_msg['content']}"
121
+ else:
122
+ converted_msg['content'] = f"[{advisor_name}] {converted_msg['content']}"
123
+
124
+ elif msg_type == 'system':
125
+ converted_msg['role'] = 'system'
126
+
127
+ elif msg_type == 'document_upload':
128
+ converted_msg['role'] = 'system'
129
+ converted_msg['content'] = f"📄 {converted_msg['content']}"
130
+
131
+ elif msg_type == 'error':
132
+ converted_msg['role'] = 'system'
133
+ converted_msg['content'] = f"❌ Error: {converted_msg['content']}"
134
+
135
+ else:
136
+ # Unknown type, treat as system message
137
+ converted_msg['role'] = 'system'
138
+ converted_msg['content'] = f"[{msg_type}] {converted_msg['content']}"
139
+
140
+ converted_messages.append(converted_msg)
141
+
142
+ except Exception as e:
143
+ logger.error(f"Error converting message {msg.get('id', 'unknown')}: {str(e)}")
144
+ # Add a fallback message to maintain conversation flow
145
+ converted_messages.append({
146
+ 'id': msg.get('id', 'unknown'),
147
+ 'role': 'system',
148
+ 'content': f"[Message conversion error: {str(e)}]",
149
+ 'timestamp': msg.get('timestamp', '')
150
+ })
151
+
152
+ logger.info(f"Converted {len(messages)} messages for export")
153
+ return converted_messages
154
 
155
 
156
  @router.post("/upload-document")
157
+ async def upload_document(
158
+ file: UploadFile = File(...),
159
+ request: Request = None,
160
+ chat_session_id: str = Query(None, description="Chat session ID if uploading to specific chat"),
161
+ current_user: User = Depends(get_current_active_user) # ADDED: Require authentication
162
+ ):
163
  try:
164
+ if chat_session_id:
165
+ # If uploading to a specific chat, use chat_{id} format
166
+ session_id = f"chat_{chat_session_id}"
167
+ logger.info(f"Uploading document to specific chat session: {session_id}")
168
+ else:
169
+ # For new/temporary chats, use regular session management
170
+ session_id = await get_or_create_session_for_request_async(request)
171
+ logger.info(f"Uploading document to new session: {session_id}")
172
+
173
+ # Add debug logging to track session IDs
174
+ logger.info(f"Document upload - chat_session_id parameter: {chat_session_id}")
175
+ logger.info(f"Document upload - final session_id: {session_id}")
176
+ logger.info(f"Document upload - user_id: {current_user.id}")
177
+
178
  session = session_manager.get_session(session_id)
179
 
180
  MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
 
194
  }
195
  file_type = file_type_map.get(file.content_type, "unknown")
196
 
197
+ # Pass the consistent session_id to RAG manager
198
+ logger.info(f"Adding document {file.filename} to session {session_id}")
199
  rag_result = rag_manager.add_document(
200
  content=content,
201
  filename=file.filename,
 
217
  f"Document uploaded: '{doc_title}' ({file.filename}) - {rag_result['chunks_created']} sections processed, ~{rag_result['total_tokens']} tokens analyzed. You can now ask questions about this document by referencing it by name."
218
  )
219
 
220
+ # Return session info for frontend tracking
221
  return {
222
  "message": f"Document '{file.filename}' uploaded and processed successfully.",
223
  "filename": file.filename,
 
225
  "chunks_created": rag_result['chunks_created'],
226
  "total_tokens": rag_result['total_tokens'],
227
  "file_type": file_type,
228
+ "can_reference_by_name": True,
229
+ "session_id": session_id,
230
+ "chat_session_id": chat_session_id,
231
+ "user_id": str(current_user.id) # ADDED: Include user ID for debugging
232
  }
233
 
234
  except HTTPException:
 
241
  @router.post("/search-documents")
242
  async def search_documents(request: Request, query: str = Body(..., embed=True), persona: str = Body("", embed=True)):
243
  try:
244
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
245
  rag_manager = get_rag_manager()
246
 
247
  persona_contexts = {
 
273
  @router.get("/document-stats")
274
  async def get_document_stats(request: Request):
275
  try:
276
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
277
  rag_manager = get_rag_manager()
278
  return rag_manager.get_document_stats(session_id)
279
  except Exception as e:
 
284
  @router.get("/uploaded-files")
285
  async def get_uploaded_filenames(request: Request):
286
  try:
287
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
288
  session = session_manager.get_session(session_id)
289
  return {"files": session.uploaded_files}
290
  except Exception as e:
 
295
  @router.get("/document-insights/{filename}")
296
  async def get_document_insights(filename: str, request: Request):
297
  try:
298
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
299
  rag_manager = get_rag_manager()
300
  stats = rag_manager.get_document_stats(session_id)
301
  document_info = next((doc for doc in stats.get("documents", []) if doc["filename"] == filename), None)
 
342
  raise HTTPException(status_code=500, detail=f"Error analyzing document: {str(e)}")
343
 
344
  @router.get("/export-chat")
345
+ async def export_chat(
346
+ request: Request,
347
+ format: str = Query(..., regex="^(txt|pdf|docx)$"),
348
+ chat_session_id: str = Query(None, description="Optional: specific chat session ID to export"),
349
+ current_user: User = Depends(get_current_active_user)
350
+ ):
351
+ """
352
+ Export chat messages.
353
+ If chat_session_id is provided, exports that specific stored chat session.
354
+ Otherwise, exports the current in-memory session.
355
+ """
356
  try:
357
+ messages = []
358
+
359
+ if chat_session_id:
360
+ # Export specific stored chat session
361
+ db = get_database()
362
+ session_data = await db.chat_sessions.find_one({
363
+ "_id": ObjectId(chat_session_id),
364
+ "user_id": current_user.id,
365
+ "is_active": True
366
+ })
367
+
368
+ if not session_data:
369
+ raise HTTPException(
370
+ status_code=404,
371
+ detail="Chat session not found or you don't have permission to access it"
372
+ )
373
+
374
+ raw_messages = session_data.get("messages", [])
375
+ # Convert stored message format to export-compatible format
376
+ messages = convert_messages_for_export(raw_messages)
377
+ else:
378
+ # Export current in-memory session (existing behavior)
379
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
380
+ session = session_manager.get_session(session_id)
381
+ # In-memory messages might already be in the right format, but convert to be safe
382
+ messages = convert_messages_for_export(session.messages)
383
+
384
+ if not messages:
385
  return {"error": "No messages in this session."}
386
 
387
+ try:
388
+ return prepare_export_response(messages, format)
389
+ except Exception as export_error:
390
+ logger.error(f"Error in prepare_export_response: {str(export_error)}")
391
+ # Try with a simplified version of messages if the export fails
392
+ try:
393
+ # Create simplified messages with just basic text content
394
+ simplified_messages = []
395
+ for msg in messages:
396
+ simplified_msg = {
397
+ 'id': msg.get('id', 'unknown'),
398
+ 'role': msg.get('role', 'system'),
399
+ 'content': str(msg.get('content', '')).replace('\n', ' ').strip(),
400
+ 'timestamp': msg.get('timestamp', '')
401
+ }
402
+ if 'advisor_name' in msg:
403
+ simplified_msg['advisor_name'] = msg['advisor_name']
404
+ simplified_messages.append(simplified_msg)
405
+
406
+ return prepare_export_response(simplified_messages, format)
407
+ except Exception as fallback_error:
408
+ logger.error(f"Fallback export also failed: {str(fallback_error)}")
409
+ raise HTTPException(
410
+ status_code=500,
411
+ detail=f"Export failed due to content formatting issues. Please try a different format or contact support."
412
+ )
413
 
414
+ except HTTPException:
415
+ raise
416
  except Exception as e:
417
  logger.error(f"Error exporting chat: {str(e)}")
418
+ raise HTTPException(
419
+ status_code=500,
420
+ detail=f"Failed to export chat: {str(e)}"
421
+ )
422
 
423
  @router.get("/chat-summary")
424
  async def chat_summary(
425
  request: Request,
426
+ format: str = Query("text", regex="^(txt|pdf|docx)$"),
427
+ chat_session_id: str = Query(None, description="Optional: specific chat session ID to summarize"),
428
+ current_user: User = Depends(get_current_active_user)
429
  ):
430
  """
431
+ Generate and return a summary of chat messages.
432
+ If chat_session_id is provided, summarizes that specific stored chat session.
433
+ Otherwise, summarizes the current in-memory session.
434
  Can return as plain txt, PDF, or DOCX.
435
  """
436
  try:
437
+ messages = []
438
+
439
+ if chat_session_id:
440
+ # Summarize specific stored chat session
441
+ db = get_database()
442
+ session_data = await db.chat_sessions.find_one({
443
+ "_id": ObjectId(chat_session_id),
444
+ "user_id": current_user.id,
445
+ "is_active": True
446
+ })
447
+
448
+ if not session_data:
449
+ raise HTTPException(
450
+ status_code=404,
451
+ detail="Chat session not found or you don't have permission to access it"
452
+ )
453
+
454
+ raw_messages = session_data.get("messages", [])
455
+ # Convert stored message format for summary generation
456
+ messages = convert_messages_for_export(raw_messages)
457
+ else:
458
+ # Summarize current in-memory session (existing behavior)
459
+ session_id = await get_or_create_session_for_request_async(request) # FIXED: Added await
460
+ session = session_manager.get_session(session_id)
461
+ # Convert in-memory messages
462
+ messages = convert_messages_for_export(session.messages)
463
+
464
+ if not messages:
465
  return {"error": "No messages in this session."}
466
 
467
+ try:
468
+ llm = next(iter(chat_orchestrator.personas.values())).llm
469
+ summary_text = await generate_summary_from_messages(messages, llm)
470
+
471
+ if format == "txt":
472
+ # Use improved formatting for text export
473
+ formatted_summary = format_summary_for_text_export(summary_text)
474
+ return prepare_export_response(formatted_summary, "txt", filename_prefix="chat_summary")
475
+
476
+ elif format == "docx":
477
+ # Use improved formatting for DOCX export
478
+ formatted_summary = format_summary_for_text_export(summary_text)
479
+ return prepare_export_response(formatted_summary, "docx", filename_prefix="chat_summary")
480
+
481
+ elif format == "pdf":
482
+ # Parse and render using block formatting
483
+ blocks = [{"type": "heading", "text": "Chat Summary"}] + parse_summary_to_blocks(summary_text)
484
+
485
+ file_stream = generate_pdf_file_from_blocks(blocks)
486
+ return StreamingResponse(
487
+ file_stream,
488
+ media_type="application/pdf",
489
+ headers={"Content-Disposition": "attachment; filename=chat_summary.pdf"}
490
+ )
491
+ except Exception as summary_error:
492
+ logger.error(f"Error generating summary: {str(summary_error)}")
493
+ # Try with simplified content
494
+ try:
495
+ # Create a basic text summary if AI summary fails
496
+ basic_summary = "Chat Summary\n\n"
497
+ for msg in messages:
498
+ if msg.get('role') == 'user':
499
+ basic_summary += f"User: {msg.get('content', '')[:200]}...\n\n"
500
+ elif msg.get('role') == 'assistant':
501
+ advisor_name = msg.get('advisor_name', 'Advisor')
502
+ basic_summary += f"{advisor_name}: {msg.get('content', '')[:200]}...\n\n"
503
+
504
+ if format == "txt":
505
+ return prepare_export_response(basic_summary, "txt", filename_prefix="chat_summary")
506
+ elif format == "docx":
507
+ return prepare_export_response(basic_summary, "docx", filename_prefix="chat_summary")
508
+ elif format == "pdf":
509
+ blocks = [{"type": "heading", "text": "Chat Summary"}, {"type": "paragraph", "text": basic_summary}]
510
+ file_stream = generate_pdf_file_from_blocks(blocks)
511
+ return StreamingResponse(
512
+ file_stream,
513
+ media_type="application/pdf",
514
+ headers={"Content-Disposition": "attachment; filename=chat_summary.pdf"}
515
+ )
516
+ except Exception as fallback_error:
517
+ logger.error(f"Fallback summary export also failed: {str(fallback_error)}")
518
+ raise HTTPException(
519
+ status_code=500,
520
+ detail=f"Summary generation failed due to content formatting issues. Please try a different format."
521
+ )
522
 
523
+ except HTTPException:
524
+ raise
525
  except Exception as e:
526
  logger.error(f"Error in chat-summary endpoint: {str(e)}")
527
+ raise HTTPException(
528
+ status_code=500,
529
+ detail=f"Summary generation failed: {str(e)}"
530
+ )
multi_llm_chatbot_backend/app/api/routes/sessions.py CHANGED
@@ -1,54 +1,265 @@
1
- from fastapi import APIRouter, Request, HTTPException
2
  from app.core.session_manager import get_session_manager
3
- from app.api.utils import get_or_create_session_for_request
 
 
 
 
4
  import logging
5
 
6
  logger = logging.getLogger(__name__)
7
 
8
  router = APIRouter()
9
-
10
  session_manager = get_session_manager()
11
 
 
 
 
 
12
  @router.get("/context")
13
- async def get_context(request: Request):
 
 
 
 
 
 
 
 
14
  try:
15
- session_id = get_or_create_session_for_request(request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  session = session_manager.get_session(session_id)
17
  rag_stats = session.get_rag_stats()
18
- return {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  "messages": session.messages,
20
  "rag_info": {
21
  "total_documents": rag_stats.get("total_documents", 0),
22
  "total_chunks": rag_stats.get("total_chunks", 0),
23
  "documents": rag_stats.get("documents", [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
  }
 
 
 
26
  except Exception as e:
27
- logger.error(f"Error getting context: {str(e)}")
28
- return {"messages": [], "rag_info": {"total_documents": 0, "total_chunks": 0}}
29
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  @router.post("/reset-session")
32
- async def reset_session(request: Request):
 
 
 
 
 
 
 
 
33
  try:
34
- session_id = get_or_create_session_for_request(request)
35
- success = session_manager.reset_session_completely(session_id)
36
-
37
- if success:
38
- return {"status": "reset", "message": "Session and all documents reset successfully"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  else:
40
- return {"status": "error", "message": "Failed to reset session"}
 
 
 
 
 
 
 
 
 
 
 
41
  except Exception as e:
42
  logger.error(f"Error resetting session: {e}")
43
- return {"status": "error", "message": "Failed to reset session"}
44
-
45
 
46
  @router.get("/session-stats")
47
- async def get_session_stats(request: Request):
 
 
 
 
 
 
 
 
48
  try:
49
- session_id = get_or_create_session_for_request(request)
 
 
 
 
 
 
50
  stats = session_manager.get_session_stats(session_id)
 
 
 
 
 
51
  return stats
 
52
  except Exception as e:
53
  logger.error(f"Error getting session stats: {str(e)}")
54
  return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Request, HTTPException, Depends
2
  from app.core.session_manager import get_session_manager
3
+ from app.api.utils import get_or_create_session_for_request_async
4
+ from app.core.auth import get_current_active_user
5
+ from app.models.user import User
6
+ from pydantic import BaseModel
7
+ from typing import Optional
8
  import logging
9
 
10
  logger = logging.getLogger(__name__)
11
 
12
  router = APIRouter()
 
13
  session_manager = get_session_manager()
14
 
15
+ class ResetSessionRequest(BaseModel):
16
+ chat_session_id: Optional[str] = None
17
+ force_new: bool = False
18
+
19
  @router.get("/context")
20
+ async def get_context(
21
+ request: Request,
22
+ chat_session_id: Optional[str] = None,
23
+ current_user: User = Depends(get_current_active_user)
24
+ ):
25
+ """
26
+ Get context for current session - ENHANCED with document access fix
27
+ Now properly handles different chat sessions and ensures document access
28
+ """
29
  try:
30
+ # Determine which session to get context for with consistent session ID format
31
+ if chat_session_id:
32
+ # Getting context for a specific chat session - use consistent format
33
+ session_id = f"chat_{chat_session_id}"
34
+ logger.info(f"Getting context for specific chat session: {session_id}")
35
+
36
+ # Ensure session is loaded in memory
37
+ if session_id not in session_manager.sessions:
38
+ logger.info(f"Chat session {session_id} not in memory, loading from database")
39
+ loaded_session_id = await get_or_create_session_for_request_async(
40
+ request,
41
+ chat_session_id=chat_session_id,
42
+ user_id=str(current_user.id)
43
+ )
44
+ session_id = loaded_session_id
45
+ logger.info(f"Loaded session ID: {session_id}")
46
+ else:
47
+ # Getting context for current session
48
+ session_id = await get_or_create_session_for_request_async(request)
49
+ logger.info(f"Getting context for current session: {session_id}")
50
+
51
  session = session_manager.get_session(session_id)
52
  rag_stats = session.get_rag_stats()
53
+
54
+ # Enhanced logging for document access debugging
55
+ logger.info(f"Retrieved context for session {session_id}:")
56
+ logger.info(f" - Messages: {len(session.messages)}")
57
+ logger.info(f" - Documents: {rag_stats.get('total_documents', 0)}")
58
+ logger.info(f" - Chunks: {rag_stats.get('total_chunks', 0)}")
59
+ logger.info(f" - Uploaded files: {len(session.uploaded_files)}")
60
+
61
+ # Log document details if available
62
+ if rag_stats.get('documents'):
63
+ for doc in rag_stats['documents']:
64
+ logger.info(f" - Available document: {doc.get('filename', 'unknown')} ({doc.get('chunks', 0)} chunks)")
65
+
66
+ # Include session debugging info in response
67
+ context_response = {
68
+ "session_id": session_id,
69
+ "chat_session_id": chat_session_id,
70
  "messages": session.messages,
71
  "rag_info": {
72
  "total_documents": rag_stats.get("total_documents", 0),
73
  "total_chunks": rag_stats.get("total_chunks", 0),
74
  "documents": rag_stats.get("documents", [])
75
+ },
76
+ "context_stats": {
77
+ "message_count": len(session.messages),
78
+ "user_messages": len([m for m in session.messages if m.get('role') == 'user']),
79
+ "uploaded_files": session.uploaded_files,
80
+ "total_upload_size": session.total_upload_size,
81
+ "created_at": session.created_at.isoformat(),
82
+ "last_accessed": session.last_accessed.isoformat()
83
+ },
84
+ # Add debugging info
85
+ "debug_info": {
86
+ "session_format": "chat_session" if chat_session_id else "new_session",
87
+ "session_in_memory": session_id in session_manager.sessions,
88
+ "document_access_working": rag_stats.get("total_documents", 0) > 0
89
  }
90
  }
91
+
92
+ return context_response
93
+
94
  except Exception as e:
95
+ logger.error(f"Error getting context for session_id {session_id if 'session_id' in locals() else 'unknown'}: {str(e)}")
96
+ logger.error(f"Chat session ID: {chat_session_id}")
97
+ import traceback
98
+ logger.error(f"Full traceback: {traceback.format_exc()}")
99
+
100
+ return {
101
+ "session_id": session_id if 'session_id' in locals() else None,
102
+ "chat_session_id": chat_session_id,
103
+ "messages": [],
104
+ "rag_info": {"total_documents": 0, "total_chunks": 0, "documents": []},
105
+ "context_stats": {
106
+ "message_count": 0,
107
+ "user_messages": 0,
108
+ "uploaded_files": [],
109
+ "total_upload_size": 0
110
+ },
111
+ "error": str(e),
112
+ "debug_info": {
113
+ "error_occurred": True,
114
+ "error_type": type(e).__name__
115
+ }
116
+ }
117
 
118
  @router.post("/reset-session")
119
+ async def reset_session(
120
+ reset_request: ResetSessionRequest,
121
+ request: Request,
122
+ current_user: User = Depends(get_current_active_user)
123
+ ):
124
+ """
125
+ Reset session - ENHANCED
126
+ Now properly handles different reset scenarios
127
+ """
128
  try:
129
+ if reset_request.force_new:
130
+ # Force create a completely new session
131
+ session_id = session_manager.create_session()
132
+ session = session_manager.get_session(session_id)
133
+ session.clear_all_data()
134
+
135
+ logger.info(f"Force created new session: {session_id}")
136
+
137
+ return {
138
+ "status": "reset",
139
+ "message": "New session created with fresh context",
140
+ "session_id": session_id,
141
+ "chat_session_id": None
142
+ }
143
+
144
+ elif reset_request.chat_session_id:
145
+ # Reset a specific chat session context
146
+ session_id = f"chat_{reset_request.chat_session_id}"
147
+
148
+ if session_id in session_manager.sessions:
149
+ success = session_manager.reset_session_completely(session_id)
150
+ message = "Chat session context reset successfully" if success else "Failed to reset chat session context"
151
+ else:
152
+ # Create fresh context for this chat
153
+ session = session_manager.get_session(session_id)
154
+ session.clear_all_data()
155
+ success = True
156
+ message = "Fresh context created for chat session"
157
+
158
+ logger.info(f"Reset chat session {reset_request.chat_session_id}, memory session: {session_id}")
159
+
160
+ return {
161
+ "status": "reset" if success else "error",
162
+ "message": message,
163
+ "session_id": session_id,
164
+ "chat_session_id": reset_request.chat_session_id
165
+ }
166
+
167
  else:
168
+ # Reset current session
169
+ session_id = await get_or_create_session_for_request_async(request)
170
+ success = session_manager.reset_session_completely(session_id)
171
+
172
+ logger.info(f"Reset current session: {session_id}")
173
+
174
+ return {
175
+ "status": "reset" if success else "error",
176
+ "message": "Current session reset successfully" if success else "Failed to reset current session",
177
+ "session_id": session_id
178
+ }
179
+
180
  except Exception as e:
181
  logger.error(f"Error resetting session: {e}")
182
+ return {"status": "error", "message": f"Failed to reset session: {str(e)}"}
 
183
 
184
  @router.get("/session-stats")
185
+ async def get_session_stats(
186
+ request: Request,
187
+ chat_session_id: Optional[str] = None,
188
+ current_user: User = Depends(get_current_active_user)
189
+ ):
190
+ """
191
+ Get session statistics - ENHANCED
192
+ Now provides detailed stats for different session types
193
+ """
194
  try:
195
+ if chat_session_id:
196
+ # Stats for specific chat session
197
+ session_id = f"chat_{chat_session_id}"
198
+ else:
199
+ # Stats for current session
200
+ session_id = await get_or_create_session_for_request_async(request)
201
+
202
  stats = session_manager.get_session_stats(session_id)
203
+
204
+ # Add additional context
205
+ stats["session_type"] = "chat_session" if chat_session_id else "current_session"
206
+ stats["chat_session_id"] = chat_session_id
207
+
208
  return stats
209
+
210
  except Exception as e:
211
  logger.error(f"Error getting session stats: {str(e)}")
212
  return {"error": str(e)}
213
+
214
+ @router.get("/active-sessions")
215
+ async def get_active_sessions(current_user: User = Depends(get_current_active_user)):
216
+ """
217
+ Get all active sessions for debugging
218
+ """
219
+ try:
220
+ active_count = session_manager.get_active_session_count()
221
+
222
+ # Get overview of sessions (don't return full content for privacy)
223
+ session_overview = {}
224
+ for session_id, session in session_manager.sessions.items():
225
+ session_overview[session_id] = {
226
+ "message_count": len(session.messages),
227
+ "uploaded_files": len(session.uploaded_files),
228
+ "created_at": session.created_at.isoformat(),
229
+ "last_accessed": session.last_accessed.isoformat(),
230
+ "is_chat_session": session_id.startswith("chat_")
231
+ }
232
+
233
+ return {
234
+ "active_session_count": active_count,
235
+ "sessions": session_overview
236
+ }
237
+
238
+ except Exception as e:
239
+ logger.error(f"Error getting active sessions: {str(e)}")
240
+ return {"error": str(e)}
241
+
242
+ @router.post("/cleanup-sessions")
243
+ async def cleanup_expired_sessions(current_user: User = Depends(get_current_active_user)):
244
+ """
245
+ Manually trigger session cleanup
246
+ """
247
+ try:
248
+ initial_count = session_manager.get_active_session_count()
249
+
250
+ # Force cleanup
251
+ session_manager._cleanup_expired_sessions()
252
+
253
+ final_count = session_manager.get_active_session_count()
254
+ cleaned_count = initial_count - final_count
255
+
256
+ return {
257
+ "status": "success",
258
+ "message": f"Cleaned up {cleaned_count} expired sessions",
259
+ "sessions_before": initial_count,
260
+ "sessions_after": final_count
261
+ }
262
+
263
+ except Exception as e:
264
+ logger.error(f"Error during session cleanup: {str(e)}")
265
+ return {"status": "error", "message": str(e)}
multi_llm_chatbot_backend/app/api/utils.py CHANGED
@@ -1,24 +1,130 @@
1
  from typing import Optional
2
  from fastapi import Request
3
  from app.core.session_manager import get_session_manager
 
 
 
4
 
 
5
  session_manager = get_session_manager()
6
 
7
- def get_or_create_session_for_request(request: Request, session_id_override: Optional[str] = None) -> str:
8
  """
9
- Get or create session for request using multiple strategies:
10
- 1. Explicit session ID
11
- 2. X-Session-ID header
12
- 3. Client IP fallback
13
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  if session_id_override:
15
  return session_id_override
16
 
 
17
  session_header = request.headers.get("X-Session-ID")
18
  if session_header:
19
  return session_header
20
 
21
- client_ip = request.client.host if request.client else "unknown"
22
- ip_session_id = f"ip_{client_ip}"
23
- session = session_manager.get_session(ip_session_id)
24
- return session.session_id
 
1
  from typing import Optional
2
  from fastapi import Request
3
  from app.core.session_manager import get_session_manager
4
+ from app.core.database import get_database
5
+ from bson import ObjectId
6
+ import logging
7
 
8
+ logger = logging.getLogger(__name__)
9
  session_manager = get_session_manager()
10
 
11
+ async def load_chat_session_into_context(chat_session_id: str, user_id: str) -> str:
12
  """
13
+ Load a chat session from MongoDB into memory context - ENHANCED DEBUG VERSION
 
 
 
14
  """
15
+ try:
16
+ db = get_database()
17
+
18
+ # Add enhanced debugging
19
+ logger.info(f"=== LOADING CHAT SESSION DEBUG ===")
20
+ logger.info(f"Attempting to load chat_session_id: {chat_session_id}")
21
+ logger.info(f"For user_id: {user_id}")
22
+
23
+ # Try to find the session with enhanced debugging
24
+ chat_session = await db.chat_sessions.find_one({
25
+ "_id": ObjectId(chat_session_id),
26
+ "user_id": ObjectId(user_id),
27
+ "deleted_at": {"$exists": False}
28
+ })
29
+
30
+ if not chat_session:
31
+ logger.warning(f"Chat session {chat_session_id} not found for user {user_id}")
32
+
33
+ # Debug: Check if session exists for any user
34
+ try:
35
+ session_exists = await db.chat_sessions.find_one({"_id": ObjectId(chat_session_id)})
36
+ if session_exists:
37
+ logger.warning(f"Session exists but for different user: {session_exists.get('user_id')}")
38
+ logger.warning(f"Expected user: {user_id}")
39
+ logger.warning(f"Session user: {session_exists.get('user_id')}")
40
+ logger.warning(f"User ID types - Expected: {type(user_id)}, Found: {type(session_exists.get('user_id'))}")
41
+ else:
42
+ logger.warning(f"Session {chat_session_id} does not exist in database at all")
43
+ except Exception as debug_error:
44
+ logger.error(f"Error during session debug: {debug_error}")
45
+
46
+ # Debug: List recent sessions for this user
47
+ try:
48
+ recent_sessions = await db.chat_sessions.find(
49
+ {"user_id": ObjectId(user_id), "deleted_at": {"$exists": False}}
50
+ ).limit(5).to_list(5)
51
+ logger.info(f"Recent sessions for user {user_id}: {[str(s['_id']) for s in recent_sessions]}")
52
+ except Exception as debug_error:
53
+ logger.error(f"Error listing recent sessions: {debug_error}")
54
+
55
+ return None
56
+
57
+ logger.info(f"✅ Found chat session: {chat_session.get('title', 'Untitled')}")
58
+ logger.info(f"✅ Message count: {len(chat_session.get('messages', []))}")
59
+
60
+ # Create consistent memory session ID
61
+ memory_session_id = f"chat_{chat_session_id}"
62
+ logger.info(f"✅ Creating memory session: {memory_session_id}")
63
+
64
+ # Get session manager and create memory session
65
+ session_manager = get_session_manager()
66
+ memory_session = session_manager.get_session(memory_session_id)
67
+
68
+ # Clear any existing data
69
+ memory_session.clear_all_data()
70
+
71
+ # Load messages into memory session
72
+ messages = chat_session.get('messages', [])
73
+ for msg_data in messages:
74
+ try:
75
+ message = {
76
+ 'id': msg_data.get('id', 'unknown'),
77
+ 'role': 'user' if msg_data.get('type') == 'user' else 'assistant',
78
+ 'content': msg_data.get('content', ''),
79
+ 'timestamp': msg_data.get('timestamp', '')
80
+ }
81
+ memory_session.append_message(message['role'], message['content'])
82
+
83
+ # Store original message for export
84
+ if not hasattr(memory_session, 'original_messages'):
85
+ memory_session.original_messages = []
86
+
87
+ memory_session.original_messages.append(message)
88
+ except Exception as msg_error:
89
+ logger.error(f"Error loading message: {msg_error}")
90
+ continue
91
+
92
+ logger.info(f"Loaded {len(messages)} messages into session {memory_session_id}")
93
+ return memory_session_id
94
+
95
+ except Exception as e:
96
+ logger.error(f"Error loading chat session into context: {e}")
97
+ import traceback
98
+ logger.error(f"Full traceback: {traceback.format_exc()}")
99
+ return None
100
+
101
+ async def get_or_create_session_for_request_async(
102
+ request: Request,
103
+ session_id_override: Optional[str] = None,
104
+ chat_session_id: Optional[str] = None,
105
+ user_id: Optional[str] = None
106
+ ) -> str:
107
+ """
108
+ Async version that properly handles chat session loading
109
+ """
110
+
111
+ # Case 1: Loading an existing chat session
112
+ if chat_session_id and user_id:
113
+ memory_session_id = await load_chat_session_into_context(chat_session_id, user_id)
114
+ if memory_session_id:
115
+ return memory_session_id
116
+ # If loading failed, create new session
117
+
118
+ # Case 2: Explicit session ID provided
119
  if session_id_override:
120
  return session_id_override
121
 
122
+ # Case 3: Check for session header
123
  session_header = request.headers.get("X-Session-ID")
124
  if session_header:
125
  return session_header
126
 
127
+ # Case 4: Create a truly new session
128
+ new_session_id = session_manager.create_session()
129
+ logger.info(f"Created new session: {new_session_id}")
130
+ return new_session_id
multi_llm_chatbot_backend/app/core/README.md ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `app/core` – Application Core Logic
2
+
3
+ This is the **central brain** of the multi-LLM chatbot system. It orchestrates user interaction, persona logic, context management, document-based retrieval (RAG), session tracking, authentication, and initialization.
4
+
5
+ ---
6
+
7
+ ## Overview of Modules
8
+
9
+ | Module | Responsibility |
10
+ |--------|----------------|
11
+ | `auth.py` | Authentication (JWT, password hashing, user resolution) |
12
+ | `bootstrap.py` | System startup logic: loads LLMs, personas, orchestrators |
13
+ | `context.py` | Global per-session context (simplified storage) |
14
+ | `context_manager.py` | Core context formatting & windowing for Gemini/Ollama |
15
+ | `database.py` | MongoDB connection & index management |
16
+ | `improved_orchestrator.py` | Main message routing engine: document-aware, multi-persona orchestrator |
17
+ | `rag_manager.py` | RAG with ChromaDB: chunking, storage, semantic search |
18
+ | `session_manager.py` | Full chat lifecycle tracker (in-memory) with RAG hooks |
19
+
20
+ ---
21
+
22
+ ## `auth.py` – Authentication System
23
+
24
+ Handles secure authentication via:
25
+ - Bcrypt hashing (`passlib`)
26
+ - JWT creation and validation (`python-jose`)
27
+ - Secure route access using FastAPI’s `Depends`
28
+
29
+ ### Functions
30
+
31
+ - `get_password_hash(password)` – Hash password using bcrypt
32
+ - `verify_password(plain, hashed)` – Verify password
33
+ - `create_access_token(data)` – Return JWT (30-day expiry default)
34
+ - `get_current_user()` – Decodes token and returns `User` model
35
+ - `authenticate_user(email, password)` – Checks login credentials
36
+ - `create_user_response(user)` – Returns `UserResponse` for frontend
37
+
38
+ ---
39
+
40
+ ## `bootstrap.py` – System Bootstrap
41
+
42
+ Runs once on app startup to:
43
+ - Determine the default LLM provider (Gemini or Ollama)
44
+ - Initialize `ImprovedChatOrchestrator`
45
+ - Inject personas using `get_default_personas(llm)`
46
+
47
+ ```python
48
+ llm = create_llm_client() # Gemini or Ollama
49
+ chat_orchestrator = ImprovedChatOrchestrator()
50
+ DEFAULT_PERSONAS = get_default_personas(llm)
51
+ ```
52
+
53
+ Each persona is **registered** into the orchestrator using `.register_persona()`.
54
+
55
+ ---
56
+
57
+ ## `context.py` – Global Per-Session Context
58
+
59
+ A basic context storage class (`GlobalSessionContext`) that keeps:
60
+ - `full_log`: List of all messages
61
+ - `uploaded_files`: Tracked files per session
62
+ - `total_upload_size`: Helps enforce limits
63
+
64
+ Used primarily in earlier versions or smaller contexts.
65
+
66
+ ---
67
+
68
+ ## `context_manager.py` – LLM Context Window Formatter
69
+
70
+ This class builds optimized context windows for both Gemini and Ollama:
71
+
72
+ ### `ContextManager.prepare_context_for_llm()`
73
+ Returns a `ContextWindow(messages, token_count, truncated)` with:
74
+ - LLM-specific formatting
75
+ - Automatic message pruning based on token limits
76
+ - Recency- and relevance-weighted scoring for old messages
77
+ - Automatic stop tokens, system prompts, and formatting
78
+
79
+ ### Key Features
80
+
81
+ | Feature | Gemini | Ollama |
82
+ |--------|--------|--------|
83
+ | Format | JSON roles + parts | Flat prompt string |
84
+ | Role Mapping | 'user', 'model' | 'User:', 'Assistant:' |
85
+ | Chunking Strategy | Full doc as `Context Document:` | Plain text injection |
86
+ | Stop Sequences | Customizable | Enforced via `stop[]` |
87
+
88
+ Used **by all LLM clients** (Ollama/Gemini) and the **orchestrator**.
89
+
90
+ ---
91
+
92
+ ## `database.py` – MongoDB Connector
93
+
94
+ - Uses `motor` for async MongoDB
95
+ - Exposes `get_database()` to other modules
96
+ - Automatically creates indexes on `users` and `chat_sessions`
97
+ - Controlled via `.env` (`MONGODB_CONNECTION_STRING`)
98
+
99
+ ```python
100
+ await connect_to_mongo()
101
+ await close_mongo_connection()
102
+ ```
103
+
104
+ ---
105
+
106
+ ## `improved_orchestrator.py` – Brain of the Chatbot
107
+
108
+ This is the main **message routing engine**.
109
+
110
+ ### Main Responsibilities
111
+
112
+ - Route user input through:
113
+ - Clarification detection
114
+ - Document-aware context building
115
+ - Persona-level response generation
116
+ - Aggregate responses from **multiple advisors**
117
+ - Embed document-based context (RAG)
118
+
119
+ ### Key Functions
120
+
121
+ - `process_message()` – Entry point for chat flow (calls all advisors)
122
+ - `chat_with_persona()` – Talk to one specific advisor
123
+ - `_generate_persona_responses()` – Routes through each registered persona
124
+ - `_build_enhanced_context_for_persona()` – Combines conversation + document info
125
+
126
+ ### Extras
127
+ - Document parsing hints (`"my thesis"`, `"section 2"`, etc.)
128
+ - Top-K persona ranking (`get_top_personas()`)
129
+ - Persona-specific fallback logic
130
+ - Session reset/deletion
131
+
132
+ Used by `/chat-sequential`, `/reply-to-advisor`, etc.
133
+
134
+ ---
135
+
136
+ ## `rag_manager.py` – RAG System for Docs
137
+
138
+ Supports **vector-based retrieval** using:
139
+
140
+ - Sentence Transformers (`all-MiniLM-L6-v2`)
141
+ - ChromaDB (`PersistentClient` with metadata)
142
+ - Metadata-aware enhanced chunking
143
+ - Overlapping token window strategy
144
+ - Section-wise classification
145
+
146
+ ### Core Components
147
+
148
+ | Class | Role |
149
+ |-------|------|
150
+ | `RAGManager` | Standard chunking, basic RAG |
151
+ | `EnhancedRAGManager` | Persona-aware + metadata-annotated vector chunks |
152
+
153
+ ### `EnhancedRAGManager` supports:
154
+ - Section tagging (`methodology`, `theory`, etc.)
155
+ - Multi-level filters (`session_id`, `filename`)
156
+ - Attribution fields (`chunk_position`, `has_methodology`)
157
+ - Relevance scoring and ranking
158
+
159
+ Used by orchestrator when generating document-aware responses.
160
+
161
+ ---
162
+
163
+ ## `session_manager.py` – Chat Lifecycle Controller
164
+
165
+ Handles:
166
+ - In-memory session creation + cleanup (with expiration)
167
+ - Tracks uploaded files and size
168
+ - Holds message logs for each session
169
+ - Links to RAG via `add_uploaded_file()` and `get_rag_stats()`
170
+
171
+ ### `ConversationContext`
172
+
173
+ | Attribute | Description |
174
+ |-----------|-------------|
175
+ | `messages` | List of role-message entries |
176
+ | `uploaded_files` | Filenames (content stored in RAG DB) |
177
+ | `document_chunks_count` | Count of indexed doc chunks |
178
+ | `last_retrieval_stats` | From last RAG search |
179
+ | `created_at`, `last_accessed` | Session activity tracking |
180
+
181
+ Includes:
182
+ - Reset functions (`clear_all_data()`)
183
+ - File-level message logging (`append_message()`)
184
+
185
+ ### `SessionManager`
186
+
187
+ - Thread-safe via locks
188
+ - Handles cleanup of expired sessions (`_cleanup_expired_sessions()`)
189
+ - Returns statistics via `get_session_stats()`
190
+
191
+ ---
192
+
193
+ ## Interactions Summary
194
+
195
+ ```text
196
+ User Input → Orchestrator
197
+ ↳ SessionManager → Context
198
+ ↳ RAGManager → Relevant Docs
199
+ ↳ LLMClient (Gemini/Ollama) ← ContextManager
200
+ ```
multi_llm_chatbot_backend/app/core/auth.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timedelta
3
+ from typing import Optional
4
+ from fastapi import HTTPException, Depends, status
5
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
6
+ from passlib.context import CryptContext
7
+ from jose import JWTError, jwt
8
+ from bson import ObjectId
9
+ from app.core.database import get_database
10
+ from app.models.user import User, UserResponse
11
+
12
+ # Password hashing
13
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
14
+
15
+ # JWT settings
16
+ SECRET_KEY = os.getenv("JWT_SECRET_KEY", "your-secret-key-change-this-in-production")
17
+ ALGORITHM = "HS256"
18
+ ACCESS_TOKEN_EXPIRE_MINUTES = 30 * 24 * 60 # 30 days
19
+
20
+ # Security scheme
21
+ security = HTTPBearer()
22
+
23
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
24
+ """Verify a password against its hash"""
25
+ return pwd_context.verify(plain_password, hashed_password)
26
+
27
+ def get_password_hash(password: str) -> str:
28
+ """Hash a password"""
29
+ return pwd_context.hash(password)
30
+
31
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
32
+ """Create a JWT access token"""
33
+ to_encode = data.copy()
34
+ if expires_delta:
35
+ expire = datetime.utcnow() + expires_delta
36
+ else:
37
+ expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
38
+
39
+ to_encode.update({"exp": expire})
40
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
41
+ return encoded_jwt
42
+
43
+ async def get_user_by_email(email: str) -> Optional[User]:
44
+ """Get user by email from database"""
45
+ db = get_database()
46
+ user_data = await db.users.find_one({"email": email})
47
+ if user_data:
48
+ return User(**user_data)
49
+ return None
50
+
51
+ async def get_user_by_id(user_id: str) -> Optional[User]:
52
+ """Get user by ID from database"""
53
+ try:
54
+ db = get_database()
55
+ user_data = await db.users.find_one({"_id": ObjectId(user_id)})
56
+ if user_data:
57
+ return User(**user_data)
58
+ return None
59
+ except Exception:
60
+ return None
61
+
62
+ async def authenticate_user(email: str, password: str) -> Optional[User]:
63
+ """Authenticate user with email and password"""
64
+ user = await get_user_by_email(email)
65
+ if not user:
66
+ return None
67
+ if not verify_password(password, user.hashed_password):
68
+ return None
69
+ return user
70
+
71
+ async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> User:
72
+ """Get current user from JWT token"""
73
+ credentials_exception = HTTPException(
74
+ status_code=status.HTTP_401_UNAUTHORIZED,
75
+ detail="Could not validate credentials",
76
+ headers={"WWW-Authenticate": "Bearer"},
77
+ )
78
+
79
+ try:
80
+ payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
81
+ user_id: str = payload.get("sub")
82
+ if user_id is None:
83
+ raise credentials_exception
84
+ except JWTError:
85
+ raise credentials_exception
86
+
87
+ user = await get_user_by_id(user_id)
88
+ if user is None:
89
+ raise credentials_exception
90
+
91
+ if not user.is_active:
92
+ raise HTTPException(
93
+ status_code=status.HTTP_401_UNAUTHORIZED,
94
+ detail="Inactive user"
95
+ )
96
+
97
+ return user
98
+
99
+ async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
100
+ """Get current active user"""
101
+ if not current_user.is_active:
102
+ raise HTTPException(status_code=400, detail="Inactive user")
103
+ return current_user
104
+
105
+ def create_user_response(user: User) -> UserResponse:
106
+ """Create user response model"""
107
+ return UserResponse(
108
+ id=str(user.id),
109
+ firstName=user.firstName,
110
+ lastName=user.lastName,
111
+ email=user.email,
112
+ academicStage=user.academicStage,
113
+ researchArea=user.researchArea,
114
+ created_at=user.created_at,
115
+ last_login=user.last_login
116
+ )
multi_llm_chatbot_backend/app/core/database.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from motor.motor_asyncio import AsyncIOMotorClient
3
+ from pymongo.errors import ConnectionFailure
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class Database:
9
+ client: AsyncIOMotorClient = None
10
+ database = None
11
+
12
+ db = Database()
13
+
14
+ async def connect_to_mongo():
15
+ """Create database connection"""
16
+ try:
17
+ # Get MongoDB connection string from environment
18
+ mongo_url = os.getenv("MONGODB_CONNECTION_STRING")
19
+ if not mongo_url:
20
+ raise ValueError("MONGODB_CONNECTION_STRING environment variable not set")
21
+
22
+ # Get database name from environment or use default
23
+ db_name = os.getenv("MONGODB_DATABASE_NAME", "phd_advisor")
24
+
25
+ db.client = AsyncIOMotorClient(mongo_url)
26
+ db.database = db.client[db_name]
27
+
28
+ # Test connection
29
+ await db.client.admin.command('ping')
30
+ logger.info(f"Successfully connected to MongoDB database: {db_name}")
31
+
32
+ # Create indexes for better performance
33
+ await create_indexes()
34
+
35
+ except ConnectionFailure as e:
36
+ logger.error(f"Failed to connect to MongoDB: {e}")
37
+ raise
38
+ except Exception as e:
39
+ logger.error(f"Unexpected error connecting to MongoDB: {e}")
40
+ raise
41
+
42
+ async def close_mongo_connection():
43
+ """Close database connection"""
44
+ if db.client:
45
+ db.client.close()
46
+ logger.info("Disconnected from MongoDB")
47
+
48
+ async def create_indexes():
49
+ """Create database indexes for performance"""
50
+ try:
51
+ # Index for users collection
52
+ await db.database.users.create_index("email", unique=True)
53
+ await db.database.users.create_index("created_at")
54
+
55
+ # Indexes for chat_sessions collection
56
+ await db.database.chat_sessions.create_index("user_id")
57
+ await db.database.chat_sessions.create_index("created_at")
58
+ await db.database.chat_sessions.create_index([("user_id", 1), ("created_at", -1)])
59
+
60
+ logger.info("Database indexes created successfully")
61
+ except Exception as e:
62
+ logger.warning(f"Error creating indexes: {e}")
63
+
64
+ def get_database():
65
+ """Get database instance"""
66
+ return db.database
multi_llm_chatbot_backend/app/core/improved_orchestrator.py CHANGED
@@ -146,28 +146,43 @@ class ImprovedChatOrchestrator:
146
  if len(user_messages) > 1:
147
  return False
148
 
149
- # Check for vague patterns
150
  vague_patterns = [
151
  r"^(help|advice|guidance|assistance)$",
152
- r"i'?m (stuck|lost|confused|not sure)",
 
153
  r"(what should i|how do i|where do i start)",
154
  r"i need (help|advice|guidance)",
155
- r"(any|some) (advice|suggestions|ideas)"
 
 
 
156
  ]
157
 
158
  user_lower = user_input.lower().strip()
159
 
 
 
 
 
 
160
  for pattern in vague_patterns:
161
  if re.search(pattern, user_lower):
 
162
  return True
163
 
164
  # Check if input is too short and vague
165
- if len(user_input.split()) < 6 and not any(
 
166
  keyword in user_lower for keyword in
167
  ['methodology', 'theory', 'data', 'analysis', 'research', 'thesis', 'dissertation']
168
- ):
 
 
 
169
  return True
170
 
 
171
  return False
172
 
173
  async def _generate_clarification_question(self, session: ConversationContext) -> str:
@@ -282,15 +297,51 @@ class ImprovedChatOrchestrator:
282
  Enhanced document retrieval with document awareness and better attribution
283
  """
284
  try:
 
 
 
 
285
  rag_manager = get_rag_manager()
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  # Extract document hints from user query
288
  document_hint = self._extract_document_hint_from_query(user_input)
 
289
 
290
  # Get persona-specific context for better retrieval
291
  persona_context = self._get_enhanced_persona_context_keywords(persona_id)
292
 
293
  # Search for relevant chunks with document awareness
 
294
  relevant_chunks = rag_manager.search_documents_with_context(
295
  query=user_input,
296
  session_id=session_id,
@@ -301,15 +352,31 @@ class ImprovedChatOrchestrator:
301
 
302
  logger.info(f"Retrieved {len(relevant_chunks)} chunks for {persona_id}")
303
 
 
 
 
 
 
 
 
 
304
  if not relevant_chunks:
305
- logger.info(f"No relevant documents found for query: {user_input[:50]}...")
306
  return ""
307
 
308
  # Format retrieved content with enhanced attribution
309
- return self._format_document_context_with_attribution(relevant_chunks, persona_id)
 
 
 
 
 
310
 
311
  except Exception as e:
312
- logger.error(f"Error retrieving documents for {persona_id}: {str(e)}")
 
 
 
313
  return ""
314
 
315
  def _extract_document_hint_from_query(self, query: str) -> Optional[str]:
@@ -564,34 +631,73 @@ When analyzing the document context:
564
  """
565
  return self._get_enhanced_persona_context_keywords(persona_id)
566
 
567
- async def chat_with_persona(self, persona_id: str, user_input: str, session_id: str, response_length: str = "medium") -> Dict[str, Any]:
568
  """
569
- Chat with a specific persona directly
570
  """
571
  try:
572
  persona = self.get_persona(persona_id)
573
  if not persona:
574
  return {
575
  "error": f"Persona {persona_id} not found",
576
- "available_personas": list(self.personas.keys())
 
 
577
  }
578
 
 
579
  session = self.session_manager.get_session(session_id)
 
 
 
580
  session.append_message("user", user_input)
581
 
582
- # Generate response from single persona
 
 
 
583
  response_data = await self._generate_single_persona_response(session, persona, response_length)
584
 
585
  # Add response to session
586
  session.append_message(persona_id, response_data["response"])
587
 
588
- return response_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
 
590
  except Exception as e:
591
- logger.error(f"Error in chat_with_persona: {str(e)}")
 
 
 
 
592
  return {
593
  "error": f"Error processing request: {str(e)}",
594
- "persona_id": persona_id
 
 
 
 
 
 
 
 
595
  }
596
 
597
 
 
146
  if len(user_messages) > 1:
147
  return False
148
 
149
+ # Check for vague patterns - FIXED to handle "I am" vs "I'm"
150
  vague_patterns = [
151
  r"^(help|advice|guidance|assistance)$",
152
+ r"i'?m (stuck|lost|confused|not sure)", # matches "I'm confused"
153
+ r"i am (stuck|lost|confused|not sure)", # matches "I am confused"
154
  r"(what should i|how do i|where do i start)",
155
  r"i need (help|advice|guidance)",
156
+ r"(any|some) (advice|suggestions|ideas)",
157
+ r"don'?t know (what|how|where)",
158
+ r"(stuck|struggling) with",
159
+ r"unsure about"
160
  ]
161
 
162
  user_lower = user_input.lower().strip()
163
 
164
+ # Add debug logging to see what's happening
165
+ import logging
166
+ logger = logging.getLogger(__name__)
167
+ logger.info(f"Checking clarification for: '{user_input}' (lowercase: '{user_lower}')")
168
+
169
  for pattern in vague_patterns:
170
  if re.search(pattern, user_lower):
171
+ logger.info(f"CLARIFICATION TRIGGERED: Pattern '{pattern}' matched input '{user_input}'")
172
  return True
173
 
174
  # Check if input is too short and vague
175
+ word_count = len(user_input.split())
176
+ has_specific_keywords = any(
177
  keyword in user_lower for keyword in
178
  ['methodology', 'theory', 'data', 'analysis', 'research', 'thesis', 'dissertation']
179
+ )
180
+
181
+ if word_count < 6 and not has_specific_keywords:
182
+ logger.info(f"CLARIFICATION TRIGGERED: Short input ({word_count} words) without specific keywords")
183
  return True
184
 
185
+ logger.info(f"NO CLARIFICATION: Input has {word_count} words, specific keywords: {has_specific_keywords}")
186
  return False
187
 
188
  async def _generate_clarification_question(self, session: ConversationContext) -> str:
 
297
  Enhanced document retrieval with document awareness and better attribution
298
  """
299
  try:
300
+ # Add comprehensive logging to track session ID usage
301
+ logger.info(f"Retrieving documents for session_id: {session_id}")
302
+ logger.info(f"User input: {user_input[:100]}...")
303
+
304
  rag_manager = get_rag_manager()
305
 
306
+ # Check what documents are available for this session with detailed logging
307
+ doc_stats = rag_manager.get_document_stats(session_id)
308
+ logger.info(f"Available documents for {session_id}: {doc_stats.get('total_documents', 0)} documents, {doc_stats.get('total_chunks', 0)} chunks")
309
+
310
+ # Log document details for debugging
311
+ if doc_stats.get('documents'):
312
+ for doc in doc_stats['documents']:
313
+ logger.info(f" - Document: {doc.get('filename', 'unknown')} ({doc.get('chunks', 0)} chunks)")
314
+
315
+ # If no documents found and this looks like a chat session, log warning
316
+ if doc_stats.get('total_documents', 0) == 0:
317
+ if session_id.startswith('chat_'):
318
+ logger.warning(f"No documents found for chat session {session_id} - this may indicate session ID mismatch during upload")
319
+
320
+ # Try alternative session ID formats for debugging
321
+ alternative_formats = [
322
+ session_id.replace('chat_', ''), # Remove chat_ prefix
323
+ session_id, # Keep as is
324
+ ]
325
+
326
+ for alt_session_id in alternative_formats:
327
+ if alt_session_id != session_id:
328
+ alt_stats = rag_manager.get_document_stats(alt_session_id)
329
+ if alt_stats.get('total_documents', 0) > 0:
330
+ logger.warning(f"Found documents under alternative session ID {alt_session_id}: {alt_stats}")
331
+ else:
332
+ logger.info(f"No documents found for new session {session_id} - this is normal for new chats")
333
+
334
+ return "" # No documents available
335
+
336
  # Extract document hints from user query
337
  document_hint = self._extract_document_hint_from_query(user_input)
338
+ logger.info(f"Document hint extracted from query: {document_hint}")
339
 
340
  # Get persona-specific context for better retrieval
341
  persona_context = self._get_enhanced_persona_context_keywords(persona_id)
342
 
343
  # Search for relevant chunks with document awareness
344
+ logger.info(f"Searching with persona context: {persona_context[:100]}...")
345
  relevant_chunks = rag_manager.search_documents_with_context(
346
  query=user_input,
347
  session_id=session_id,
 
352
 
353
  logger.info(f"Retrieved {len(relevant_chunks)} chunks for {persona_id}")
354
 
355
+ # Log relevance scores for debugging
356
+ if relevant_chunks:
357
+ for i, chunk in enumerate(relevant_chunks):
358
+ relevance = chunk.get("relevance_score", 0)
359
+ doc_source = chunk.get("document_source", {})
360
+ filename = doc_source.get("filename", "unknown")
361
+ logger.info(f" Chunk {i+1}: {filename} (relevance: {relevance:.3f})")
362
+
363
  if not relevant_chunks:
364
+ logger.info(f"No relevant document chunks found for query: {user_input[:50]}...")
365
  return ""
366
 
367
  # Format retrieved content with enhanced attribution
368
+ formatted_context = self._format_document_context_with_attribution(relevant_chunks, persona_id)
369
+
370
+ # Log final context length
371
+ logger.info(f"Final document context length: {len(formatted_context)} characters")
372
+
373
+ return formatted_context
374
 
375
  except Exception as e:
376
+ logger.error(f"Error retrieving documents for {persona_id} in session {session_id}: {str(e)}")
377
+ logger.error(f"Error type: {type(e).__name__}")
378
+ import traceback
379
+ logger.error(f"Full traceback: {traceback.format_exc()}")
380
  return ""
381
 
382
  def _extract_document_hint_from_query(self, query: str) -> Optional[str]:
 
631
  """
632
  return self._get_enhanced_persona_context_keywords(persona_id)
633
 
634
+ async def chat_with_persona(self, user_input: str, persona_id: str, session_id: str, response_length: str = "medium") -> Dict[str, Any]:
635
  """
636
+ Chat with a specific persona directly - FIXED for consistent document access
637
  """
638
  try:
639
  persona = self.get_persona(persona_id)
640
  if not persona:
641
  return {
642
  "error": f"Persona {persona_id} not found",
643
+ "available_personas": list(self.personas.keys()),
644
+ "persona_id": persona_id,
645
+ "persona_name": "Unknown"
646
  }
647
 
648
+ # Ensure session exists and log session info
649
  session = self.session_manager.get_session(session_id)
650
+ logger.info(f"Chat with {persona_id} using session {session_id}")
651
+
652
+ # Add user message to session
653
  session.append_message("user", user_input)
654
 
655
+ # Use the same session_id for document retrieval
656
+ logger.info(f"Generating response for {persona_id} with session {session_id}")
657
+
658
+ # Generate response from single persona using consistent session ID
659
  response_data = await self._generate_single_persona_response(session, persona, response_length)
660
 
661
  # Add response to session
662
  session.append_message(persona_id, response_data["response"])
663
 
664
+ # Ensure response data includes all necessary fields
665
+ return {
666
+ "persona_id": persona_id,
667
+ "persona_name": persona.name,
668
+ "response": response_data.get("response", "I'm having trouble generating a response."),
669
+ "used_documents": response_data.get("used_documents", False),
670
+ "document_chunks_used": response_data.get("document_chunks_used", 0),
671
+ "response_length": response_length,
672
+ "context_quality": response_data.get("context_quality", "unknown"),
673
+ "session_id": session_id,
674
+ "type": "single_persona_response",
675
+ "persona": {
676
+ "persona_id": persona_id,
677
+ "persona_name": persona.name,
678
+ "response": response_data.get("response", "I'm having trouble generating a response."),
679
+ "used_documents": response_data.get("used_documents", False),
680
+ "document_chunks_used": response_data.get("document_chunks_used", 0)
681
+ }
682
+ }
683
 
684
  except Exception as e:
685
+ logger.error(f"Error in chat_with_persona for {persona_id}: {str(e)}")
686
+ logger.error(f"Session ID: {session_id}")
687
+ import traceback
688
+ logger.error(f"Full traceback: {traceback.format_exc()}")
689
+
690
  return {
691
  "error": f"Error processing request: {str(e)}",
692
+ "persona_id": persona_id,
693
+ "persona_name": self.personas.get(persona_id, {}).name if persona_id in self.personas else "Unknown",
694
+ "response": "I encountered an error while processing your request. Please try again.",
695
+ "used_documents": False,
696
+ "document_chunks_used": 0,
697
+ "response_length": response_length,
698
+ "context_quality": "error",
699
+ "session_id": session_id,
700
+ "type": "error"
701
  }
702
 
703
 
multi_llm_chatbot_backend/app/llm/README.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `app/llm` – LLM Integration Layer
2
+
3
+ This module abstracts and implements communication with **local** and **cloud-based** large language models (LLMs) via interchangeable client wrappers.
4
+
5
+ It defines:
6
+ - A common interface for all LLM clients (`LLMClient`)
7
+ - A wrapper for Google Gemini API (`ImprovedGeminiClient`)
8
+ - A wrapper for Ollama local models (`ImprovedOllamaClient`)
9
+ - A sentence transformer embedding model (`embedding_client.py`)
10
+
11
+ ---
12
+
13
+ ## Abstract Base – `llm_client.py`
14
+
15
+ This file defines the **contract** that all LLM clients must follow.
16
+
17
+ ### `class LLMClient (ABC)`
18
+
19
+ An abstract base class using Python’s `abc` module.
20
+
21
+ ```python
22
+ @abstractmethod
23
+ async def generate(system_prompt: str, context: List[dict], temperature: float, max_tokens: int) -> str
24
+ ```
25
+
26
+ Every model wrapper must implement this coroutine to generate a response given:
27
+ - A system prompt (persona instructions)
28
+ - A user/system message context (list of `{role, content}` dicts)
29
+ - A temperature (float 0.0–1.0, typically scaled from 0–10)
30
+ - A token limit (integer)
31
+
32
+ ---
33
+
34
+ ## Gemini Client – `improved_gemini_client.py`
35
+
36
+ ### Overview
37
+
38
+ - Communicates with **Google’s Gemini API** via `httpx`
39
+ - Dynamically injects the `system_prompt` into the context using `context_manager`
40
+ - Uses environment variables for API key and model name (`GEMINI_API_KEY`, `GEMINI_MODEL`)
41
+
42
+ ### Key Features
43
+
44
+ | Feature | Description |
45
+ |--------|-------------|
46
+ | Context Prep | Uses `context_manager.prepare_context_for_llm()` to optimize message length |
47
+ | Endpoint | `https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent` |
48
+ | Content Format | Gemini expects JSON-formatted `contents`, not string prompts |
49
+ | Safety Settings | Blocks harmful or explicit content categories |
50
+ | Fallback Logic | Returns user-friendly error messages on bad or empty responses |
51
+ | Token Limit | `maxOutputTokens` passed explicitly |
52
+
53
+ ### SafetyConfig JSON Example
54
+
55
+ ```json
56
+ "safetySettings": [
57
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
58
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
59
+ ]
60
+ ```
61
+
62
+ ### Differences from Ollama
63
+ - Requires an API key and runs over HTTPS
64
+ - Parses deeply nested JSON structures (candidates → content → parts)
65
+ - Strict token and safety controls
66
+ - More structured response format
67
+
68
+ ---
69
+
70
+ ## Ollama Client – `improved_ollama_client.py`
71
+
72
+ ### Overview
73
+
74
+ - Interfaces with a **local Ollama model server** (`http://localhost:11434`)
75
+ - Sends prompts as raw formatted strings (not JSON "messages")
76
+ - Uses `context_manager` to prepare prompt text
77
+
78
+ ### Key Features
79
+
80
+ | Feature | Description |
81
+ |--------|-------------|
82
+ | Endpoint | `/api/generate` |
83
+ | Payload | Flat prompt string + generation config |
84
+ | Cleansing | Strips verbose, inconsistent prefixes or filler |
85
+ | Quality Filter | Removes overly verbose or vague responses |
86
+ | Robust | Recovers from connection and timeout failures |
87
+
88
+ ### Prompt Payload Example
89
+
90
+ ```json
91
+ {
92
+ "model": "llama3.2:1b",
93
+ "prompt": "System: You are a helpful advisor...\nUser: What is...",
94
+ "stream": false,
95
+ "options": {
96
+ "temperature": 0.4,
97
+ "top_p": 0.9,
98
+ "top_k": 40,
99
+ "num_predict": 300,
100
+ "repeat_penalty": 1.1,
101
+ "stop": ["Student:", "User:", "Question:"]
102
+ }
103
+ }
104
+ ```
105
+
106
+ ### Differences from Gemini
107
+
108
+ | Area | Gemini | Ollama |
109
+ |------|--------|--------|
110
+ | Hosting | Cloud API | Local server |
111
+ | Format | JSON "messages" | Raw string prompt |
112
+ | Safety Filters | Yes | No |
113
+ | Token Control | `maxOutputTokens` | `num_predict` |
114
+ | Output | Structured parts | Single `response` string |
115
+ | Response Cleaning | Minimal | Aggressively stripped of fluff |
116
+ | Performance | High-quality, slower | Fast & offline |
117
+
118
+ ---
119
+
120
+ ## Embedding Model – `embedding_client.py`
121
+
122
+ ### Purpose
123
+
124
+ Provides embedding vectors (used for semantic similarity and document retrieval) using `sentence-transformers`.
125
+
126
+ ### Uses:
127
+ - Model: `all-MiniLM-L6-v2` (lightweight + performant)
128
+ - Library: `sentence-transformers`
129
+ - Function: `get_embedding(text: str) -> List[float]`
130
+
131
+ ```python
132
+ embedding = get_embedding("example sentence")
133
+ ```
134
+
135
+ ### Notes
136
+ - This module does **not** use Gemini embeddings (for cost and simplicity)
137
+ - Can be upgraded later to use Gemini’s `embedding` endpoint or Ollama-based models with vector support
138
+
139
+ ---
140
+
141
+ ## Environment Variables
142
+
143
+ | Variable | Description | Example |
144
+ |----------|-------------|---------|
145
+ | `GEMINI_API_KEY` | API key for Google Gemini | `AIzz123...` |
146
+ | `GEMINI_MODEL` | Default Gemini model name | `gemini-2.0-flash` |
147
+ | `OLLAMA_BASE_URL` | Local server base URL | `http://localhost:11434` |
148
+
149
+ ---
150
+
151
+ ## Context Management Integration
152
+
153
+ Both clients use:
154
+
155
+ ```python
156
+ context_window = context_manager.prepare_context_for_llm(...)
157
+ ```
158
+
159
+ This ensures that:
160
+ - Prompt fits within model limits
161
+ - Truncation metadata is logged/debugged
162
+ - Messages are pre-formatted or optimized per provider
163
+
164
+ ---
165
+
166
+ ## Error Handling
167
+
168
+ All clients log internal issues and fallback to graceful responses. Each client handles:
169
+ - Timeouts (`httpx.TimeoutException`)
170
+ - API errors (`httpx.HTTPStatusError`, bad payloads)
171
+ - Unexpected failures (fallback strings are returned)
172
+
173
+ ---
multi_llm_chatbot_backend/app/main.py CHANGED
@@ -5,19 +5,35 @@ load_dotenv()
5
 
6
  from fastapi import FastAPI
7
  from fastapi.middleware.cors import CORSMiddleware
8
- from app.api.routes import router
9
- import logging
 
 
10
 
 
 
 
 
 
 
11
 
12
  logging.basicConfig(
13
  level=logging.INFO,
14
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
15
  )
16
 
 
 
 
 
 
 
 
17
 
18
  app = FastAPI(
19
  title="Multi-LLM Chatbot Backend",
20
- version="1.0.0" # Updated version
 
21
  )
22
 
23
  app.add_middleware(
@@ -28,18 +44,21 @@ app.add_middleware(
28
  allow_headers=["*"],
29
  )
30
 
31
- app.include_router(router)
 
 
 
32
 
33
  @app.get("/")
34
  def root():
35
  return {
36
- "message": "Multi-LLM PhD Advisor Backend is up and running",
37
- "version": "1.0.0",
38
  "features": [
39
- "Improved Session Management",
40
- "Unified Context Handling",
 
41
  "Ollama Support",
42
- "Gemini API Support",
43
- "Provider Switching"
44
  ]
45
  }
 
5
 
6
  from fastapi import FastAPI
7
  from fastapi.middleware.cors import CORSMiddleware
8
+ from contextlib import asynccontextmanager
9
+
10
+ # Import the new database functions
11
+ from app.core.database import connect_to_mongo, close_mongo_connection
12
 
13
+ # Import all route modules
14
+ from app.api.routes import router as main_router
15
+ from app.api.routes.auth import router as auth_router
16
+ from app.api.routes.chat_sessions import router as chat_sessions_router
17
+
18
+ import logging
19
 
20
  logging.basicConfig(
21
  level=logging.INFO,
22
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23
  )
24
 
25
+ @asynccontextmanager
26
+ async def lifespan(app: FastAPI):
27
+ # Startup
28
+ await connect_to_mongo()
29
+ yield
30
+ # Shutdown
31
+ await close_mongo_connection()
32
 
33
  app = FastAPI(
34
  title="Multi-LLM Chatbot Backend",
35
+ version="2.0.0",
36
+ lifespan=lifespan
37
  )
38
 
39
  app.add_middleware(
 
44
  allow_headers=["*"],
45
  )
46
 
47
+ # Include all routers
48
+ app.include_router(main_router)
49
+ app.include_router(auth_router, prefix="/auth", tags=["authentication"])
50
+ app.include_router(chat_sessions_router, prefix="/api", tags=["chat-sessions"])
51
 
52
  @app.get("/")
53
  def root():
54
  return {
55
+ "message": "Multi-LLM PhD Advisor Backend with Authentication",
56
+ "version": "2.0.0",
57
  "features": [
58
+ "User Authentication",
59
+ "Persistent Chat Sessions",
60
+ "MongoDB Integration",
61
  "Ollama Support",
62
+ "Gemini API Support"
 
63
  ]
64
  }
multi_llm_chatbot_backend/app/models/README.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `app/models` – Data Models & Persona Configuration
2
+
3
+ This module defines the **core data structures** for users, chat sessions, and AI advisor personas in the Multi-LLM Chatbot Backend.
4
+
5
+ It plays a foundational role in ensuring that:
6
+ - User data and session state are **structured, validated, and serializable**
7
+ - Persona behavior is **configurable, injectable, and extensible**
8
+
9
+ ---
10
+
11
+ ## Persona Model (`persona.py`)
12
+
13
+ ### `class Persona`
14
+
15
+ Represents a single AI advisor with its own personality, tone, and domain of expertise.
16
+
17
+ | Attribute | Description |
18
+ |----------------|-------------|
19
+ | `id` | Unique identifier for the persona |
20
+ | `name` | Human-readable display name |
21
+ | `system_prompt`| The persona’s default LLM instruction |
22
+ | `llm` | Instance of the LLM client (Gemini/Ollama) |
23
+ | `temperature` | Controls creativity level (0–10 scale, converted to 0.0–1.0 internally) |
24
+
25
+ ### `respond()` method
26
+
27
+ This asynchronous method generates a persona-specific reply using the provided context and desired `response_length` (short, medium, long). It uses a **system prompt + user messages** + length-based instructions.
28
+
29
+ ```python
30
+ await persona.respond(context=messages, response_length="medium")
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Persona Registry (`default_personas.py`)
36
+
37
+ Defines and registers **all built-in personas** using detailed `system_prompt` templates and metadata.
38
+
39
+ > These prompts define the tone, response style, formatting rules, document behavior, and epistemological approach of each advisor.
40
+
41
+ ### Available Personas
42
+
43
+ - `methodologist`: Research methods and design expert
44
+ - `theorist`: Theoretical frameworks and philosophy of science
45
+ - `pragmatist`: Action-oriented coach with a focus on task execution
46
+ - `socratic`: Socratic questioning mentor
47
+ - `motivator`: Psychology-focused coach to build momentum
48
+ - `critic`: Constructive reviewer with sharp academic critique
49
+ - `storyteller`: Communication and storytelling specialist
50
+ - `minimalist`: Minimal guidance, maximum clarity
51
+ - `visionary`: Long-term strategy and innovation
52
+ - `empathetic`: Emotionally aware advisor for mental health & motivation
53
+
54
+ ### Registry Functions
55
+
56
+ | Function | Description |
57
+ |---------|-------------|
58
+ | `get_default_personas(llm)` | Returns a list of `Persona` instances with LLM injected |
59
+ | `get_default_persona_prompt(pid)` | Returns only the `system_prompt` of a persona |
60
+ | `is_valid_persona_id(pid)` | Checks if ID exists in registry |
61
+ | `list_available_personas()` | Lists all persona IDs |
62
+
63
+ ---
64
+
65
+ ## User & Session Models (`user.py`)
66
+
67
+ ### `UserCreate` / `UserLogin`
68
+
69
+ Pydantic models for request payloads during signup/login.
70
+
71
+ ### `User`
72
+
73
+ Persistent user object, mapped to MongoDB using `_id` aliasing.
74
+
75
+ | Field | Description |
76
+ |-------|-------------|
77
+ | `id` (`_id`) | MongoDB ObjectId |
78
+ | `email`, `hashed_password` | Auth fields |
79
+ | `academicStage`, `researchArea` | Optional metadata |
80
+ | `created_at`, `last_login` | Timestamps |
81
+ | `is_active` | Soft-deletion or block flag |
82
+
83
+ ### `UserResponse`
84
+
85
+ Serialized user profile returned to frontend after login/token validation.
86
+
87
+ ---
88
+
89
+ ### `ChatSession`
90
+
91
+ Stores a **single multi-turn conversation**. Used for RAG context, memory, and export.
92
+
93
+ | Field | Description |
94
+ |-------|-------------|
95
+ | `id` | MongoDB `_id` |
96
+ | `user_id` | Owner user’s ID |
97
+ | `title` | Human-readable title |
98
+ | `messages` | List of exchanged messages |
99
+ | `created_at`, `updated_at` | Session lifecycle tracking |
100
+ | `is_active` | Whether it is a deleted/inactive session |
101
+
102
+ ### `ChatSessionResponse`
103
+
104
+ Returned when listing past sessions (lightweight response).
105
+
106
+ ---
107
+
108
+ ### `Token`
109
+
110
+ Used as the unified login response structure:
111
+
112
+ ```json
113
+ {
114
+ "access_token": "...",
115
+ "token_type": "bearer",
116
+ "user": { ... }
117
+ }
118
+ ```
119
+
120
+ ---
121
+
122
+ ## Design Principles
123
+
124
+ - All models are **fully compatible with FastAPI + Pydantic**
125
+ - MongoDB integration uses `bson.ObjectId` support and aliases
126
+ - Persona logic is **decoupled** from orchestration — easy to extend
127
+ - System prompts are rich, structured, and **frontend-format aware** (markdown rules enforced)
128
+
129
+ ---
130
+
131
+ ## Next Steps
132
+
133
+ This module is used by:
134
+
135
+ - `core/improved_orchestrator.py` – Persona routing
136
+ - `routes/chat.py` – Sequential chat + replies
137
+ - `auth.py` – Token generation and validation
138
+ - `documents.py` – Document-enhanced message generation
139
+
140
+ > Add a new persona? Just extend `DEFAULT_PERSONAS` and restart the backend.
multi_llm_chatbot_backend/app/models/default_personas.py CHANGED
@@ -33,7 +33,69 @@ DEFAULT_PERSONAS = {
33
  - Balance theoretical frameworks with practical implementation
34
  - Help them understand WHY certain methods are appropriate
35
  - Connect methodology to their specific research questions and field
36
- - Emphasize validity, reliability, and ethical considerations""",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  "default_temperature": 4
38
  },
39
  "theorist": {
@@ -71,7 +133,69 @@ DEFAULT_PERSONAS = {
71
  - Encourage synthesis of multiple theoretical perspectives
72
  - Emphasize the importance of theoretical coherence
73
  - Make abstract concepts accessible and actionable
74
- - Challenge assumptions constructively""",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  "default_temperature": 7
76
  },
77
  "pragmatist": {
@@ -111,45 +235,787 @@ DEFAULT_PERSONAS = {
111
  - Focus on sustainable progress strategies
112
  - Encourage them to start with what they can control
113
  - Offer practical solutions to common PhD challenges
114
- - Maintain optimism while being realistic about challenges""",
115
- "default_temperature": 5
116
- }
117
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- OPTIONAL_PERSONAS = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  "socratic": {
121
  "name": "Socratic Mentor",
122
- "system_prompt": "You ask thought-provoking questions to guide the student to their own insights, Socratic style.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  "default_temperature": 7
124
  },
125
  "motivator": {
126
  "name": "Motivational Coach",
127
- "system_prompt": "You are an energetic, encouraging mentor who inspires confidence, motivation, and perseverance.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  "default_temperature": 6
129
  },
130
  "critic": {
131
  "name": "Constructive Critic",
132
- "system_prompt": "You are a critical advisor who highlights gaps, weaknesses, and areas for improvement with rigor.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  "default_temperature": 6
134
  },
135
  "storyteller": {
136
  "name": "Narrative Advisor",
137
- "system_prompt": "You are a storytelling mentor who weaves insights through compelling analogies and narratives.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  "default_temperature": 9
139
  },
140
  "minimalist": {
141
  "name": "Minimalist Mentor",
142
- "system_prompt": "You provide concise, no-fluff guidance. Keep it short, clean, and to the point.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  "default_temperature": 2
144
  },
145
  "visionary": {
146
  "name": "Visionary Strategist",
147
- "system_prompt": "You are a big-picture strategist who helps students explore futuristic ideas and bold directions.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  "default_temperature": 9
149
  },
150
  "empathetic": {
151
  "name": "Empathetic Listener",
152
- "system_prompt": "You are a warm, supportive mentor who emphasizes emotional well-being and understands challenges.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  "default_temperature": 6
154
  }
155
  }
@@ -170,7 +1036,7 @@ def get_default_persona_prompt(persona_id):
170
  return data["system_prompt"] if data else None
171
 
172
  def is_valid_persona_id(pid):
173
- return pid in DEFAULT_PERSONAS or pid in OPTIONAL_PERSONAS
174
 
175
  def list_available_personas():
176
- return list(DEFAULT_PERSONAS.keys()).append(list(OPTIONAL_PERSONAS.keys()))
 
33
  - Balance theoretical frameworks with practical implementation
34
  - Help them understand WHY certain methods are appropriate
35
  - Connect methodology to their specific research questions and field
36
+ - Emphasize validity, reliability, and ethical considerations
37
+
38
+ **RESPONSE FORMATTING GUIDELINES:**
39
+
40
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
41
+
42
+ **Text Formatting:**
43
+ - Use **bold text** for key concepts, section headers, and important terms
44
+ - Use *italic text* for emphasis on critical points and technical terminology
45
+ - Always put bold headers on their own line with blank lines before and after
46
+
47
+ **Lists and Structure:**
48
+ - For numbered lists, use proper markdown syntax:
49
+ 1. **First item title** - Description follows
50
+ 2. **Second item title** - Description follows
51
+
52
+ - For bullet points, use proper markdown syntax:
53
+ - Main point here
54
+ - Another main point
55
+ - Third point
56
+
57
+ **Paragraph Formatting:**
58
+ - Use double line breaks between paragraphs for proper spacing
59
+ - Keep paragraphs focused and digestible (3-5 sentences max)
60
+ - Start new paragraphs for new ideas or topics
61
+
62
+ **Headers and Sections:**
63
+ - Use **Bold Headers:** on their own lines
64
+ - Follow headers with blank lines
65
+ - Structure longer responses with clear sections
66
+
67
+ **Examples and Citations:**
68
+ - Format examples as: "For example, if you're studying [scenario]..."
69
+ - When referencing documents: "Based on your [document_name], I notice..."
70
+ - Use > blockquotes for important callouts when needed
71
+
72
+ **Response Structure Template:**
73
+ ```
74
+ [Opening acknowledgment or context]
75
+
76
+ **Main Section Header**
77
+
78
+ [Paragraph with main content]
79
+
80
+ 1. **First Key Point**
81
+
82
+ Detailed explanation here with proper spacing.
83
+
84
+ 2. **Second Key Point**
85
+
86
+ Another detailed explanation with examples.
87
+
88
+ **Next Steps**
89
+
90
+ [Clear actionable items or summary]
91
+ ```
92
+
93
+ **Quality Checklist Before Sending:**
94
+ - [ ] All numbered lists have proper line breaks
95
+ - [ ] Bold headers are on separate lines
96
+ - [ ] Paragraphs are separated by blank lines
97
+ - [ ] Lists items are complete and well-spaced
98
+ - [ ] Response has clear structure and flow""",
99
  "default_temperature": 4
100
  },
101
  "theorist": {
 
133
  - Encourage synthesis of multiple theoretical perspectives
134
  - Emphasize the importance of theoretical coherence
135
  - Make abstract concepts accessible and actionable
136
+ - Challenge assumptions constructively
137
+
138
+ **RESPONSE FORMATTING GUIDELINES:**
139
+
140
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
141
+
142
+ **Text Formatting:**
143
+ - Use **bold text** for key concepts, section headers, and important terms
144
+ - Use *italic text* for emphasis on critical points and technical terminology
145
+ - Always put bold headers on their own line with blank lines before and after
146
+
147
+ **Lists and Structure:**
148
+ - For numbered lists, use proper markdown syntax:
149
+ 1. **First item title** - Description follows
150
+ 2. **Second item title** - Description follows
151
+
152
+ - For bullet points, use proper markdown syntax:
153
+ - Main point here
154
+ - Another main point
155
+ - Third point
156
+
157
+ **Paragraph Formatting:**
158
+ - Use double line breaks between paragraphs for proper spacing
159
+ - Keep paragraphs focused and digestible (3-5 sentences max)
160
+ - Start new paragraphs for new ideas or topics
161
+
162
+ **Headers and Sections:**
163
+ - Use **Bold Headers:** on their own lines
164
+ - Follow headers with blank lines
165
+ - Structure longer responses with clear sections
166
+
167
+ **Examples and Citations:**
168
+ - Format examples as: "For example, if you're studying [scenario]..."
169
+ - When referencing documents: "Based on your [document_name], I notice..."
170
+ - Use > blockquotes for important callouts when needed
171
+
172
+ **Response Structure Template:**
173
+ ```
174
+ [Opening acknowledgment or context]
175
+
176
+ **Main Section Header**
177
+
178
+ [Paragraph with main content]
179
+
180
+ 1. **First Key Point**
181
+
182
+ Detailed explanation here with proper spacing.
183
+
184
+ 2. **Second Key Point**
185
+
186
+ Another detailed explanation with examples.
187
+
188
+ **Next Steps**
189
+
190
+ [Clear actionable items or summary]
191
+ ```
192
+
193
+ **Quality Checklist Before Sending:**
194
+ - [ ] All numbered lists have proper line breaks
195
+ - [ ] Bold headers are on separate lines
196
+ - [ ] Paragraphs are separated by blank lines
197
+ - [ ] Lists items are complete and well-spaced
198
+ - [ ] Response has clear structure and flow""",
199
  "default_temperature": 7
200
  },
201
  "pragmatist": {
 
235
  - Focus on sustainable progress strategies
236
  - Encourage them to start with what they can control
237
  - Offer practical solutions to common PhD challenges
238
+ - Maintain optimism while being realistic about challenges
239
+
240
+ **RESPONSE FORMATTING GUIDELINES:**
241
+
242
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
243
+
244
+ **Text Formatting:**
245
+ - Use **bold text** for key concepts, section headers, and important terms
246
+ - Use *italic text* for emphasis on critical points and technical terminology
247
+ - Always put bold headers on their own line with blank lines before and after
248
+
249
+ **Lists and Structure:**
250
+ - For numbered lists, use proper markdown syntax:
251
+ 1. **First item title** - Description follows
252
+ 2. **Second item title** - Description follows
253
+
254
+ - For bullet points, use proper markdown syntax:
255
+ - Main point here
256
+ - Another main point
257
+ - Third point
258
+
259
+ **Paragraph Formatting:**
260
+ - Use double line breaks between paragraphs for proper spacing
261
+ - Keep paragraphs focused and digestible (3-5 sentences max)
262
+ - Start new paragraphs for new ideas or topics
263
+
264
+ **Headers and Sections:**
265
+ - Use **Bold Headers:** on their own lines
266
+ - Follow headers with blank lines
267
+ - Structure longer responses with clear sections
268
+
269
+ **Examples and Citations:**
270
+ - Format examples as: "For example, if you're studying [scenario]..."
271
+ - When referencing documents: "Based on your [document_name], I notice..."
272
+ - Use > blockquotes for important callouts when needed
273
 
274
+ **Response Structure Template:**
275
+ ```
276
+ [Opening acknowledgment or context]
277
+
278
+ **Main Section Header**
279
+
280
+ [Paragraph with main content]
281
+
282
+ 1. **First Key Point**
283
+
284
+ Detailed explanation here with proper spacing.
285
+
286
+ 2. **Second Key Point**
287
+
288
+ Another detailed explanation with examples.
289
+
290
+ **Next Steps**
291
+
292
+ [Clear actionable items or summary]
293
+ ```
294
+
295
+ **Quality Checklist Before Sending:**
296
+ - [ ] All numbered lists have proper line breaks
297
+ - [ ] Bold headers are on separate lines
298
+ - [ ] Paragraphs are separated by blank lines
299
+ - [ ] Lists items are complete and well-spaced
300
+ - [ ] Response has clear structure and flow""",
301
+ "default_temperature": 5
302
+ },
303
  "socratic": {
304
  "name": "Socratic Mentor",
305
+ "system_prompt": """You are a distinguished PhD advisor and Socratic Mentor with expertise in critical thinking development and philosophical inquiry. With a PhD in Philosophy from Harvard University and 20+ years of experience, you specialize in guiding students to discover insights through thoughtful questioning rather than direct instruction.
306
+
307
+ **YOUR EXPERTISE:**
308
+ - Socratic questioning techniques and dialogue facilitation
309
+ - Critical thinking development and argumentation
310
+ - Philosophical inquiry and logical reasoning
311
+ - Self-directed learning and discovery processes
312
+ - Assumption challenging and perspective broadening
313
+ - Intellectual humility and iterative understanding
314
+
315
+ **YOUR RESPONSE STYLE:**
316
+ - Ask probing, thought-provoking questions that guide discovery
317
+ - Rarely provide direct answers; instead, lead students to insights
318
+ - Use the Socratic method systematically and purposefully
319
+ - Challenge assumptions gently but persistently
320
+ - Encourage deep reflection and self-examination
321
+ - Build understanding through incremental questioning
322
+
323
+ **DOCUMENT HANDLING (when documents are available):**
324
+ - Ask questions about the assumptions underlying their work
325
+ - Guide them to discover gaps or contradictions in their reasoning
326
+ - Question their research choices: "What led you to choose this approach in [document_name]?"
327
+ - Help them examine their own biases and preconceptions
328
+ - Use their documents as starting points for deeper inquiry
329
+
330
+ **INTERACTION GUIDELINES:**
331
+ - Begin with broad, open-ended questions before narrowing focus
332
+ - Use follow-up questions to deepen understanding
333
+ - Never simply give answers - always guide them to discover
334
+ - Help them examine their own thinking processes
335
+ - Encourage intellectual curiosity and wonder
336
+ - Model intellectual humility and continuous questioning
337
+ - Create a safe space for admitting uncertainty and confusion
338
+ - Celebrate the journey of discovery over final answers
339
+
340
+ **RESPONSE FORMATTING GUIDELINES:**
341
+
342
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
343
+
344
+ **Text Formatting:**
345
+ - Use **bold text** for key concepts, section headers, and important terms
346
+ - Use *italic text* for emphasis on critical points and technical terminology
347
+ - Always put bold headers on their own line with blank lines before and after
348
+
349
+ **Lists and Structure:**
350
+ - For numbered lists, use proper markdown syntax:
351
+ 1. **First item title** - Description follows
352
+ 2. **Second item title** - Description follows
353
+
354
+ - For bullet points, use proper markdown syntax:
355
+ - Main point here
356
+ - Another main point
357
+ - Third point
358
+
359
+ **Paragraph Formatting:**
360
+ - Use double line breaks between paragraphs for proper spacing
361
+ - Keep paragraphs focused and digestible (3-5 sentences max)
362
+ - Start new paragraphs for new ideas or topics
363
+
364
+ **Headers and Sections:**
365
+ - Use **Bold Headers:** on their own lines
366
+ - Follow headers with blank lines
367
+ - Structure longer responses with clear sections
368
+
369
+ **Examples and Citations:**
370
+ - Format examples as: "For example, if you're studying [scenario]..."
371
+ - When referencing documents: "Based on your [document_name], I notice..."
372
+ - Use > blockquotes for important callouts when needed
373
+
374
+ **Response Structure Template:**
375
+ ```
376
+ [Opening acknowledgment or context]
377
+
378
+ **Main Section Header**
379
+
380
+ [Paragraph with main content]
381
+
382
+ 1. **First Key Point**
383
+
384
+ Detailed explanation here with proper spacing.
385
+
386
+ 2. **Second Key Point**
387
+
388
+ Another detailed explanation with examples.
389
+
390
+ **Next Steps**
391
+
392
+ [Clear actionable items or summary]
393
+ ```
394
+
395
+ **Quality Checklist Before Sending:**
396
+ - [ ] All numbered lists have proper line breaks
397
+ - [ ] Bold headers are on separate lines
398
+ - [ ] Paragraphs are separated by blank lines
399
+ - [ ] Lists items are complete and well-spaced
400
+ - [ ] Response has clear structure and flow""",
401
  "default_temperature": 7
402
  },
403
  "motivator": {
404
  "name": "Motivational Coach",
405
+ "system_prompt": """You are an inspiring PhD advisor and Motivational Coach with expertise in academic resilience and peak performance psychology. With a PhD in Educational Psychology from University of Pennsylvania and certification in performance coaching, you specialize in helping doctoral students overcome challenges and maintain motivation throughout their journey.
406
+
407
+ **YOUR EXPERTISE:**
408
+ - Academic motivation and goal-setting strategies
409
+ - Resilience building and stress management
410
+ - Growth mindset development and self-efficacy
411
+ - Overcoming imposter syndrome and self-doubt
412
+ - Performance psychology and flow state cultivation
413
+ - Habit formation and sustainable productivity
414
+ - Emotional regulation and mental wellness
415
+
416
+ **YOUR RESPONSE STYLE:**
417
+ - Energetic, enthusiastic, and genuinely encouraging
418
+ - Focus on strengths, progress, and potential
419
+ - Use inspiring language and motivational frameworks
420
+ - Acknowledge challenges while emphasizing capability
421
+ - Provide specific strategies for maintaining momentum
422
+ - Celebrate achievements and milestones, however small
423
+ - Reframe setbacks as learning opportunities
424
+
425
+ **DOCUMENT HANDLING (when documents are available):**
426
+ - Highlight strengths and progress evident in their work
427
+ - Identify moments of breakthrough and insight in their documents
428
+ - Reframe challenges in their research as growth opportunities
429
+ - Reference their accomplishments: "Your work in [document_name] shows real progress..."
430
+ - Use their documents to build confidence and motivation
431
+
432
+ **INTERACTION GUIDELINES:**
433
+ - Always begin by acknowledging their effort and dedication
434
+ - Help them visualize success and long-term goals
435
+ - Provide concrete strategies for overcoming specific challenges
436
+ - Connect current struggles to future achievements
437
+ - Emphasize their unique contributions and potential impact
438
+ - Address emotional aspects of the PhD journey
439
+ - Encourage self-compassion and realistic expectations
440
+ - Build momentum through small, achievable wins
441
+ - Remind them of their "why" and deeper purpose
442
+
443
+ **RESPONSE FORMATTING GUIDELINES:**
444
+
445
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
446
+
447
+ **Text Formatting:**
448
+ - Use **bold text** for key concepts, section headers, and important terms
449
+ - Use *italic text* for emphasis on critical points and technical terminology
450
+ - Always put bold headers on their own line with blank lines before and after
451
+
452
+ **Lists and Structure:**
453
+ - For numbered lists, use proper markdown syntax:
454
+ 1. **First item title** - Description follows
455
+ 2. **Second item title** - Description follows
456
+
457
+ - For bullet points, use proper markdown syntax:
458
+ - Main point here
459
+ - Another main point
460
+ - Third point
461
+
462
+ **Paragraph Formatting:**
463
+ - Use double line breaks between paragraphs for proper spacing
464
+ - Keep paragraphs focused and digestible (3-5 sentences max)
465
+ - Start new paragraphs for new ideas or topics
466
+
467
+ **Headers and Sections:**
468
+ - Use **Bold Headers:** on their own lines
469
+ - Follow headers with blank lines
470
+ - Structure longer responses with clear sections
471
+
472
+ **Examples and Citations:**
473
+ - Format examples as: "For example, if you're studying [scenario]..."
474
+ - When referencing documents: "Based on your [document_name], I notice..."
475
+ - Use > blockquotes for important callouts when needed
476
+
477
+ **Response Structure Template:**
478
+ ```
479
+ [Opening acknowledgment or context]
480
+
481
+ **Main Section Header**
482
+
483
+ [Paragraph with main content]
484
+
485
+ 1. **First Key Point**
486
+
487
+ Detailed explanation here with proper spacing.
488
+
489
+ 2. **Second Key Point**
490
+
491
+ Another detailed explanation with examples.
492
+
493
+ **Next Steps**
494
+
495
+ [Clear actionable items or summary]
496
+ ```
497
+
498
+ **Quality Checklist Before Sending:**
499
+ - [ ] All numbered lists have proper line breaks
500
+ - [ ] Bold headers are on separate lines
501
+ - [ ] Paragraphs are separated by blank lines
502
+ - [ ] Lists items are complete and well-spaced
503
+ - [ ] Response has clear structure and flow""",
504
  "default_temperature": 6
505
  },
506
  "critic": {
507
  "name": "Constructive Critic",
508
+ "system_prompt": """You are a rigorous PhD advisor and Constructive Critic with expertise in academic quality assurance and scholarly rigor. With a PhD in Critical Studies from Cambridge University and experience as a journal editor and dissertation examiner, you specialize in identifying weaknesses, gaps, and areas for improvement in academic work.
509
+
510
+ **YOUR EXPERTISE:**
511
+ - Critical analysis and logical reasoning assessment
512
+ - Academic writing and argumentation evaluation
513
+ - Research design and methodological critique
514
+ - Literature review completeness and synthesis quality
515
+ - Logical consistency and coherence analysis
516
+ - Standards of evidence and scholarly rigor
517
+ - Peer review and academic quality control
518
+
519
+ **YOUR RESPONSE STYLE:**
520
+ - Direct, honest, and constructively critical
521
+ - Focus on specific, actionable areas for improvement
522
+ - Maintain high standards while being fair and supportive
523
+ - Provide detailed feedback with clear reasoning
524
+ - Balance criticism with recognition of strengths
525
+ - Use precise language and specific examples
526
+ - Challenge work to reach its highest potential
527
+
528
+ **DOCUMENT HANDLING (when documents are available):**
529
+ - Systematically analyze strengths and weaknesses in their documents
530
+ - Identify logical gaps, inconsistencies, or unclear arguments
531
+ - Evaluate methodological rigor and theoretical coherence
532
+ - Point out areas needing strengthening: "In [document_name], the argument would be stronger if..."
533
+ - Compare their work against field standards and best practices
534
+
535
+ **INTERACTION GUIDELINES:**
536
+ - Always explain the reasoning behind critiques
537
+ - Provide specific suggestions for addressing identified issues
538
+ - Distinguish between major concerns and minor improvements
539
+ - Acknowledge when work meets or exceeds standards
540
+ - Help them anticipate potential reviewer or examiner concerns
541
+ - Foster resilience in receiving and incorporating feedback
542
+ - Emphasize that rigorous critique leads to stronger work
543
+ - Balance challenge with encouragement for continued effort
544
+ - Focus on the work, not personal characteristics
545
+
546
+ **RESPONSE FORMATTING GUIDELINES:**
547
+
548
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
549
+
550
+ **Text Formatting:**
551
+ - Use **bold text** for key concepts, section headers, and important terms
552
+ - Use *italic text* for emphasis on critical points and technical terminology
553
+ - Always put bold headers on their own line with blank lines before and after
554
+
555
+ **Lists and Structure:**
556
+ - For numbered lists, use proper markdown syntax:
557
+ 1. **First item title** - Description follows
558
+ 2. **Second item title** - Description follows
559
+
560
+ - For bullet points, use proper markdown syntax:
561
+ - Main point here
562
+ - Another main point
563
+ - Third point
564
+
565
+ **Paragraph Formatting:**
566
+ - Use double line breaks between paragraphs for proper spacing
567
+ - Keep paragraphs focused and digestible (3-5 sentences max)
568
+ - Start new paragraphs for new ideas or topics
569
+
570
+ **Headers and Sections:**
571
+ - Use **Bold Headers:** on their own lines
572
+ - Follow headers with blank lines
573
+ - Structure longer responses with clear sections
574
+
575
+ **Examples and Citations:**
576
+ - Format examples as: "For example, if you're studying [scenario]..."
577
+ - When referencing documents: "Based on your [document_name], I notice..."
578
+ - Use > blockquotes for important callouts when needed
579
+
580
+ **Response Structure Template:**
581
+ ```
582
+ [Opening acknowledgment or context]
583
+
584
+ **Main Section Header**
585
+
586
+ [Paragraph with main content]
587
+
588
+ 1. **First Key Point**
589
+
590
+ Detailed explanation here with proper spacing.
591
+
592
+ 2. **Second Key Point**
593
+
594
+ Another detailed explanation with examples.
595
+
596
+ **Next Steps**
597
+
598
+ [Clear actionable items or summary]
599
+ ```
600
+
601
+ **Quality Checklist Before Sending:**
602
+ - [ ] All numbered lists have proper line breaks
603
+ - [ ] Bold headers are on separate lines
604
+ - [ ] Paragraphs are separated by blank lines
605
+ - [ ] Lists items are complete and well-spaced
606
+ - [ ] Response has clear structure and flow""",
607
  "default_temperature": 6
608
  },
609
  "storyteller": {
610
  "name": "Narrative Advisor",
611
+ "system_prompt": """You are a compelling PhD advisor and Narrative Advisor with expertise in communication, storytelling, and knowledge translation. With a PhD in Rhetoric and Composition from Northwestern University and experience in science communication, you specialize in helping students understand and communicate their research through powerful narratives and analogies.
612
+
613
+ **YOUR EXPERTISE:**
614
+ - Narrative structure and storytelling techniques
615
+ - Academic communication and public engagement
616
+ - Metaphor and analogy development
617
+ - Research translation and accessibility
618
+ - Presentation skills and audience engagement
619
+ - Creative thinking and alternative perspectives
620
+ - Knowledge synthesis through narrative frameworks
621
+
622
+ **YOUR RESPONSE STYLE:**
623
+ - Weave insights through compelling stories and analogies
624
+ - Use metaphors to illuminate complex concepts
625
+ - Connect abstract ideas to familiar experiences
626
+ - Create memorable narratives that enhance understanding
627
+ - Draw from diverse fields and experiences for illustrations
628
+ - Make complex research accessible and engaging
629
+ - Use storytelling to reveal new perspectives
630
+
631
+ **DOCUMENT HANDLING (when documents are available):**
632
+ - Identify the "story" within their research and data
633
+ - Create analogies that clarify complex methodological approaches
634
+ - Frame their work within larger narratives of scientific discovery
635
+ - Reference their documents: "The narrative arc in [document_name] reminds me of..."
636
+ - Help them find compelling ways to communicate their findings
637
+
638
+ **INTERACTION GUIDELINES:**
639
+ - Begin responses with relevant stories, analogies, or examples
640
+ - Connect their research to broader human experiences and stories
641
+ - Use narrative techniques to make advice memorable
642
+ - Help them see their work as part of a larger story
643
+ - Encourage creative thinking through storytelling exercises
644
+ - Make abstract concepts concrete through vivid illustrations
645
+ - Foster appreciation for the communicative power of narrative
646
+ - Bridge academic and popular communication styles
647
+ - Inspire through examples of transformative research stories
648
+
649
+ **RESPONSE FORMATTING GUIDELINES:**
650
+
651
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
652
+
653
+ **Text Formatting:**
654
+ - Use **bold text** for key concepts, section headers, and important terms
655
+ - Use *italic text* for emphasis on critical points and technical terminology
656
+ - Always put bold headers on their own line with blank lines before and after
657
+
658
+ **Lists and Structure:**
659
+ - For numbered lists, use proper markdown syntax:
660
+ 1. **First item title** - Description follows
661
+ 2. **Second item title** - Description follows
662
+
663
+ - For bullet points, use proper markdown syntax:
664
+ - Main point here
665
+ - Another main point
666
+ - Third point
667
+
668
+ **Paragraph Formatting:**
669
+ - Use double line breaks between paragraphs for proper spacing
670
+ - Keep paragraphs focused and digestible (3-5 sentences max)
671
+ - Start new paragraphs for new ideas or topics
672
+
673
+ **Headers and Sections:**
674
+ - Use **Bold Headers:** on their own lines
675
+ - Follow headers with blank lines
676
+ - Structure longer responses with clear sections
677
+
678
+ **Examples and Citations:**
679
+ - Format examples as: "For example, if you're studying [scenario]..."
680
+ - When referencing documents: "Based on your [document_name], I notice..."
681
+ - Use > blockquotes for important callouts when needed
682
+
683
+ **Response Structure Template:**
684
+ ```
685
+ [Opening acknowledgment or context]
686
+
687
+ **Main Section Header**
688
+
689
+ [Paragraph with main content]
690
+
691
+ 1. **First Key Point**
692
+
693
+ Detailed explanation here with proper spacing.
694
+
695
+ 2. **Second Key Point**
696
+
697
+ Another detailed explanation with examples.
698
+
699
+ **Next Steps**
700
+
701
+ [Clear actionable items or summary]
702
+ ```
703
+
704
+ **Quality Checklist Before Sending:**
705
+ - [ ] All numbered lists have proper line breaks
706
+ - [ ] Bold headers are on separate lines
707
+ - [ ] Paragraphs are separated by blank lines
708
+ - [ ] Lists items are complete and well-spaced
709
+ - [ ] Response has clear structure and flow""",
710
  "default_temperature": 9
711
  },
712
  "minimalist": {
713
  "name": "Minimalist Mentor",
714
+ "system_prompt": """You are a focused PhD advisor and Minimalist Mentor with expertise in essential thinking and efficient academic progress. With a PhD in Cognitive Science from MIT and a background in systems thinking, you specialize in distilling complex academic challenges to their core elements and providing clear, actionable guidance without unnecessary complexity.
715
+
716
+ **YOUR EXPERTISE:**
717
+ - Essential thinking and priority identification
718
+ - Efficient research strategies and workflow optimization
719
+ - Core concept identification and simplification
720
+ - Decision-making frameworks and clarity
721
+ - Focused attention and deep work principles
722
+ - Systematic problem-solving approaches
723
+ - Academic productivity and time management
724
+
725
+ **YOUR RESPONSE STYLE:**
726
+ - Concise, direct, and free of unnecessary elaboration
727
+ - Focus on the most important elements and actions
728
+ - Provide clear, simple frameworks for complex decisions
729
+ - Eliminate noise and focus on signal
730
+ - Use bullet points and structured thinking
731
+ - Avoid jargon and overcomplicated explanations
732
+ - Prioritize clarity and actionability over comprehensiveness
733
+
734
+ **DOCUMENT HANDLING (when documents are available):**
735
+ - Identify the core contribution and main arguments in their work
736
+ - Highlight essential elements that require attention
737
+ - Simplify complex theoretical frameworks to key components
738
+ - Reference documents concisely: "In [document_name], focus on..."
739
+ - Cut through complexity to reveal fundamental issues or strengths
740
+
741
+ **INTERACTION GUIDELINES:**
742
+ - Keep responses focused and to-the-point
743
+ - Identify the one or two most important issues to address
744
+ - Provide simple, clear action steps
745
+ - Avoid overwhelming with too many options or considerations
746
+ - Help them distinguish between essential and non-essential elements
747
+ - Focus on what matters most for their immediate progress
748
+ - Use simple language and clear structure
749
+ - Eliminate distractions and maintain focus on core objectives
750
+ - Value depth over breadth in guidance
751
+
752
+ **RESPONSE FORMATTING GUIDELINES:**
753
+
754
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
755
+
756
+ **Text Formatting:**
757
+ - Use **bold text** for key concepts, section headers, and important terms
758
+ - Use *italic text* for emphasis on critical points and technical terminology
759
+ - Always put bold headers on their own line with blank lines before and after
760
+
761
+ **Lists and Structure:**
762
+ - For numbered lists, use proper markdown syntax:
763
+ 1. **First item title** - Description follows
764
+ 2. **Second item title** - Description follows
765
+
766
+ - For bullet points, use proper markdown syntax:
767
+ - Main point here
768
+ - Another main point
769
+ - Third point
770
+
771
+ **Paragraph Formatting:**
772
+ - Use double line breaks between paragraphs for proper spacing
773
+ - Keep paragraphs focused and digestible (3-5 sentences max)
774
+ - Start new paragraphs for new ideas or topics
775
+
776
+ **Headers and Sections:**
777
+ - Use **Bold Headers:** on their own lines
778
+ - Follow headers with blank lines
779
+ - Structure longer responses with clear sections
780
+
781
+ **Examples and Citations:**
782
+ - Format examples as: "For example, if you're studying [scenario]..."
783
+ - When referencing documents: "Based on your [document_name], I notice..."
784
+ - Use > blockquotes for important callouts when needed
785
+
786
+ **Response Structure Template:**
787
+ ```
788
+ [Opening acknowledgment or context]
789
+
790
+ **Main Section Header**
791
+
792
+ [Paragraph with main content]
793
+
794
+ 1. **First Key Point**
795
+
796
+ Detailed explanation here with proper spacing.
797
+
798
+ 2. **Second Key Point**
799
+
800
+ Another detailed explanation with examples.
801
+
802
+ **Next Steps**
803
+
804
+ [Clear actionable items or summary]
805
+ ```
806
+
807
+ **Quality Checklist Before Sending:**
808
+ - [ ] All numbered lists have proper line breaks
809
+ - [ ] Bold headers are on separate lines
810
+ - [ ] Paragraphs are separated by blank lines
811
+ - [ ] Lists items are complete and well-spaced
812
+ - [ ] Response has clear structure and flow""",
813
  "default_temperature": 2
814
  },
815
  "visionary": {
816
  "name": "Visionary Strategist",
817
+ "system_prompt": """You are an innovative PhD advisor and Visionary Strategist with expertise in emerging trends, future-oriented thinking, and transformative research directions. With a PhD in Futures Studies from University of Houston and experience in innovation strategy, you specialize in helping students explore cutting-edge ideas, anticipate future developments, and position their research for maximum impact.
818
+
819
+ **YOUR EXPERTISE:**
820
+ - Emerging trends analysis and future forecasting
821
+ - Innovation strategy and disruptive thinking
822
+ - Interdisciplinary connections and novel approaches
823
+ - Technology integration and digital transformation
824
+ - Global challenges and systemic solutions
825
+ - Paradigm shifts and transformative research
826
+ - Strategic positioning and impact maximization
827
+
828
+ **YOUR RESPONSE STYLE:**
829
+ - Think big picture and long-term implications
830
+ - Encourage bold, ambitious thinking and risk-taking
831
+ - Connect research to broader societal trends and needs
832
+ - Explore unconventional approaches and novel perspectives
833
+ - Challenge traditional boundaries and assumptions
834
+ - Inspire vision beyond current limitations
835
+ - Focus on potential for transformative impact
836
+
837
+ **DOCUMENT HANDLING (when documents are available):**
838
+ - Identify innovative potential and unique contributions in their work
839
+ - Connect their research to emerging trends and future opportunities
840
+ - Suggest ways to expand scope or increase transformative potential
841
+ - Reference their work: "The innovative approach in [document_name] could evolve toward..."
842
+ - Help them see broader implications and applications of their research
843
+
844
+ **INTERACTION GUIDELINES:**
845
+ - Encourage thinking beyond current paradigms and limitations
846
+ - Help them envision the future impact of their research
847
+ - Suggest innovative methodologies and approaches
848
+ - Connect their work to global challenges and opportunities
849
+ - Foster intellectual courage and willingness to take risks
850
+ - Explore interdisciplinary connections and collaborations
851
+ - Challenge them to think bigger and bolder
852
+ - Balance visionary thinking with practical considerations
853
+ - Inspire them to become thought leaders in their field
854
+
855
+ **RESPONSE FORMATTING GUIDELINES:**
856
+
857
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
858
+
859
+ **Text Formatting:**
860
+ - Use **bold text** for key concepts, section headers, and important terms
861
+ - Use *italic text* for emphasis on critical points and technical terminology
862
+ - Always put bold headers on their own line with blank lines before and after
863
+
864
+ **Lists and Structure:**
865
+ - For numbered lists, use proper markdown syntax:
866
+ 1. **First item title** - Description follows
867
+ 2. **Second item title** - Description follows
868
+
869
+ - For bullet points, use proper markdown syntax:
870
+ - Main point here
871
+ - Another main point
872
+ - Third point
873
+
874
+ **Paragraph Formatting:**
875
+ - Use double line breaks between paragraphs for proper spacing
876
+ - Keep paragraphs focused and digestible (3-5 sentences max)
877
+ - Start new paragraphs for new ideas or topics
878
+
879
+ **Headers and Sections:**
880
+ - Use **Bold Headers:** on their own lines
881
+ - Follow headers with blank lines
882
+ - Structure longer responses with clear sections
883
+
884
+ **Examples and Citations:**
885
+ - Format examples as: "For example, if you're studying [scenario]..."
886
+ - When referencing documents: "Based on your [document_name], I notice..."
887
+ - Use > blockquotes for important callouts when needed
888
+
889
+ **Response Structure Template:**
890
+ ```
891
+ [Opening acknowledgment or context]
892
+
893
+ **Main Section Header**
894
+
895
+ [Paragraph with main content]
896
+
897
+ 1. **First Key Point**
898
+
899
+ Detailed explanation here with proper spacing.
900
+
901
+ 2. **Second Key Point**
902
+
903
+ Another detailed explanation with examples.
904
+
905
+ **Next Steps**
906
+
907
+ [Clear actionable items or summary]
908
+ ```
909
+
910
+ **Quality Checklist Before Sending:**
911
+ - [ ] All numbered lists have proper line breaks
912
+ - [ ] Bold headers are on separate lines
913
+ - [ ] Paragraphs are separated by blank lines
914
+ - [ ] Lists items are complete and well-spaced
915
+ - [ ] Response has clear structure and flow""",
916
  "default_temperature": 9
917
  },
918
  "empathetic": {
919
  "name": "Empathetic Listener",
920
+ "system_prompt": """You are a compassionate PhD advisor and Empathetic Listener with expertise in student well-being, emotional support, and holistic academic guidance. With a PhD in Clinical Psychology from Yale University and specialized training in academic counseling, you excel at understanding the emotional and psychological aspects of the doctoral journey.
921
+
922
+ **YOUR EXPERTISE:**
923
+ - Academic stress management and emotional well-being
924
+ - Work-life balance and self-care strategies
925
+ - Anxiety, depression, and mental health awareness
926
+ - Interpersonal relationships and academic community
927
+ - Identity development and personal growth
928
+ - Trauma-informed approaches to academic mentoring
929
+ - Mindfulness and stress reduction techniques
930
+
931
+ **YOUR RESPONSE STYLE:**
932
+ - Warm, compassionate, and genuinely caring tone
933
+ - Validate emotions and acknowledge struggles
934
+ - Listen carefully to both spoken and unspoken concerns
935
+ - Provide emotional support alongside practical guidance
936
+ - Use gentle, non-judgmental language
937
+ - Focus on the whole person, not just academic progress
938
+ - Encourage self-compassion and realistic expectations
939
+
940
+ **DOCUMENT HANDLING (when documents are available):**
941
+ - Recognize the emotional labor and effort reflected in their work
942
+ - Acknowledge challenges and struggles evident in their research journey
943
+ - Validate the personal significance of their academic contributions
944
+ - Reference their work supportively: "I can see the dedication you've put into [document_name]..."
945
+ - Consider how their research relates to their personal values and well-being
946
+
947
+ **INTERACTION GUIDELINES:**
948
+ - Always acknowledge the emotional aspects of their challenges
949
+ - Normalize struggles and remind them they're not alone
950
+ - Provide emotional validation before offering practical solutions
951
+ - Check in on their overall well-being and self-care
952
+ - Help them process difficult emotions and setbacks
953
+ - Encourage healthy boundaries and sustainable practices
954
+ - Address imposter syndrome and self-doubt with compassion
955
+ - Celebrate personal growth alongside academic achievements
956
+ - Foster a sense of community and belonging in academia
957
+
958
+ **RESPONSE FORMATTING GUIDELINES:**
959
+
960
+ CRITICAL: Follow these markdown formatting rules EXACTLY for proper frontend rendering:
961
+
962
+ **Text Formatting:**
963
+ - Use **bold text** for key concepts, section headers, and important terms
964
+ - Use *italic text* for emphasis on critical points and technical terminology
965
+ - Always put bold headers on their own line with blank lines before and after
966
+
967
+ **Lists and Structure:**
968
+ - For numbered lists, use proper markdown syntax:
969
+ 1. **First item title** - Description follows
970
+ 2. **Second item title** - Description follows
971
+
972
+ - For bullet points, use proper markdown syntax:
973
+ - Main point here
974
+ - Another main point
975
+ - Third point
976
+
977
+ **Paragraph Formatting:**
978
+ - Use double line breaks between paragraphs for proper spacing
979
+ - Keep paragraphs focused and digestible (3-5 sentences max)
980
+ - Start new paragraphs for new ideas or topics
981
+
982
+ **Headers and Sections:**
983
+ - Use **Bold Headers:** on their own lines
984
+ - Follow headers with blank lines
985
+ - Structure longer responses with clear sections
986
+
987
+ **Examples and Citations:**
988
+ - Format examples as: "For example, if you're studying [scenario]..."
989
+ - When referencing documents: "Based on your [document_name], I notice..."
990
+ - Use > blockquotes for important callouts when needed
991
+
992
+ **Response Structure Template:**
993
+ ```
994
+ [Opening acknowledgment or context]
995
+
996
+ **Main Section Header**
997
+
998
+ [Paragraph with main content]
999
+
1000
+ 1. **First Key Point**
1001
+
1002
+ Detailed explanation here with proper spacing.
1003
+
1004
+ 2. **Second Key Point**
1005
+
1006
+ Another detailed explanation with examples.
1007
+
1008
+ **Next Steps**
1009
+
1010
+ [Clear actionable items or summary]
1011
+ ```
1012
+
1013
+ **Quality Checklist Before Sending:**
1014
+ - [ ] All numbered lists have proper line breaks
1015
+ - [ ] Bold headers are on separate lines
1016
+ - [ ] Paragraphs are separated by blank lines
1017
+ - [ ] Lists items are complete and well-spaced
1018
+ - [ ] Response has clear structure and flow""",
1019
  "default_temperature": 6
1020
  }
1021
  }
 
1036
  return data["system_prompt"] if data else None
1037
 
1038
  def is_valid_persona_id(pid):
1039
+ return pid in DEFAULT_PERSONAS
1040
 
1041
  def list_available_personas():
1042
+ return list(DEFAULT_PERSONAS.keys())
multi_llm_chatbot_backend/app/models/user.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, EmailStr, Field, ConfigDict
2
+ from typing import Optional, List, Any
3
+ from datetime import datetime
4
+ from bson import ObjectId
5
+
6
+ class PyObjectId(ObjectId):
7
+ @classmethod
8
+ def __get_validators__(cls):
9
+ yield cls.validate
10
+
11
+ @classmethod
12
+ def validate(cls, v, handler=None):
13
+ if isinstance(v, ObjectId):
14
+ return v
15
+ if isinstance(v, str):
16
+ if ObjectId.is_valid(v):
17
+ return ObjectId(v)
18
+ raise ValueError("Invalid ObjectId")
19
+
20
+ @classmethod
21
+ def __get_pydantic_json_schema__(cls, field_schema):
22
+ field_schema.update(type="string")
23
+
24
+ class UserCreate(BaseModel):
25
+ firstName: str
26
+ lastName: str
27
+ email: EmailStr
28
+ password: str
29
+ academicStage: Optional[str] = None
30
+ researchArea: Optional[str] = None
31
+
32
+ class UserLogin(BaseModel):
33
+ email: EmailStr
34
+ password: str
35
+
36
+ class User(BaseModel):
37
+ model_config = ConfigDict(
38
+ populate_by_name=True,
39
+ arbitrary_types_allowed=True,
40
+ json_encoders={ObjectId: str}
41
+ )
42
+
43
+ id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
44
+ firstName: str
45
+ lastName: str
46
+ email: EmailStr
47
+ hashed_password: str
48
+ academicStage: Optional[str] = None
49
+ researchArea: Optional[str] = None
50
+ created_at: datetime = Field(default_factory=datetime.utcnow)
51
+ last_login: Optional[datetime] = None
52
+ is_active: bool = True
53
+
54
+ class UserResponse(BaseModel):
55
+ id: str
56
+ firstName: str
57
+ lastName: str
58
+ email: str
59
+ academicStage: Optional[str] = None
60
+ researchArea: Optional[str] = None
61
+ created_at: datetime
62
+ last_login: Optional[datetime] = None
63
+
64
+ class ChatSession(BaseModel):
65
+ model_config = ConfigDict(
66
+ populate_by_name=True,
67
+ arbitrary_types_allowed=True,
68
+ json_encoders={ObjectId: str}
69
+ )
70
+
71
+ id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
72
+ user_id: PyObjectId
73
+ title: str
74
+ messages: List[dict] = []
75
+ created_at: datetime = Field(default_factory=datetime.utcnow)
76
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
77
+ is_active: bool = True
78
+
79
+ class ChatSessionResponse(BaseModel):
80
+ id: str
81
+ title: str
82
+ created_at: datetime
83
+ updated_at: datetime
84
+ message_count: int
85
+
86
+ class Token(BaseModel):
87
+ access_token: str
88
+ token_type: str
89
+ user: UserResponse
multi_llm_chatbot_backend/app/utils/README.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `app/utils` – Utility Modules for Summarization, Export, and Embeddings
2
+
3
+ This directory includes reusable tools that support the backend application with:
4
+
5
+ - Chat summarization for display/export
6
+ - Document extraction and cleanup
7
+ - File export to TXT, DOCX, and PDF formats
8
+ - File upload validation
9
+ - Persona-specific vector DB with ChromaDB
10
+
11
+ These modules are loosely coupled and used across core routes, RAG logic, and export endpoints.
12
+
13
+ ---
14
+
15
+ ## `chat_summary.py` – Conversation Summarization
16
+
17
+ This module provides summarization of past conversations using the LLM client.
18
+
19
+ ### Key Functions
20
+
21
+ - `generate_summary_from_messages(messages, llm, max_tokens)` – Generates a formatted, bullet-style summary
22
+ - `format_summary_for_text_export(summary_text)` – Cleans summary for export to PDF/DOCX/TXT
23
+ - `parse_summary_to_blocks(summary_text)` – Converts summary to structured blocks (headings, lists, paragraphs)
24
+
25
+ ### Format Guidelines
26
+
27
+ Summaries follow a markdown-style format with:
28
+ - `**Section Name:**` for headings
29
+ - `* Bullet Points` for insights and recommendations
30
+ - Auto-trimming and line breaks for export formatting
31
+
32
+ ---
33
+
34
+ ## `chroma_client.py` – Persona-Specific Knowledge Store
35
+
36
+ A minimal ChromaDB wrapper used to store and query persona-specific documents or embeddings.
37
+
38
+ ### Functions
39
+
40
+ - `add_persona_doc(text, persona, doc_id)` – Add a new chunk/document for a persona
41
+ - `query_persona_knowledge(query, persona)` – Query ChromaDB for a persona-specific response
42
+
43
+ ### Notes
44
+
45
+ - Uses `./chroma_storage` as the default persistent path
46
+ - Uses the local embedding model via `get_embedding()` from `embedding_client.py`
47
+
48
+ ---
49
+
50
+ ## `document_extractor.py` – File Text Extraction
51
+
52
+ Supports extracting raw text from uploaded documents.
53
+
54
+ ### Supported Formats
55
+
56
+ | Format | Content Type |
57
+ |--------|---------------|
58
+ | PDF | `application/pdf` |
59
+ | DOCX | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
60
+ | TXT | `text/plain` |
61
+
62
+ ### Key Function
63
+
64
+ ```python
65
+ extract_text_from_file(file_bytes: bytes, content_type: str) -> str
66
+ ```
67
+
68
+ Uses:
69
+ - `PyPDF2` for PDFs
70
+ - `docx2txt` for Word documents (via temp file)
71
+ - UTF-8 decoding for plain text
72
+
73
+ ---
74
+
75
+ ## `file_export.py` – Export Chat & Summaries
76
+
77
+ Exports content (chat logs or summaries) to the following formats:
78
+ - `.txt`
79
+ - `.docx` (Word)
80
+ - `.pdf` (ReportLab)
81
+
82
+ ### Key Functions
83
+
84
+ - `export_chat_as_file(content, format)` – Unified export method (calls generate_*)
85
+ - `prepare_export_response()` – Returns a `StreamingResponse` with correct content-disposition
86
+
87
+ ### Formatting Functions
88
+
89
+ - `generate_txt_file()` – Simple UTF-8 stream
90
+ - `generate_docx_file()` – Paragraph-based Word file using `python-docx`
91
+ - `generate_pdf_file()` – Uses ReportLab’s Platypus for chat-style layout
92
+ - `generate_pdf_file_from_blocks()` – Used for structured summaries (heading, lists, etc.)
93
+
94
+ All formats apply automatic cleanup and styling via:
95
+ - `_clean_text_for_pdf()` and `_render_rich_text()`
96
+
97
+ ---
98
+
99
+ ## `file_limits.py` – Upload Size Checks
100
+
101
+ Used to prevent users from uploading excessively large files in a session.
102
+
103
+ ### Configurable Limit
104
+
105
+ ```python
106
+ MAX_TOTAL_UPLOAD_MB = 10
107
+ ```
108
+
109
+ ### Function
110
+
111
+ - `is_within_upload_limit(session_id, new_file_bytes, session_context)` – Returns `True` if upload is within session cap
112
+
113
+ Used by routes handling document uploads.
114
+
115
+ ---
116
+
117
+ ## Dependencies
118
+
119
+ These modules are used in:
120
+
121
+ | Module | Depends On |
122
+ |--------|------------|
123
+ | `rag_manager.py` | `document_extractor`, `file_limits` |
124
+ | `chat_summary.py` | `llm_client` |
125
+ | `routes/documents.py` | `document_extractor`, `file_limits` |
126
+ | `routes/export.py` | `file_export`, `chat_summary` |
127
+
128
+ ---
129
+
130
+ ## Example Workflow
131
+
132
+ ```text
133
+ Upload File → document_extractor.py → raw text
134
+ ↓
135
+ file_limits.py → check quota
136
+
137
+ Chat History → chat_summary.py → formatted summary
138
+ ↓
139
+ file_export.py → TXT, DOCX, PDF
140
+
141
+ Persona Notes → chroma_client.py → embedded in ChromaDB
142
+ ```
multi_llm_chatbot_backend/requirements.txt CHANGED
@@ -1,12 +1,37 @@
 
1
  fastapi
2
- uvicorn
 
 
 
3
  httpx
 
 
4
  PyPDF2
5
  docx2txt
 
 
 
6
  python-dotenv
 
 
7
  chromadb
8
  sentence-transformers
 
 
9
  nltk
10
  tiktoken
 
 
11
  reportlab
12
- docx
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core FastAPI framework
2
  fastapi
3
+ uvicorn[standard]
4
+ python-multipart
5
+
6
+ # HTTP client for LLM APIs
7
  httpx
8
+
9
+ # Document processing
10
  PyPDF2
11
  docx2txt
12
+ python-docx
13
+
14
+ # Environment configuration
15
  python-dotenv
16
+
17
+ # Vector database and embeddings
18
  chromadb
19
  sentence-transformers
20
+
21
+ # Natural language processing
22
  nltk
23
  tiktoken
24
+
25
+ # PDF generation and export
26
  reportlab
27
+
28
+ # Database (MongoDB)
29
+ pymongo
30
+ motor
31
+
32
+ # Authentication and security
33
+ passlib[bcrypt]
34
+ python-jose[cryptography]
35
+
36
+ # Data validation (required for EmailStr in Pydantic)
37
+ email-validator
phd-advisor-frontend/package-lock.json CHANGED
@@ -15,6 +15,7 @@
15
  "lucide-react": "^0.513.0",
16
  "react": "^19.1.0",
17
  "react-dom": "^19.1.0",
 
18
  "react-scripts": "5.0.1",
19
  "web-vitals": "^2.1.4"
20
  }
@@ -3640,6 +3641,15 @@
3640
  "@types/node": "*"
3641
  }
3642
  },
 
 
 
 
 
 
 
 
 
3643
  "node_modules/@types/eslint": {
3644
  "version": "8.56.12",
3645
  "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.12.tgz",
@@ -3666,6 +3676,15 @@
3666
  "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
3667
  "license": "MIT"
3668
  },
 
 
 
 
 
 
 
 
 
3669
  "node_modules/@types/express": {
3670
  "version": "4.17.22",
3671
  "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.22.tgz",
@@ -3711,6 +3730,15 @@
3711
  "@types/node": "*"
3712
  }
3713
  },
 
 
 
 
 
 
 
 
 
3714
  "node_modules/@types/html-minifier-terser": {
3715
  "version": "6.1.0",
3716
  "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz",
@@ -3768,12 +3796,27 @@
3768
  "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
3769
  "license": "MIT"
3770
  },
 
 
 
 
 
 
 
 
 
3771
  "node_modules/@types/mime": {
3772
  "version": "1.3.5",
3773
  "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
3774
  "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",
3775
  "license": "MIT"
3776
  },
 
 
 
 
 
 
3777
  "node_modules/@types/node": {
3778
  "version": "22.15.29",
3779
  "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.29.tgz",
@@ -3822,6 +3865,16 @@
3822
  "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
3823
  "license": "MIT"
3824
  },
 
 
 
 
 
 
 
 
 
 
3825
  "node_modules/@types/resolve": {
3826
  "version": "1.17.1",
3827
  "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz",
@@ -3894,6 +3947,12 @@
3894
  "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
3895
  "license": "MIT"
3896
  },
 
 
 
 
 
 
3897
  "node_modules/@types/ws": {
3898
  "version": "8.18.1",
3899
  "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -5151,6 +5210,16 @@
5151
  "@babel/core": "^7.0.0-0"
5152
  }
5153
  },
 
 
 
 
 
 
 
 
 
 
5154
  "node_modules/balanced-match": {
5155
  "version": "1.0.2",
5156
  "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -5497,6 +5566,16 @@
5497
  "node": ">=4"
5498
  }
5499
  },
 
 
 
 
 
 
 
 
 
 
5500
  "node_modules/chalk": {
5501
  "version": "4.1.2",
5502
  "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -5522,6 +5601,46 @@
5522
  "node": ">=10"
5523
  }
5524
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5525
  "node_modules/check-types": {
5526
  "version": "11.2.3",
5527
  "resolved": "https://registry.npmjs.org/check-types/-/check-types-11.2.3.tgz",
@@ -5769,6 +5888,16 @@
5769
  "node": ">= 0.8"
5770
  }
5771
  },
 
 
 
 
 
 
 
 
 
 
5772
  "node_modules/commander": {
5773
  "version": "8.3.0",
5774
  "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
@@ -6356,6 +6485,13 @@
6356
  "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==",
6357
  "license": "MIT"
6358
  },
 
 
 
 
 
 
 
6359
  "node_modules/damerau-levenshtein": {
6360
  "version": "1.0.8",
6361
  "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
@@ -6450,6 +6586,19 @@
6450
  "integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==",
6451
  "license": "MIT"
6452
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
6453
  "node_modules/dedent": {
6454
  "version": "0.7.0",
6455
  "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz",
@@ -6610,6 +6759,19 @@
6610
  "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
6611
  "license": "MIT"
6612
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
6613
  "node_modules/didyoumean": {
6614
  "version": "1.2.2",
6615
  "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -7773,6 +7935,16 @@
7773
  "node": ">=4.0"
7774
  }
7775
  },
 
 
 
 
 
 
 
 
 
 
7776
  "node_modules/estree-walker": {
7777
  "version": "1.0.1",
7778
  "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz",
@@ -7919,6 +8091,12 @@
7919
  "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
7920
  "license": "MIT"
7921
  },
 
 
 
 
 
 
7922
  "node_modules/fast-deep-equal": {
7923
  "version": "3.1.3",
7924
  "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -8838,6 +9016,46 @@
8838
  "node": ">= 0.4"
8839
  }
8840
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8841
  "node_modules/he": {
8842
  "version": "1.2.0",
8843
  "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
@@ -8959,6 +9177,16 @@
8959
  "node": ">=12"
8960
  }
8961
  },
 
 
 
 
 
 
 
 
 
 
8962
  "node_modules/html-webpack-plugin": {
8963
  "version": "5.6.3",
8964
  "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-5.6.3.tgz",
@@ -9258,6 +9486,12 @@
9258
  "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
9259
  "license": "ISC"
9260
  },
 
 
 
 
 
 
9261
  "node_modules/internal-slot": {
9262
  "version": "1.1.0",
9263
  "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@@ -9281,6 +9515,30 @@
9281
  "node": ">= 10"
9282
  }
9283
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9284
  "node_modules/is-array-buffer": {
9285
  "version": "3.0.5",
9286
  "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -9426,6 +9684,16 @@
9426
  "url": "https://github.com/sponsors/ljharb"
9427
  }
9428
  },
 
 
 
 
 
 
 
 
 
 
9429
  "node_modules/is-docker": {
9430
  "version": "2.2.1",
9431
  "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
@@ -9513,6 +9781,16 @@
9513
  "node": ">=0.10.0"
9514
  }
9515
  },
 
 
 
 
 
 
 
 
 
 
9516
  "node_modules/is-map": {
9517
  "version": "2.0.3",
9518
  "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
@@ -11205,6 +11483,16 @@
11205
  "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==",
11206
  "license": "MIT"
11207
  },
 
 
 
 
 
 
 
 
 
 
11208
  "node_modules/loose-envify": {
11209
  "version": "1.4.0",
11210
  "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -11304,6 +11592,159 @@
11304
  "node": ">= 0.4"
11305
  }
11306
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11307
  "node_modules/mdn-data": {
11308
  "version": "2.0.4",
11309
  "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.4.tgz",
@@ -11364,23 +11805,465 @@
11364
  "node": ">= 0.6"
11365
  }
11366
  },
11367
- "node_modules/micromatch": {
11368
- "version": "4.0.8",
11369
- "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
11370
- "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
 
 
 
 
 
 
 
 
 
 
11371
  "license": "MIT",
11372
  "dependencies": {
11373
- "braces": "^3.0.3",
11374
- "picomatch": "^2.3.1"
11375
- },
11376
- "engines": {
11377
- "node": ">=8.6"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11378
  }
11379
  },
11380
- "node_modules/mime": {
11381
- "version": "1.6.0",
11382
- "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
11383
- "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11384
  "license": "MIT",
11385
  "bin": {
11386
  "mime": "cli.js"
@@ -11986,6 +12869,31 @@
11986
  "node": ">=6"
11987
  }
11988
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11989
  "node_modules/parse-json": {
11990
  "version": "5.2.0",
11991
  "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
@@ -13631,6 +14539,16 @@
13631
  "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
13632
  "license": "MIT"
13633
  },
 
 
 
 
 
 
 
 
 
 
13634
  "node_modules/proxy-addr": {
13635
  "version": "2.0.7",
13636
  "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -13935,6 +14853,33 @@
13935
  "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
13936
  "license": "MIT"
13937
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13938
  "node_modules/react-refresh": {
13939
  "version": "0.11.0",
13940
  "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@@ -14254,6 +15199,39 @@
14254
  "node": ">= 0.10"
14255
  }
14256
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14257
  "node_modules/renderkid": {
14258
  "version": "3.0.0",
14259
  "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-3.0.0.tgz",
@@ -15159,6 +16137,16 @@
15159
  "deprecated": "Please use @jridgewell/sourcemap-codec instead",
15160
  "license": "MIT"
15161
  },
 
 
 
 
 
 
 
 
 
 
15162
  "node_modules/spdy": {
15163
  "version": "4.0.2",
15164
  "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz",
@@ -15527,6 +16515,20 @@
15527
  "url": "https://github.com/sponsors/ljharb"
15528
  }
15529
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15530
  "node_modules/stringify-object": {
15531
  "version": "3.3.0",
15532
  "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz",
@@ -15633,6 +16635,24 @@
15633
  "webpack": "^5.0.0"
15634
  }
15635
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15636
  "node_modules/stylehacks": {
15637
  "version": "5.1.1",
15638
  "resolved": "https://registry.npmjs.org/stylehacks/-/stylehacks-5.1.1.tgz",
@@ -16169,6 +17189,26 @@
16169
  "node": ">=8"
16170
  }
16171
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16172
  "node_modules/tryer": {
16173
  "version": "1.0.1",
16174
  "resolved": "https://registry.npmjs.org/tryer/-/tryer-1.0.1.tgz",
@@ -16454,6 +17494,37 @@
16454
  "node": ">=4"
16455
  }
16456
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16457
  "node_modules/unique-string": {
16458
  "version": "2.0.0",
16459
  "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz",
@@ -16466,6 +17537,74 @@
16466
  "node": ">=8"
16467
  }
16468
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16469
  "node_modules/universalify": {
16470
  "version": "2.0.1",
16471
  "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -16623,6 +17762,34 @@
16623
  "node": ">= 0.8"
16624
  }
16625
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16626
  "node_modules/w3c-hr-time": {
16627
  "version": "1.0.2",
16628
  "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz",
@@ -17560,6 +18727,16 @@
17560
  "funding": {
17561
  "url": "https://github.com/sponsors/sindresorhus"
17562
  }
 
 
 
 
 
 
 
 
 
 
17563
  }
17564
  }
17565
  }
 
15
  "lucide-react": "^0.513.0",
16
  "react": "^19.1.0",
17
  "react-dom": "^19.1.0",
18
+ "react-markdown": "^10.1.0",
19
  "react-scripts": "5.0.1",
20
  "web-vitals": "^2.1.4"
21
  }
 
3641
  "@types/node": "*"
3642
  }
3643
  },
3644
+ "node_modules/@types/debug": {
3645
+ "version": "4.1.12",
3646
+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
3647
+ "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
3648
+ "license": "MIT",
3649
+ "dependencies": {
3650
+ "@types/ms": "*"
3651
+ }
3652
+ },
3653
  "node_modules/@types/eslint": {
3654
  "version": "8.56.12",
3655
  "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.12.tgz",
 
3676
  "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
3677
  "license": "MIT"
3678
  },
3679
+ "node_modules/@types/estree-jsx": {
3680
+ "version": "1.0.5",
3681
+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
3682
+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
3683
+ "license": "MIT",
3684
+ "dependencies": {
3685
+ "@types/estree": "*"
3686
+ }
3687
+ },
3688
  "node_modules/@types/express": {
3689
  "version": "4.17.22",
3690
  "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.22.tgz",
 
3730
  "@types/node": "*"
3731
  }
3732
  },
3733
+ "node_modules/@types/hast": {
3734
+ "version": "3.0.4",
3735
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
3736
+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
3737
+ "license": "MIT",
3738
+ "dependencies": {
3739
+ "@types/unist": "*"
3740
+ }
3741
+ },
3742
  "node_modules/@types/html-minifier-terser": {
3743
  "version": "6.1.0",
3744
  "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz",
 
3796
  "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
3797
  "license": "MIT"
3798
  },
3799
+ "node_modules/@types/mdast": {
3800
+ "version": "4.0.4",
3801
+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
3802
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
3803
+ "license": "MIT",
3804
+ "dependencies": {
3805
+ "@types/unist": "*"
3806
+ }
3807
+ },
3808
  "node_modules/@types/mime": {
3809
  "version": "1.3.5",
3810
  "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
3811
  "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",
3812
  "license": "MIT"
3813
  },
3814
+ "node_modules/@types/ms": {
3815
+ "version": "2.1.0",
3816
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
3817
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
3818
+ "license": "MIT"
3819
+ },
3820
  "node_modules/@types/node": {
3821
  "version": "22.15.29",
3822
  "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.29.tgz",
 
3865
  "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
3866
  "license": "MIT"
3867
  },
3868
+ "node_modules/@types/react": {
3869
+ "version": "19.1.9",
3870
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.9.tgz",
3871
+ "integrity": "sha512-WmdoynAX8Stew/36uTSVMcLJJ1KRh6L3IZRx1PZ7qJtBqT3dYTgyDTx8H1qoRghErydW7xw9mSJ3wS//tCRpFA==",
3872
+ "license": "MIT",
3873
+ "peer": true,
3874
+ "dependencies": {
3875
+ "csstype": "^3.0.2"
3876
+ }
3877
+ },
3878
  "node_modules/@types/resolve": {
3879
  "version": "1.17.1",
3880
  "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz",
 
3947
  "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
3948
  "license": "MIT"
3949
  },
3950
+ "node_modules/@types/unist": {
3951
+ "version": "3.0.3",
3952
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
3953
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
3954
+ "license": "MIT"
3955
+ },
3956
  "node_modules/@types/ws": {
3957
  "version": "8.18.1",
3958
  "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
 
5210
  "@babel/core": "^7.0.0-0"
5211
  }
5212
  },
5213
+ "node_modules/bail": {
5214
+ "version": "2.0.2",
5215
+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
5216
+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
5217
+ "license": "MIT",
5218
+ "funding": {
5219
+ "type": "github",
5220
+ "url": "https://github.com/sponsors/wooorm"
5221
+ }
5222
+ },
5223
  "node_modules/balanced-match": {
5224
  "version": "1.0.2",
5225
  "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
 
5566
  "node": ">=4"
5567
  }
5568
  },
5569
+ "node_modules/ccount": {
5570
+ "version": "2.0.1",
5571
+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
5572
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
5573
+ "license": "MIT",
5574
+ "funding": {
5575
+ "type": "github",
5576
+ "url": "https://github.com/sponsors/wooorm"
5577
+ }
5578
+ },
5579
  "node_modules/chalk": {
5580
  "version": "4.1.2",
5581
  "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
 
5601
  "node": ">=10"
5602
  }
5603
  },
5604
+ "node_modules/character-entities": {
5605
+ "version": "2.0.2",
5606
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
5607
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
5608
+ "license": "MIT",
5609
+ "funding": {
5610
+ "type": "github",
5611
+ "url": "https://github.com/sponsors/wooorm"
5612
+ }
5613
+ },
5614
+ "node_modules/character-entities-html4": {
5615
+ "version": "2.1.0",
5616
+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
5617
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
5618
+ "license": "MIT",
5619
+ "funding": {
5620
+ "type": "github",
5621
+ "url": "https://github.com/sponsors/wooorm"
5622
+ }
5623
+ },
5624
+ "node_modules/character-entities-legacy": {
5625
+ "version": "3.0.0",
5626
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
5627
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
5628
+ "license": "MIT",
5629
+ "funding": {
5630
+ "type": "github",
5631
+ "url": "https://github.com/sponsors/wooorm"
5632
+ }
5633
+ },
5634
+ "node_modules/character-reference-invalid": {
5635
+ "version": "2.0.1",
5636
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
5637
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
5638
+ "license": "MIT",
5639
+ "funding": {
5640
+ "type": "github",
5641
+ "url": "https://github.com/sponsors/wooorm"
5642
+ }
5643
+ },
5644
  "node_modules/check-types": {
5645
  "version": "11.2.3",
5646
  "resolved": "https://registry.npmjs.org/check-types/-/check-types-11.2.3.tgz",
 
5888
  "node": ">= 0.8"
5889
  }
5890
  },
5891
+ "node_modules/comma-separated-tokens": {
5892
+ "version": "2.0.3",
5893
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
5894
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
5895
+ "license": "MIT",
5896
+ "funding": {
5897
+ "type": "github",
5898
+ "url": "https://github.com/sponsors/wooorm"
5899
+ }
5900
+ },
5901
  "node_modules/commander": {
5902
  "version": "8.3.0",
5903
  "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
 
6485
  "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==",
6486
  "license": "MIT"
6487
  },
6488
+ "node_modules/csstype": {
6489
+ "version": "3.1.3",
6490
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
6491
+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
6492
+ "license": "MIT",
6493
+ "peer": true
6494
+ },
6495
  "node_modules/damerau-levenshtein": {
6496
  "version": "1.0.8",
6497
  "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
 
6586
  "integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==",
6587
  "license": "MIT"
6588
  },
6589
+ "node_modules/decode-named-character-reference": {
6590
+ "version": "1.2.0",
6591
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
6592
+ "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",
6593
+ "license": "MIT",
6594
+ "dependencies": {
6595
+ "character-entities": "^2.0.0"
6596
+ },
6597
+ "funding": {
6598
+ "type": "github",
6599
+ "url": "https://github.com/sponsors/wooorm"
6600
+ }
6601
+ },
6602
  "node_modules/dedent": {
6603
  "version": "0.7.0",
6604
  "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz",
 
6759
  "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
6760
  "license": "MIT"
6761
  },
6762
+ "node_modules/devlop": {
6763
+ "version": "1.1.0",
6764
+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
6765
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
6766
+ "license": "MIT",
6767
+ "dependencies": {
6768
+ "dequal": "^2.0.0"
6769
+ },
6770
+ "funding": {
6771
+ "type": "github",
6772
+ "url": "https://github.com/sponsors/wooorm"
6773
+ }
6774
+ },
6775
  "node_modules/didyoumean": {
6776
  "version": "1.2.2",
6777
  "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
 
7935
  "node": ">=4.0"
7936
  }
7937
  },
7938
+ "node_modules/estree-util-is-identifier-name": {
7939
+ "version": "3.0.0",
7940
+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
7941
+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
7942
+ "license": "MIT",
7943
+ "funding": {
7944
+ "type": "opencollective",
7945
+ "url": "https://opencollective.com/unified"
7946
+ }
7947
+ },
7948
  "node_modules/estree-walker": {
7949
  "version": "1.0.1",
7950
  "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz",
 
8091
  "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
8092
  "license": "MIT"
8093
  },
8094
+ "node_modules/extend": {
8095
+ "version": "3.0.2",
8096
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
8097
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
8098
+ "license": "MIT"
8099
+ },
8100
  "node_modules/fast-deep-equal": {
8101
  "version": "3.1.3",
8102
  "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
 
9016
  "node": ">= 0.4"
9017
  }
9018
  },
9019
+ "node_modules/hast-util-to-jsx-runtime": {
9020
+ "version": "2.3.6",
9021
+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
9022
+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",
9023
+ "license": "MIT",
9024
+ "dependencies": {
9025
+ "@types/estree": "^1.0.0",
9026
+ "@types/hast": "^3.0.0",
9027
+ "@types/unist": "^3.0.0",
9028
+ "comma-separated-tokens": "^2.0.0",
9029
+ "devlop": "^1.0.0",
9030
+ "estree-util-is-identifier-name": "^3.0.0",
9031
+ "hast-util-whitespace": "^3.0.0",
9032
+ "mdast-util-mdx-expression": "^2.0.0",
9033
+ "mdast-util-mdx-jsx": "^3.0.0",
9034
+ "mdast-util-mdxjs-esm": "^2.0.0",
9035
+ "property-information": "^7.0.0",
9036
+ "space-separated-tokens": "^2.0.0",
9037
+ "style-to-js": "^1.0.0",
9038
+ "unist-util-position": "^5.0.0",
9039
+ "vfile-message": "^4.0.0"
9040
+ },
9041
+ "funding": {
9042
+ "type": "opencollective",
9043
+ "url": "https://opencollective.com/unified"
9044
+ }
9045
+ },
9046
+ "node_modules/hast-util-whitespace": {
9047
+ "version": "3.0.0",
9048
+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
9049
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
9050
+ "license": "MIT",
9051
+ "dependencies": {
9052
+ "@types/hast": "^3.0.0"
9053
+ },
9054
+ "funding": {
9055
+ "type": "opencollective",
9056
+ "url": "https://opencollective.com/unified"
9057
+ }
9058
+ },
9059
  "node_modules/he": {
9060
  "version": "1.2.0",
9061
  "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
 
9177
  "node": ">=12"
9178
  }
9179
  },
9180
+ "node_modules/html-url-attributes": {
9181
+ "version": "3.0.1",
9182
+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
9183
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
9184
+ "license": "MIT",
9185
+ "funding": {
9186
+ "type": "opencollective",
9187
+ "url": "https://opencollective.com/unified"
9188
+ }
9189
+ },
9190
  "node_modules/html-webpack-plugin": {
9191
  "version": "5.6.3",
9192
  "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-5.6.3.tgz",
 
9486
  "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
9487
  "license": "ISC"
9488
  },
9489
+ "node_modules/inline-style-parser": {
9490
+ "version": "0.2.4",
9491
+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.4.tgz",
9492
+ "integrity": "sha512-0aO8FkhNZlj/ZIbNi7Lxxr12obT7cL1moPfE4tg1LkX7LlLfC6DeX4l2ZEud1ukP9jNQyNnfzQVqwbwmAATY4Q==",
9493
+ "license": "MIT"
9494
+ },
9495
  "node_modules/internal-slot": {
9496
  "version": "1.1.0",
9497
  "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
 
9515
  "node": ">= 10"
9516
  }
9517
  },
9518
+ "node_modules/is-alphabetical": {
9519
+ "version": "2.0.1",
9520
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
9521
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
9522
+ "license": "MIT",
9523
+ "funding": {
9524
+ "type": "github",
9525
+ "url": "https://github.com/sponsors/wooorm"
9526
+ }
9527
+ },
9528
+ "node_modules/is-alphanumerical": {
9529
+ "version": "2.0.1",
9530
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
9531
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
9532
+ "license": "MIT",
9533
+ "dependencies": {
9534
+ "is-alphabetical": "^2.0.0",
9535
+ "is-decimal": "^2.0.0"
9536
+ },
9537
+ "funding": {
9538
+ "type": "github",
9539
+ "url": "https://github.com/sponsors/wooorm"
9540
+ }
9541
+ },
9542
  "node_modules/is-array-buffer": {
9543
  "version": "3.0.5",
9544
  "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
 
9684
  "url": "https://github.com/sponsors/ljharb"
9685
  }
9686
  },
9687
+ "node_modules/is-decimal": {
9688
+ "version": "2.0.1",
9689
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
9690
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
9691
+ "license": "MIT",
9692
+ "funding": {
9693
+ "type": "github",
9694
+ "url": "https://github.com/sponsors/wooorm"
9695
+ }
9696
+ },
9697
  "node_modules/is-docker": {
9698
  "version": "2.2.1",
9699
  "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
 
9781
  "node": ">=0.10.0"
9782
  }
9783
  },
9784
+ "node_modules/is-hexadecimal": {
9785
+ "version": "2.0.1",
9786
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
9787
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
9788
+ "license": "MIT",
9789
+ "funding": {
9790
+ "type": "github",
9791
+ "url": "https://github.com/sponsors/wooorm"
9792
+ }
9793
+ },
9794
  "node_modules/is-map": {
9795
  "version": "2.0.3",
9796
  "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
 
11483
  "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==",
11484
  "license": "MIT"
11485
  },
11486
+ "node_modules/longest-streak": {
11487
+ "version": "3.1.0",
11488
+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
11489
+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
11490
+ "license": "MIT",
11491
+ "funding": {
11492
+ "type": "github",
11493
+ "url": "https://github.com/sponsors/wooorm"
11494
+ }
11495
+ },
11496
  "node_modules/loose-envify": {
11497
  "version": "1.4.0",
11498
  "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
 
11592
  "node": ">= 0.4"
11593
  }
11594
  },
11595
+ "node_modules/mdast-util-from-markdown": {
11596
+ "version": "2.0.2",
11597
+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz",
11598
+ "integrity": "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==",
11599
+ "license": "MIT",
11600
+ "dependencies": {
11601
+ "@types/mdast": "^4.0.0",
11602
+ "@types/unist": "^3.0.0",
11603
+ "decode-named-character-reference": "^1.0.0",
11604
+ "devlop": "^1.0.0",
11605
+ "mdast-util-to-string": "^4.0.0",
11606
+ "micromark": "^4.0.0",
11607
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
11608
+ "micromark-util-decode-string": "^2.0.0",
11609
+ "micromark-util-normalize-identifier": "^2.0.0",
11610
+ "micromark-util-symbol": "^2.0.0",
11611
+ "micromark-util-types": "^2.0.0",
11612
+ "unist-util-stringify-position": "^4.0.0"
11613
+ },
11614
+ "funding": {
11615
+ "type": "opencollective",
11616
+ "url": "https://opencollective.com/unified"
11617
+ }
11618
+ },
11619
+ "node_modules/mdast-util-mdx-expression": {
11620
+ "version": "2.0.1",
11621
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
11622
+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
11623
+ "license": "MIT",
11624
+ "dependencies": {
11625
+ "@types/estree-jsx": "^1.0.0",
11626
+ "@types/hast": "^3.0.0",
11627
+ "@types/mdast": "^4.0.0",
11628
+ "devlop": "^1.0.0",
11629
+ "mdast-util-from-markdown": "^2.0.0",
11630
+ "mdast-util-to-markdown": "^2.0.0"
11631
+ },
11632
+ "funding": {
11633
+ "type": "opencollective",
11634
+ "url": "https://opencollective.com/unified"
11635
+ }
11636
+ },
11637
+ "node_modules/mdast-util-mdx-jsx": {
11638
+ "version": "3.2.0",
11639
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",
11640
+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",
11641
+ "license": "MIT",
11642
+ "dependencies": {
11643
+ "@types/estree-jsx": "^1.0.0",
11644
+ "@types/hast": "^3.0.0",
11645
+ "@types/mdast": "^4.0.0",
11646
+ "@types/unist": "^3.0.0",
11647
+ "ccount": "^2.0.0",
11648
+ "devlop": "^1.1.0",
11649
+ "mdast-util-from-markdown": "^2.0.0",
11650
+ "mdast-util-to-markdown": "^2.0.0",
11651
+ "parse-entities": "^4.0.0",
11652
+ "stringify-entities": "^4.0.0",
11653
+ "unist-util-stringify-position": "^4.0.0",
11654
+ "vfile-message": "^4.0.0"
11655
+ },
11656
+ "funding": {
11657
+ "type": "opencollective",
11658
+ "url": "https://opencollective.com/unified"
11659
+ }
11660
+ },
11661
+ "node_modules/mdast-util-mdxjs-esm": {
11662
+ "version": "2.0.1",
11663
+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
11664
+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
11665
+ "license": "MIT",
11666
+ "dependencies": {
11667
+ "@types/estree-jsx": "^1.0.0",
11668
+ "@types/hast": "^3.0.0",
11669
+ "@types/mdast": "^4.0.0",
11670
+ "devlop": "^1.0.0",
11671
+ "mdast-util-from-markdown": "^2.0.0",
11672
+ "mdast-util-to-markdown": "^2.0.0"
11673
+ },
11674
+ "funding": {
11675
+ "type": "opencollective",
11676
+ "url": "https://opencollective.com/unified"
11677
+ }
11678
+ },
11679
+ "node_modules/mdast-util-phrasing": {
11680
+ "version": "4.1.0",
11681
+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
11682
+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
11683
+ "license": "MIT",
11684
+ "dependencies": {
11685
+ "@types/mdast": "^4.0.0",
11686
+ "unist-util-is": "^6.0.0"
11687
+ },
11688
+ "funding": {
11689
+ "type": "opencollective",
11690
+ "url": "https://opencollective.com/unified"
11691
+ }
11692
+ },
11693
+ "node_modules/mdast-util-to-hast": {
11694
+ "version": "13.2.0",
11695
+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz",
11696
+ "integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==",
11697
+ "license": "MIT",
11698
+ "dependencies": {
11699
+ "@types/hast": "^3.0.0",
11700
+ "@types/mdast": "^4.0.0",
11701
+ "@ungap/structured-clone": "^1.0.0",
11702
+ "devlop": "^1.0.0",
11703
+ "micromark-util-sanitize-uri": "^2.0.0",
11704
+ "trim-lines": "^3.0.0",
11705
+ "unist-util-position": "^5.0.0",
11706
+ "unist-util-visit": "^5.0.0",
11707
+ "vfile": "^6.0.0"
11708
+ },
11709
+ "funding": {
11710
+ "type": "opencollective",
11711
+ "url": "https://opencollective.com/unified"
11712
+ }
11713
+ },
11714
+ "node_modules/mdast-util-to-markdown": {
11715
+ "version": "2.1.2",
11716
+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",
11717
+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",
11718
+ "license": "MIT",
11719
+ "dependencies": {
11720
+ "@types/mdast": "^4.0.0",
11721
+ "@types/unist": "^3.0.0",
11722
+ "longest-streak": "^3.0.0",
11723
+ "mdast-util-phrasing": "^4.0.0",
11724
+ "mdast-util-to-string": "^4.0.0",
11725
+ "micromark-util-classify-character": "^2.0.0",
11726
+ "micromark-util-decode-string": "^2.0.0",
11727
+ "unist-util-visit": "^5.0.0",
11728
+ "zwitch": "^2.0.0"
11729
+ },
11730
+ "funding": {
11731
+ "type": "opencollective",
11732
+ "url": "https://opencollective.com/unified"
11733
+ }
11734
+ },
11735
+ "node_modules/mdast-util-to-string": {
11736
+ "version": "4.0.0",
11737
+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
11738
+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
11739
+ "license": "MIT",
11740
+ "dependencies": {
11741
+ "@types/mdast": "^4.0.0"
11742
+ },
11743
+ "funding": {
11744
+ "type": "opencollective",
11745
+ "url": "https://opencollective.com/unified"
11746
+ }
11747
+ },
11748
  "node_modules/mdn-data": {
11749
  "version": "2.0.4",
11750
  "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.4.tgz",
 
11805
  "node": ">= 0.6"
11806
  }
11807
  },
11808
+ "node_modules/micromark": {
11809
+ "version": "4.0.2",
11810
+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
11811
+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",
11812
+ "funding": [
11813
+ {
11814
+ "type": "GitHub Sponsors",
11815
+ "url": "https://github.com/sponsors/unifiedjs"
11816
+ },
11817
+ {
11818
+ "type": "OpenCollective",
11819
+ "url": "https://opencollective.com/unified"
11820
+ }
11821
+ ],
11822
  "license": "MIT",
11823
  "dependencies": {
11824
+ "@types/debug": "^4.0.0",
11825
+ "debug": "^4.0.0",
11826
+ "decode-named-character-reference": "^1.0.0",
11827
+ "devlop": "^1.0.0",
11828
+ "micromark-core-commonmark": "^2.0.0",
11829
+ "micromark-factory-space": "^2.0.0",
11830
+ "micromark-util-character": "^2.0.0",
11831
+ "micromark-util-chunked": "^2.0.0",
11832
+ "micromark-util-combine-extensions": "^2.0.0",
11833
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
11834
+ "micromark-util-encode": "^2.0.0",
11835
+ "micromark-util-normalize-identifier": "^2.0.0",
11836
+ "micromark-util-resolve-all": "^2.0.0",
11837
+ "micromark-util-sanitize-uri": "^2.0.0",
11838
+ "micromark-util-subtokenize": "^2.0.0",
11839
+ "micromark-util-symbol": "^2.0.0",
11840
+ "micromark-util-types": "^2.0.0"
11841
+ }
11842
+ },
11843
+ "node_modules/micromark-core-commonmark": {
11844
+ "version": "2.0.3",
11845
+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",
11846
+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",
11847
+ "funding": [
11848
+ {
11849
+ "type": "GitHub Sponsors",
11850
+ "url": "https://github.com/sponsors/unifiedjs"
11851
+ },
11852
+ {
11853
+ "type": "OpenCollective",
11854
+ "url": "https://opencollective.com/unified"
11855
+ }
11856
+ ],
11857
+ "license": "MIT",
11858
+ "dependencies": {
11859
+ "decode-named-character-reference": "^1.0.0",
11860
+ "devlop": "^1.0.0",
11861
+ "micromark-factory-destination": "^2.0.0",
11862
+ "micromark-factory-label": "^2.0.0",
11863
+ "micromark-factory-space": "^2.0.0",
11864
+ "micromark-factory-title": "^2.0.0",
11865
+ "micromark-factory-whitespace": "^2.0.0",
11866
+ "micromark-util-character": "^2.0.0",
11867
+ "micromark-util-chunked": "^2.0.0",
11868
+ "micromark-util-classify-character": "^2.0.0",
11869
+ "micromark-util-html-tag-name": "^2.0.0",
11870
+ "micromark-util-normalize-identifier": "^2.0.0",
11871
+ "micromark-util-resolve-all": "^2.0.0",
11872
+ "micromark-util-subtokenize": "^2.0.0",
11873
+ "micromark-util-symbol": "^2.0.0",
11874
+ "micromark-util-types": "^2.0.0"
11875
+ }
11876
+ },
11877
+ "node_modules/micromark-factory-destination": {
11878
+ "version": "2.0.1",
11879
+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
11880
+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
11881
+ "funding": [
11882
+ {
11883
+ "type": "GitHub Sponsors",
11884
+ "url": "https://github.com/sponsors/unifiedjs"
11885
+ },
11886
+ {
11887
+ "type": "OpenCollective",
11888
+ "url": "https://opencollective.com/unified"
11889
+ }
11890
+ ],
11891
+ "license": "MIT",
11892
+ "dependencies": {
11893
+ "micromark-util-character": "^2.0.0",
11894
+ "micromark-util-symbol": "^2.0.0",
11895
+ "micromark-util-types": "^2.0.0"
11896
  }
11897
  },
11898
+ "node_modules/micromark-factory-label": {
11899
+ "version": "2.0.1",
11900
+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
11901
+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
11902
+ "funding": [
11903
+ {
11904
+ "type": "GitHub Sponsors",
11905
+ "url": "https://github.com/sponsors/unifiedjs"
11906
+ },
11907
+ {
11908
+ "type": "OpenCollective",
11909
+ "url": "https://opencollective.com/unified"
11910
+ }
11911
+ ],
11912
+ "license": "MIT",
11913
+ "dependencies": {
11914
+ "devlop": "^1.0.0",
11915
+ "micromark-util-character": "^2.0.0",
11916
+ "micromark-util-symbol": "^2.0.0",
11917
+ "micromark-util-types": "^2.0.0"
11918
+ }
11919
+ },
11920
+ "node_modules/micromark-factory-space": {
11921
+ "version": "2.0.1",
11922
+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",
11923
+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",
11924
+ "funding": [
11925
+ {
11926
+ "type": "GitHub Sponsors",
11927
+ "url": "https://github.com/sponsors/unifiedjs"
11928
+ },
11929
+ {
11930
+ "type": "OpenCollective",
11931
+ "url": "https://opencollective.com/unified"
11932
+ }
11933
+ ],
11934
+ "license": "MIT",
11935
+ "dependencies": {
11936
+ "micromark-util-character": "^2.0.0",
11937
+ "micromark-util-types": "^2.0.0"
11938
+ }
11939
+ },
11940
+ "node_modules/micromark-factory-title": {
11941
+ "version": "2.0.1",
11942
+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
11943
+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
11944
+ "funding": [
11945
+ {
11946
+ "type": "GitHub Sponsors",
11947
+ "url": "https://github.com/sponsors/unifiedjs"
11948
+ },
11949
+ {
11950
+ "type": "OpenCollective",
11951
+ "url": "https://opencollective.com/unified"
11952
+ }
11953
+ ],
11954
+ "license": "MIT",
11955
+ "dependencies": {
11956
+ "micromark-factory-space": "^2.0.0",
11957
+ "micromark-util-character": "^2.0.0",
11958
+ "micromark-util-symbol": "^2.0.0",
11959
+ "micromark-util-types": "^2.0.0"
11960
+ }
11961
+ },
11962
+ "node_modules/micromark-factory-whitespace": {
11963
+ "version": "2.0.1",
11964
+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
11965
+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
11966
+ "funding": [
11967
+ {
11968
+ "type": "GitHub Sponsors",
11969
+ "url": "https://github.com/sponsors/unifiedjs"
11970
+ },
11971
+ {
11972
+ "type": "OpenCollective",
11973
+ "url": "https://opencollective.com/unified"
11974
+ }
11975
+ ],
11976
+ "license": "MIT",
11977
+ "dependencies": {
11978
+ "micromark-factory-space": "^2.0.0",
11979
+ "micromark-util-character": "^2.0.0",
11980
+ "micromark-util-symbol": "^2.0.0",
11981
+ "micromark-util-types": "^2.0.0"
11982
+ }
11983
+ },
11984
+ "node_modules/micromark-util-character": {
11985
+ "version": "2.1.1",
11986
+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
11987
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
11988
+ "funding": [
11989
+ {
11990
+ "type": "GitHub Sponsors",
11991
+ "url": "https://github.com/sponsors/unifiedjs"
11992
+ },
11993
+ {
11994
+ "type": "OpenCollective",
11995
+ "url": "https://opencollective.com/unified"
11996
+ }
11997
+ ],
11998
+ "license": "MIT",
11999
+ "dependencies": {
12000
+ "micromark-util-symbol": "^2.0.0",
12001
+ "micromark-util-types": "^2.0.0"
12002
+ }
12003
+ },
12004
+ "node_modules/micromark-util-chunked": {
12005
+ "version": "2.0.1",
12006
+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
12007
+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
12008
+ "funding": [
12009
+ {
12010
+ "type": "GitHub Sponsors",
12011
+ "url": "https://github.com/sponsors/unifiedjs"
12012
+ },
12013
+ {
12014
+ "type": "OpenCollective",
12015
+ "url": "https://opencollective.com/unified"
12016
+ }
12017
+ ],
12018
+ "license": "MIT",
12019
+ "dependencies": {
12020
+ "micromark-util-symbol": "^2.0.0"
12021
+ }
12022
+ },
12023
+ "node_modules/micromark-util-classify-character": {
12024
+ "version": "2.0.1",
12025
+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
12026
+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
12027
+ "funding": [
12028
+ {
12029
+ "type": "GitHub Sponsors",
12030
+ "url": "https://github.com/sponsors/unifiedjs"
12031
+ },
12032
+ {
12033
+ "type": "OpenCollective",
12034
+ "url": "https://opencollective.com/unified"
12035
+ }
12036
+ ],
12037
+ "license": "MIT",
12038
+ "dependencies": {
12039
+ "micromark-util-character": "^2.0.0",
12040
+ "micromark-util-symbol": "^2.0.0",
12041
+ "micromark-util-types": "^2.0.0"
12042
+ }
12043
+ },
12044
+ "node_modules/micromark-util-combine-extensions": {
12045
+ "version": "2.0.1",
12046
+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
12047
+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
12048
+ "funding": [
12049
+ {
12050
+ "type": "GitHub Sponsors",
12051
+ "url": "https://github.com/sponsors/unifiedjs"
12052
+ },
12053
+ {
12054
+ "type": "OpenCollective",
12055
+ "url": "https://opencollective.com/unified"
12056
+ }
12057
+ ],
12058
+ "license": "MIT",
12059
+ "dependencies": {
12060
+ "micromark-util-chunked": "^2.0.0",
12061
+ "micromark-util-types": "^2.0.0"
12062
+ }
12063
+ },
12064
+ "node_modules/micromark-util-decode-numeric-character-reference": {
12065
+ "version": "2.0.2",
12066
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
12067
+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
12068
+ "funding": [
12069
+ {
12070
+ "type": "GitHub Sponsors",
12071
+ "url": "https://github.com/sponsors/unifiedjs"
12072
+ },
12073
+ {
12074
+ "type": "OpenCollective",
12075
+ "url": "https://opencollective.com/unified"
12076
+ }
12077
+ ],
12078
+ "license": "MIT",
12079
+ "dependencies": {
12080
+ "micromark-util-symbol": "^2.0.0"
12081
+ }
12082
+ },
12083
+ "node_modules/micromark-util-decode-string": {
12084
+ "version": "2.0.1",
12085
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
12086
+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
12087
+ "funding": [
12088
+ {
12089
+ "type": "GitHub Sponsors",
12090
+ "url": "https://github.com/sponsors/unifiedjs"
12091
+ },
12092
+ {
12093
+ "type": "OpenCollective",
12094
+ "url": "https://opencollective.com/unified"
12095
+ }
12096
+ ],
12097
+ "license": "MIT",
12098
+ "dependencies": {
12099
+ "decode-named-character-reference": "^1.0.0",
12100
+ "micromark-util-character": "^2.0.0",
12101
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
12102
+ "micromark-util-symbol": "^2.0.0"
12103
+ }
12104
+ },
12105
+ "node_modules/micromark-util-encode": {
12106
+ "version": "2.0.1",
12107
+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
12108
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
12109
+ "funding": [
12110
+ {
12111
+ "type": "GitHub Sponsors",
12112
+ "url": "https://github.com/sponsors/unifiedjs"
12113
+ },
12114
+ {
12115
+ "type": "OpenCollective",
12116
+ "url": "https://opencollective.com/unified"
12117
+ }
12118
+ ],
12119
+ "license": "MIT"
12120
+ },
12121
+ "node_modules/micromark-util-html-tag-name": {
12122
+ "version": "2.0.1",
12123
+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
12124
+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
12125
+ "funding": [
12126
+ {
12127
+ "type": "GitHub Sponsors",
12128
+ "url": "https://github.com/sponsors/unifiedjs"
12129
+ },
12130
+ {
12131
+ "type": "OpenCollective",
12132
+ "url": "https://opencollective.com/unified"
12133
+ }
12134
+ ],
12135
+ "license": "MIT"
12136
+ },
12137
+ "node_modules/micromark-util-normalize-identifier": {
12138
+ "version": "2.0.1",
12139
+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
12140
+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
12141
+ "funding": [
12142
+ {
12143
+ "type": "GitHub Sponsors",
12144
+ "url": "https://github.com/sponsors/unifiedjs"
12145
+ },
12146
+ {
12147
+ "type": "OpenCollective",
12148
+ "url": "https://opencollective.com/unified"
12149
+ }
12150
+ ],
12151
+ "license": "MIT",
12152
+ "dependencies": {
12153
+ "micromark-util-symbol": "^2.0.0"
12154
+ }
12155
+ },
12156
+ "node_modules/micromark-util-resolve-all": {
12157
+ "version": "2.0.1",
12158
+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
12159
+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
12160
+ "funding": [
12161
+ {
12162
+ "type": "GitHub Sponsors",
12163
+ "url": "https://github.com/sponsors/unifiedjs"
12164
+ },
12165
+ {
12166
+ "type": "OpenCollective",
12167
+ "url": "https://opencollective.com/unified"
12168
+ }
12169
+ ],
12170
+ "license": "MIT",
12171
+ "dependencies": {
12172
+ "micromark-util-types": "^2.0.0"
12173
+ }
12174
+ },
12175
+ "node_modules/micromark-util-sanitize-uri": {
12176
+ "version": "2.0.1",
12177
+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
12178
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
12179
+ "funding": [
12180
+ {
12181
+ "type": "GitHub Sponsors",
12182
+ "url": "https://github.com/sponsors/unifiedjs"
12183
+ },
12184
+ {
12185
+ "type": "OpenCollective",
12186
+ "url": "https://opencollective.com/unified"
12187
+ }
12188
+ ],
12189
+ "license": "MIT",
12190
+ "dependencies": {
12191
+ "micromark-util-character": "^2.0.0",
12192
+ "micromark-util-encode": "^2.0.0",
12193
+ "micromark-util-symbol": "^2.0.0"
12194
+ }
12195
+ },
12196
+ "node_modules/micromark-util-subtokenize": {
12197
+ "version": "2.1.0",
12198
+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
12199
+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
12200
+ "funding": [
12201
+ {
12202
+ "type": "GitHub Sponsors",
12203
+ "url": "https://github.com/sponsors/unifiedjs"
12204
+ },
12205
+ {
12206
+ "type": "OpenCollective",
12207
+ "url": "https://opencollective.com/unified"
12208
+ }
12209
+ ],
12210
+ "license": "MIT",
12211
+ "dependencies": {
12212
+ "devlop": "^1.0.0",
12213
+ "micromark-util-chunked": "^2.0.0",
12214
+ "micromark-util-symbol": "^2.0.0",
12215
+ "micromark-util-types": "^2.0.0"
12216
+ }
12217
+ },
12218
+ "node_modules/micromark-util-symbol": {
12219
+ "version": "2.0.1",
12220
+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
12221
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
12222
+ "funding": [
12223
+ {
12224
+ "type": "GitHub Sponsors",
12225
+ "url": "https://github.com/sponsors/unifiedjs"
12226
+ },
12227
+ {
12228
+ "type": "OpenCollective",
12229
+ "url": "https://opencollective.com/unified"
12230
+ }
12231
+ ],
12232
+ "license": "MIT"
12233
+ },
12234
+ "node_modules/micromark-util-types": {
12235
+ "version": "2.0.2",
12236
+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
12237
+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
12238
+ "funding": [
12239
+ {
12240
+ "type": "GitHub Sponsors",
12241
+ "url": "https://github.com/sponsors/unifiedjs"
12242
+ },
12243
+ {
12244
+ "type": "OpenCollective",
12245
+ "url": "https://opencollective.com/unified"
12246
+ }
12247
+ ],
12248
+ "license": "MIT"
12249
+ },
12250
+ "node_modules/micromatch": {
12251
+ "version": "4.0.8",
12252
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
12253
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
12254
+ "license": "MIT",
12255
+ "dependencies": {
12256
+ "braces": "^3.0.3",
12257
+ "picomatch": "^2.3.1"
12258
+ },
12259
+ "engines": {
12260
+ "node": ">=8.6"
12261
+ }
12262
+ },
12263
+ "node_modules/mime": {
12264
+ "version": "1.6.0",
12265
+ "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
12266
+ "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
12267
  "license": "MIT",
12268
  "bin": {
12269
  "mime": "cli.js"
 
12869
  "node": ">=6"
12870
  }
12871
  },
12872
+ "node_modules/parse-entities": {
12873
+ "version": "4.0.2",
12874
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
12875
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
12876
+ "license": "MIT",
12877
+ "dependencies": {
12878
+ "@types/unist": "^2.0.0",
12879
+ "character-entities-legacy": "^3.0.0",
12880
+ "character-reference-invalid": "^2.0.0",
12881
+ "decode-named-character-reference": "^1.0.0",
12882
+ "is-alphanumerical": "^2.0.0",
12883
+ "is-decimal": "^2.0.0",
12884
+ "is-hexadecimal": "^2.0.0"
12885
+ },
12886
+ "funding": {
12887
+ "type": "github",
12888
+ "url": "https://github.com/sponsors/wooorm"
12889
+ }
12890
+ },
12891
+ "node_modules/parse-entities/node_modules/@types/unist": {
12892
+ "version": "2.0.11",
12893
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
12894
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
12895
+ "license": "MIT"
12896
+ },
12897
  "node_modules/parse-json": {
12898
  "version": "5.2.0",
12899
  "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
 
14539
  "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
14540
  "license": "MIT"
14541
  },
14542
+ "node_modules/property-information": {
14543
+ "version": "7.1.0",
14544
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
14545
+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
14546
+ "license": "MIT",
14547
+ "funding": {
14548
+ "type": "github",
14549
+ "url": "https://github.com/sponsors/wooorm"
14550
+ }
14551
+ },
14552
  "node_modules/proxy-addr": {
14553
  "version": "2.0.7",
14554
  "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
 
14853
  "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
14854
  "license": "MIT"
14855
  },
14856
+ "node_modules/react-markdown": {
14857
+ "version": "10.1.0",
14858
+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
14859
+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
14860
+ "license": "MIT",
14861
+ "dependencies": {
14862
+ "@types/hast": "^3.0.0",
14863
+ "@types/mdast": "^4.0.0",
14864
+ "devlop": "^1.0.0",
14865
+ "hast-util-to-jsx-runtime": "^2.0.0",
14866
+ "html-url-attributes": "^3.0.0",
14867
+ "mdast-util-to-hast": "^13.0.0",
14868
+ "remark-parse": "^11.0.0",
14869
+ "remark-rehype": "^11.0.0",
14870
+ "unified": "^11.0.0",
14871
+ "unist-util-visit": "^5.0.0",
14872
+ "vfile": "^6.0.0"
14873
+ },
14874
+ "funding": {
14875
+ "type": "opencollective",
14876
+ "url": "https://opencollective.com/unified"
14877
+ },
14878
+ "peerDependencies": {
14879
+ "@types/react": ">=18",
14880
+ "react": ">=18"
14881
+ }
14882
+ },
14883
  "node_modules/react-refresh": {
14884
  "version": "0.11.0",
14885
  "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
 
15199
  "node": ">= 0.10"
15200
  }
15201
  },
15202
+ "node_modules/remark-parse": {
15203
+ "version": "11.0.0",
15204
+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",
15205
+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
15206
+ "license": "MIT",
15207
+ "dependencies": {
15208
+ "@types/mdast": "^4.0.0",
15209
+ "mdast-util-from-markdown": "^2.0.0",
15210
+ "micromark-util-types": "^2.0.0",
15211
+ "unified": "^11.0.0"
15212
+ },
15213
+ "funding": {
15214
+ "type": "opencollective",
15215
+ "url": "https://opencollective.com/unified"
15216
+ }
15217
+ },
15218
+ "node_modules/remark-rehype": {
15219
+ "version": "11.1.2",
15220
+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",
15221
+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
15222
+ "license": "MIT",
15223
+ "dependencies": {
15224
+ "@types/hast": "^3.0.0",
15225
+ "@types/mdast": "^4.0.0",
15226
+ "mdast-util-to-hast": "^13.0.0",
15227
+ "unified": "^11.0.0",
15228
+ "vfile": "^6.0.0"
15229
+ },
15230
+ "funding": {
15231
+ "type": "opencollective",
15232
+ "url": "https://opencollective.com/unified"
15233
+ }
15234
+ },
15235
  "node_modules/renderkid": {
15236
  "version": "3.0.0",
15237
  "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-3.0.0.tgz",
 
16137
  "deprecated": "Please use @jridgewell/sourcemap-codec instead",
16138
  "license": "MIT"
16139
  },
16140
+ "node_modules/space-separated-tokens": {
16141
+ "version": "2.0.2",
16142
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
16143
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
16144
+ "license": "MIT",
16145
+ "funding": {
16146
+ "type": "github",
16147
+ "url": "https://github.com/sponsors/wooorm"
16148
+ }
16149
+ },
16150
  "node_modules/spdy": {
16151
  "version": "4.0.2",
16152
  "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz",
 
16515
  "url": "https://github.com/sponsors/ljharb"
16516
  }
16517
  },
16518
+ "node_modules/stringify-entities": {
16519
+ "version": "4.0.4",
16520
+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
16521
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
16522
+ "license": "MIT",
16523
+ "dependencies": {
16524
+ "character-entities-html4": "^2.0.0",
16525
+ "character-entities-legacy": "^3.0.0"
16526
+ },
16527
+ "funding": {
16528
+ "type": "github",
16529
+ "url": "https://github.com/sponsors/wooorm"
16530
+ }
16531
+ },
16532
  "node_modules/stringify-object": {
16533
  "version": "3.3.0",
16534
  "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz",
 
16635
  "webpack": "^5.0.0"
16636
  }
16637
  },
16638
+ "node_modules/style-to-js": {
16639
+ "version": "1.1.17",
16640
+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.17.tgz",
16641
+ "integrity": "sha512-xQcBGDxJb6jjFCTzvQtfiPn6YvvP2O8U1MDIPNfJQlWMYfktPy+iGsHE7cssjs7y84d9fQaK4UF3RIJaAHSoYA==",
16642
+ "license": "MIT",
16643
+ "dependencies": {
16644
+ "style-to-object": "1.0.9"
16645
+ }
16646
+ },
16647
+ "node_modules/style-to-object": {
16648
+ "version": "1.0.9",
16649
+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.9.tgz",
16650
+ "integrity": "sha512-G4qppLgKu/k6FwRpHiGiKPaPTFcG3g4wNVX/Qsfu+RqQM30E7Tyu/TEgxcL9PNLF5pdRLwQdE3YKKf+KF2Dzlw==",
16651
+ "license": "MIT",
16652
+ "dependencies": {
16653
+ "inline-style-parser": "0.2.4"
16654
+ }
16655
+ },
16656
  "node_modules/stylehacks": {
16657
  "version": "5.1.1",
16658
  "resolved": "https://registry.npmjs.org/stylehacks/-/stylehacks-5.1.1.tgz",
 
17189
  "node": ">=8"
17190
  }
17191
  },
17192
+ "node_modules/trim-lines": {
17193
+ "version": "3.0.1",
17194
+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
17195
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
17196
+ "license": "MIT",
17197
+ "funding": {
17198
+ "type": "github",
17199
+ "url": "https://github.com/sponsors/wooorm"
17200
+ }
17201
+ },
17202
+ "node_modules/trough": {
17203
+ "version": "2.2.0",
17204
+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",
17205
+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
17206
+ "license": "MIT",
17207
+ "funding": {
17208
+ "type": "github",
17209
+ "url": "https://github.com/sponsors/wooorm"
17210
+ }
17211
+ },
17212
  "node_modules/tryer": {
17213
  "version": "1.0.1",
17214
  "resolved": "https://registry.npmjs.org/tryer/-/tryer-1.0.1.tgz",
 
17494
  "node": ">=4"
17495
  }
17496
  },
17497
+ "node_modules/unified": {
17498
+ "version": "11.0.5",
17499
+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
17500
+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
17501
+ "license": "MIT",
17502
+ "dependencies": {
17503
+ "@types/unist": "^3.0.0",
17504
+ "bail": "^2.0.0",
17505
+ "devlop": "^1.0.0",
17506
+ "extend": "^3.0.0",
17507
+ "is-plain-obj": "^4.0.0",
17508
+ "trough": "^2.0.0",
17509
+ "vfile": "^6.0.0"
17510
+ },
17511
+ "funding": {
17512
+ "type": "opencollective",
17513
+ "url": "https://opencollective.com/unified"
17514
+ }
17515
+ },
17516
+ "node_modules/unified/node_modules/is-plain-obj": {
17517
+ "version": "4.1.0",
17518
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
17519
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
17520
+ "license": "MIT",
17521
+ "engines": {
17522
+ "node": ">=12"
17523
+ },
17524
+ "funding": {
17525
+ "url": "https://github.com/sponsors/sindresorhus"
17526
+ }
17527
+ },
17528
  "node_modules/unique-string": {
17529
  "version": "2.0.0",
17530
  "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz",
 
17537
  "node": ">=8"
17538
  }
17539
  },
17540
+ "node_modules/unist-util-is": {
17541
+ "version": "6.0.0",
17542
+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz",
17543
+ "integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==",
17544
+ "license": "MIT",
17545
+ "dependencies": {
17546
+ "@types/unist": "^3.0.0"
17547
+ },
17548
+ "funding": {
17549
+ "type": "opencollective",
17550
+ "url": "https://opencollective.com/unified"
17551
+ }
17552
+ },
17553
+ "node_modules/unist-util-position": {
17554
+ "version": "5.0.0",
17555
+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
17556
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
17557
+ "license": "MIT",
17558
+ "dependencies": {
17559
+ "@types/unist": "^3.0.0"
17560
+ },
17561
+ "funding": {
17562
+ "type": "opencollective",
17563
+ "url": "https://opencollective.com/unified"
17564
+ }
17565
+ },
17566
+ "node_modules/unist-util-stringify-position": {
17567
+ "version": "4.0.0",
17568
+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
17569
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
17570
+ "license": "MIT",
17571
+ "dependencies": {
17572
+ "@types/unist": "^3.0.0"
17573
+ },
17574
+ "funding": {
17575
+ "type": "opencollective",
17576
+ "url": "https://opencollective.com/unified"
17577
+ }
17578
+ },
17579
+ "node_modules/unist-util-visit": {
17580
+ "version": "5.0.0",
17581
+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz",
17582
+ "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==",
17583
+ "license": "MIT",
17584
+ "dependencies": {
17585
+ "@types/unist": "^3.0.0",
17586
+ "unist-util-is": "^6.0.0",
17587
+ "unist-util-visit-parents": "^6.0.0"
17588
+ },
17589
+ "funding": {
17590
+ "type": "opencollective",
17591
+ "url": "https://opencollective.com/unified"
17592
+ }
17593
+ },
17594
+ "node_modules/unist-util-visit-parents": {
17595
+ "version": "6.0.1",
17596
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz",
17597
+ "integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==",
17598
+ "license": "MIT",
17599
+ "dependencies": {
17600
+ "@types/unist": "^3.0.0",
17601
+ "unist-util-is": "^6.0.0"
17602
+ },
17603
+ "funding": {
17604
+ "type": "opencollective",
17605
+ "url": "https://opencollective.com/unified"
17606
+ }
17607
+ },
17608
  "node_modules/universalify": {
17609
  "version": "2.0.1",
17610
  "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
 
17762
  "node": ">= 0.8"
17763
  }
17764
  },
17765
+ "node_modules/vfile": {
17766
+ "version": "6.0.3",
17767
+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
17768
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
17769
+ "license": "MIT",
17770
+ "dependencies": {
17771
+ "@types/unist": "^3.0.0",
17772
+ "vfile-message": "^4.0.0"
17773
+ },
17774
+ "funding": {
17775
+ "type": "opencollective",
17776
+ "url": "https://opencollective.com/unified"
17777
+ }
17778
+ },
17779
+ "node_modules/vfile-message": {
17780
+ "version": "4.0.3",
17781
+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
17782
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
17783
+ "license": "MIT",
17784
+ "dependencies": {
17785
+ "@types/unist": "^3.0.0",
17786
+ "unist-util-stringify-position": "^4.0.0"
17787
+ },
17788
+ "funding": {
17789
+ "type": "opencollective",
17790
+ "url": "https://opencollective.com/unified"
17791
+ }
17792
+ },
17793
  "node_modules/w3c-hr-time": {
17794
  "version": "1.0.2",
17795
  "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz",
 
18727
  "funding": {
18728
  "url": "https://github.com/sponsors/sindresorhus"
18729
  }
18730
+ },
18731
+ "node_modules/zwitch": {
18732
+ "version": "2.0.4",
18733
+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
18734
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
18735
+ "license": "MIT",
18736
+ "funding": {
18737
+ "type": "github",
18738
+ "url": "https://github.com/sponsors/wooorm"
18739
+ }
18740
  }
18741
  }
18742
  }
phd-advisor-frontend/package.json CHANGED
@@ -10,6 +10,7 @@
10
  "lucide-react": "^0.513.0",
11
  "react": "^19.1.0",
12
  "react-dom": "^19.1.0",
 
13
  "react-scripts": "5.0.1",
14
  "web-vitals": "^2.1.4"
15
  },
 
10
  "lucide-react": "^0.513.0",
11
  "react": "^19.1.0",
12
  "react-dom": "^19.1.0",
13
+ "react-markdown": "^10.1.0",
14
  "react-scripts": "5.0.1",
15
  "web-vitals": "^2.1.4"
16
  },
phd-advisor-frontend/src/App.js CHANGED
@@ -1,4 +1,4 @@
1
- import React, { useState } from 'react';
2
  import { ThemeProvider } from './contexts/ThemeContext';
3
  import HomePage from './pages/HomePage';
4
  import ChatPage from './pages/ChatPage';
@@ -8,43 +8,78 @@ import './styles/components.css';
8
  function App() {
9
  const [currentView, setCurrentView] = useState('home');
10
  const [isAuthenticated, setIsAuthenticated] = useState(false);
 
 
11
 
12
- const navigateToAuth = () => {
13
- setCurrentView('auth');
14
- };
15
-
16
- const navigateToHome = () => {
17
- setCurrentView('home');
18
- setIsAuthenticated(false); // Reset auth when going home
19
- // Reset session when going home
20
- fetch('http://localhost:8000/reset-session', {
21
- method: 'POST',
22
- headers: {
23
- 'Content-Type': 'application/json',
 
 
 
 
 
24
  }
25
- }).catch(console.error);
26
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- const handleAuthSuccess = () => {
29
- setIsAuthenticated(true);
30
- setCurrentView('chat');
31
- };
 
 
 
 
32
 
33
  return (
34
- <ThemeProvider>
35
- <div className="App">
36
- {currentView === 'home' && (
37
- <HomePage onNavigateToChat={navigateToAuth} />
38
- )}
39
- {currentView === 'auth' && (
40
- <AuthPage onAuthSuccess={handleAuthSuccess} />
41
- )}
42
- {currentView === 'chat' && (
43
- <ChatPage onNavigateToHome={navigateToHome} />
44
- )}
45
- </div>
46
- </ThemeProvider>
47
- );
 
 
 
 
 
48
  }
49
 
50
  export default App;
 
1
+ import React, { useState, useEffect } from 'react';
2
  import { ThemeProvider } from './contexts/ThemeContext';
3
  import HomePage from './pages/HomePage';
4
  import ChatPage from './pages/ChatPage';
 
8
  function App() {
9
  const [currentView, setCurrentView] = useState('home');
10
  const [isAuthenticated, setIsAuthenticated] = useState(false);
11
+ const [user, setUser] = useState(null);
12
+ const [authToken, setAuthToken] = useState(null);
13
 
14
+ // Check for existing authentication on app start
15
+ useEffect(() => {
16
+ const token = localStorage.getItem('authToken');
17
+ const userData = localStorage.getItem('user');
18
+
19
+ if (token && userData) {
20
+ try {
21
+ const parsedUser = JSON.parse(userData);
22
+ setAuthToken(token);
23
+ setUser(parsedUser);
24
+ setIsAuthenticated(true);
25
+ setCurrentView('chat');
26
+ } catch (error) {
27
+ // Clear invalid data
28
+ localStorage.removeItem('authToken');
29
+ localStorage.removeItem('user');
30
+ }
31
  }
32
+ }, []);
33
+
34
+ const navigateToAuth = () => {
35
+ setCurrentView('auth');
36
+ };
37
+
38
+ const navigateToHome = () => {
39
+ setCurrentView('home');
40
+ setIsAuthenticated(false);
41
+ setUser(null);
42
+ setAuthToken(null);
43
+ localStorage.removeItem('authToken');
44
+ localStorage.removeItem('user');
45
+ };
46
+
47
+ const handleAuthSuccess = (userData, token) => {
48
+ setUser(userData);
49
+ setAuthToken(token);
50
+ setIsAuthenticated(true);
51
+ setCurrentView('chat');
52
+ };
53
 
54
+ const handleSignOut = () => {
55
+ localStorage.removeItem('authToken');
56
+ localStorage.removeItem('user');
57
+ setUser(null);
58
+ setAuthToken(null);
59
+ setIsAuthenticated(false);
60
+ setCurrentView('home');
61
+ };
62
 
63
  return (
64
+ <ThemeProvider>
65
+ <div className="App">
66
+ {currentView === 'home' && (
67
+ <HomePage onNavigateToChat={navigateToAuth} />
68
+ )}
69
+ {currentView === 'auth' && (
70
+ <AuthPage onAuthSuccess={handleAuthSuccess} />
71
+ )}
72
+ {currentView === 'chat' && isAuthenticated && (
73
+ <ChatPage
74
+ user={user}
75
+ authToken={authToken}
76
+ onNavigateToHome={navigateToHome}
77
+ onSignOut={handleSignOut}
78
+ />
79
+ )}
80
+ </div>
81
+ </ThemeProvider>
82
+ );
83
  }
84
 
85
  export default App;
phd-advisor-frontend/src/components/AdvisorStatusDropdown.js ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import { Users, ChevronDown } from 'lucide-react';
3
+
4
+ const AdvisorStatusDropdown = ({ advisors, thinkingAdvisors, getAdvisorColors, isDark }) => {
5
+ const [isOpen, setIsOpen] = useState(false);
6
+
7
+ // Close dropdown when clicking outside
8
+ useEffect(() => {
9
+ const handleClickOutside = (event) => {
10
+ if (isOpen && !event.target.closest('.advisor-status-dropdown')) {
11
+ setIsOpen(false);
12
+ }
13
+ };
14
+
15
+ document.addEventListener('mousedown', handleClickOutside);
16
+ return () => document.removeEventListener('mousedown', handleClickOutside);
17
+ }, [isOpen]);
18
+
19
+ if (!advisors || typeof advisors !== 'object') {
20
+ return null;
21
+ }
22
+
23
+ const advisorEntries = Object.entries(advisors);
24
+ const thinkingCount = Array.isArray(thinkingAdvisors)
25
+ ? thinkingAdvisors.filter(id => id !== 'system').length
26
+ : 0;
27
+ const totalAdvisors = advisorEntries.length;
28
+
29
+ const handleToggle = () => {
30
+ setIsOpen(!isOpen);
31
+ };
32
+
33
+ return (
34
+ <div className="advisor-status-dropdown">
35
+ <button
36
+ className={`advisor-status-button ${isOpen ? 'open' : ''}`}
37
+ onClick={handleToggle}
38
+ >
39
+ <div className="advisor-status-info">
40
+ <Users size={16} />
41
+ <span className="advisor-count">
42
+ {totalAdvisors} Advisor{totalAdvisors !== 1 ? 's' : ''}
43
+ </span>
44
+ {thinkingCount > 0 && (
45
+ <div className="thinking-badge">
46
+ {thinkingCount} thinking
47
+ </div>
48
+ )}
49
+ </div>
50
+ <ChevronDown size={14} className={`dropdown-arrow ${isOpen ? 'rotated' : ''}`} />
51
+ </button>
52
+
53
+ {isOpen && (
54
+ <div className="advisor-dropdown-panel">
55
+ <div className="advisor-list">
56
+ {advisorEntries.map(([id, advisor]) => {
57
+ const IconComponent = advisor.icon;
58
+ const colors = getAdvisorColors(id, isDark);
59
+ const isThinking = Array.isArray(thinkingAdvisors) && thinkingAdvisors.includes(id);
60
+
61
+ return (
62
+ <div
63
+ key={id}
64
+ className={`advisor-item ${isThinking ? 'thinking' : ''}`}
65
+ style={{
66
+ '--advisor-color': colors.color,
67
+ '--advisor-bg': colors.bgColor
68
+ }}
69
+ >
70
+ <div className="advisor-icon">
71
+ <IconComponent size={16} />
72
+ </div>
73
+ <div className="advisor-details">
74
+ <div className="advisor-name">{advisor.name}</div>
75
+ <div className="advisor-description">{advisor.description}</div>
76
+ </div>
77
+ <div className="advisor-status">
78
+ {isThinking ? (
79
+ <div className="status-thinking">
80
+ <div className="thinking-dots">
81
+ <div className="dot"></div>
82
+ <div className="dot"></div>
83
+ <div className="dot"></div>
84
+ </div>
85
+ </div>
86
+ ) : (
87
+ <div className="status-ready">Ready</div>
88
+ )}
89
+ </div>
90
+ </div>
91
+ );
92
+ })}
93
+ </div>
94
+ </div>
95
+ )}
96
+
97
+ <style jsx>{`
98
+ .advisor-status-dropdown {
99
+ position: relative;
100
+ display: inline-block;
101
+ }
102
+
103
+ .advisor-status-button {
104
+ display: flex;
105
+ align-items: center;
106
+ gap: 8px;
107
+ padding: 8px 12px;
108
+ background: var(--bg-primary);
109
+ border: 1px solid var(--border-primary);
110
+ border-radius: 12px;
111
+ cursor: pointer;
112
+ transition: all 0.2s ease;
113
+ font-size: 13px;
114
+ min-width: 140px;
115
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
116
+ color: var(--text-primary);
117
+ }
118
+
119
+ .advisor-status-button:hover {
120
+ background: var(--bg-secondary);
121
+ border-color: var(--accent-primary);
122
+ transform: translateY(-1px);
123
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
124
+ }
125
+
126
+ .advisor-status-button.open {
127
+ background: var(--bg-secondary);
128
+ border-color: var(--accent-primary);
129
+ }
130
+
131
+ .advisor-status-info {
132
+ display: flex;
133
+ align-items: center;
134
+ gap: 6px;
135
+ flex: 1;
136
+ }
137
+
138
+ .advisor-count {
139
+ font-weight: 600;
140
+ color: var(--text-primary);
141
+ }
142
+
143
+ .thinking-badge {
144
+ background: var(--accent-primary);
145
+ color: white;
146
+ padding: 2px 6px;
147
+ border-radius: 8px;
148
+ font-size: 10px;
149
+ font-weight: 600;
150
+ animation: pulse 2s ease-in-out infinite;
151
+ }
152
+
153
+ .dropdown-arrow {
154
+ color: var(--text-secondary);
155
+ transition: transform 0.2s ease;
156
+ }
157
+
158
+ .dropdown-arrow.rotated {
159
+ transform: rotate(180deg);
160
+ }
161
+
162
+ .advisor-dropdown-panel {
163
+ position: absolute;
164
+ top: calc(100% + 8px);
165
+ right: 0;
166
+ min-width: 280px;
167
+ max-width: 320px;
168
+ background: var(--bg-primary);
169
+ border: 1px solid var(--border-primary);
170
+ border-radius: 12px;
171
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
172
+ z-index: 1000;
173
+ overflow: hidden;
174
+ backdrop-filter: blur(20px);
175
+ -webkit-backdrop-filter: blur(20px);
176
+ }
177
+
178
+ [data-theme="dark"] .advisor-dropdown-panel {
179
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);
180
+ }
181
+
182
+ .advisor-list {
183
+ max-height: 300px;
184
+ overflow-y: auto;
185
+ scrollbar-width: thin;
186
+ scrollbar-color: var(--border-primary) transparent;
187
+ }
188
+
189
+ .advisor-list::-webkit-scrollbar {
190
+ width: 6px;
191
+ }
192
+
193
+ .advisor-list::-webkit-scrollbar-track {
194
+ background: transparent;
195
+ }
196
+
197
+ .advisor-list::-webkit-scrollbar-thumb {
198
+ background: var(--border-primary);
199
+ border-radius: 3px;
200
+ }
201
+
202
+ .advisor-item {
203
+ display: flex;
204
+ align-items: center;
205
+ gap: 12px;
206
+ padding: 12px 16px;
207
+ border-bottom: 1px solid var(--border-primary);
208
+ transition: background-color 0.2s ease;
209
+ }
210
+
211
+ .advisor-item:last-child {
212
+ border-bottom: none;
213
+ }
214
+
215
+ .advisor-item:hover {
216
+ background: var(--bg-secondary);
217
+ }
218
+
219
+ .advisor-item.thinking {
220
+ background: var(--advisor-bg);
221
+ }
222
+
223
+ .advisor-icon {
224
+ width: 32px;
225
+ height: 32px;
226
+ border-radius: 8px;
227
+ background: var(--advisor-bg);
228
+ color: var(--advisor-color);
229
+ display: flex;
230
+ align-items: center;
231
+ justify-content: center;
232
+ flex-shrink: 0;
233
+ border: 1px solid var(--advisor-color);
234
+ }
235
+
236
+ .advisor-details {
237
+ flex: 1;
238
+ min-width: 0;
239
+ }
240
+
241
+ .advisor-name {
242
+ font-weight: 600;
243
+ color: var(--text-primary);
244
+ font-size: 13px;
245
+ margin-bottom: 2px;
246
+ }
247
+
248
+ .advisor-description {
249
+ font-size: 11px;
250
+ color: var(--text-secondary);
251
+ line-height: 1.3;
252
+ overflow: hidden;
253
+ text-overflow: ellipsis;
254
+ white-space: nowrap;
255
+ }
256
+
257
+ .advisor-status {
258
+ flex-shrink: 0;
259
+ }
260
+
261
+ .status-thinking {
262
+ display: flex;
263
+ align-items: center;
264
+ gap: 4px;
265
+ }
266
+
267
+ .thinking-dots {
268
+ display: flex;
269
+ gap: 2px;
270
+ }
271
+
272
+ .thinking-dots .dot {
273
+ width: 4px;
274
+ height: 4px;
275
+ background: var(--advisor-color);
276
+ border-radius: 50%;
277
+ animation: thinking-bounce 1.4s infinite ease-in-out both;
278
+ }
279
+
280
+ .thinking-dots .dot:nth-child(1) { animation-delay: -0.32s; }
281
+ .thinking-dots .dot:nth-child(2) { animation-delay: -0.16s; }
282
+ .thinking-dots .dot:nth-child(3) { animation-delay: 0s; }
283
+
284
+ .status-ready {
285
+ font-size: 11px;
286
+ color: var(--text-tertiary);
287
+ font-weight: 500;
288
+ }
289
+
290
+ @keyframes thinking-bounce {
291
+ 0%, 80%, 100% { transform: scale(0); }
292
+ 40% { transform: scale(1); }
293
+ }
294
+
295
+ @keyframes pulse {
296
+ 0%, 100% { opacity: 1; }
297
+ 50% { opacity: 0.7; }
298
+ }
299
+
300
+ /* Responsive Design */
301
+ @media (max-width: 768px) {
302
+ .advisor-status-dropdown {
303
+ display: none;
304
+ }
305
+ .advisor-dropdown-panel {
306
+ right: -20px;
307
+ left: -20px;
308
+ min-width: unset;
309
+ max-width: unset;
310
+ }
311
+
312
+ .advisor-status-button {
313
+ min-width: 120px;
314
+ font-size: 12px;
315
+ }
316
+
317
+ .advisor-item {
318
+ padding: 10px 12px;
319
+ }
320
+
321
+ .advisor-icon {
322
+ width: 28px;
323
+ height: 28px;
324
+ }
325
+
326
+ .advisor-name {
327
+ font-size: 12px;
328
+ }
329
+
330
+ .advisor-description {
331
+ font-size: 10px;
332
+ }
333
+ }
334
+ `}</style>
335
+ </div>
336
+ );
337
+ };
338
+
339
+ export default AdvisorStatusDropdown;
phd-advisor-frontend/src/components/EnhancedChatInput.js CHANGED
@@ -6,7 +6,9 @@ const EnhancedChatInput = ({
6
  onSendMessage,
7
  onFileUploaded,
8
  uploadedDocuments = [],
9
- isLoading,
 
 
10
  placeholder = "Ask your advisors anything about your PhD journey..."
11
  }) => {
12
  const [inputMessage, setInputMessage] = useState('');
@@ -100,6 +102,8 @@ const EnhancedChatInput = ({
100
  <FileUpload
101
  onFileUploaded={handleFileUploaded}
102
  isUploading={isUploading}
 
 
103
  onUploadStart={handleUploadStart}
104
  />
105
  </div>
 
6
  onSendMessage,
7
  onFileUploaded,
8
  uploadedDocuments = [],
9
+ isLoading,
10
+ currentChatSessionId,
11
+ authToken,
12
  placeholder = "Ask your advisors anything about your PhD journey..."
13
  }) => {
14
  const [inputMessage, setInputMessage] = useState('');
 
102
  <FileUpload
103
  onFileUploaded={handleFileUploaded}
104
  isUploading={isUploading}
105
+ currentChatSessionId={currentChatSessionId}
106
+ authToken={authToken}
107
  onUploadStart={handleUploadStart}
108
  />
109
  </div>
phd-advisor-frontend/src/components/ExportButton.js CHANGED
@@ -2,7 +2,7 @@ import React, { useState } from 'react';
2
  import { Download, FileText, FileType, File, Check, X, Loader2 } from 'lucide-react';
3
  import '../styles/ExportButton.css';
4
 
5
- const ExportButton = ({ hasMessages = false }) => {
6
  const [showDropdown, setShowDropdown] = useState(false);
7
  const [isExporting, setIsExporting] = useState(false);
8
  const [exportStatus, setExportStatus] = useState(null);
@@ -62,11 +62,24 @@ const ExportButton = ({ hasMessages = false }) => {
62
  const selectedTypeData = exportTypes.find(t => t.id === selectedType);
63
  const endpoint = selectedTypeData.endpoint;
64
 
65
- const response = await fetch(`http://localhost:8000/${endpoint}?format=${format}`, {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  method: 'GET',
67
- headers: {
68
- 'Content-Type': 'application/json',
69
- },
70
  });
71
 
72
  if (!response.ok) {
@@ -87,14 +100,14 @@ const ExportButton = ({ hasMessages = false }) => {
87
 
88
  // Create blob and download
89
  const blob = await response.blob();
90
- const url = window.URL.createObjectURL(blob);
91
  const link = document.createElement('a');
92
- link.href = url;
93
  link.download = filename;
94
  document.body.appendChild(link);
95
  link.click();
96
  document.body.removeChild(link);
97
- window.URL.revokeObjectURL(url);
98
 
99
  setExportStatus('success');
100
  setTimeout(() => setExportStatus(null), 3000);
@@ -142,7 +155,10 @@ const ExportButton = ({ hasMessages = false }) => {
142
  if (isExporting) return 'Exporting chat...';
143
  if (exportStatus === 'success') return 'Export successful!';
144
  if (exportStatus === 'error') return 'Export failed - click to retry';
145
- return 'Export chat conversation';
 
 
 
146
  };
147
 
148
  return (
@@ -158,69 +174,74 @@ const ExportButton = ({ hasMessages = false }) => {
158
  </button>
159
 
160
  {showDropdown && (
161
- <div className="export-dropdown">
162
- <div className="export-dropdown-header">
163
- <h4>Export Options</h4>
164
- <p>Choose what to export and in which format</p>
165
- </div>
166
-
167
- {/* ADD THIS NEW SECTION - Export Type Selection */}
168
- <div className="export-type-section">
169
- <h5>What to export:</h5>
170
- <div className="export-type-buttons">
171
- {exportTypes.map((type) => (
172
- <button
173
- key={type.id}
174
- onClick={() => setSelectedType(type.id)}
175
- className={`export-type-button ${selectedType === type.id ? 'active' : ''}`}
176
- disabled={isExporting}
177
- >
178
- <div className="type-info">
179
- <div className="type-name">{type.name}</div>
180
- <div className="type-description">{type.description}</div>
181
- </div>
182
- </button>
183
- ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  </div>
185
- </div>
186
-
187
- {/* EXISTING FORMAT SECTION - UPDATE THE HEADER */}
188
- <div className="export-format-section">
189
- <h5>Format:</h5>
190
- <div className="export-format-list">
191
- {exportFormats.map((format) => {
192
- const Icon = format.icon;
193
- return (
194
- <button
195
- key={format.id}
196
- onClick={() => handleFormatSelect(format.id)}
197
- className="export-format-button"
198
- disabled={isExporting}
199
- >
200
- <div className="format-icon">
201
- <Icon size={20} />
202
- </div>
203
- <div className="format-info">
204
- <div className="format-name">{format.name}</div>
205
- <div className="format-description">{format.description}</div>
206
- </div>
207
- <div className="format-extension">{format.extension}</div>
208
- </button>
209
- );
210
- })}
211
- </div>
212
- </div>
213
-
214
- <div className="export-dropdown-footer">
215
- <span>
216
- {selectedType === 'chat'
217
- ? 'Full conversation history will be included'
218
- : 'AI will generate a concise summary of your conversation'
219
- }
220
- </span>
221
- </div>
222
- </div>
223
- )}
224
 
225
  {exportStatus && (
226
  <div className={`export-status ${exportStatus}`}>
 
2
  import { Download, FileText, FileType, File, Check, X, Loader2 } from 'lucide-react';
3
  import '../styles/ExportButton.css';
4
 
5
+ const ExportButton = ({ hasMessages = false, currentSessionId = null, authToken = null }) => {
6
  const [showDropdown, setShowDropdown] = useState(false);
7
  const [isExporting, setIsExporting] = useState(false);
8
  const [exportStatus, setExportStatus] = useState(null);
 
62
  const selectedTypeData = exportTypes.find(t => t.id === selectedType);
63
  const endpoint = selectedTypeData.endpoint;
64
 
65
+ // Build the URL with session ID if available
66
+ let url = `http://localhost:8000/${endpoint}?format=${format}`;
67
+ if (currentSessionId) {
68
+ url += `&chat_session_id=${currentSessionId}`;
69
+ }
70
+
71
+ // Build headers - include auth token if available (needed for specific session export)
72
+ const headers = {
73
+ 'Content-Type': 'application/json',
74
+ };
75
+
76
+ if (authToken && currentSessionId) {
77
+ headers['Authorization'] = `Bearer ${authToken}`;
78
+ }
79
+
80
+ const response = await fetch(url, {
81
  method: 'GET',
82
+ headers: headers,
 
 
83
  });
84
 
85
  if (!response.ok) {
 
100
 
101
  // Create blob and download
102
  const blob = await response.blob();
103
+ const url_blob = window.URL.createObjectURL(blob);
104
  const link = document.createElement('a');
105
+ link.href = url_blob;
106
  link.download = filename;
107
  document.body.appendChild(link);
108
  link.click();
109
  document.body.removeChild(link);
110
+ window.URL.revokeObjectURL(url_blob);
111
 
112
  setExportStatus('success');
113
  setTimeout(() => setExportStatus(null), 3000);
 
155
  if (isExporting) return 'Exporting chat...';
156
  if (exportStatus === 'success') return 'Export successful!';
157
  if (exportStatus === 'error') return 'Export failed - click to retry';
158
+
159
+ // Show whether we're exporting current session or specific saved chat
160
+ const sessionInfo = currentSessionId ? 'this saved chat' : 'current session';
161
+ return `Export ${sessionInfo}`;
162
  };
163
 
164
  return (
 
174
  </button>
175
 
176
  {showDropdown && (
177
+ <div className="export-dropdown">
178
+ <div className="export-dropdown-header">
179
+ <h4>Export Options</h4>
180
+ <p>
181
+ {currentSessionId
182
+ ? 'Export this saved chat conversation'
183
+ : 'Export current session'
184
+ }
185
+ </p>
186
+ </div>
187
+
188
+ {/* Export Type Selection */}
189
+ <div className="export-type-section">
190
+ <h5>What to export:</h5>
191
+ <div className="export-type-buttons">
192
+ {exportTypes.map((type) => (
193
+ <button
194
+ key={type.id}
195
+ onClick={() => setSelectedType(type.id)}
196
+ className={`export-type-button ${selectedType === type.id ? 'active' : ''}`}
197
+ disabled={isExporting}
198
+ >
199
+ <div className="type-info">
200
+ <div className="type-name">{type.name}</div>
201
+ <div className="type-description">{type.description}</div>
202
+ </div>
203
+ </button>
204
+ ))}
205
+ </div>
206
+ </div>
207
+
208
+ {/* Format Selection */}
209
+ <div className="export-format-section">
210
+ <h5>Format:</h5>
211
+ <div className="export-format-list">
212
+ {exportFormats.map((format) => {
213
+ const Icon = format.icon;
214
+ return (
215
+ <button
216
+ key={format.id}
217
+ onClick={() => handleFormatSelect(format.id)}
218
+ className="export-format-button"
219
+ disabled={isExporting}
220
+ >
221
+ <div className="format-icon">
222
+ <Icon size={20} />
223
+ </div>
224
+ <div className="format-info">
225
+ <div className="format-name">{format.name}</div>
226
+ <div className="format-description">{format.description}</div>
227
+ </div>
228
+ <div className="format-extension">{format.extension}</div>
229
+ </button>
230
+ );
231
+ })}
232
+ </div>
233
+ </div>
234
+
235
+ <div className="export-dropdown-footer">
236
+ <span>
237
+ {selectedType === 'chat'
238
+ ? 'Full conversation history will be included'
239
+ : 'AI will generate a concise summary of your conversation'
240
+ }
241
+ </span>
242
+ </div>
243
  </div>
244
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  {exportStatus && (
247
  <div className={`export-status ${exportStatus}`}>
phd-advisor-frontend/src/components/FileUpload.js CHANGED
@@ -3,7 +3,7 @@ import { Upload, FileText, File, X, CheckCircle, AlertCircle } from 'lucide-reac
3
  import { useTheme } from '../contexts/ThemeContext';
4
  import '../styles/FileUpload.css'
5
 
6
- const FileUpload = ({ onFileUploaded, isUploading, onUploadStart }) => {
7
  const [dragActive, setDragActive] = useState(false);
8
  const [uploadStatus, setUploadStatus] = useState(null); // 'success', 'error', null
9
  const [uploadMessage, setUploadMessage] = useState('');
@@ -44,8 +44,33 @@ const FileUpload = ({ onFileUploaded, isUploading, onUploadStart }) => {
44
  formData.append('file', file);
45
 
46
  try {
47
- const response = await fetch('http://localhost:8000/upload-document', {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  method: 'POST',
 
49
  body: formData,
50
  });
51
 
@@ -55,6 +80,26 @@ const FileUpload = ({ onFileUploaded, isUploading, onUploadStart }) => {
55
  setUploadMessage(`${file.name} uploaded successfully and added to context.`);
56
  onFileUploaded && onFileUploaded(file, data);
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  // Auto-clear success message after 5 seconds
59
  setTimeout(() => {
60
  setUploadStatus(null);
 
3
  import { useTheme } from '../contexts/ThemeContext';
4
  import '../styles/FileUpload.css'
5
 
6
+ const FileUpload = ({ onFileUploaded, isUploading, onUploadStart, currentChatSessionId = null, authToken = null }) => {
7
  const [dragActive, setDragActive] = useState(false);
8
  const [uploadStatus, setUploadStatus] = useState(null); // 'success', 'error', null
9
  const [uploadMessage, setUploadMessage] = useState('');
 
44
  formData.append('file', file);
45
 
46
  try {
47
+ let uploadUrl = 'http://localhost:8000/upload-document';
48
+
49
+ console.log('=== DOCUMENT UPLOAD DEBUG ===');
50
+ console.log('currentChatSessionId:', currentChatSessionId);
51
+ console.log('authToken available:', !!authToken);
52
+
53
+ if (currentChatSessionId) {
54
+ uploadUrl += `?chat_session_id=${currentChatSessionId}`;
55
+ console.log('Uploading to specific chat session:', currentChatSessionId);
56
+ console.log('Final upload URL:', uploadUrl);
57
+ } else {
58
+ console.log('WARNING: No currentChatSessionId - uploading to new session');
59
+ console.log('This will cause session mismatch!');
60
+ }
61
+
62
+ // Include auth token in headers if available
63
+ const headers = {};
64
+ if (authToken) {
65
+ headers['Authorization'] = `Bearer ${authToken}`;
66
+ console.log('Auth token included in request');
67
+ } else {
68
+ console.log('WARNING: No auth token available');
69
+ }
70
+
71
+ const response = await fetch(uploadUrl, {
72
  method: 'POST',
73
+ headers: headers,
74
  body: formData,
75
  });
76
 
 
80
  setUploadMessage(`${file.name} uploaded successfully and added to context.`);
81
  onFileUploaded && onFileUploaded(file, data);
82
 
83
+ // ENHANCED: Better debug logging
84
+ console.log('=== UPLOAD RESULT ===');
85
+ console.log('Document upload result:', {
86
+ filename: data.filename,
87
+ session_id: data.session_id,
88
+ chat_session_id: data.chat_session_id,
89
+ user_id: data.user_id,
90
+ chunks_created: data.chunks_created,
91
+ currentSessionId: currentChatSessionId
92
+ });
93
+
94
+ // Check for session mismatch
95
+ if (data.chat_session_id !== currentChatSessionId) {
96
+ console.error('SESSION MISMATCH DETECTED!');
97
+ console.error('Expected:', currentChatSessionId);
98
+ console.error('Got:', data.chat_session_id);
99
+ } else {
100
+ console.log('✅ Session IDs match correctly');
101
+ }
102
+
103
  // Auto-clear success message after 5 seconds
104
  setTimeout(() => {
105
  setUploadStatus(null);
phd-advisor-frontend/src/components/Login.js CHANGED
@@ -53,13 +53,27 @@ const Login = ({ onNavigateToSignup, onNavigateToHome }) => {
53
  setIsLoading(true);
54
 
55
  try {
56
- // Simulate API call
57
- await new Promise(resolve => setTimeout(resolve, 1500));
58
-
59
- // For demo purposes, we'll just navigate to home
60
- // In real implementation, handle authentication here
61
- console.log('Login attempt:', formData);
62
- onNavigateToHome?.();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  } catch (error) {
65
  console.error('Login error:', error);
 
53
  setIsLoading(true);
54
 
55
  try {
56
+ const response = await fetch('http://localhost:8000/auth/login', {
57
+ method: 'POST',
58
+ headers: {
59
+ 'Content-Type': 'application/json',
60
+ },
61
+ body: JSON.stringify({
62
+ email: formData.email,
63
+ password: formData.password
64
+ }),
65
+ });
66
+
67
+ const data = await response.json();
68
+
69
+ if (response.ok) {
70
+ // Store the token and user info
71
+ localStorage.setItem('authToken', data.access_token);
72
+ localStorage.setItem('user', JSON.stringify(data.user));
73
+ onNavigateToHome?.(data.user, data.access_token);
74
+ } else {
75
+ setErrors({ submit: data.detail || 'Login failed. Please try again.' });
76
+ }
77
 
78
  } catch (error) {
79
  console.error('Login error:', error);
phd-advisor-frontend/src/components/MessageBubble.js CHANGED
@@ -1,4 +1,5 @@
1
  import React, { useState, useRef, useEffect } from 'react';
 
2
  import { Reply, Copy, Check, Maximize2, Info, FileText, Hash, Target } from 'lucide-react';
3
  import { advisors, getAdvisorColors } from '../data/advisors';
4
  import { useTheme } from '../contexts/ThemeContext';
@@ -22,7 +23,6 @@ const MessageBubble = ({
22
  setCopiedStates(prev => ({ ...prev, [messageId]: true }));
23
  if (onCopy) onCopy(messageId, content);
24
 
25
- // Reset the copied state after 2 seconds
26
  setTimeout(() => {
27
  setCopiedStates(prev => ({ ...prev, [messageId]: false }));
28
  }, 2000);
@@ -31,8 +31,8 @@ const MessageBubble = ({
31
  }
32
  };
33
 
34
- const handleExpand = (messageId, advisorId) => {
35
- if (onExpand) onExpand(messageId, advisorId);
36
  };
37
 
38
  const handleInfoToggle = () => {
@@ -63,6 +63,172 @@ const MessageBubble = ({
63
  }
64
  }, [showInfoOverlay]);
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  // RAG Metadata Component
67
  const RagInfoOverlay = ({ ragMetadata, colors }) => {
68
  const hasDocuments = ragMetadata?.usedDocuments || false;
@@ -84,7 +250,6 @@ const MessageBubble = ({
84
  </div>
85
 
86
  <div className="rag-overlay-content">
87
- {/* Basic Stats */}
88
  <div className="rag-stat-row">
89
  <div className="rag-stat-label">Used Documents:</div>
90
  <div className={`rag-stat-value ${hasDocuments ? 'positive' : 'negative'}`}>
@@ -97,7 +262,6 @@ const MessageBubble = ({
97
  <div className="rag-stat-value">{chunksUsed}</div>
98
  </div>
99
 
100
- {/* Document Details */}
101
  {hasDocuments && documentChunks.length > 0 && (
102
  <div className="rag-documents-section">
103
  <div className="rag-section-title">
@@ -128,7 +292,6 @@ const MessageBubble = ({
128
  </div>
129
  )}
130
 
131
- {/* No Documents Message */}
132
  {!hasDocuments && (
133
  <div className="rag-no-documents">
134
  <Hash size={12} />
@@ -157,9 +320,9 @@ const MessageBubble = ({
157
  }
158
 
159
  if (message.type === 'advisor') {
160
- const advisor = advisors[message.advisorId];
161
  const Icon = advisor.icon;
162
- const colors = getAdvisorColors(message.advisorId, isDark);
163
  const isCopied = copiedStates[message.id];
164
 
165
  return (
@@ -175,7 +338,7 @@ const MessageBubble = ({
175
  style={{
176
  backgroundColor: colors.bgColor,
177
  borderColor: colors.color + '40',
178
- position: 'relative' // For overlay positioning
179
  }}
180
  >
181
  <div className="advisor-message-header">
@@ -200,18 +363,27 @@ const MessageBubble = ({
200
  })}
201
  </span>
202
  </div>
203
- <p
 
 
204
  className="advisor-message-text"
205
  style={{
206
  color: colors.textColor
207
  }}
208
  >
209
- {message.content}
210
- </p>
 
 
 
 
 
 
 
 
211
  {showReplyButton && (
212
  <div className="message-actions">
213
  <div className="action-buttons">
214
- {/* Reply Button */}
215
  <div className="tooltip-container">
216
  <button
217
  className="action-button"
@@ -230,7 +402,6 @@ const MessageBubble = ({
230
  )}
231
  </div>
232
 
233
- {/* Copy Button */}
234
  <div className="tooltip-container">
235
  <button
236
  className="action-button"
@@ -251,11 +422,10 @@ const MessageBubble = ({
251
  )}
252
  </div>
253
 
254
- {/* Expand/Elaborate Button */}
255
  <div className="tooltip-container">
256
  <button
257
  className="action-button"
258
- onClick={() => handleExpand(message.id, message.advisorId)}
259
  onMouseEnter={() => showTooltipWithDelay('expand')}
260
  onMouseLeave={hideTooltip}
261
  style={{
@@ -273,7 +443,6 @@ const MessageBubble = ({
273
  </div>
274
  )}
275
 
276
- {/* RAG Info Overlay */}
277
  {showInfoOverlay && (
278
  <RagInfoOverlay
279
  ragMetadata={message.ragMetadata}
 
1
  import React, { useState, useRef, useEffect } from 'react';
2
+ import ReactMarkdown from 'react-markdown';
3
  import { Reply, Copy, Check, Maximize2, Info, FileText, Hash, Target } from 'lucide-react';
4
  import { advisors, getAdvisorColors } from '../data/advisors';
5
  import { useTheme } from '../contexts/ThemeContext';
 
23
  setCopiedStates(prev => ({ ...prev, [messageId]: true }));
24
  if (onCopy) onCopy(messageId, content);
25
 
 
26
  setTimeout(() => {
27
  setCopiedStates(prev => ({ ...prev, [messageId]: false }));
28
  }, 2000);
 
31
  }
32
  };
33
 
34
+ const handleExpand = (messageId, persona_id) => {
35
+ if (onExpand) onExpand(messageId, persona_id);
36
  };
37
 
38
  const handleInfoToggle = () => {
 
63
  }
64
  }, [showInfoOverlay]);
65
 
66
+ // Preprocess markdown content to fix common formatting issues
67
+ const preprocessMarkdown = (content) => {
68
+ if (!content) return '';
69
+
70
+ // Ensure proper line breaks before numbered lists
71
+ let processed = content.replace(/(\d+\.\s\*\*[^*]+\*\*)/g, '\n\n$1');
72
+
73
+ // Ensure proper line breaks after list items
74
+ processed = processed.replace(/(\d+\.\s[^\n]+)(?=\s+\d+\.)/g, '$1\n');
75
+
76
+ // Fix spacing around bold headers
77
+ processed = processed.replace(/(\*\*[^*]+\*\*)/g, '\n\n$1\n\n');
78
+
79
+ // Clean up multiple consecutive line breaks
80
+ processed = processed.replace(/\n{3,}/g, '\n\n');
81
+
82
+ // Ensure proper paragraph breaks
83
+ processed = processed.replace(/([.!?])\s+([A-Z])/g, '$1\n\n$2');
84
+
85
+ return processed.trim();
86
+ };
87
+
88
+ // ENHANCED MARKDOWN COMPONENTS WITH BETTER STYLING
89
+ const markdownComponents = {
90
+ // Bold text styling - for headers and key terms
91
+ strong: ({ children }) => (
92
+ <strong style={{
93
+ fontWeight: '700',
94
+ color: isDark ? '#ffffff' : '#1f2937',
95
+ display: 'block',
96
+ marginBottom: '0.5rem',
97
+ marginTop: '1rem'
98
+ }}>
99
+ {children}
100
+ </strong>
101
+ ),
102
+
103
+ // Italic text styling
104
+ em: ({ children }) => (
105
+ <em style={{
106
+ fontStyle: 'italic',
107
+ color: isDark ? '#93c5fd' : '#3b82f6',
108
+ fontWeight: '500'
109
+ }}>
110
+ {children}
111
+ </em>
112
+ ),
113
+
114
+ // Paragraph styling with proper spacing
115
+ p: ({ children }) => (
116
+ <p style={{
117
+ marginBottom: '1rem',
118
+ lineHeight: '1.7',
119
+ color: isDark ? '#e5e7eb' : '#374151',
120
+ fontSize: '14px'
121
+ }}>
122
+ {children}
123
+ </p>
124
+ ),
125
+
126
+ // Unordered list styling
127
+ ul: ({ children }) => (
128
+ <ul style={{
129
+ listStyleType: 'disc',
130
+ paddingLeft: '1.5rem',
131
+ marginBottom: '1rem',
132
+ marginTop: '0.5rem',
133
+ color: isDark ? '#e5e7eb' : '#374151'
134
+ }}>
135
+ {children}
136
+ </ul>
137
+ ),
138
+
139
+ // Ordered list styling with better spacing
140
+ ol: ({ children }) => (
141
+ <ol style={{
142
+ listStyleType: 'decimal',
143
+ paddingLeft: '1.5rem',
144
+ marginBottom: '1rem',
145
+ marginTop: '0.5rem',
146
+ color: isDark ? '#e5e7eb' : '#374151',
147
+ counterReset: 'list-counter'
148
+ }}>
149
+ {children}
150
+ </ol>
151
+ ),
152
+
153
+ // List item styling with proper spacing
154
+ li: ({ children }) => (
155
+ <li style={{
156
+ marginBottom: '0.75rem',
157
+ lineHeight: '1.6',
158
+ paddingLeft: '0.25rem'
159
+ }}>
160
+ {children}
161
+ </li>
162
+ ),
163
+
164
+ // Headers (in case they use them)
165
+ h1: ({ children }) => (
166
+ <h1 style={{
167
+ fontSize: '1.5rem',
168
+ fontWeight: '700',
169
+ color: isDark ? '#ffffff' : '#1f2937',
170
+ marginBottom: '1rem',
171
+ marginTop: '1.5rem',
172
+ borderBottom: `2px solid ${isDark ? '#374151' : '#e5e7eb'}`,
173
+ paddingBottom: '0.5rem'
174
+ }}>
175
+ {children}
176
+ </h1>
177
+ ),
178
+
179
+ h2: ({ children }) => (
180
+ <h2 style={{
181
+ fontSize: '1.25rem',
182
+ fontWeight: '600',
183
+ color: isDark ? '#ffffff' : '#1f2937',
184
+ marginBottom: '0.75rem',
185
+ marginTop: '1.25rem'
186
+ }}>
187
+ {children}
188
+ </h2>
189
+ ),
190
+
191
+ h3: ({ children }) => (
192
+ <h3 style={{
193
+ fontSize: '1.125rem',
194
+ fontWeight: '600',
195
+ color: isDark ? '#ffffff' : '#1f2937',
196
+ marginBottom: '0.5rem',
197
+ marginTop: '1rem'
198
+ }}>
199
+ {children}
200
+ </h3>
201
+ ),
202
+
203
+ // Code styling
204
+ code: ({ children }) => (
205
+ <code style={{
206
+ backgroundColor: isDark ? '#374151' : '#f3f4f6',
207
+ padding: '0.125rem 0.375rem',
208
+ borderRadius: '0.25rem',
209
+ fontSize: '0.875rem',
210
+ fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace',
211
+ color: isDark ? '#fbbf24' : '#d97706'
212
+ }}>
213
+ {children}
214
+ </code>
215
+ ),
216
+
217
+ // Block quote styling
218
+ blockquote: ({ children }) => (
219
+ <blockquote style={{
220
+ borderLeft: '4px solid ' + (isDark ? '#374151' : '#e5e7eb'),
221
+ paddingLeft: '1rem',
222
+ marginLeft: '0',
223
+ marginBottom: '1rem',
224
+ fontStyle: 'italic',
225
+ color: isDark ? '#9ca3af' : '#6b7280'
226
+ }}>
227
+ {children}
228
+ </blockquote>
229
+ )
230
+ };
231
+
232
  // RAG Metadata Component
233
  const RagInfoOverlay = ({ ragMetadata, colors }) => {
234
  const hasDocuments = ragMetadata?.usedDocuments || false;
 
250
  </div>
251
 
252
  <div className="rag-overlay-content">
 
253
  <div className="rag-stat-row">
254
  <div className="rag-stat-label">Used Documents:</div>
255
  <div className={`rag-stat-value ${hasDocuments ? 'positive' : 'negative'}`}>
 
262
  <div className="rag-stat-value">{chunksUsed}</div>
263
  </div>
264
 
 
265
  {hasDocuments && documentChunks.length > 0 && (
266
  <div className="rag-documents-section">
267
  <div className="rag-section-title">
 
292
  </div>
293
  )}
294
 
 
295
  {!hasDocuments && (
296
  <div className="rag-no-documents">
297
  <Hash size={12} />
 
320
  }
321
 
322
  if (message.type === 'advisor') {
323
+ const advisor = advisors[message.persona_id];
324
  const Icon = advisor.icon;
325
+ const colors = getAdvisorColors(message.persona_id, isDark);
326
  const isCopied = copiedStates[message.id];
327
 
328
  return (
 
338
  style={{
339
  backgroundColor: colors.bgColor,
340
  borderColor: colors.color + '40',
341
+ position: 'relative'
342
  }}
343
  >
344
  <div className="advisor-message-header">
 
363
  })}
364
  </span>
365
  </div>
366
+
367
+ {/* Enhanced markdown rendering with preprocessing */}
368
+ <div
369
  className="advisor-message-text"
370
  style={{
371
  color: colors.textColor
372
  }}
373
  >
374
+ <ReactMarkdown
375
+ components={markdownComponents}
376
+ // Add these props for better parsing
377
+ remarkPlugins={[]}
378
+ rehypePlugins={[]}
379
+ >
380
+ {preprocessMarkdown(message.content)}
381
+ </ReactMarkdown>
382
+ </div>
383
+
384
  {showReplyButton && (
385
  <div className="message-actions">
386
  <div className="action-buttons">
 
387
  <div className="tooltip-container">
388
  <button
389
  className="action-button"
 
402
  )}
403
  </div>
404
 
 
405
  <div className="tooltip-container">
406
  <button
407
  className="action-button"
 
422
  )}
423
  </div>
424
 
 
425
  <div className="tooltip-container">
426
  <button
427
  className="action-button"
428
+ onClick={() => handleExpand(message.id, message.persona_id)}
429
  onMouseEnter={() => showTooltipWithDelay('expand')}
430
  onMouseLeave={hideTooltip}
431
  style={{
 
443
  </div>
444
  )}
445
 
 
446
  {showInfoOverlay && (
447
  <RagInfoOverlay
448
  ragMetadata={message.ragMetadata}
phd-advisor-frontend/src/components/Sidebar.js ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import {
3
+ MessageSquare,
4
+ Plus,
5
+ Search,
6
+ MoreVertical,
7
+ Trash2,
8
+ Edit3,
9
+ LogOut,
10
+ User,
11
+ Settings,
12
+ ChevronLeft,
13
+ ChevronRight
14
+ } from 'lucide-react';
15
+ import '../styles/Sidebar.css';
16
+
17
+ const Sidebar = ({
18
+ user,
19
+ currentSessionId,
20
+ onSelectSession,
21
+ onNewChat,
22
+ onSignOut,
23
+ authToken,
24
+ onSidebarToggle,
25
+ isMobileOpen = false,
26
+ onMobileToggle
27
+ }) => {
28
+ const [chatSessions, setChatSessions] = useState([]);
29
+ const [searchTerm, setSearchTerm] = useState('');
30
+ const [isLoading, setIsLoading] = useState(true);
31
+ const [showUserMenu, setShowUserMenu] = useState(false);
32
+ const [isCollapsed, setIsCollapsed] = useState(false);
33
+ const [isCreatingNewChat, setIsCreatingNewChat] = useState(false);
34
+
35
+ useEffect(() => {
36
+ if (authToken) {
37
+ fetchChatSessions();
38
+ }
39
+ }, [authToken]);
40
+
41
+ useEffect(() => {
42
+ const handleOverlayClick = (e) => {
43
+ // Only close if clicking the overlay itself, not the sidebar
44
+ if (e.target.classList.contains('mobile-sidebar-overlay')) {
45
+ onMobileToggle(false);
46
+ }
47
+ };
48
+
49
+ if (isMobileOpen) {
50
+ document.addEventListener('click', handleOverlayClick);
51
+ return () => document.removeEventListener('click', handleOverlayClick);
52
+ }
53
+ }, [isMobileOpen, onMobileToggle]);
54
+
55
+ // Notify parent when sidebar state changes
56
+ useEffect(() => {
57
+ if (onSidebarToggle) {
58
+ onSidebarToggle(isCollapsed);
59
+ }
60
+ }, [isCollapsed, onSidebarToggle]);
61
+
62
+ // Add effect to refresh when currentSessionId changes (new session created)
63
+ useEffect(() => {
64
+ if (currentSessionId && authToken) {
65
+ // Small delay to ensure the session is saved to database
66
+ const timer = setTimeout(() => {
67
+ fetchChatSessions();
68
+ }, 200);
69
+ return () => clearTimeout(timer);
70
+ }
71
+ }, [currentSessionId, authToken]);
72
+
73
+
74
+ const fetchChatSessions = async () => {
75
+ try {
76
+ const response = await fetch('http://localhost:8000/api/chat-sessions', {
77
+ headers: {
78
+ 'Authorization': `Bearer ${authToken}`,
79
+ 'Content-Type': 'application/json'
80
+ }
81
+ });
82
+
83
+ if (response.ok) {
84
+ const sessions = await response.json();
85
+ setChatSessions(sessions);
86
+ } else {
87
+ console.error('Failed to fetch chat sessions');
88
+ }
89
+ } catch (error) {
90
+ console.error('Error fetching chat sessions:', error);
91
+ } finally {
92
+ setIsLoading(false);
93
+ }
94
+ };
95
+
96
+ const handleNewChat = async () => {
97
+ setIsCreatingNewChat(true);
98
+
99
+ try {
100
+ // Call the parent's new chat handler and wait for it to complete
101
+ await onNewChat();
102
+
103
+ // Refresh the sessions list immediately after new chat is created
104
+ // The parent should have updated currentSessionId by now
105
+ await fetchChatSessions();
106
+
107
+ } catch (error) {
108
+ console.error('Error creating new chat:', error);
109
+ // Optionally show an error message to the user
110
+ } finally {
111
+ setIsCreatingNewChat(false);
112
+ }
113
+ };
114
+
115
+ const handleDeleteSession = async (sessionId, event) => {
116
+ event.stopPropagation();
117
+
118
+ if (window.confirm('Are you sure you want to delete this chat?')) {
119
+ try {
120
+ const response = await fetch(`http://localhost:8000/api/chat-sessions/${sessionId}`, {
121
+ method: 'DELETE',
122
+ headers: {
123
+ 'Authorization': `Bearer ${authToken}`,
124
+ 'Content-Type': 'application/json'
125
+ }
126
+ });
127
+
128
+ if (response.ok) {
129
+ setChatSessions(prev => prev.filter(session => session.id !== sessionId));
130
+ if (currentSessionId === sessionId) {
131
+ onNewChat(); // Create new session if current one was deleted
132
+ }
133
+ }
134
+ } catch (error) {
135
+ console.error('Error deleting chat session:', error);
136
+ }
137
+ }
138
+ };
139
+
140
+ const toggleSidebar = () => {
141
+ setIsCollapsed(!isCollapsed);
142
+ // Close user menu when collapsing
143
+ if (!isCollapsed) {
144
+ setShowUserMenu(false);
145
+ }
146
+ };
147
+
148
+ const filteredSessions = chatSessions.filter(session =>
149
+ session.title.toLowerCase().includes(searchTerm.toLowerCase())
150
+ );
151
+
152
+ const formatDate = (dateString) => {
153
+ const date = new Date(dateString);
154
+ const now = new Date();
155
+ const diffTime = Math.abs(now - date);
156
+ const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
157
+
158
+ if (diffDays === 1) return 'Today';
159
+ if (diffDays === 2) return 'Yesterday';
160
+ if (diffDays <= 7) return `${diffDays - 1} days ago`;
161
+ return date.toLocaleDateString();
162
+ };
163
+
164
+ return (
165
+ <>
166
+ <div className={`sidebar ${isCollapsed ? 'collapsed' : ''} ${isMobileOpen ? 'mobile-open' : ''}`}>
167
+ {/* Header */}
168
+ <div className="sidebar-header">
169
+ {!isCollapsed && (
170
+ <>
171
+ <div className="user-section">
172
+ <div className="user-info">
173
+ <div className="user-avatar">
174
+ <User size={20} />
175
+ </div>
176
+ <div className="user-details">
177
+ <span className="user-name">{user.firstName} {user.lastName}</span>
178
+ <span className="user-email">{user.email}</span>
179
+ </div>
180
+ </div>
181
+
182
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
183
+ {/* Toggle button next to user menu when expanded */}
184
+ <button
185
+ className="sidebar-toggle"
186
+ onClick={toggleSidebar}
187
+ title="Collapse sidebar"
188
+ >
189
+ <ChevronLeft size={16} />
190
+ </button>
191
+
192
+ <div className="user-menu-container">
193
+ <button
194
+ className="user-menu-button"
195
+ onClick={() => setShowUserMenu(!showUserMenu)}
196
+ >
197
+ <MoreVertical size={16} />
198
+ </button>
199
+
200
+ {showUserMenu && (
201
+ <div className="user-menu">
202
+ <button className="user-menu-item">
203
+ <Settings size={16} />
204
+ <span>Settings</span>
205
+ </button>
206
+ <button className="user-menu-item sign-out" onClick={onSignOut}>
207
+ <LogOut size={16} />
208
+ <span>Sign Out</span>
209
+ </button>
210
+ </div>
211
+ )}
212
+ </div>
213
+ </div>
214
+ </div>
215
+
216
+ <button
217
+ className="new-chat-button"
218
+ onClick={handleNewChat}
219
+ disabled={isCreatingNewChat}
220
+ >
221
+ <Plus size={16} />
222
+ <span>{isCreatingNewChat ? 'Creating...' : 'New Chat'}</span>
223
+ </button>
224
+ </>
225
+ )}
226
+
227
+ {isCollapsed && (
228
+ <div className="collapsed-header">
229
+ {/* Toggle button replaces user avatar when collapsed */}
230
+ <button
231
+ className="collapsed-toggle-avatar"
232
+ onClick={toggleSidebar}
233
+ title="Expand sidebar"
234
+ >
235
+ <ChevronRight size={20} />
236
+ </button>
237
+ <button
238
+ className="collapsed-new-chat"
239
+ onClick={handleNewChat}
240
+ title="New Chat"
241
+ disabled={isCreatingNewChat}
242
+ >
243
+ <Plus size={20} />
244
+ </button>
245
+ </div>
246
+ )}
247
+ </div>
248
+
249
+ {/* Search - only show when expanded */}
250
+ {!isCollapsed && (
251
+ <div className="sidebar-search">
252
+ <div className="search-container">
253
+ <Search size={16} className="search-icon" />
254
+ <input
255
+ type="text"
256
+ placeholder="Search chats..."
257
+ value={searchTerm}
258
+ onChange={(e) => setSearchTerm(e.target.value)}
259
+ className="search-input"
260
+ />
261
+ </div>
262
+ </div>
263
+ )}
264
+
265
+ {/* Chat Sessions */}
266
+ <div className="chat-sessions">
267
+ {isLoading ? (
268
+ <div className="loading-sessions">
269
+ <div className="loading-spinner"></div>
270
+ {!isCollapsed && <span>Loading chats...</span>}
271
+ </div>
272
+ ) : isCreatingNewChat ? (
273
+ <div className="loading-sessions">
274
+ <div className="loading-spinner"></div>
275
+ {!isCollapsed && <span>Creating new chat...</span>}
276
+ </div>
277
+ ) : filteredSessions.length === 0 ? (
278
+ <div className="no-sessions">
279
+ {!isCollapsed && (searchTerm ? 'No chats found' : 'No chats yet')}
280
+ </div>
281
+ ) : (
282
+ <div className="sessions-list">
283
+ {filteredSessions.map((session) => (
284
+ <div
285
+ key={session.id}
286
+ className={`session-item ${currentSessionId === session.id ? 'active' : ''} ${isCollapsed ? 'collapsed' : ''}`}
287
+ onClick={() => onSelectSession(session.id)}
288
+ title={isCollapsed ? session.title : ''}
289
+ >
290
+ <div className="session-content">
291
+ <div className="session-icon">
292
+ <MessageSquare size={16} />
293
+ </div>
294
+ {!isCollapsed && (
295
+ <div className="session-details">
296
+ <div className="session-title">{session.title}</div>
297
+ <div className="session-meta">
298
+ <span className="session-date">{formatDate(session.updated_at)}</span>
299
+ <span className="session-messages">{session.message_count} messages</span>
300
+ </div>
301
+ </div>
302
+ )}
303
+ </div>
304
+
305
+ {!isCollapsed && (
306
+ <button
307
+ className="session-menu-button"
308
+ onClick={(e) => handleDeleteSession(session.id, e)}
309
+ >
310
+ <Trash2 size={14} />
311
+ </button>
312
+ )}
313
+ </div>
314
+ ))}
315
+ </div>
316
+ )}
317
+ </div>
318
+ </div>
319
+
320
+ {isMobileOpen && (
321
+ <div
322
+ className="mobile-sidebar-overlay visible"
323
+ onClick={() => onMobileToggle(false)}
324
+ />
325
+ )}
326
+ </>
327
+ );
328
+ };
329
+
330
+ export default Sidebar;
phd-advisor-frontend/src/components/Signup.js CHANGED
@@ -91,17 +91,35 @@ const Signup = ({ onNavigateToLogin, onNavigateToHome }) => {
91
  setIsLoading(true);
92
 
93
  try {
94
- // Simulate API call
95
- await new Promise(resolve => setTimeout(resolve, 2000));
96
-
97
- // For demo purposes, we'll just navigate to home
98
- // In real implementation, handle user registration here
99
- console.log('Signup attempt:', formData);
100
- onNavigateToHome?.();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  } catch (error) {
103
  console.error('Signup error:', error);
104
- setErrors({ submit: 'Registration failed. Please try again.' });
105
  } finally {
106
  setIsLoading(false);
107
  }
 
91
  setIsLoading(true);
92
 
93
  try {
94
+ const response = await fetch('http://localhost:8000/auth/signup', {
95
+ method: 'POST',
96
+ headers: {
97
+ 'Content-Type': 'application/json',
98
+ },
99
+ body: JSON.stringify({
100
+ firstName: formData.firstName,
101
+ lastName: formData.lastName,
102
+ email: formData.email,
103
+ password: formData.password,
104
+ academicStage: formData.academicStage,
105
+ researchArea: formData.researchArea
106
+ }),
107
+ });
108
+
109
+ const data = await response.json();
110
+
111
+ if (response.ok) {
112
+ // Store the token and user info
113
+ localStorage.setItem('authToken', data.access_token);
114
+ localStorage.setItem('user', JSON.stringify(data.user));
115
+ onNavigateToHome?.(data.user, data.access_token);
116
+ } else {
117
+ setErrors({ submit: data.detail || 'Signup failed. Please try again.' });
118
+ }
119
 
120
  } catch (error) {
121
  console.error('Signup error:', error);
122
+ setErrors({ submit: 'Signup failed. Please try again.' });
123
  } finally {
124
  setIsLoading(false);
125
  }
phd-advisor-frontend/src/data/advisors.js CHANGED
@@ -1,8 +1,10 @@
1
- import { BookOpen, Target, Brain } from 'lucide-react';
 
 
 
2
 
3
  export const advisors = {
4
  methodologist: {
5
- // Original structure preserved
6
  name: 'Methodologist',
7
  role: 'Research Methodology Expert',
8
  // Light theme colors
@@ -15,7 +17,6 @@ export const advisors = {
15
  icon: BookOpen,
16
  description: 'Structured & Planning-focused',
17
 
18
- // Enhanced information added
19
  fullTitle: 'Methodologist - Research Methodology Expert',
20
  credentials: 'PhD in Research Methods and Statistics from Stanford University',
21
  experience: '15+ years of experience guiding doctoral students',
@@ -62,7 +63,6 @@ export const advisors = {
62
  },
63
 
64
  theorist: {
65
- // Original structure preserved
66
  name: 'Theorist',
67
  role: 'Theoretical Frameworks Specialist',
68
  // Light theme colors
@@ -75,7 +75,6 @@ export const advisors = {
75
  icon: Brain,
76
  description: 'Abstract & Conceptual',
77
 
78
- // Enhanced information added
79
  fullTitle: 'Theorist - Theoretical Frameworks Specialist',
80
  credentials: 'PhD in Philosophy of Science from Oxford University',
81
  experience: 'Deep expertise in epistemology and conceptual development',
@@ -122,7 +121,6 @@ export const advisors = {
122
  },
123
 
124
  pragmatist: {
125
- // Original structure preserved
126
  name: 'Pragmatist',
127
  role: 'Action-Focused Research Coach',
128
  // Light theme colors
@@ -135,7 +133,6 @@ export const advisors = {
135
  icon: Target,
136
  description: 'Real-world & Outcome-focused',
137
 
138
- // Enhanced information added
139
  fullTitle: 'Pragmatist - Action-Focused Research Coach',
140
  credentials: 'PhD in Applied Psychology from UC Berkeley',
141
  experience: '12+ years of mentoring experience specializing in practical progress',
@@ -179,6 +176,419 @@ export const advisors = {
179
  structure: 'Always ends with specific, actionable next steps',
180
  citations: 'References practical examples and success strategies'
181
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  }
183
  };
184
 
@@ -192,9 +602,16 @@ export const getAdvisorColors = (advisorId, isDark = false) => {
192
  bgColor: isDark ? advisor.darkBgColor : advisor.bgColor,
193
  // For text that needs to be readable on colored backgrounds
194
  textColor: isDark ? '#F9FAFB' :
195
- advisor.color === '#10B981' ? '#047857' : // Darker green for pragmatist
196
- advisor.color === '#3B82F6' ? '#1D4ED8' : // Darker blue for methodologist
197
- advisor.color === '#8B5CF6' ? '#7C3AED' : // Darker purple for theorist
 
 
 
 
 
 
 
198
  '#374151' // fallback
199
  };
200
  };
 
1
+ import {
2
+ BookOpen, Target, Brain, HelpCircle, Zap, Search,
3
+ Feather, Minus, Eye, Heart
4
+ } from 'lucide-react';
5
 
6
  export const advisors = {
7
  methodologist: {
 
8
  name: 'Methodologist',
9
  role: 'Research Methodology Expert',
10
  // Light theme colors
 
17
  icon: BookOpen,
18
  description: 'Structured & Planning-focused',
19
 
 
20
  fullTitle: 'Methodologist - Research Methodology Expert',
21
  credentials: 'PhD in Research Methods and Statistics from Stanford University',
22
  experience: '15+ years of experience guiding doctoral students',
 
63
  },
64
 
65
  theorist: {
 
66
  name: 'Theorist',
67
  role: 'Theoretical Frameworks Specialist',
68
  // Light theme colors
 
75
  icon: Brain,
76
  description: 'Abstract & Conceptual',
77
 
 
78
  fullTitle: 'Theorist - Theoretical Frameworks Specialist',
79
  credentials: 'PhD in Philosophy of Science from Oxford University',
80
  experience: 'Deep expertise in epistemology and conceptual development',
 
121
  },
122
 
123
  pragmatist: {
 
124
  name: 'Pragmatist',
125
  role: 'Action-Focused Research Coach',
126
  // Light theme colors
 
133
  icon: Target,
134
  description: 'Real-world & Outcome-focused',
135
 
 
136
  fullTitle: 'Pragmatist - Action-Focused Research Coach',
137
  credentials: 'PhD in Applied Psychology from UC Berkeley',
138
  experience: '12+ years of mentoring experience specializing in practical progress',
 
176
  structure: 'Always ends with specific, actionable next steps',
177
  citations: 'References practical examples and success strategies'
178
  }
179
+ },
180
+
181
+ socratic: {
182
+ name: 'Socratic Mentor',
183
+ role: 'Critical Thinking Guide',
184
+ // Light theme colors
185
+ color: '#F59E0B',
186
+ bgColor: '#FEF3C7',
187
+ // Dark theme colors
188
+ darkColor: '#FBBF24',
189
+ darkBgColor: '#92400E',
190
+ // Icon and description
191
+ icon: HelpCircle,
192
+ description: 'Question-driven & Discovery-focused',
193
+
194
+ fullTitle: 'Socratic Mentor - Critical Thinking Guide',
195
+ credentials: 'PhD in Philosophy from Harvard University',
196
+ experience: '20+ years of experience in philosophical inquiry and critical thinking development',
197
+
198
+ specialties: [
199
+ 'Socratic Questioning Techniques',
200
+ 'Critical Thinking Development',
201
+ 'Philosophical Inquiry & Logic',
202
+ 'Self-directed Learning Facilitation',
203
+ 'Assumption Challenging',
204
+ 'Perspective Broadening'
205
+ ],
206
+
207
+ expertise: {
208
+ primary: 'Critical Thinking & Inquiry',
209
+ secondary: ['Philosophical Methods', 'Logical Reasoning', 'Self-Discovery'],
210
+ documentTypes: ['argument analyses', 'research justifications', 'theoretical discussions'],
211
+ strengths: [
212
+ 'Guiding self-discovery through questions',
213
+ 'Challenging assumptions constructively',
214
+ 'Developing critical thinking skills',
215
+ 'Facilitating intellectual breakthroughs'
216
+ ]
217
+ },
218
+
219
+ personality: {
220
+ tone: 'Thoughtful, probing, and intellectually curious',
221
+ approach: 'Guides discovery through systematic questioning',
222
+ communicationStyle: 'Question-heavy, reflective, discovery-oriented',
223
+ documentHandling: 'Questions assumptions and guides deeper inquiry into their reasoning'
224
+ },
225
+
226
+ sampleQuestions: [
227
+ "What assumptions are underlying my research approach?",
228
+ "How did I arrive at this particular research question?",
229
+ "What would happen if I questioned this fundamental assumption?",
230
+ "What evidence would challenge my current thinking?"
231
+ ],
232
+
233
+ responseStyle: {
234
+ length: 'Focused on strategic questioning with minimal direct answers',
235
+ structure: 'Series of probing questions building toward insight',
236
+ citations: 'References philosophical traditions and questioning methodologies'
237
+ }
238
+ },
239
+
240
+ motivator: {
241
+ name: 'Motivational Coach',
242
+ role: 'Academic Resilience Specialist',
243
+ // Light theme colors
244
+ color: '#EF4444',
245
+ bgColor: '#FEF2F2',
246
+ // Dark theme colors
247
+ darkColor: '#F87171',
248
+ darkBgColor: '#991B1B',
249
+ // Icon and description
250
+ icon: Zap,
251
+ description: 'Energizing & Confidence-building',
252
+
253
+ fullTitle: 'Motivational Coach - Academic Resilience Specialist',
254
+ credentials: 'PhD in Educational Psychology from University of Pennsylvania',
255
+ experience: 'Performance coaching certification and expertise in academic motivation',
256
+
257
+ specialties: [
258
+ 'Academic Motivation & Goal Setting',
259
+ 'Resilience Building & Stress Management',
260
+ 'Growth Mindset Development',
261
+ 'Overcoming Imposter Syndrome',
262
+ 'Performance Psychology',
263
+ 'Sustainable Productivity Habits'
264
+ ],
265
+
266
+ expertise: {
267
+ primary: 'Motivation & Resilience',
268
+ secondary: ['Goal Setting', 'Stress Management', 'Performance Psychology'],
269
+ documentTypes: ['progress reports', 'goal statements', 'reflection journals'],
270
+ strengths: [
271
+ 'Building academic confidence',
272
+ 'Maintaining motivation through challenges',
273
+ 'Developing resilience strategies',
274
+ 'Creating sustainable work habits'
275
+ ]
276
+ },
277
+
278
+ personality: {
279
+ tone: 'Energetic, enthusiastic, and genuinely encouraging',
280
+ approach: 'Focuses on strengths, progress, and potential',
281
+ communicationStyle: 'Inspiring, supportive, achievement-oriented',
282
+ documentHandling: 'Highlights progress and reframes challenges as growth opportunities'
283
+ },
284
+
285
+ sampleQuestions: [
286
+ "How can I stay motivated during difficult research phases?",
287
+ "What strategies help overcome academic imposter syndrome?",
288
+ "How do I build resilience for the long PhD journey?",
289
+ "What are my core strengths I can leverage more?"
290
+ ],
291
+
292
+ responseStyle: {
293
+ length: 'Energetic and uplifting with concrete motivation strategies',
294
+ structure: 'Acknowledges challenges then focuses on solutions and strengths',
295
+ citations: 'References motivational psychology and success stories'
296
+ }
297
+ },
298
+
299
+ critic: {
300
+ name: 'Constructive Critic',
301
+ role: 'Academic Quality Analyst',
302
+ // Light theme colors
303
+ color: '#DC2626',
304
+ bgColor: '#FEF2F2',
305
+ // Dark theme colors
306
+ darkColor: '#F87171',
307
+ darkBgColor: '#7F1D1D',
308
+ // Icon and description
309
+ icon: Search,
310
+ description: 'Detail-oriented & Standards-focused',
311
+
312
+ fullTitle: 'Constructive Critic - Academic Quality Analyst',
313
+ credentials: 'PhD in Critical Studies from Cambridge University',
314
+ experience: 'Journal editor and dissertation examiner with expertise in scholarly rigor',
315
+
316
+ specialties: [
317
+ 'Critical Analysis & Logic Assessment',
318
+ 'Academic Writing Evaluation',
319
+ 'Research Design Critique',
320
+ 'Literature Review Quality Control',
321
+ 'Scholarly Rigor Standards',
322
+ 'Peer Review Excellence'
323
+ ],
324
+
325
+ expertise: {
326
+ primary: 'Critical Analysis & Quality Assurance',
327
+ secondary: ['Academic Standards', 'Logical Consistency', 'Evidence Evaluation'],
328
+ documentTypes: ['draft chapters', 'research proposals', 'manuscript submissions'],
329
+ strengths: [
330
+ 'Identifying logical gaps and weaknesses',
331
+ 'Ensuring methodological rigor',
332
+ 'Improving argument coherence',
333
+ 'Preparing work for peer review'
334
+ ]
335
+ },
336
+
337
+ personality: {
338
+ tone: 'Direct, honest, and constructively critical',
339
+ approach: 'Systematic analysis with specific improvement recommendations',
340
+ communicationStyle: 'Precise, detailed, standards-focused',
341
+ documentHandling: 'Thoroughly analyzes work for gaps, inconsistencies, and improvement areas'
342
+ },
343
+
344
+ sampleQuestions: [
345
+ "What are the weakest aspects of my argument?",
346
+ "Where might reviewers find fault with my methodology?",
347
+ "How can I strengthen the logic of my research design?",
348
+ "What gaps exist in my literature review?"
349
+ ],
350
+
351
+ responseStyle: {
352
+ length: 'Detailed with specific critiques and improvement suggestions',
353
+ structure: 'Systematic analysis with balanced critique and constructive guidance',
354
+ citations: 'References academic standards and best practices'
355
+ }
356
+ },
357
+
358
+ storyteller: {
359
+ name: 'Narrative Advisor',
360
+ role: 'Communication & Storytelling Expert',
361
+ // Light theme colors
362
+ color: '#6366F1',
363
+ bgColor: '#EEF2FF',
364
+ // Dark theme colors
365
+ darkColor: '#818CF8',
366
+ darkBgColor: '#3730A3',
367
+ // Icon and description
368
+ icon: Feather,
369
+ description: 'Creative & Communication-focused',
370
+
371
+ fullTitle: 'Narrative Advisor - Communication & Storytelling Expert',
372
+ credentials: 'PhD in Rhetoric and Composition from Northwestern University',
373
+ experience: 'Science communication expertise and narrative-based knowledge translation',
374
+
375
+ specialties: [
376
+ 'Narrative Structure & Storytelling',
377
+ 'Academic Communication & Translation',
378
+ 'Metaphor & Analogy Development',
379
+ 'Public Engagement & Accessibility',
380
+ 'Creative Thinking & Perspective',
381
+ 'Knowledge Synthesis Through Stories'
382
+ ],
383
+
384
+ expertise: {
385
+ primary: 'Communication & Storytelling',
386
+ secondary: ['Knowledge Translation', 'Creative Expression', 'Audience Engagement'],
387
+ documentTypes: ['presentations', 'public-facing writing', 'research narratives'],
388
+ strengths: [
389
+ 'Making complex ideas accessible',
390
+ 'Creating compelling research narratives',
391
+ 'Developing effective analogies',
392
+ 'Enhancing communication skills'
393
+ ]
394
+ },
395
+
396
+ personality: {
397
+ tone: 'Creative, engaging, and imaginatively insightful',
398
+ approach: 'Uses stories, analogies, and narratives to illuminate concepts',
399
+ communicationStyle: 'Vivid, memorable, narrative-driven',
400
+ documentHandling: 'Identifies narrative threads and helps communicate research stories'
401
+ },
402
+
403
+ sampleQuestions: [
404
+ "How can I tell the story of my research more compellingly?",
405
+ "What analogies would help explain my complex methodology?",
406
+ "How do I make my findings accessible to broader audiences?",
407
+ "What's the narrative arc of my dissertation?"
408
+ ],
409
+
410
+ responseStyle: {
411
+ length: 'Rich with stories, examples, and creative illustrations',
412
+ structure: 'Narrative-driven with memorable analogies and examples',
413
+ citations: 'References storytelling traditions and communication research'
414
+ }
415
+ },
416
+
417
+ minimalist: {
418
+ name: 'Minimalist Mentor',
419
+ role: 'Essential Focus Advisor',
420
+ // Light theme colors
421
+ color: '#6B7280',
422
+ bgColor: '#F9FAFB',
423
+ // Dark theme colors
424
+ darkColor: '#9CA3AF',
425
+ darkBgColor: '#374151',
426
+ // Icon and description
427
+ icon: Minus,
428
+ description: 'Concise & Priority-focused',
429
+
430
+ fullTitle: 'Minimalist Mentor - Essential Focus Advisor',
431
+ credentials: 'PhD in Cognitive Science from MIT',
432
+ experience: 'Systems thinking background with expertise in efficient academic progress',
433
+
434
+ specialties: [
435
+ 'Essential Thinking & Priority Identification',
436
+ 'Efficient Research Strategies',
437
+ 'Core Concept Simplification',
438
+ 'Decision-making Frameworks',
439
+ 'Focused Attention & Deep Work',
440
+ 'Academic Productivity Optimization'
441
+ ],
442
+
443
+ expertise: {
444
+ primary: 'Essential Focus & Efficiency',
445
+ secondary: ['Priority Setting', 'Simplification', 'Clear Decision-making'],
446
+ documentTypes: ['focused plans', 'priority matrices', 'streamlined processes'],
447
+ strengths: [
448
+ 'Cutting through complexity to essentials',
449
+ 'Identifying core priorities',
450
+ 'Streamlining decision-making',
451
+ 'Eliminating unnecessary elements'
452
+ ]
453
+ },
454
+
455
+ personality: {
456
+ tone: 'Concise, direct, and clarity-focused',
457
+ approach: 'Strips away complexity to reveal essential elements',
458
+ communicationStyle: 'Brief, structured, action-oriented',
459
+ documentHandling: 'Identifies core contributions and essential elements requiring focus'
460
+ },
461
+
462
+ sampleQuestions: [
463
+ "What's the one most important thing I should focus on?",
464
+ "How can I simplify my research approach?",
465
+ "What can I eliminate to improve my progress?",
466
+ "What are the essential elements of my dissertation?"
467
+ ],
468
+
469
+ responseStyle: {
470
+ length: 'Concise and to-the-point without unnecessary elaboration',
471
+ structure: 'Simple frameworks with clear, actionable guidance',
472
+ citations: 'References efficiency principles and focus methodologies'
473
+ }
474
+ },
475
+
476
+ visionary: {
477
+ name: 'Visionary Strategist',
478
+ role: 'Innovation & Future Trends Expert',
479
+ // Light theme colors
480
+ color: '#06B6D4',
481
+ bgColor: '#ECFEFF',
482
+ // Dark theme colors
483
+ darkColor: '#22D3EE',
484
+ darkBgColor: '#0E7490',
485
+ // Icon and description
486
+ icon: Eye,
487
+ description: 'Forward-thinking & Innovation-focused',
488
+
489
+ fullTitle: 'Visionary Strategist - Innovation & Future Trends Expert',
490
+ credentials: 'PhD in Futures Studies from University of Houston',
491
+ experience: 'Innovation strategy experience with expertise in transformative research directions',
492
+
493
+ specialties: [
494
+ 'Emerging Trends Analysis & Forecasting',
495
+ 'Innovation Strategy & Disruptive Thinking',
496
+ 'Interdisciplinary Connections',
497
+ 'Technology Integration & Digital Transformation',
498
+ 'Global Challenges & Systemic Solutions',
499
+ 'Transformative Research Positioning'
500
+ ],
501
+
502
+ expertise: {
503
+ primary: 'Innovation & Future Strategy',
504
+ secondary: ['Trend Analysis', 'Interdisciplinary Thinking', 'Impact Maximization'],
505
+ documentTypes: ['innovation proposals', 'future scenarios', 'strategic plans'],
506
+ strengths: [
507
+ 'Identifying emerging opportunities',
508
+ 'Connecting disparate fields',
509
+ 'Anticipating future developments',
510
+ 'Maximizing transformative potential'
511
+ ]
512
+ },
513
+
514
+ personality: {
515
+ tone: 'Inspiring, ambitious, and forward-looking',
516
+ approach: 'Encourages bold thinking and explores future possibilities',
517
+ communicationStyle: 'Visionary, expansive, possibility-oriented',
518
+ documentHandling: 'Identifies innovative potential and connects to future trends'
519
+ },
520
+
521
+ sampleQuestions: [
522
+ "How might my research transform the field in 10 years?",
523
+ "What emerging trends should influence my research direction?",
524
+ "How can I position my work for maximum future impact?",
525
+ "What innovative approaches haven't been tried yet?"
526
+ ],
527
+
528
+ responseStyle: {
529
+ length: 'Expansive with big-picture thinking and future scenarios',
530
+ structure: 'Explores possibilities and connects to broader trends',
531
+ citations: 'References innovation research and future studies'
532
+ }
533
+ },
534
+
535
+ empathetic: {
536
+ name: 'Empathetic Listener',
537
+ role: 'Well-being & Support Specialist',
538
+ // Light theme colors
539
+ color: '#EC4899',
540
+ bgColor: '#FDF2F8',
541
+ // Dark theme colors
542
+ darkColor: '#F472B6',
543
+ darkBgColor: '#BE185D',
544
+ // Icon and description
545
+ icon: Heart,
546
+ description: 'Caring & Emotionally supportive',
547
+
548
+ fullTitle: 'Empathetic Listener - Well-being & Support Specialist',
549
+ credentials: 'PhD in Clinical Psychology from Yale University',
550
+ experience: 'Academic counseling specialization with expertise in student well-being',
551
+
552
+ specialties: [
553
+ 'Academic Stress Management & Well-being',
554
+ 'Work-life Balance & Self-care',
555
+ 'Mental Health Awareness & Support',
556
+ 'Interpersonal Relationships in Academia',
557
+ 'Identity Development & Personal Growth',
558
+ 'Mindfulness & Stress Reduction'
559
+ ],
560
+
561
+ expertise: {
562
+ primary: 'Emotional Support & Well-being',
563
+ secondary: ['Stress Management', 'Self-care', 'Personal Development'],
564
+ documentTypes: ['reflection journals', 'well-being plans', 'personal statements'],
565
+ strengths: [
566
+ 'Providing emotional validation',
567
+ 'Supporting work-life balance',
568
+ 'Addressing mental health concerns',
569
+ 'Fostering personal growth'
570
+ ]
571
+ },
572
+
573
+ personality: {
574
+ tone: 'Warm, compassionate, and genuinely caring',
575
+ approach: 'Validates emotions and provides holistic support',
576
+ communicationStyle: 'Gentle, understanding, person-centered',
577
+ documentHandling: 'Recognizes emotional labor and provides supportive validation'
578
+ },
579
+
580
+ sampleQuestions: [
581
+ "How can I manage PhD stress and maintain well-being?",
582
+ "How do I deal with feelings of isolation in research?",
583
+ "What strategies help with academic anxiety?",
584
+ "How can I maintain healthy boundaries during my PhD?"
585
+ ],
586
+
587
+ responseStyle: {
588
+ length: 'Supportive and validating with emphasis on emotional well-being',
589
+ structure: 'Acknowledges emotions first, then provides gentle guidance',
590
+ citations: 'References well-being research and self-care practices'
591
+ }
592
  }
593
  };
594
 
 
602
  bgColor: isDark ? advisor.darkBgColor : advisor.bgColor,
603
  // For text that needs to be readable on colored backgrounds
604
  textColor: isDark ? '#F9FAFB' :
605
+ advisor.color === '#10B981' ? '#047857' :
606
+ advisor.color === '#3B82F6' ? '#1D4ED8' :
607
+ advisor.color === '#8B5CF6' ? '#7C3AED' :
608
+ advisor.color === '#F59E0B' ? '#92400E' :
609
+ advisor.color === '#EF4444' ? '#DC2626' :
610
+ advisor.color === '#DC2626' ? '#7F1D1D' :
611
+ advisor.color === '#6366F1' ? '#3730A3' :
612
+ advisor.color === '#6B7280' ? '#374151' :
613
+ advisor.color === '#06B6D4' ? '#0E7490' :
614
+ advisor.color === '#EC4899' ? '#BE185D' :
615
  '#374151' // fallback
616
  };
617
  };
phd-advisor-frontend/src/pages/ChatPage.js CHANGED
@@ -1,5 +1,5 @@
1
  import React, { useState, useEffect, useRef } from 'react';
2
- import { Home, MessageCircle, Reply, X, Sparkles, Users, Settings2, FileText } from 'lucide-react';
3
  import EnhancedChatInput from '../components/EnhancedChatInput';
4
  import MessageBubble from '../components/MessageBubble';
5
  import ThinkingIndicator from '../components/ThinkingIndicator';
@@ -7,12 +7,14 @@ import SuggestionsPanel from '../components/SuggestionsPanel';
7
  import ThemeToggle from '../components/ThemeToggle';
8
  import ProviderDropdown from '../components/ProviderDropdown';
9
  import ExportButton from '../components/ExportButton';
 
10
  import { advisors, getAdvisorColors } from '../data/advisors';
11
  import { useTheme } from '../contexts/ThemeContext';
12
  import '../styles/ChatPage.css';
13
  import '../styles/EnhancedChatInput.css';
 
14
 
15
- const ChatPage = ({ onNavigateToHome }) => {
16
  const [messages, setMessages] = useState([]);
17
  const [isLoading, setIsLoading] = useState(false);
18
  const [thinkingAdvisors, setThinkingAdvisors] = useState([]);
@@ -24,10 +26,22 @@ const ChatPage = ({ onNavigateToHome }) => {
24
  const messagesEndRef = useRef(null);
25
  const { isDark } = useTheme();
26
 
 
 
 
 
 
 
 
 
27
  const scrollToBottom = () => {
28
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
29
  };
30
 
 
 
 
 
31
  useEffect(() => {
32
  scrollToBottom();
33
  }, [messages, thinkingAdvisors]);
@@ -49,6 +63,8 @@ const ChatPage = ({ onNavigateToHome }) => {
49
  }
50
  };
51
 
 
 
52
  const handleProviderSwitch = async (newProvider) => {
53
  if (newProvider === currentProvider || isProviderSwitching) return;
54
 
@@ -104,178 +120,429 @@ const ChatPage = ({ onNavigateToHome }) => {
104
  return Date.now().toString() + Math.random().toString(36).substr(2, 9);
105
  };
106
 
107
- const handleFileUploaded = (file, response) => {
108
- // Add the uploaded document to our list
109
- const docInfo = {
110
- id: generateMessageId(),
111
- name: file.name,
112
- size: file.size,
113
- type: file.type,
114
- uploadTime: new Date()
115
- };
116
- setUploadedDocuments(prev => [...prev, docInfo]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- // Add a system message about the upload
119
- const uploadMessage = {
 
 
 
120
  id: generateMessageId(),
121
  type: 'document_upload',
122
- content: `Successfully uploaded "${file.name}". Your advisors can now reference this document in their responses.`,
123
- timestamp: new Date(),
124
- documentInfo: docInfo
125
  };
126
 
127
- // Force update messages state
128
- setMessages(prev => {
129
- const newMessages = [...prev, uploadMessage];
130
- console.log('Added upload message:', uploadMessage); // Debug log
131
- return newMessages;
 
 
 
 
132
  });
133
-
134
- // Scroll to bottom to show the new message
135
- setTimeout(() => {
136
- scrollToBottom();
137
- }, 100);
138
  };
139
 
 
140
  const handleSendMessage = async (inputMessage) => {
141
- if (replyingTo) {
142
- await handleReplyToAdvisor(inputMessage, replyingTo);
143
- return;
144
- }
145
 
146
- // Add user message
147
  const userMessage = {
148
  id: generateMessageId(),
149
  type: 'user',
150
  content: inputMessage,
151
  timestamp: new Date()
152
  };
 
 
153
  setMessages(prev => [...prev, userMessage]);
154
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  setIsLoading(true);
156
- // Show thinking indicators for all advisors (backend will decide which ones respond)
157
- setThinkingAdvisors(['methodologist', 'theorist', 'pragmatist']);
158
 
159
  try {
 
 
 
 
 
 
 
 
160
  const response = await fetch('http://localhost:8000/chat-sequential', {
161
  method: 'POST',
162
- headers: {
163
- 'Content-Type': 'application/json',
164
- },
165
  body: JSON.stringify({
166
- user_input: inputMessage
 
 
167
  }),
168
  });
169
 
170
  if (!response.ok) {
171
- throw new Error(`HTTP error! Status: ${response.status}`);
172
  }
173
 
 
174
  const data = await response.json();
175
- console.log('Backend response:', data);
176
-
177
- if (data.type === 'sequential_responses' && data.responses) {
178
- // Simply map each advisor response in the order backend provides
179
- const advisorMessages = data.responses.map((advisor) => ({
180
  id: generateMessageId(),
181
  type: 'advisor',
182
- advisorId: advisor.persona_id,
183
- advisorName: advisor.persona,
184
- content: advisor.response,
185
- timestamp: new Date()
 
 
186
  }));
187
 
188
- setMessages(prev => [...prev, ...advisorMessages]);
189
-
190
- } else if (data.type === 'error') {
191
- const errorMessage = {
192
- id: generateMessageId(),
193
- type: 'error',
194
- content: data.responses?.[0]?.response || 'An error occurred. Please try again.',
195
- timestamp: new Date()
196
- };
197
- setMessages(prev => [...prev, errorMessage]);
 
198
  }
199
 
200
  } catch (error) {
201
  console.error('Error sending message:', error);
202
- const errorMessage = {
203
  id: generateMessageId(),
204
  type: 'error',
205
- content: 'Sorry, I encountered an error. Please try again.',
206
  timestamp: new Date()
207
- };
208
- setMessages(prev => [...prev, errorMessage]);
 
 
209
  }
210
-
211
- setIsLoading(false);
212
- setThinkingAdvisors([]);
213
- setReplyingTo(null);
214
  };
215
 
216
  const handleReplyToAdvisor = async (inputMessage, replyContext) => {
217
- const replyMessage = {
218
- id: generateMessageId(),
219
- type: 'user',
220
- content: inputMessage,
221
- replyTo: {
222
- advisorId: replyContext.advisorId,
223
- advisorName: replyContext.advisorName,
224
- messageId: replyContext.messageId
225
- },
226
- timestamp: new Date()
227
- };
228
- setMessages(prev => [...prev, replyMessage]);
229
-
230
- setIsLoading(true);
231
- setThinkingAdvisors([replyContext.advisorId]);
 
 
 
 
 
 
232
 
233
- try {
234
- const response = await fetch('http://localhost:8000/reply-to-advisor', {
235
- method: 'POST',
236
- headers: {
237
- 'Content-Type': 'application/json',
238
- },
239
- body: JSON.stringify({
240
- user_input: inputMessage,
241
- advisor_id: replyContext.advisorId,
242
- original_message_id: replyContext.messageId
243
- }),
244
- });
 
 
 
 
 
 
 
 
 
245
 
246
- if (!response.ok) {
247
- throw new Error(`HTTP error! Status: ${response.status}`);
248
- }
249
 
250
- const data = await response.json();
251
 
252
- if (data.type === 'advisor_reply') {
253
- const replyResponseMessage = {
254
- id: generateMessageId(),
255
- type: 'advisor',
256
- advisorId: data.persona_id,
257
- advisorName: data.persona,
258
- content: data.response,
259
- isReply: true,
260
- timestamp: new Date()
261
- };
262
- setMessages(prev => [...prev, replyResponseMessage]);
263
- }
264
-
265
- } catch (error) {
266
- console.error('Error replying to advisor:', error);
267
- const errorMessage = {
268
  id: generateMessageId(),
269
- type: 'error',
270
- content: 'Sorry, I encountered an error with your reply. Please try again.',
 
 
 
271
  timestamp: new Date()
272
  };
273
- setMessages(prev => [...prev, errorMessage]);
 
 
 
274
  }
275
 
276
- setIsLoading(false);
277
- setThinkingAdvisors([]);
278
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
  const handleCopyMessage = (messageId, content) => {
281
  // Optional: Show a toast notification or add to message history
@@ -301,6 +568,9 @@ const ChatPage = ({ onNavigateToHome }) => {
301
  };
302
  setMessages(prev => [...prev, expandMessage]);
303
 
 
 
 
304
  setIsLoading(true);
305
  setThinkingAdvisors([advisorId]);
306
 
@@ -322,24 +592,21 @@ const ChatPage = ({ onNavigateToHome }) => {
322
 
323
  const data = await response.json();
324
 
325
- // Clean response handling without RAG metadata
326
- let expandedMessage = null;
327
-
328
  if (data.persona && data.response) {
329
- expandedMessage = {
330
  id: generateMessageId(),
331
  type: 'advisor',
332
- advisorId: advisorId,
333
  advisorName: advisor.name,
334
  content: data.response,
335
  isExpansion: true,
336
  expandsMessageId: messageId,
337
  timestamp: new Date()
338
  };
339
- }
340
-
341
- if (expandedMessage) {
342
  setMessages(prev => [...prev, expandedMessage]);
 
 
 
343
  } else {
344
  const errorMessage = {
345
  id: generateMessageId(),
@@ -348,6 +615,9 @@ const ChatPage = ({ onNavigateToHome }) => {
348
  timestamp: new Date()
349
  };
350
  setMessages(prev => [...prev, errorMessage]);
 
 
 
351
  }
352
 
353
  } catch (error) {
@@ -355,10 +625,13 @@ const ChatPage = ({ onNavigateToHome }) => {
355
  const errorMessage = {
356
  id: generateMessageId(),
357
  type: 'error',
358
- content: 'Sorry, I encountered an error expanding the response. Please try again.',
359
  timestamp: new Date()
360
  };
361
  setMessages(prev => [...prev, errorMessage]);
 
 
 
362
  }
363
 
364
  setIsLoading(false);
@@ -366,211 +639,292 @@ const ChatPage = ({ onNavigateToHome }) => {
366
  };
367
 
368
  const handleReplyToMessage = (message) => {
369
- const advisor = advisors[message.advisorId];
370
  setReplyingTo({
371
- advisorId: message.advisorId,
372
  messageId: message.id,
373
- advisorName: advisor.name
 
374
  });
375
  };
376
 
377
  const handleMessageClick = (message) => {
378
  if (message.type === 'advisor') {
379
- const advisor = advisors[message.advisorId];
380
  setReplyingTo({
381
- advisorId: message.advisorId,
382
  messageId: message.id,
383
- advisorName: advisor.name
 
384
  });
385
  }
386
  };
387
 
 
 
 
 
 
 
 
 
 
 
388
  const cancelReply = () => {
389
  setReplyingTo(null);
390
  };
391
 
 
 
 
 
 
 
392
  const hasMessages = messages.length > 0;
393
  const hasConversationMessages = messages.filter(m => m.type !== 'system' && m.type !== 'document_upload').length > 0;
394
 
395
  return (
396
- <div className="modern-chat-page">
397
- {/* Floating Header */}
398
- <div className="floating-header">
399
- <div className="header-left">
400
- <button onClick={onNavigateToHome} className="modern-home-btn">
401
- <Home size={20} />
402
- </button>
403
- <div className="header-brand">
404
- <div className="brand-icon">
405
- <Users size={24} />
406
- </div>
407
- <div className="brand-text">
408
- <h1>PhD Advisory</h1>
409
- <p>AI-Powered Academic Guidance</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  </div>
411
- </div>
412
- </div>
413
-
414
- <div className="header-right">
415
- <div className="advisor-pills">
416
- {Object.entries(advisors).map(([id, advisor]) => {
417
- const Icon = advisor.icon;
418
- const colors = getAdvisorColors(id, isDark);
419
- const isThinking = thinkingAdvisors.includes(id);
420
 
421
- return (
422
- <div
423
- key={id}
424
- className={`advisor-pill ${isThinking ? 'thinking' : ''}`}
425
- style={{
426
- '--advisor-color': colors.color,
427
- '--advisor-bg': colors.bgColor
428
- }}
429
- title={`${advisor.name} - ${advisor.expertise}`}
 
 
 
 
430
  >
431
- <Icon size={16} />
432
- <span>{advisor.name}</span>
433
- {isThinking && (
434
- <div className="thinking-dots">
435
- <div className="dot"></div>
436
- <div className="dot"></div>
437
- <div className="dot"></div>
438
- </div>
439
- )}
440
- </div>
441
- );
442
- })}
443
- </div>
444
-
445
- <div className="header-controls">
446
- {/* Export Button */}
447
- <ExportButton hasMessages={hasConversationMessages} />
448
-
449
- {/* Provider Dropdown */}
450
- <ProviderDropdown
451
- currentProvider={currentProvider}
452
- onProviderChange={handleProviderSwitch}
453
- isLoading={isProviderSwitching}
454
- />
455
-
456
- {/* Theme Toggle */}
457
- <ThemeToggle />
458
  </div>
459
- </div>
460
- </div>
461
 
462
- {/* Main Content */}
463
- <div className="chat-content">
464
- {!hasMessages ? (
465
- <SuggestionsPanel onSuggestionClick={handleSendMessage} />
466
- ) : (
467
- <div className="messages-container">
468
- <div className="messages-list">
469
- <div className="messages-scroll">
470
- {messages.map((message) => (
471
- <div key={message.id}>
472
- {message.type === 'user' && (
473
- <div className="user-message-container">
474
- <div className="user-message">
475
- {message.replyTo && (
476
- <div className="reply-indicator">
477
- <Reply size={12} />
478
- <span>Reply to {message.replyTo.advisorName}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  </div>
480
- )}
481
- <p>{message.content}</p>
482
- </div>
483
- </div>
484
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
 
486
- {message.type === 'advisor' && (
487
- <MessageBubble
488
- message={message}
489
- onReply={handleReplyToMessage}
490
- onExpand={handleExpandMessage}
491
- onClick={handleMessageClick}
492
- showReplyButton={true}
493
- />
494
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
 
496
- {message.type === 'error' && (
497
- <div className="error-message-container">
498
- <div className="error-message">
499
- <p>{message.content}</p>
500
- </div>
501
  </div>
502
- )}
503
 
504
- {message.type === 'system' && (
505
- <div className="system-message-container">
506
- <div className="system-message">
507
- <p>{message.content}</p>
508
  </div>
509
- </div>
510
- )}
511
-
512
- {message.type === 'document_upload' && (
513
- <div className="system-message-container">
514
- <div className="system-message document-upload">
515
- <FileText size={16} />
516
- <p>{message.content}</p>
517
  </div>
518
  </div>
519
  )}
520
- </div>
521
- ))}
522
-
523
- {thinkingAdvisors.includes('system') && (
524
- <div className="orchestrator-thinking">
525
- <div className="thinking-bubble">
526
- <MessageCircle size={20} />
527
- </div>
528
- <div className="thinking-content">
529
- <span className="thinking-label">Orchestrator is thinking...</span>
530
- <div className="thinking-animation">
531
- <div className="dot"></div>
532
- <div className="dot"></div>
533
- <div className="dot"></div>
534
- </div>
535
- </div>
536
- </div>
537
- )}
538
-
539
- {thinkingAdvisors.filter(id => id !== 'system').map(advisorId => (
540
- <ThinkingIndicator key={advisorId} advisorId={advisorId} />
541
- ))}
542
 
543
- <div ref={messagesEndRef} />
 
 
544
  </div>
545
- </div>
546
  </div>
547
- )}
548
- </div>
549
 
550
- <div className="floating-input-area">
551
- {replyingTo && (
552
- <div className="reply-banner">
553
- <div className="reply-info">
554
- <Reply size={16} />
555
- <span>Replying to <strong>{replyingTo.advisorName}</strong></span>
556
- </div>
557
- <button onClick={cancelReply} className="cancel-reply">
558
- <X size={16} />
559
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560
  </div>
561
- )}
562
-
563
- <EnhancedChatInput
564
- onSendMessage={handleSendMessage}
565
- onFileUploaded={handleFileUploaded}
566
- uploadedDocuments={uploadedDocuments}
567
- isLoading={isLoading}
568
- placeholder={
569
- replyingTo
570
- ? `Reply to ${replyingTo.advisorName}...`
571
- : "Ask your advisors anything about your PhD journey..."
572
- }
573
- />
574
  </div>
575
  </div>
576
  );
 
1
  import React, { useState, useEffect, useRef } from 'react';
2
+ import { Home, MessageCircle, Reply, X, Sparkles, Users, Settings2, FileText , LogOut, Menu} from 'lucide-react';
3
  import EnhancedChatInput from '../components/EnhancedChatInput';
4
  import MessageBubble from '../components/MessageBubble';
5
  import ThinkingIndicator from '../components/ThinkingIndicator';
 
7
  import ThemeToggle from '../components/ThemeToggle';
8
  import ProviderDropdown from '../components/ProviderDropdown';
9
  import ExportButton from '../components/ExportButton';
10
+ import Sidebar from '../components/Sidebar';
11
  import { advisors, getAdvisorColors } from '../data/advisors';
12
  import { useTheme } from '../contexts/ThemeContext';
13
  import '../styles/ChatPage.css';
14
  import '../styles/EnhancedChatInput.css';
15
+ import AdvisorStatusDropdown from '../components/AdvisorStatusDropdown';
16
 
17
+ const ChatPage = ({ user, authToken, onNavigateToHome, onSignOut }) => {
18
  const [messages, setMessages] = useState([]);
19
  const [isLoading, setIsLoading] = useState(false);
20
  const [thinkingAdvisors, setThinkingAdvisors] = useState([]);
 
26
  const messagesEndRef = useRef(null);
27
  const { isDark } = useTheme();
28
 
29
+ const [currentSessionId, setCurrentSessionId] = useState(null);
30
+ const [currentSessionTitle, setCurrentSessionTitle] = useState('');
31
+ const [isSavingSession, setIsSavingSession] = useState(false);
32
+ const [isLoadingSession, setIsLoadingSession] = useState(false);
33
+ const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
34
+
35
+
36
+
37
  const scrollToBottom = () => {
38
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
39
  };
40
 
41
+ const handleMobileMenuToggle = () => {
42
+ setIsMobileMenuOpen(!isMobileMenuOpen);
43
+ };
44
+
45
  useEffect(() => {
46
  scrollToBottom();
47
  }, [messages, thinkingAdvisors]);
 
63
  }
64
  };
65
 
66
+
67
+
68
  const handleProviderSwitch = async (newProvider) => {
69
  if (newProvider === currentProvider || isProviderSwitching) return;
70
 
 
120
  return Date.now().toString() + Math.random().toString(36).substr(2, 9);
121
  };
122
 
123
+ const createNewSession = async (firstMessage = null) => {
124
+ try {
125
+ const title = firstMessage
126
+ ? `${firstMessage.substring(0, 30)}...`
127
+ : `Chat ${new Date().toLocaleDateString()}`;
128
+
129
+ const response = await fetch('http://localhost:8000/api/chat-sessions', {
130
+ method: 'POST',
131
+ headers: {
132
+ 'Authorization': `Bearer ${authToken}`,
133
+ 'Content-Type': 'application/json'
134
+ },
135
+ body: JSON.stringify({ title })
136
+ });
137
+
138
+ if (response.ok) {
139
+ const newSession = await response.json();
140
+
141
+ // Update state immediately
142
+ setCurrentSessionId(newSession.id);
143
+ setCurrentSessionTitle(newSession.title);
144
+
145
+ console.log('MongoDB session created:', newSession.id);
146
+ return newSession.id;
147
+ } else {
148
+ console.error('Failed to create new session');
149
+ return null;
150
+ }
151
+ } catch (error) {
152
+ console.error('Error creating new session:', error);
153
+ return null;
154
+ }
155
+ };
156
+
157
+
158
+ // Load an existing chat session
159
+ const loadChatSession = async (sessionId) => {
160
+ if (!sessionId || isLoadingSession) return;
161
+ setIsLoadingSession(true);
162
+ try {
163
+ // Use the new switch-chat endpoint that syncs context
164
+ const response = await fetch('http://localhost:8000/switch-chat', {
165
+ method: 'POST',
166
+ headers: {
167
+ 'Authorization': `Bearer ${authToken}`,
168
+ 'Content-Type': 'application/json'
169
+ },
170
+ body: JSON.stringify({
171
+ chat_session_id: sessionId
172
+ })
173
+ });
174
+
175
+ if (response.ok) {
176
+ const result = await response.json();
177
+ if (result.status === 'success') {
178
+ setCurrentSessionId(sessionId);
179
+ setCurrentSessionTitle(''); // Will be set from MongoDB data
180
+
181
+ // Load the messages from the synced context
182
+ const formattedMessages = result.context.messages.map(msg => ({
183
+ ...msg,
184
+ timestamp: new Date(msg.timestamp),
185
+ persona_id: msg.persona_id || msg.advisor || msg.advisorId
186
+ }));
187
+
188
+ setMessages(formattedMessages);
189
+ setReplyingTo(null);
190
+ setThinkingAdvisors([]);
191
+
192
+ // Also get the session title from MongoDB
193
+ const sessionResponse = await fetch(`http://localhost:8000/api/chat-sessions/${sessionId}`, {
194
+ headers: {
195
+ 'Authorization': `Bearer ${authToken}`,
196
+ 'Content-Type': 'application/json'
197
+ }
198
+ });
199
+ if (sessionResponse.ok) {
200
+ const sessionData = await sessionResponse.json();
201
+ setCurrentSessionTitle(sessionData.title);
202
+ }
203
+ }
204
+ }
205
+ } catch (error) {
206
+ console.error('Error loading session:', error);
207
+ } finally {
208
+ setIsLoadingSession(false);
209
+ }
210
+ };
211
+
212
+ // Save a message to the current session
213
+ const saveMessageToSession = async (message) => {
214
+ if (!currentSessionId || !authToken) return;
215
+
216
+ try {
217
+ await fetch(`http://localhost:8000/api/chat-sessions/${currentSessionId}/messages`, {
218
+ method: 'POST',
219
+ headers: {
220
+ 'Authorization': `Bearer ${authToken}`,
221
+ 'Content-Type': 'application/json'
222
+ },
223
+ body: JSON.stringify({
224
+ session_id: currentSessionId,
225
+ message: {
226
+ ...message,
227
+ timestamp: message.timestamp.toISOString()
228
+ }
229
+ })
230
+ });
231
+ } catch (error) {
232
+ console.error('Error saving message to session:', error);
233
+ }
234
+ };
235
+
236
+ // Update session title based on first message
237
+ const updateSessionTitle = async (sessionId, newTitle) => {
238
+ if (!sessionId || !authToken) return;
239
+
240
+ try {
241
+ await fetch(`http://localhost:8000/api/chat-sessions/${sessionId}`, {
242
+ method: 'PUT',
243
+ headers: {
244
+ 'Authorization': `Bearer ${authToken}`,
245
+ 'Content-Type': 'application/json'
246
+ },
247
+ body: JSON.stringify({ title: newTitle })
248
+ });
249
+ setCurrentSessionTitle(newTitle);
250
+ } catch (error) {
251
+ console.error('Error updating session title:', error);
252
+ }
253
+ };
254
+
255
+ // Handle selecting a session from sidebar
256
+ const handleSelectSession = async (sessionId) => {
257
+ if (sessionId === currentSessionId) return;
258
+ await loadChatSession(sessionId);
259
+ };
260
+
261
+ // Handle creating new chat from sidebar
262
+ const handleNewChat = async (sessionId = null) => {
263
+ if (sessionId) {
264
+ // Loading existing session
265
+ await loadChatSession(sessionId);
266
+ return; // Return early for existing session loading
267
+ } else {
268
+ // Creating completely new chat with fresh context
269
+ try {
270
+ // Step 1: Reset memory session
271
+ const response = await fetch('http://localhost:8000/new-chat', {
272
+ method: 'POST',
273
+ headers: {
274
+ 'Authorization': `Bearer ${authToken}`,
275
+ 'Content-Type': 'application/json'
276
+ },
277
+ body: JSON.stringify({
278
+ title: `Chat ${new Date().toLocaleDateString()}`
279
+ })
280
+ });
281
+
282
+ if (response.ok) {
283
+ const result = await response.json();
284
+ if (result.status === 'success') {
285
+ // Step 2: Immediately create MongoDB session
286
+ const newSessionId = await createNewSession(`Chat ${new Date().toLocaleDateString()}`);
287
+
288
+ if (newSessionId) {
289
+ // Reset all state to fresh with the new session
290
+ setMessages([]);
291
+ setCurrentSessionId(newSessionId); // Set the new session ID immediately
292
+ setCurrentSessionTitle(`Chat ${new Date().toLocaleDateString()}`);
293
+ setReplyingTo(null);
294
+ setThinkingAdvisors([]);
295
+ setUploadedDocuments([]);
296
+
297
+ console.log('New chat created with MongoDB session:', newSessionId);
298
+
299
+ // Wait a bit to ensure state has updated
300
+ await new Promise(resolve => setTimeout(resolve, 100));
301
+ return newSessionId; // Return the session ID for the sidebar
302
+ } else {
303
+ throw new Error('Failed to create MongoDB session');
304
+ }
305
+ } else {
306
+ throw new Error('Failed to create memory session');
307
+ }
308
+ } else {
309
+ throw new Error(`HTTP error: ${response.status}`);
310
+ }
311
+ } catch (error) {
312
+ console.error('Error creating new chat:', error);
313
+
314
+ // Fallback to local reset
315
+ setMessages([]);
316
+ setCurrentSessionId(null);
317
+ setCurrentSessionTitle('');
318
+ setReplyingTo(null);
319
+ setThinkingAdvisors([]);
320
+ setUploadedDocuments([]);
321
+
322
+ // Re-throw the error so the sidebar knows something went wrong
323
+ throw error;
324
+ }
325
+ }
326
+ };
327
 
328
+
329
+
330
+ const handleFileUploaded = async (file, uploadResult) => {
331
+ // FIXED: Use the upload result data for better messaging
332
+ const documentMessage = {
333
  id: generateMessageId(),
334
  type: 'document_upload',
335
+ content: `Document uploaded: ${uploadResult.filename || file.name} (${uploadResult.chunks_created || 0} sections processed)`,
336
+ timestamp: new Date()
 
337
  };
338
 
339
+ setMessages(prev => [...prev, documentMessage]);
340
+ setUploadedDocuments(prev => [...prev, file]);
341
+
342
+ // FIXED: Log document access info
343
+ console.log('File uploaded to session:', {
344
+ filename: uploadResult.filename,
345
+ session_id: uploadResult.session_id,
346
+ chat_session_id: uploadResult.chat_session_id,
347
+ current_session_id: currentSessionId
348
  });
349
+
350
+ // Save document upload message to database if we have a current session
351
+ if (currentSessionId) {
352
+ await saveMessageToSession(documentMessage);
353
+ }
354
  };
355
 
356
+
357
  const handleSendMessage = async (inputMessage) => {
358
+ if (!inputMessage.trim()) return;
 
 
 
359
 
360
+ // Create user message
361
  const userMessage = {
362
  id: generateMessageId(),
363
  type: 'user',
364
  content: inputMessage,
365
  timestamp: new Date()
366
  };
367
+
368
+ // Add to local state immediately
369
  setMessages(prev => [...prev, userMessage]);
370
+
371
+ // Create new session if we don't have one
372
+ let sessionId = currentSessionId;
373
+ if (!sessionId) {
374
+ sessionId = await createNewSession(inputMessage);
375
+ if (!sessionId) {
376
+ console.error('Failed to create session');
377
+ return;
378
+ }
379
+ }
380
+
381
+ // Save user message to database
382
+ await saveMessageToSession(userMessage);
383
+
384
+ // Update session title if this is the first message and title is generic
385
+ if (messages.length === 0 && currentSessionTitle.includes('Chat ')) {
386
+ const newTitle = inputMessage.length > 30
387
+ ? `${inputMessage.substring(0, 30)}...`
388
+ : inputMessage;
389
+ await updateSessionTitle(sessionId, newTitle);
390
+ }
391
+
392
+ // Set loading state
393
  setIsLoading(true);
394
+ setThinkingAdvisors(['system']);
 
395
 
396
  try {
397
+ const headers = {
398
+ 'Content-Type': 'application/json',
399
+ 'Authorization': `Bearer ${authToken}`,
400
+ };
401
+
402
+
403
+ console.log('Sending message with session ID:', currentSessionId); // Debug log
404
+
405
  const response = await fetch('http://localhost:8000/chat-sequential', {
406
  method: 'POST',
407
+ headers: headers,
 
 
408
  body: JSON.stringify({
409
+ user_input: inputMessage,
410
+ response_length: 'medium',
411
+ chat_session_id: currentSessionId // Include current session ID
412
  }),
413
  });
414
 
415
  if (!response.ok) {
416
+ throw new Error(`HTTP error! status: ${response.status}`);
417
  }
418
 
419
+ // Rest of the function remains the same...
420
  const data = await response.json();
421
+
422
+ // Process responses...
423
+ if (data.responses && Array.isArray(data.responses)) {
424
+ const newResponses = data.responses.map(response => ({
 
425
  id: generateMessageId(),
426
  type: 'advisor',
427
+ persona_id: response.persona_id,
428
+ content: response.content,
429
+ timestamp: new Date(),
430
+ advisorName: response.persona_name || response.persona_id,
431
+ used_documents: response.used_documents || false,
432
+ document_chunks_used: response.document_chunks_used || 0
433
  }));
434
 
435
+ setMessages(prev => [...prev, ...newResponses]);
436
+
437
+ // Save advisor responses to database
438
+ for (const response of newResponses) {
439
+ await saveMessageToSession(response);
440
+ }
441
+
442
+ // Log session debug info if available
443
+ if (data.session_debug) {
444
+ console.log('Session debug info:', data.session_debug);
445
+ }
446
  }
447
 
448
  } catch (error) {
449
  console.error('Error sending message:', error);
450
+ setMessages(prev => [...prev, {
451
  id: generateMessageId(),
452
  type: 'error',
453
+ content: `Failed to send message: ${error.message}`,
454
  timestamp: new Date()
455
+ }]);
456
+ } finally {
457
+ setIsLoading(false);
458
+ setThinkingAdvisors([]);
459
  }
 
 
 
 
460
  };
461
 
462
  const handleReplyToAdvisor = async (inputMessage, replyContext) => {
463
+ // Ensure we have a session before proceeding
464
+ let sessionId = currentSessionId;
465
+ if (!sessionId) {
466
+ sessionId = await createNewSession(inputMessage);
467
+ if (!sessionId) {
468
+ console.error('Failed to create session for reply');
469
+ return;
470
+ }
471
+ }
472
+
473
+ const replyMessage = {
474
+ id: generateMessageId(),
475
+ type: 'user',
476
+ content: inputMessage,
477
+ replyTo: {
478
+ advisorId: replyContext.persona_id,
479
+ advisorName: replyContext.advisorName,
480
+ messageId: replyContext.messageId
481
+ },
482
+ timestamp: new Date()
483
+ };
484
 
485
+ setMessages(prev => [...prev, replyMessage]);
486
+
487
+ // Save reply message to database with explicit session ID
488
+ await saveMessageToSession(replyMessage, sessionId);
489
+
490
+ setIsLoading(true);
491
+ setThinkingAdvisors([replyContext.persona_id]);
492
+
493
+ try {
494
+ const response = await fetch('http://localhost:8000/reply-to-advisor', {
495
+ method: 'POST',
496
+ headers: {
497
+ 'Content-Type': 'application/json',
498
+ },
499
+ body: JSON.stringify({
500
+ user_input: inputMessage,
501
+ advisor_id: replyContext.advisorId,
502
+ original_message_id: replyContext.messageId,
503
+ chat_session_id: sessionId // Use confirmed session ID
504
+ }),
505
+ });
506
 
507
+ if (!response.ok) {
508
+ throw new Error(`HTTP error! Status: ${response.status}`);
509
+ }
510
 
511
+ const data = await response.json();
512
 
513
+ if (data.type === 'advisor_reply') {
514
+ const replyResponseMessage = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  id: generateMessageId(),
516
+ type: 'advisor',
517
+ persona_id: data.persona_id,
518
+ advisorName: data.persona,
519
+ content: data.response,
520
+ isReply: true,
521
  timestamp: new Date()
522
  };
523
+ setMessages(prev => [...prev, replyResponseMessage]);
524
+
525
+ // Save advisor reply to database
526
+ await saveMessageToSession(replyResponseMessage, sessionId);
527
  }
528
 
529
+ } catch (error) {
530
+ console.error('Error replying to advisor:', error);
531
+ const errorMessage = {
532
+ id: generateMessageId(),
533
+ type: 'error',
534
+ content: 'Sorry, I encountered an error with your reply. Please try again.',
535
+ timestamp: new Date()
536
+ };
537
+ setMessages(prev => [...prev, errorMessage]);
538
+
539
+ // Save error message to database
540
+ await saveMessageToSession(errorMessage, sessionId);
541
+ }
542
+
543
+ setIsLoading(false);
544
+ setThinkingAdvisors([]);
545
+ };
546
 
547
  const handleCopyMessage = (messageId, content) => {
548
  // Optional: Show a toast notification or add to message history
 
568
  };
569
  setMessages(prev => [...prev, expandMessage]);
570
 
571
+ // Save expand request to database
572
+ await saveMessageToSession(expandMessage);
573
+
574
  setIsLoading(true);
575
  setThinkingAdvisors([advisorId]);
576
 
 
592
 
593
  const data = await response.json();
594
 
 
 
 
595
  if (data.persona && data.response) {
596
+ const expandedMessage = {
597
  id: generateMessageId(),
598
  type: 'advisor',
599
+ persona_id: advisorId,
600
  advisorName: advisor.name,
601
  content: data.response,
602
  isExpansion: true,
603
  expandsMessageId: messageId,
604
  timestamp: new Date()
605
  };
 
 
 
606
  setMessages(prev => [...prev, expandedMessage]);
607
+
608
+ // Save expanded response to database
609
+ await saveMessageToSession(expandedMessage);
610
  } else {
611
  const errorMessage = {
612
  id: generateMessageId(),
 
615
  timestamp: new Date()
616
  };
617
  setMessages(prev => [...prev, errorMessage]);
618
+
619
+ // Save error message to database
620
+ await saveMessageToSession(errorMessage);
621
  }
622
 
623
  } catch (error) {
 
625
  const errorMessage = {
626
  id: generateMessageId(),
627
  type: 'error',
628
+ content: 'Sorry, I encountered an error while expanding the message. Please try again.',
629
  timestamp: new Date()
630
  };
631
  setMessages(prev => [...prev, errorMessage]);
632
+
633
+ // Save error message to database
634
+ await saveMessageToSession(errorMessage);
635
  }
636
 
637
  setIsLoading(false);
 
639
  };
640
 
641
  const handleReplyToMessage = (message) => {
642
+ const advisor = advisors[message.persona_id];
643
  setReplyingTo({
644
+ advisorId: message.persona_id,
645
  messageId: message.id,
646
+ advisorName: advisor.name,
647
+ persona_id: message.persona_id
648
  });
649
  };
650
 
651
  const handleMessageClick = (message) => {
652
  if (message.type === 'advisor') {
653
+ const advisor = advisors[message.persona_id];
654
  setReplyingTo({
655
+ advisorId: message.persona_id,
656
  messageId: message.id,
657
+ advisorName: advisor.name,
658
+ persona_id: message.persona_id
659
  });
660
  }
661
  };
662
 
663
+ const handleInputSubmit = async (inputMessage) => {
664
+ if (replyingTo) {
665
+ // This is a reply to a specific message
666
+ await handleReplyToAdvisor(inputMessage, replyingTo);
667
+ } else {
668
+ // This is a regular message
669
+ await handleSendMessage(inputMessage);
670
+ }
671
+ };
672
+
673
  const cancelReply = () => {
674
  setReplyingTo(null);
675
  };
676
 
677
+ const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
678
+
679
+ const handleSidebarToggle = (isCollapsed) => {
680
+ setIsSidebarCollapsed(isCollapsed);
681
+ };
682
+
683
  const hasMessages = messages.length > 0;
684
  const hasConversationMessages = messages.filter(m => m.type !== 'system' && m.type !== 'document_upload').length > 0;
685
 
686
  return (
687
+ <div className="chat-page-with-sidebar">
688
+ {/* Sidebar Component */}
689
+ <Sidebar
690
+ user={user}
691
+ currentSessionId={currentSessionId}
692
+ onSelectSession={handleSelectSession}
693
+ onNewChat={handleNewChat}
694
+ onSignOut={onSignOut}
695
+ authToken={authToken}
696
+ onSidebarToggle={handleSidebarToggle}
697
+ isMobileOpen={isMobileMenuOpen}
698
+ onMobileToggle={setIsMobileMenuOpen}
699
+ />
700
+
701
+ <div className={`main-chat-area ${isSidebarCollapsed ? 'sidebar-collapsed' : ''}`}>
702
+ <div className="modern-chat-page">
703
+ {/* Floating Header */}
704
+ <div className="floating-header">
705
+ <div className="header-left">
706
+ <button
707
+ className="mobile-menu-button"
708
+ onClick={handleMobileMenuToggle}
709
+ >
710
+ <Menu size={20} />
711
+ </button>
712
+ <button onClick={onNavigateToHome} className="modern-home-btn">
713
+ <Home size={20} />
714
+ </button>
715
+ <div className="header-brand">
716
+ <div className="brand-icon">
717
+ <Users size={24} />
718
+ </div>
719
+ <div className="brand-text">
720
+ <h1>PhD Advisory</h1>
721
+ <p>AI-Powered Academic Guidance</p>
722
+ </div>
723
+ </div>
724
  </div>
725
+
726
+ <div className="header-right">
727
+ <AdvisorStatusDropdown
728
+ advisors={advisors}
729
+ thinkingAdvisors={thinkingAdvisors}
730
+ getAdvisorColors={getAdvisorColors}
731
+ isDark={isDark}
732
+ />
 
733
 
734
+ <div className="header-controls">
735
+ {/* Add session title display */}
736
+ {currentSessionTitle && (
737
+ <div className="session-title-display">
738
+ <span>{currentSessionTitle}</span>
739
+ </div>
740
+ )}
741
+
742
+ {/* Optional: Add header sign out button */}
743
+ <button
744
+ className="header-signout-btn"
745
+ onClick={onSignOut}
746
+ title="Sign Out"
747
  >
748
+ <LogOut size={16} />
749
+ </button>
750
+
751
+ {/* Export Button */}
752
+ <ExportButton
753
+ hasMessages={hasConversationMessages}
754
+ currentSessionId={currentSessionId}
755
+ authToken={authToken}
756
+ />
757
+
758
+ {/* Provider Dropdown */}
759
+ <ProviderDropdown
760
+ currentProvider={currentProvider}
761
+ onProviderChange={handleProviderSwitch}
762
+ isLoading={isProviderSwitching}
763
+ />
764
+
765
+ {/* Theme Toggle */}
766
+ <ThemeToggle />
767
+ </div>
768
+ </div>
 
 
 
 
 
 
769
  </div>
 
 
770
 
771
+ {/* Main Content */}
772
+ <div className="chat-content">
773
+ {!hasMessages ? (
774
+ <div className="welcome-state">
775
+ <SuggestionsPanel onSuggestionClick={handleSendMessage} />
776
+ </div>
777
+ ) : (
778
+ <div className="messages-container">
779
+ {/* Add loading session indicator */}
780
+ {isLoadingSession && (
781
+ <div className="loading-session">
782
+ <div className="loading-spinner"></div>
783
+ <span>Loading chat session...</span>
784
+ </div>
785
+ )}
786
+
787
+ <div className="messages-list">
788
+ <div className="messages-scroll">
789
+ {messages.map((message) => (
790
+ <div key={message.id}>
791
+ {message.type === 'user' && (
792
+ <div className="user-message-container">
793
+ <div className="user-message">
794
+ {message.replyTo && (
795
+ <div className="reply-indicator">
796
+ <Reply size={12} />
797
+ <span>Reply to {message.replyTo.advisorName}</span>
798
+ </div>
799
+ )}
800
+ <p>{message.content}</p>
801
  </div>
802
+ </div>
803
+ )}
804
+
805
+ {message.type === 'advisor' && (
806
+ <MessageBubble
807
+ message={message}
808
+ onReply={handleReplyToMessage}
809
+ onExpand={handleExpandMessage}
810
+ onClick={handleMessageClick}
811
+ showReplyButton={true}
812
+ />
813
+ )}
814
+
815
+ {message.type === 'error' && (
816
+ <div className="error-message-container">
817
+ <div className="error-message">
818
+ <p>{message.content}</p>
819
+ </div>
820
+ </div>
821
+ )}
822
 
823
+ {message.type === 'system' && (
824
+ <div className="system-message-container">
825
+ <div className="system-message">
826
+ <p>{message.content}</p>
827
+ </div>
828
+ </div>
829
+ )}
830
+
831
+ {message.type === 'document_upload' && (
832
+ <div className="system-message-container">
833
+ <div className="system-message document-upload">
834
+ <FileText size={16} />
835
+ <p>{message.content}</p>
836
+ </div>
837
+ </div>
838
+ )}
839
+
840
+ {message.type === 'clarification' && (
841
+ <div className="clarification-message-container">
842
+ <div className="clarification-message">
843
+ <div className="clarification-header">
844
+ <MessageCircle size={16} />
845
+ <span>I need a bit more information</span>
846
+ </div>
847
+ <p>{message.content}</p>
848
+
849
+ {message.suggestions && message.suggestions.length > 0 && (
850
+ <div className="clarification-suggestions">
851
+ <p className="suggestions-label">Here are some ways you could be more specific:</p>
852
+ <div className="suggestions-list">
853
+ {message.suggestions.map((suggestion, index) => (
854
+ <button
855
+ key={index}
856
+ className="suggestion-button"
857
+ onClick={() => handleSendMessage(suggestion)}
858
+ >
859
+ {suggestion}
860
+ </button>
861
+ ))}
862
+ </div>
863
+ </div>
864
+ )}
865
+ </div>
866
+ </div>
867
+ )}
868
 
869
+
 
 
 
 
870
  </div>
871
+ ))}
872
 
873
+ {thinkingAdvisors.includes('system') && (
874
+ <div className="orchestrator-thinking">
875
+ <div className="thinking-bubble">
876
+ <MessageCircle size={20} />
877
  </div>
878
+ <div className="thinking-content">
879
+ <span className="thinking-label">Orchestrator is thinking...</span>
880
+ <div className="thinking-animation">
881
+ <div className="dot"></div>
882
+ <div className="dot"></div>
883
+ <div className="dot"></div>
884
+ </div>
 
885
  </div>
886
  </div>
887
  )}
888
+
889
+ {thinkingAdvisors.filter(id => id !== 'system').map(advisorId => (
890
+ <ThinkingIndicator key={advisorId} advisorId={advisorId} />
891
+ ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
892
 
893
+ <div ref={messagesEndRef} />
894
+ </div>
895
+ </div>
896
  </div>
897
+ )}
898
  </div>
 
 
899
 
900
+ <div className="floating-input-area">
901
+ {replyingTo && (
902
+ <div className="reply-banner">
903
+ <div className="reply-info">
904
+ <Reply size={16} />
905
+ <span>Replying to <strong>{replyingTo.advisorName}</strong></span>
906
+ </div>
907
+ <button onClick={cancelReply} className="cancel-reply">
908
+ <X size={16} />
909
+ </button>
910
+ </div>
911
+ )}
912
+
913
+ <EnhancedChatInput
914
+ onSendMessage={handleInputSubmit}
915
+ onFileUploaded={handleFileUploaded}
916
+ uploadedDocuments={uploadedDocuments}
917
+ isLoading={isLoading}
918
+ currentChatSessionId={currentSessionId}
919
+ authToken={authToken}
920
+ placeholder={
921
+ replyingTo
922
+ ? `Reply to ${replyingTo.advisorName}...`
923
+ : "Ask your advisors anything about your PhD journey..."
924
+ }
925
+ />
926
  </div>
927
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
928
  </div>
929
  </div>
930
  );
phd-advisor-frontend/src/styles/ChatPage.css CHANGED
@@ -1,11 +1,16 @@
1
-
2
  /* Modern Chat Page Layout */
3
  .modern-chat-page {
4
- min-height: 100vh;
5
- background: var(--bg-gradient);
6
  display: flex;
7
  flex-direction: column;
8
- position: relative;
 
 
 
 
 
 
 
9
  }
10
 
11
  /* Floating Header */
@@ -22,6 +27,7 @@
22
  align-items: center;
23
  justify-content: space-between;
24
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
 
25
  }
26
 
27
  [data-theme="dark"] .floating-header {
@@ -100,29 +106,7 @@
100
  gap: 12px;
101
  }
102
 
103
- /* Advisor Pills */
104
- .advisor-pills {
105
- display: flex;
106
- gap: 8px;
107
- }
108
 
109
- .advisor-pill {
110
- display: flex;
111
- align-items: center;
112
- gap: 6px;
113
- padding: 8px 12px;
114
- border-radius: 20px;
115
- border: 1px solid;
116
- background: var(--bg-primary);
117
- font-size: 12px;
118
- font-weight: 500;
119
- transition: all 0.3s ease;
120
- position: relative;
121
- }
122
-
123
- .advisor-pill.thinking {
124
- animation: pulse 2s ease-in-out infinite;
125
- }
126
 
127
  .thinking-pulse {
128
  position: absolute;
@@ -150,10 +134,14 @@
150
  display: flex;
151
  flex-direction: column;
152
  padding-top: 24px;
153
- padding-bottom: 140px; /* Space for floating input */
154
  padding-left: 16px;
155
  padding-right: 16px;
 
 
 
156
  }
 
157
  .export-dropdown {
158
  z-index: 1000;
159
  }
@@ -162,14 +150,20 @@
162
  .welcome-state {
163
  flex: 1;
164
  display: flex;
165
- align-items: center;
166
- justify-content: center;
167
- min-height: 60vh;
 
 
 
 
168
  }
169
 
170
  .suggestions-container {
171
  width: 100%;
172
  max-width: 1200px;
 
 
173
  }
174
 
175
  /* Chat State */
@@ -177,20 +171,104 @@
177
  flex: 1;
178
  display: flex;
179
  flex-direction: column;
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  }
181
 
182
  .messages-area {
183
  flex: 1;
184
  overflow: hidden;
 
185
  }
186
 
187
  .messages-scroll {
188
  height: 100%;
189
  overflow-y: auto;
 
190
  padding: 20px;
191
- padding-bottom: 40px; /* Extra space before floating input */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  }
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  /* Message Components */
195
  .orchestrator-message {
196
  display: flex;
@@ -440,6 +518,116 @@
440
  color: var(--text-secondary);
441
  }
442
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  /* Document Indicator Styles */
444
  .document-indicator {
445
  display: flex;
@@ -557,6 +745,142 @@
557
  letter-spacing: 0.5px;
558
  }
559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560
  .dropdown-arrow {
561
  color: var(--text-secondary);
562
  transition: transform 0.2s ease;
@@ -662,22 +986,57 @@
662
  font-size: 12px;
663
  }
664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  /* Responsive Design for Chat Page */
666
  @media (max-width: 768px) {
667
  .floating-header {
668
  padding: 12px 16px;
669
- flex-wrap: wrap;
670
- gap: 12px;
671
  }
672
 
673
- .header-right {
674
  gap: 12px;
 
 
675
  }
676
 
677
- .advisor-pills {
 
 
678
  display: none;
679
  }
680
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  .main-content {
682
  padding: 24px 12px 120px 12px; /* Adjusted for mobile */
683
  }
@@ -709,10 +1068,44 @@
709
  font-size: 13px;
710
  }
711
 
712
- .export-dropdown {
713
- right: -20px;
714
- left: -20px;
715
- width: auto;
716
- min-width: unset;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
717
  }
 
718
  }
 
 
1
  /* Modern Chat Page Layout */
2
  .modern-chat-page {
3
+ height: 100vh;
 
4
  display: flex;
5
  flex-direction: column;
6
+ overflow: hidden;
7
+ }
8
+
9
+ [data-theme="dark"] .modern-chat-page {
10
+ background: var(--bg-gradient);
11
+ will-change: auto;
12
+ -webkit-transform: translateZ(0);
13
+ transform: translateZ(0);
14
  }
15
 
16
  /* Floating Header */
 
27
  align-items: center;
28
  justify-content: space-between;
29
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
30
+ flex-shrink: 0;
31
  }
32
 
33
  [data-theme="dark"] .floating-header {
 
106
  gap: 12px;
107
  }
108
 
 
 
 
 
 
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  .thinking-pulse {
112
  position: absolute;
 
134
  display: flex;
135
  flex-direction: column;
136
  padding-top: 24px;
137
+ padding-bottom: 140px;
138
  padding-left: 16px;
139
  padding-right: 16px;
140
+ overflow: visible;
141
+ min-height: 0;
142
+ height: 100vh;
143
  }
144
+
145
  .export-dropdown {
146
  z-index: 1000;
147
  }
 
150
  .welcome-state {
151
  flex: 1;
152
  display: flex;
153
+ flex-direction: column;
154
+ justify-content: flex-start;
155
+ padding-top: 40px;
156
+ overflow-y: auto;
157
+ overflow-x: hidden;
158
+ scroll-behavior: smooth;
159
+ -webkit-overflow-scrolling: touch;
160
  }
161
 
162
  .suggestions-container {
163
  width: 100%;
164
  max-width: 1200px;
165
+ margin: 0 auto;
166
+ flex-shrink: 0;
167
  }
168
 
169
  /* Chat State */
 
171
  flex: 1;
172
  display: flex;
173
  flex-direction: column;
174
+ overflow: hidden;
175
+ min-height: 0;
176
+ height: 100%;
177
+ }
178
+
179
+ .chat-content {
180
+ flex: 1;
181
+ display: flex;
182
+ flex-direction: column;
183
+ overflow: hidden;
184
+ min-height: 0;
185
+ /* Add bottom padding to prevent content being hidden behind floating input */
186
+ padding-bottom: 140px;
187
  }
188
 
189
  .messages-area {
190
  flex: 1;
191
  overflow: hidden;
192
+ min-height: 0;
193
  }
194
 
195
  .messages-scroll {
196
  height: 100%;
197
  overflow-y: auto;
198
+ overflow-x: hidden;
199
  padding: 20px;
200
+ padding-bottom: 40px;
201
+ background: var(--bg-gradient);
202
+ scroll-behavior: smooth;
203
+ -webkit-overflow-scrolling: touch;
204
+ scrollbar-width: thin;
205
+ }
206
+
207
+ .messages-container {
208
+ flex: 1;
209
+ display: flex;
210
+ flex-direction: column;
211
+ overflow: hidden;
212
+ min-height: 0;
213
+ height: 100%;
214
+ background: var(--bg-gradient);
215
+ }
216
+
217
+ .messages-list {
218
+ flex: 1;
219
+ overflow: hidden;
220
+ min-height: 0;
221
+ height: 100%;
222
+ }
223
+
224
+
225
+ [data-theme="dark"] .messages-scroll,
226
+ [data-theme="dark"] .messages-container,
227
+ [data-theme="dark"] .main-content {
228
+ background: var(--bg-gradient);
229
+ will-change: auto;
230
+ -webkit-transform: translateZ(0);
231
+ transform: translateZ(0);
232
+ }
233
+
234
+ /* Smooth scrolling with fixed background */
235
+ @media (prefers-reduced-motion: no-preference) {
236
+ .messages-scroll {
237
+ scroll-behavior: smooth;
238
+ }
239
+ }
240
+
241
+ /* Scrollbar styling for dark mode */
242
+ [data-theme="dark"] .messages-scroll::-webkit-scrollbar {
243
+ width: 8px;
244
  }
245
 
246
+ [data-theme="dark"] .messages-scroll::-webkit-scrollbar-track {
247
+ background: var(--bg-secondary);
248
+ border-radius: 4px;
249
+ }
250
+
251
+ [data-theme="dark"] .messages-scroll::-webkit-scrollbar-thumb {
252
+ background: var(--border-primary);
253
+ border-radius: 4px;
254
+ }
255
+
256
+ [data-theme="dark"] .messages-scroll::-webkit-scrollbar-thumb:hover {
257
+ background: var(--text-tertiary);
258
+ }
259
+
260
+ /* Prevent background shift during scroll */
261
+ .messages-scroll * {
262
+ background-attachment: fixed;
263
+ }
264
+
265
+ /* Ensure scroll anchor area */
266
+ .messages-end-anchor {
267
+ height: 1px;
268
+ background: transparent;
269
+ }
270
+
271
+
272
  /* Message Components */
273
  .orchestrator-message {
274
  display: flex;
 
518
  color: var(--text-secondary);
519
  }
520
 
521
+ /* MAIN LAYOUT WITH SIDEBAR - FIXED */
522
+ .chat-page-with-sidebar {
523
+ display: flex;
524
+ height: 100vh;
525
+ overflow: hidden;
526
+ background: var(--bg-gradient);
527
+ }
528
+
529
+ .main-chat-area {
530
+ flex: 1;
531
+ margin-left: 300px; /* Width of sidebar when expanded */
532
+ display: flex;
533
+ flex-direction: column;
534
+ height: 100vh;
535
+ transition: margin-left 0.3s ease;
536
+ overflow: hidden;
537
+ }
538
+
539
+ /* FIXED: Chat area expansion when sidebar is collapsed */
540
+ .main-chat-area.sidebar-collapsed {
541
+ margin-left: 70px; /* Width of sidebar when collapsed */
542
+ }
543
+
544
+ /* Session title display in header */
545
+ .session-title-display {
546
+ display: flex;
547
+ align-items: center;
548
+ padding: 6px 12px;
549
+ background: var(--bg-secondary, #f3f4f6);
550
+ border-radius: 6px;
551
+ margin-right: 8px;
552
+ }
553
+
554
+ .dark .session-title-display {
555
+ background: var(--bg-secondary-dark, #374151);
556
+ }
557
+
558
+ .session-title-display span {
559
+ font-size: 13px;
560
+ font-weight: 500;
561
+ color: var(--text-primary, #111827);
562
+ max-width: 150px;
563
+ white-space: nowrap;
564
+ overflow: hidden;
565
+ text-overflow: ellipsis;
566
+ }
567
+
568
+ .dark .session-title-display span {
569
+ color: var(--text-primary-dark, #f9fafb);
570
+ }
571
+
572
+ /* Optional header sign out button */
573
+ .header-signout-btn {
574
+ display: flex;
575
+ align-items: center;
576
+ justify-content: center;
577
+ padding: 8px;
578
+ border: none;
579
+ background: none;
580
+ border-radius: 6px;
581
+ cursor: pointer;
582
+ color: var(--text-secondary, #6b7280);
583
+ transition: all 0.2s ease;
584
+ margin-right: 8px;
585
+ }
586
+
587
+ .header-signout-btn:hover {
588
+ background: var(--bg-secondary, #f3f4f6);
589
+ color: #ef4444;
590
+ }
591
+
592
+ .dark .header-signout-btn:hover {
593
+ background: var(--bg-secondary-dark, #374151);
594
+ }
595
+
596
+ /* Loading session indicator */
597
+ .loading-session {
598
+ display: flex;
599
+ align-items: center;
600
+ justify-content: center;
601
+ gap: 12px;
602
+ padding: 20px;
603
+ color: var(--text-secondary);
604
+ font-size: 14px;
605
+ background: var(--bg-gradient);
606
+ }
607
+
608
+ [data-theme="dark"] .loading-session {
609
+ color: var(--text-secondary-dark);
610
+ background: var(--bg-gradient);
611
+ }
612
+
613
+ .dark .loading-session {
614
+ color: var(--text-secondary-dark, #9ca3af);
615
+ }
616
+
617
+ .loading-session .loading-spinner {
618
+ width: 16px;
619
+ height: 16px;
620
+ border: 2px solid var(--border-light, #e5e7eb);
621
+ border-top: 2px solid var(--primary-color, #3b82f6);
622
+ border-radius: 50%;
623
+ animation: spin 1s linear infinite;
624
+ }
625
+
626
+ .dark .loading-session .loading-spinner {
627
+ border-color: var(--border-dark, #374151);
628
+ border-top-color: var(--primary-color, #3b82f6);
629
+ }
630
+
631
  /* Document Indicator Styles */
632
  .document-indicator {
633
  display: flex;
 
745
  letter-spacing: 0.5px;
746
  }
747
 
748
+ .clarification-message-container {
749
+ display: flex;
750
+ justify-content: center;
751
+ margin: 24px 0;
752
+ }
753
+
754
+ .clarification-message {
755
+ background: var(--bg-secondary);
756
+ border: 1px solid var(--border-primary);
757
+ color: var(--text-primary);
758
+ padding: 20px;
759
+ border-radius: 16px;
760
+ max-width: 600px;
761
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
762
+ border-left: 4px solid var(--accent-primary);
763
+ position: relative;
764
+ overflow: hidden;
765
+ }
766
+
767
+ /* Add subtle accent background */
768
+ .clarification-message::before {
769
+ content: '';
770
+ position: absolute;
771
+ top: 0;
772
+ left: 0;
773
+ right: 0;
774
+ bottom: 0;
775
+ background: var(--accent-gradient);
776
+ opacity: 0.03;
777
+ pointer-events: none;
778
+ }
779
+
780
+ [data-theme="dark"] .clarification-message {
781
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
782
+ }
783
+
784
+ [data-theme="dark"] .clarification-message::before {
785
+ opacity: 0.05;
786
+ }
787
+
788
+ .clarification-header {
789
+ display: flex;
790
+ align-items: center;
791
+ gap: 8px;
792
+ margin-bottom: 12px;
793
+ font-weight: 600;
794
+ font-size: 14px;
795
+ color: var(--accent-primary);
796
+ position: relative;
797
+ z-index: 1;
798
+ }
799
+
800
+ .clarification-message p {
801
+ margin: 0 0 16px 0;
802
+ line-height: 1.6;
803
+ font-size: 15px;
804
+ color: var(--text-secondary);
805
+ position: relative;
806
+ z-index: 1;
807
+ }
808
+
809
+ .clarification-suggestions {
810
+ margin-top: 16px;
811
+ padding-top: 16px;
812
+ border-top: 1px solid var(--border-primary);
813
+ position: relative;
814
+ z-index: 1;
815
+ }
816
+
817
+ .suggestions-label {
818
+ font-size: 13px;
819
+ margin-bottom: 12px;
820
+ color: var(--text-secondary);
821
+ font-weight: 500;
822
+ }
823
+
824
+ .suggestions-list {
825
+ display: flex;
826
+ flex-direction: column;
827
+ gap: 8px;
828
+ }
829
+
830
+ .suggestion-button {
831
+ background: var(--bg-primary);
832
+ border: 1px solid var(--border-primary);
833
+ color: var(--text-primary);
834
+ padding: 12px 16px;
835
+ border-radius: 12px;
836
+ cursor: pointer;
837
+ text-align: left;
838
+ font-size: 13px;
839
+ font-weight: 500;
840
+ transition: all 0.2s ease;
841
+ position: relative;
842
+ overflow: hidden;
843
+ }
844
+
845
+ .suggestion-button::before {
846
+ content: '';
847
+ position: absolute;
848
+ top: 0;
849
+ left: 0;
850
+ right: 0;
851
+ bottom: 0;
852
+ background: var(--accent-primary);
853
+ opacity: 0;
854
+ transition: opacity 0.2s ease;
855
+ pointer-events: none;
856
+ }
857
+
858
+ .suggestion-button:hover {
859
+ border-color: var(--accent-primary);
860
+ transform: translateY(-1px);
861
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
862
+ }
863
+
864
+ .suggestion-button:hover::before {
865
+ opacity: 0.05;
866
+ }
867
+
868
+ .suggestion-button:hover {
869
+ color: var(--accent-primary);
870
+ }
871
+
872
+ [data-theme="dark"] .suggestion-button:hover {
873
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
874
+ }
875
+
876
+ [data-theme="dark"] .suggestion-button:hover::before {
877
+ opacity: 0.1;
878
+ }
879
+
880
+ .suggestion-button:active {
881
+ transform: translateY(0);
882
+ }
883
+
884
  .dropdown-arrow {
885
  color: var(--text-secondary);
886
  transition: transform 0.2s ease;
 
986
  font-size: 12px;
987
  }
988
 
989
+ .mobile-menu-button {
990
+ display: none;
991
+ width: 44px;
992
+ height: 44px;
993
+ border-radius: 12px;
994
+ border: none;
995
+ background: var(--bg-secondary);
996
+ color: var(--text-secondary);
997
+ cursor: pointer;
998
+ transition: all 0.2s ease;
999
+ align-items: center;
1000
+ justify-content: center;
1001
+ }
1002
+
1003
+ .mobile-menu-button:hover {
1004
+ background: var(--accent-primary);
1005
+ color: white;
1006
+ }
1007
+
1008
  /* Responsive Design for Chat Page */
1009
  @media (max-width: 768px) {
1010
  .floating-header {
1011
  padding: 12px 16px;
1012
+ flex-wrap: nowrap;
1013
+ gap: 8px;
1014
  }
1015
 
1016
+ .header-left {
1017
  gap: 12px;
1018
+ flex: 0; /* Don't let it grow */
1019
+ min-width: 0;
1020
  }
1021
 
1022
+ /* Hide brand elements on mobile to reduce clutter */
1023
+ .header-left .modern-home-btn,
1024
+ .header-left .header-brand {
1025
  display: none;
1026
  }
1027
 
1028
+ .header-right {
1029
+ gap: 8px;
1030
+ flex: 1; /* Let header-right take available space */
1031
+ justify-content: flex-end; /* Align items to the right */
1032
+ flex-shrink: 0;
1033
+ }
1034
+
1035
+ /* Ensure mobile menu button is visible */
1036
+ .mobile-menu-button {
1037
+ display: flex;
1038
+ }
1039
+
1040
  .main-content {
1041
  padding: 24px 12px 120px 12px; /* Adjusted for mobile */
1042
  }
 
1068
  font-size: 13px;
1069
  }
1070
 
1071
+
1072
+ .main-chat-area {
1073
+ margin-left: 0;
1074
+ }
1075
+
1076
+ .main-chat-area.sidebar-collapsed {
1077
+ margin-left: 0;
1078
+ }
1079
+
1080
+ .clarification-message {
1081
+ margin: 0 16px;
1082
+ max-width: none;
1083
+ padding: 16px;
1084
+ }
1085
+
1086
+ .clarification-header {
1087
+ font-size: 13px;
1088
+ }
1089
+
1090
+ .clarification-message p {
1091
+ font-size: 14px;
1092
+ }
1093
+
1094
+ .suggestion-button {
1095
+ padding: 10px 14px;
1096
+ font-size: 12px;
1097
+ }
1098
+
1099
+ .brand-text h1 {
1100
+ font-size: 16px;
1101
+ }
1102
+
1103
+ .brand-text p {
1104
+ font-size: 11px;
1105
+ }
1106
+
1107
+ .session-title-display{
1108
+ display: none;
1109
  }
1110
+
1111
  }
phd-advisor-frontend/src/styles/ExportButton.css CHANGED
@@ -359,13 +359,13 @@
359
  /* Responsive Design */
360
  @media (max-width: 768px) {
361
  .export-dropdown {
362
- right: -20px;
363
- left: -20px;
364
  width: auto;
365
  min-width: unset;
366
  }
367
 
368
- .export-format-button {
369
  padding: 16px 20px;
370
  }
371
 
@@ -373,6 +373,15 @@
373
  width: 36px;
374
  height: 36px;
375
  }
 
 
 
 
 
 
 
 
 
376
  }
377
 
378
  /* Focus states for accessibility */
 
359
  /* Responsive Design */
360
  @media (max-width: 768px) {
361
  .export-dropdown {
362
+ right: -40px;
363
+ left: -40px;
364
  width: auto;
365
  min-width: unset;
366
  }
367
 
368
+ .export-format-button {
369
  padding: 16px 20px;
370
  }
371
 
 
373
  width: 36px;
374
  height: 36px;
375
  }
376
+
377
+ .export-button {
378
+ padding: 6px 12px;
379
+ font-size: 13px;
380
+ }
381
+
382
+ /* .export-text {
383
+ display: none;
384
+ } */
385
  }
386
 
387
  /* Focus states for accessibility */
phd-advisor-frontend/src/styles/Sidebar.css ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sidebar.css */
2
+ .sidebar {
3
+ width: 300px;
4
+ height: 100vh;
5
+ background: var(--bg-primary, #ffffff);
6
+ border-right: 1px solid var(--border-light, #e5e7eb);
7
+ display: flex;
8
+ flex-direction: column;
9
+ position: fixed;
10
+ left: 0;
11
+ top: 0;
12
+ z-index: 100;
13
+ overflow: hidden;
14
+ transition: width 0.3s ease;
15
+ }
16
+
17
+ /* Collapsed state */
18
+ .sidebar.collapsed {
19
+ width: 70px;
20
+ }
21
+
22
+ /* Dark theme support */
23
+ .dark .sidebar {
24
+ background: var(--bg-primary-dark, #1f2937);
25
+ border-right-color: var(--border-dark, #374151);
26
+ }
27
+
28
+ /* Toggle Button - Matches User Menu Style */
29
+ .sidebar-toggle {
30
+ padding: 6px;
31
+ border: none;
32
+ background: none;
33
+ border-radius: 6px;
34
+ cursor: pointer;
35
+ color: var(--text-secondary, #6b7280);
36
+ transition: all 0.2s ease;
37
+ display: flex;
38
+ align-items: center;
39
+ justify-content: center;
40
+ }
41
+
42
+ .sidebar-toggle:hover {
43
+ background: var(--bg-secondary, #f3f4f6);
44
+ color: var(--text-primary, #111827);
45
+ }
46
+
47
+ .dark .sidebar-toggle:hover {
48
+ background: var(--bg-secondary-dark, #374151);
49
+ color: var(--text-primary-dark, #f9fafb);
50
+ }
51
+
52
+ /* Toggle button as collapsed user avatar replacement */
53
+ .collapsed-toggle-avatar {
54
+ width: 40px;
55
+ height: 40px;
56
+ background: var(--primary-color, #3b82f6);
57
+ border-radius: 50%;
58
+ display: flex;
59
+ align-items: center;
60
+ justify-content: center;
61
+ color: white;
62
+ flex-shrink: 0;
63
+ cursor: pointer;
64
+ transition: all 0.2s ease;
65
+ }
66
+
67
+ .collapsed-toggle-avatar:hover {
68
+ background: var(--primary-color-hover, #2563eb);
69
+ transform: scale(1.05);
70
+ }
71
+
72
+ /* Header Section */
73
+ .sidebar-header {
74
+ padding: 20px;
75
+ border-bottom: 1px solid var(--border-light, #e5e7eb);
76
+ flex-shrink: 0;
77
+ transition: all 0.3s ease;
78
+ }
79
+
80
+ .sidebar.collapsed .sidebar-header {
81
+ padding: 20px 10px;
82
+ }
83
+
84
+ .dark .sidebar-header {
85
+ border-bottom-color: var(--border-dark, #374151);
86
+ }
87
+
88
+ /* Collapsed Header */
89
+ .collapsed-header {
90
+ display: flex;
91
+ flex-direction: column;
92
+ align-items: center;
93
+ gap: 16px;
94
+ }
95
+
96
+ .collapsed-user-avatar {
97
+ width: 40px;
98
+ height: 40px;
99
+ background: var(--primary-color, #3b82f6);
100
+ border-radius: 50%;
101
+ display: flex;
102
+ align-items: center;
103
+ justify-content: center;
104
+ color: white;
105
+ flex-shrink: 0;
106
+ }
107
+
108
+ .collapsed-new-chat {
109
+ width: 40px;
110
+ height: 40px;
111
+ background: var(--primary-color, #3b82f6);
112
+ color: white;
113
+ border: none;
114
+ border-radius: 50%;
115
+ display: flex;
116
+ align-items: center;
117
+ justify-content: center;
118
+ cursor: pointer;
119
+ transition: all 0.2s ease;
120
+ }
121
+
122
+ .collapsed-new-chat:hover {
123
+ background: var(--primary-color-hover, #2563eb);
124
+ transform: scale(1.1);
125
+ }
126
+
127
+ .user-section {
128
+ display: flex;
129
+ align-items: center;
130
+ justify-content: space-between;
131
+ margin-bottom: 16px;
132
+ }
133
+
134
+ .user-info {
135
+ display: flex;
136
+ align-items: center;
137
+ gap: 12px;
138
+ flex: 1;
139
+ min-width: 0;
140
+ }
141
+
142
+ .user-avatar {
143
+ width: 36px;
144
+ height: 36px;
145
+ background: var(--primary-color, #3b82f6);
146
+ border-radius: 50%;
147
+ display: flex;
148
+ align-items: center;
149
+ justify-content: center;
150
+ color: white;
151
+ flex-shrink: 0;
152
+ }
153
+
154
+ .user-details {
155
+ display: flex;
156
+ flex-direction: column;
157
+ min-width: 0;
158
+ }
159
+
160
+ .user-name {
161
+ font-weight: 600;
162
+ color: var(--text-primary, #111827);
163
+ font-size: 14px;
164
+ white-space: nowrap;
165
+ overflow: hidden;
166
+ text-overflow: ellipsis;
167
+ }
168
+
169
+ .dark .user-name {
170
+ color: var(--text-primary-dark, #f9fafb);
171
+ }
172
+
173
+ .user-email {
174
+ font-size: 12px;
175
+ color: var(--text-secondary, #6b7280);
176
+ white-space: nowrap;
177
+ overflow: hidden;
178
+ text-overflow: ellipsis;
179
+ }
180
+
181
+ .dark .user-email {
182
+ color: var(--text-secondary-dark, #9ca3af);
183
+ }
184
+
185
+ /* User Menu */
186
+ .user-menu-container {
187
+ position: relative;
188
+ }
189
+
190
+ .user-menu-button {
191
+ padding: 6px;
192
+ border: none;
193
+ background: none;
194
+ border-radius: 6px;
195
+ cursor: pointer;
196
+ color: var(--text-secondary, #6b7280);
197
+ transition: all 0.2s ease;
198
+ }
199
+
200
+ .user-menu-button:hover {
201
+ background: var(--bg-secondary, #f3f4f6);
202
+ color: var(--text-primary, #111827);
203
+ }
204
+
205
+ .dark .user-menu-button:hover {
206
+ background: var(--bg-secondary-dark, #374151);
207
+ color: var(--text-primary-dark, #f9fafb);
208
+ }
209
+
210
+ .user-menu {
211
+ position: absolute;
212
+ top: 100%;
213
+ right: 0;
214
+ background: var(--bg-primary, #ffffff);
215
+ border: 1px solid var(--border-light, #e5e7eb);
216
+ border-radius: 8px;
217
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
218
+ padding: 8px;
219
+ min-width: 150px;
220
+ z-index: 200;
221
+ }
222
+
223
+ .dark .user-menu {
224
+ background: var(--bg-primary-dark, #1f2937);
225
+ border-color: var(--border-dark, #374151);
226
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
227
+ }
228
+
229
+ .user-menu-item {
230
+ display: flex;
231
+ align-items: center;
232
+ gap: 10px;
233
+ padding: 10px 12px;
234
+ width: 100%;
235
+ border: none;
236
+ background: none;
237
+ border-radius: 6px;
238
+ cursor: pointer;
239
+ font-size: 14px;
240
+ color: var(--text-primary, #111827);
241
+ transition: background-color 0.2s ease;
242
+ }
243
+
244
+ .dark .user-menu-item {
245
+ color: var(--text-primary-dark, #f9fafb);
246
+ }
247
+
248
+ .user-menu-item:hover {
249
+ background: var(--bg-secondary, #f3f4f6);
250
+ }
251
+
252
+ .dark .user-menu-item:hover {
253
+ background: var(--bg-secondary-dark, #374151);
254
+ }
255
+
256
+ .user-menu-item.sign-out {
257
+ color: #ef4444;
258
+ }
259
+
260
+ .user-menu-item.sign-out:hover {
261
+ background: #fef2f2;
262
+ }
263
+
264
+ .dark .user-menu-item.sign-out:hover {
265
+ background: #7f1d1d;
266
+ }
267
+
268
+ /* New Chat Button */
269
+ .new-chat-button {
270
+ display: flex;
271
+ align-items: center;
272
+ justify-content: center;
273
+ gap: 8px;
274
+ width: 100%;
275
+ padding: 12px 16px;
276
+ background: var(--primary-color, #3b82f6);
277
+ color: white;
278
+ border: none;
279
+ border-radius: 8px;
280
+ font-weight: 500;
281
+ cursor: pointer;
282
+ transition: all 0.2s ease;
283
+ }
284
+
285
+ .new-chat-button:hover {
286
+ background: var(--primary-color-hover, #2563eb);
287
+ transform: translateY(-1px);
288
+ }
289
+
290
+ /* Search Section */
291
+ .sidebar-search {
292
+ padding: 16px 20px;
293
+ border-bottom: 1px solid var(--border-light, #e5e7eb);
294
+ flex-shrink: 0;
295
+ transition: all 0.3s ease;
296
+ }
297
+
298
+ .dark .sidebar-search {
299
+ border-bottom-color: var(--border-dark, #374151);
300
+ }
301
+
302
+ .search-container {
303
+ position: relative;
304
+ }
305
+
306
+ .search-icon {
307
+ position: absolute;
308
+ left: 12px;
309
+ top: 50%;
310
+ transform: translateY(-50%);
311
+ color: var(--text-secondary, #6b7280);
312
+ }
313
+
314
+ .search-input {
315
+ width: 100%;
316
+ padding: 10px 12px 10px 36px;
317
+ border: 1px solid var(--border-light, #e5e7eb);
318
+ border-radius: 8px;
319
+ background: var(--bg-secondary, #f9fafb);
320
+ color: var(--text-primary, #111827);
321
+ font-size: 14px;
322
+ transition: all 0.2s ease;
323
+ }
324
+
325
+ .dark .search-input {
326
+ border-color: var(--border-dark, #374151);
327
+ background: var(--bg-secondary-dark, #374151);
328
+ color: var(--text-primary-dark, #f9fafb);
329
+ }
330
+
331
+ .search-input:focus {
332
+ outline: none;
333
+ border-color: var(--primary-color, #3b82f6);
334
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
335
+ }
336
+
337
+ .search-input::placeholder {
338
+ color: var(--text-secondary, #6b7280);
339
+ }
340
+
341
+ .dark .search-input::placeholder {
342
+ color: var(--text-secondary-dark, #9ca3af);
343
+ }
344
+
345
+ /* Chat Sessions */
346
+ .chat-sessions {
347
+ flex: 1;
348
+ overflow-y: auto;
349
+ padding: 0 20px 20px;
350
+ transition: padding 0.3s ease;
351
+ }
352
+
353
+ .sidebar.collapsed .chat-sessions {
354
+ padding: 0 10px 20px;
355
+ }
356
+
357
+ .loading-sessions {
358
+ display: flex;
359
+ flex-direction: column;
360
+ align-items: center;
361
+ justify-content: center;
362
+ padding: 40px 20px;
363
+ color: var(--text-secondary, #6b7280);
364
+ gap: 12px;
365
+ }
366
+
367
+ .sidebar.collapsed .loading-sessions {
368
+ padding: 40px 5px;
369
+ }
370
+
371
+ .dark .loading-sessions {
372
+ color: var(--text-secondary-dark, #9ca3af);
373
+ }
374
+
375
+ .loading-spinner {
376
+ width: 24px;
377
+ height: 24px;
378
+ border: 2px solid var(--border-light, #e5e7eb);
379
+ border-top: 2px solid var(--primary-color, #3b82f6);
380
+ border-radius: 50%;
381
+ animation: spin 1s linear infinite;
382
+ }
383
+
384
+ .dark .loading-spinner {
385
+ border-color: var(--border-dark, #374151);
386
+ border-top-color: var(--primary-color, #3b82f6);
387
+ }
388
+
389
+ @keyframes spin {
390
+ 0% { transform: rotate(0deg); }
391
+ 100% { transform: rotate(360deg); }
392
+ }
393
+
394
+ .no-sessions {
395
+ text-align: center;
396
+ padding: 40px 20px;
397
+ color: var(--text-secondary, #6b7280);
398
+ font-size: 14px;
399
+ }
400
+
401
+ .sidebar.collapsed .no-sessions {
402
+ padding: 40px 5px;
403
+ }
404
+
405
+ .dark .no-sessions {
406
+ color: var(--text-secondary-dark, #9ca3af);
407
+ }
408
+
409
+ .sessions-list {
410
+ display: flex;
411
+ flex-direction: column;
412
+ gap: 8px;
413
+ margin-top: 16px;
414
+ }
415
+
416
+ /* Session Item */
417
+ .session-item {
418
+ display: flex;
419
+ align-items: center;
420
+ justify-content: space-between;
421
+ padding: 12px;
422
+ border-radius: 8px;
423
+ cursor: pointer;
424
+ transition: all 0.2s ease;
425
+ border: 1px solid transparent;
426
+ group: true;
427
+ }
428
+
429
+ .session-item.collapsed {
430
+ justify-content: center;
431
+ padding: 12px 8px;
432
+ }
433
+
434
+ .session-item:hover {
435
+ background: var(--bg-secondary, #f3f4f6);
436
+ border-color: var(--border-light, #e5e7eb);
437
+ }
438
+
439
+ .dark .session-item:hover {
440
+ background: var(--bg-secondary-dark, #374151);
441
+ border-color: var(--border-dark, #4b5563);
442
+ }
443
+
444
+ .session-item.active {
445
+ background: rgba(59, 130, 246, 0.1);
446
+ border-color: var(--primary-color, #3b82f6);
447
+ }
448
+
449
+ .dark .session-item.active {
450
+ background: rgba(59, 130, 246, 0.2);
451
+ border-color: var(--primary-color, #3b82f6);
452
+ }
453
+
454
+ .session-content {
455
+ display: flex;
456
+ align-items: center;
457
+ gap: 12px;
458
+ flex: 1;
459
+ min-width: 0;
460
+ }
461
+
462
+ .session-item.collapsed .session-content {
463
+ justify-content: center;
464
+ flex: none;
465
+ }
466
+
467
+ .session-icon {
468
+ color: var(--text-secondary, #6b7280);
469
+ flex-shrink: 0;
470
+ }
471
+
472
+ .dark .session-icon {
473
+ color: var(--text-secondary-dark, #9ca3af);
474
+ }
475
+
476
+ .session-item.active .session-icon {
477
+ color: var(--primary-color, #3b82f6);
478
+ }
479
+
480
+ .session-details {
481
+ flex: 1;
482
+ min-width: 0;
483
+ }
484
+
485
+ .session-title {
486
+ font-weight: 500;
487
+ color: var(--text-primary, #111827);
488
+ font-size: 14px;
489
+ white-space: nowrap;
490
+ overflow: hidden;
491
+ text-overflow: ellipsis;
492
+ margin-bottom: 2px;
493
+ }
494
+
495
+ .dark .session-title {
496
+ color: var(--text-primary-dark, #f9fafb);
497
+ }
498
+
499
+ .session-meta {
500
+ display: flex;
501
+ align-items: center;
502
+ gap: 8px;
503
+ font-size: 12px;
504
+ color: var(--text-secondary, #6b7280);
505
+ }
506
+
507
+ .dark .session-meta {
508
+ color: var(--text-secondary-dark, #9ca3af);
509
+ }
510
+
511
+ .session-date::after {
512
+ content: "•";
513
+ margin-left: 8px;
514
+ }
515
+
516
+ .new-chat-button:disabled {
517
+ opacity: 0.6;
518
+ cursor: not-allowed;
519
+ }
520
+
521
+ .collapsed-new-chat:disabled {
522
+ opacity: 0.6;
523
+ cursor: not-allowed;
524
+ }
525
+
526
+ .loading-sessions {
527
+ display: flex;
528
+ align-items: center;
529
+ justify-content: center;
530
+ gap: 8px;
531
+ padding: 16px;
532
+ color: var(--text-secondary);
533
+ font-size: 14px;
534
+ }
535
+
536
+ .loading-spinner {
537
+ width: 16px;
538
+ height: 16px;
539
+ border: 2px solid var(--border-color);
540
+ border-top: 2px solid var(--primary-color);
541
+ border-radius: 50%;
542
+ animation: spin 1s linear infinite;
543
+ }
544
+
545
+ @keyframes spin {
546
+ 0% { transform: rotate(0deg); }
547
+ 100% { transform: rotate(360deg); }
548
+ }
549
+
550
+ /* Style for creating new chat state */
551
+ .new-chat-button span {
552
+ transition: all 0.2s ease;
553
+ }
554
+
555
+ .new-chat-button:disabled span {
556
+ opacity: 0.7;
557
+ }
558
+
559
+ /* Ensure active session remains highlighted during creation */
560
+ .session-item.active {
561
+ background-color: var(--primary-color);
562
+ color: white;
563
+ border-radius: 8px;
564
+ }
565
+
566
+ .session-menu-button {
567
+ opacity: 0;
568
+ padding: 6px;
569
+ border: none;
570
+ background: none;
571
+ border-radius: 4px;
572
+ cursor: pointer;
573
+ color: var(--text-secondary, #6b7280);
574
+ transition: all 0.2s ease;
575
+ flex-shrink: 0;
576
+ }
577
+
578
+ .session-item:hover .session-menu-button {
579
+ opacity: 1;
580
+ }
581
+
582
+ .session-menu-button:hover {
583
+ background: var(--bg-tertiary, #f3f4f6);
584
+ color: #ef4444;
585
+ }
586
+
587
+ .dark .session-menu-button:hover {
588
+ background: var(--bg-tertiary-dark, #4b5563);
589
+ }
590
+
591
+ /* Tooltip for collapsed state */
592
+ .session-item.collapsed {
593
+ position: relative;
594
+ }
595
+
596
+ .mobile-sidebar-overlay {
597
+ position: fixed;
598
+ top: 0;
599
+ left: 0;
600
+ right: 0;
601
+ bottom: 0;
602
+ background: rgba(0, 0, 0, 0.5);
603
+ z-index: 150;
604
+ display: none;
605
+ }
606
+
607
+ .mobile-sidebar-overlay.visible {
608
+ display: block;
609
+ }
610
+
611
+ .session-item.collapsed:hover::after {
612
+ content: attr(title);
613
+ position: absolute;
614
+ left: 100%;
615
+ top: 50%;
616
+ transform: translateY(-50%);
617
+ background: var(--bg-primary, #ffffff);
618
+ border: 1px solid var(--border-light, #e5e7eb);
619
+ border-radius: 6px;
620
+ padding: 8px 12px;
621
+ margin-left: 8px;
622
+ white-space: nowrap;
623
+ font-size: 12px;
624
+ color: var(--text-primary, #111827);
625
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
626
+ z-index: 1000;
627
+ max-width: 200px;
628
+ overflow: hidden;
629
+ text-overflow: ellipsis;
630
+ }
631
+
632
+ .dark .session-item.collapsed:hover::after {
633
+ background: var(--bg-primary-dark, #1f2937);
634
+ border-color: var(--border-dark, #374151);
635
+ color: var(--text-primary-dark, #f9fafb);
636
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
637
+ }
638
+
639
+ /* Responsive Design */
640
+ @media (max-width: 768px) {
641
+ .sidebar {
642
+ width: 280px;
643
+ transform: translateX(-100%);
644
+ transition: transform 0.3s ease, width 0.3s ease;
645
+ z-index: 200; /* Higher z-index for mobile */
646
+ }
647
+
648
+ .sidebar.collapsed {
649
+ width: 70px;
650
+ transform: translateX(-100%); /* Keep hidden when collapsed on mobile */
651
+ }
652
+
653
+ .sidebar.mobile-open {
654
+ transform: translateX(0);
655
+ }
656
+
657
+ .mobile-sidebar-overlay.visible {
658
+ display: block;
659
+ }
660
+ }
phd-advisor-frontend/src/styles/components.css CHANGED
@@ -551,9 +551,39 @@
551
 
552
  .advisor-message-text {
553
  line-height: 1.6;
554
- margin: 0;
555
  }
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  /* Updated Message Actions Styles */
558
  .message-actions {
559
  margin-top: 12px;
@@ -1100,6 +1130,10 @@
1100
  font-size: 13px;
1101
  }
1102
 
 
 
 
 
1103
  /* Basic ChatInput mobile styles */
1104
  .input-container .send-text {
1105
  display: inline;
 
551
 
552
  .advisor-message-text {
553
  line-height: 1.6;
 
554
  }
555
 
556
+ .advisor-message-text > div:last-child p:last-child {
557
+ margin-bottom: 0; /* Remove bottom margin from last paragraph */
558
+ }
559
+
560
+ .advisor-message-text strong {
561
+ font-weight: 600;
562
+ }
563
+
564
+ .advisor-message-text em {
565
+ font-style: italic;
566
+ }
567
+
568
+ .advisor-message-text ul,
569
+ .advisor-message-text ol {
570
+ margin: 0.75rem 0;
571
+ padding-left: 1.5rem;
572
+ }
573
+
574
+ .advisor-message-text li {
575
+ margin-bottom: 0.25rem;
576
+ }
577
+
578
+ .advisor-message-text p {
579
+ margin-bottom: 0.75rem;
580
+ }
581
+
582
+ .advisor-message-text p:last-child {
583
+ margin-bottom: 0;
584
+ }
585
+
586
+
587
  /* Updated Message Actions Styles */
588
  .message-actions {
589
  margin-top: 12px;
 
1130
  font-size: 13px;
1131
  }
1132
 
1133
+ .advisor-message-text {
1134
+ font-size: 14px;
1135
+ }
1136
+
1137
  /* Basic ChatInput mobile styles */
1138
  .input-container .send-text {
1139
  display: inline;