# HR RAG Chatbot for WordPress

An intelligent HR policy chatbot powered by RAG (Retrieval-Augmented Generation) technology with support for Google Gemini and OpenAI.

## Features

### Core Functionality
- **RAG Technology**: Retrieves relevant policy information before generating answers
- **Multiple AI Providers**: Google Gemini (free tier) and OpenAI support
- **Smart Document Processing**: Automatic chunking and indexing
- **Context-Aware**: Collects employee information for personalized responses
- **Conversation Memory**: Maintains chat history for follow-up questions

### Document Management
- Upload HR policies in multiple formats (PDF, DOCX, TXT, MD)
- Manual text entry option
- Automatic page number tracking
- Table of Contents filtering
- Document versioning

### User Experience
- Clean, responsive chat interface
- Multi-line input (Shift+Enter)
- Source citations with page numbers
- Formatted responses (bullets, tables, bold text)
- Customizable appearance (colors, fonts)

### Administration
- Easy-to-use admin interface
- API key management
- Document indexing controls
- Chat log auditing
- Employee context configuration

## Installation

### Requirements
- WordPress 5.8 or higher
- PHP 7.4 or higher
- MySQL 5.6 or higher
- Google Gemini API key OR OpenAI API key

### Steps

1. **Download and Install**
   ```bash
   cd wp-content/plugins/
   # Upload plugin folder or install via WordPress admin
   ```

2. **Activate Plugin**
   - Go to WordPress Admin → Plugins
   - Find "HR RAG Chatbot"
   - Click "Activate"

3. **Configure API Key**
   - Go to HR RAG Chatbot → General Settings
   - Add your Gemini or OpenAI API key
   - Test the connection

4. **Upload Documents**
   - Go to Knowledge Base tab
   - Upload your HR policy documents
   - Click "Rebuild RAG Index"

5. **Add to Page**
   - Use shortcode: `[hr_rag_policy_chatbot]`
   - Or use Gutenberg block: "HR Policy Chatbot"

## Configuration

### Getting API Keys

#### Google Gemini (Free Tier Available)
1. Visit https://ai.google.dev/
2. Sign in with Google account
3. Go to "Get API Key"
4. Create new API key
5. Copy and paste into plugin settings

#### OpenAI (Paid)
1. Visit https://platform.openai.com/
2. Create account
3. Go to API Keys section
4. Create new secret key
5. Copy and paste into plugin settings

### Employee Context Fields

Configure which employee information to collect:
- Designation/Job Title
- Grade/Level
- Years of Service
- Department
- Location

### Appearance Customization

Customize the chatbot look:
- User message colors and fonts
- Bot message colors and fonts
- Background colors
- Font sizes

## Usage

### For Administrators

#### Uploading Documents
1. Go to HR RAG Chatbot → Knowledge Base
2. Choose upload method:
   - **File Upload**: PDF, DOCX, TXT, MD files
   - **Manual Entry**: Copy-paste text directly
3. Add document title
4. Click "Upload Document" or "Add Document"
5. Wait for indexing to complete

#### Managing Index
- **Rebuild Index**: Reprocess all documents
- **Clear Data**: Remove all indexed content
- **View Documents**: See uploaded files and chunk count

#### Monitoring Usage
- Go to Chat Logs tab
- View all conversations
- Search and filter logs
- Export for analysis

### For Employees

#### Asking Questions
1. Find chatbot on designated page
2. Type your HR policy question
3. Use Shift+Enter for multi-line questions
4. Click Send or press Enter

#### Example Questions
- "What is the medical allowance for Grade B employees?"
- "How many annual leave days do I get?"
- "What are the working hours?"
- "Tell me about the maternity leave policy"
- "What benefits am I eligible for?"

#### Follow-up Questions
The chatbot remembers context:
- "What about Grade C?" (after asking about Grade B)
- "And for 5 years of service?" (continuing previous topic)

## Technical Details

### Database Tables

The plugin creates three tables:

1. **wp_hr_rag_docs**: Stores uploaded documents
2. **wp_hr_rag_chunks**: Stores document chunks with embeddings
3. **wp_hr_rag_chats**: Stores chat logs

### RAG Process Flow

1. User asks question
2. System retrieves relevant document chunks
3. Chunks sent to AI with employee context
4. AI generates answer based only on provided context
5. Answer displayed with source citations

### Security Features

- Nonce verification on all forms
- Capability checks (manage_options)
- Input sanitization
- Output escaping
- API key encryption in database

### Performance Optimization

- Document size limits (200KB per document)
- Chunk limits (150 chunks per document)
- Memory management (512MB limit)
- Efficient database queries
- Session-based caching

## Troubleshooting

### Documents Not Indexing

**Problem**: Upload succeeds but shows "Not Indexed"

**Solutions**:
1. Check PHP memory limit (increase to 512MB)
2. Enable WordPress debug logging
3. Check debug.log for errors
4. Try smaller documents
5. Use manual text entry instead

### API Errors

**Problem**: "AI service unavailable" message

**Solutions**:
1. Verify API key is correct
2. Check API quota/limits
3. Test API connection in settings
4. Try alternative provider
5. Check internet connectivity

### No Answers Returned

**Problem**: Chatbot says "information not available"

**Solutions**:
1. Verify documents are indexed (check chunk count)
2. Rebuild RAG index
3. Check if question matches document content
4. Try rephrasing question
5. Upload more relevant documents

### Memory Errors

**Problem**: "Memory exhausted" error

**Solutions**:
1. Reduce document size
2. Increase PHP memory_limit
3. Clear old indexed data
4. Process documents one at a time

## Development

### File Structure
```
hr-rag-chatbot/
├── hr-rag-chatbot.php          # Main plugin file
├── includes/
│   ├── class-hr-rag-admin.php       # Admin interface
│   ├── class-hr-rag-indexer.php     # Document processing
│   ├── class-hr-rag-llm-factory.php # LLM abstraction
│   ├── class-hr-rag-llm-gemini.php  # Gemini client
│   ├── class-hr-rag-llm-openai.php  # OpenAI client
│   └── class-hr-rag-chat-handler.php # Chat logic
├── assets/
│   ├── css/
│   │   └── chat.css                 # Chatbot styles
│   └── js/
│       └── chat.js                  # Chatbot JavaScript
├── block/                           # Gutenberg block
├── readme.txt                       # WordPress.org readme
├── README.md                        # This file
└── LICENSE                          # GPL v2 license
```

### Extending the Plugin

#### Adding New LLM Provider

1. Create new class implementing `HR_RAG_LLM_Client`
2. Add to `HR_RAG_LLM_Factory::get_client()`
3. Add settings in admin interface

#### Custom Prompt Templates

Modify `HR_RAG_LLM_Factory::build_prompt()` to customize:
- System instructions
- Context formatting
- Response format

## Support

- **Documentation**: See readme.txt
- **Issues**: Report on GitHub or WordPress.org
- **Email**: support@yourwebsite.com

## Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create feature branch
3. Make changes
4. Submit pull request

## License

GPL v2 or later. See LICENSE file.

## Credits

- Built with WordPress
- Powered by Google Gemini and OpenAI
- RAG technology implementation

## Changelog

### 1.0.0 (2024)
- Initial release
- Google Gemini support
- OpenAI support
- RAG implementation
- Document management
- Employee context
- Appearance customization
- Chat logging
