# BMC Chatbot - ChatGPT Integration Guide

## 🎯 Overview

Chatbot widget fully integrated with OpenAI ChatGPT API. Easy to customize, production-ready implementation.

---

## 📁 Files Created

| File | Purpose |
|------|---------|
| `BmcBase/views_chatbot.py` | Backend API endpoint for ChatGPT |
| `BmcBase/static/js/chatbot.js` | Frontend chatbot widget & logic |
| `BmcBase/urls.py` | URL routing for chatbot API |
| `BmcBase/templates/BmcBase/base.html` | Script integration |

---

## 🚀 Setup Instructions

### Step 1: Install Required Dependencies

```bash
pip install openai requests
# or add to requirements.txt:
# openai==0.27.8
# requests>=2.28.0
```

### Step 2: Get OpenAI API Key

1. Go to: https://platform.openai.com/account/api-keys
2. Sign up / Log in with your account
3. Create new API key
4. Copy the key (looks like: `sk-...`)

### Step 3: Configure API Key

**Option A: Environment Variable (Recommended)**

Create `.env` file in project root:
```env
OPENAI_API_KEY=sk-your-actual-api-key-here
```

**Option B: Hardcode (Development only - NOT recommended)**

Edit `BmcBase/views_chatbot.py`:
```python
OPENAI_API_KEY = 'sk-your-actual-api-key-here'
```

### Step 4: Test the Chatbot

1. Restart Django server: `python manage.py runserver`
2. Open any page in browser
3. Look for green chatbot button in bottom-right corner
4. Click to open chat
5. Send a message - it should reply!

---

## 💬 How It Works

### Frontend Flow
1. User types message in chatbot input
2. JavaScript sends to Django backend API
3. Backend forwards to OpenAI ChatGPT
4. Response comes back to frontend
5. Message displays in chat

### Backend Flow
```
User Message → Django Views → OpenAI API → Response → JSON → Frontend
```

---

## ⚙️ Configuration Options

### Change Model (in `BmcBase/views_chatbot.py`)

```python
payload = {
    'model': 'gpt-3.5-turbo',  # Change this
    # Options:
    # 'gpt-3.5-turbo'  - Fast, cheaper
    # 'gpt-4'          - Slower, more accurate, expensive
    ...
}
```

### Change System Prompt

```python
'system_content': 'You are a helpful assistant for BMC Vietnam...'
# Change this to customize chatbot behavior
```

### Adjust Response Length

```python
'max_tokens': 500,  # Change this
# Higher = longer responses (costs more)
```

### Adjust Temperature (Creativity)

```python
'temperature': 0.7,  # Change this
# 0.0  = Deterministic (same answer every time)
# 1.0  = Creative (random responses)
```

---

## 🎨 Customize Appearance

### Change Colors

Edit `BmcBase/static/js/chatbot.js` in `addChatbotStyles()`:

```javascript
// Change this to your colors:
background: linear-gradient(135deg, #39b54a 0%, #2d8a38 100%);
// From:    #39b54a (BMC Green)
// To:      #2d8a38 (Dark Green)
```

### Change Position

```javascript
// In createChatbotWidget():
bottom: 20px;  // Distance from bottom
right: 20px;   // Distance from right
// Or use: left: 20px; for left side
```

### Change Welcome Message

```javascript
// In createChatbotWidget():
<p>Xin chào! 👋 Tôi là trợ lý ảo của BMC...</p>
// Translate or modify this text
```

### Change Icon

```html
<img src="/static/img/icon-chatbot.png" alt="Chatbot">
<!-- Replace with your own icon -->
```

---

## 💰 Pricing & Costs

### OpenAI API Pricing (as of 2024)

| Model | Input | Output |
|-------|-------|--------|
| gpt-3.5-turbo | $0.0005/1K tokens | $0.0015/1K tokens |
| gpt-4 | $0.03/1K tokens | $0.06/1K tokens |

### Estimate
- Average message: 50-100 tokens
- Average response: 100-200 tokens
- Cost per conversation: ~$0.0005-0.002
- 1000 conversations/day: ~$0.50-2.00/day

### Monitor Usage
1. Go to: https://platform.openai.com/account/usage/overview
2. Set usage limits to prevent overspending
3. Keep API key safe - don't share!

---

## 🔧 Advanced Customization

### Add Conversation History

Currently, each message is independent. To add memory:

```python
# In BmcBase/views_chatbot.py

# Add this to payload messages:
'messages': [
    {'role': 'system', 'content': SYSTEM_PROMPT},
    # ... previous messages here (add to context)
    {'role': 'user', 'content': user_message}
]
```

### Add User Authentication

```python
@login_required  # Add decorator
def chatbot_api(request):
    user = request.user
    # Now you can track per-user conversations
```

### Add Database Storage

```python
from django.db import models

class ChatMessage(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.CharField(max_length=10)  # 'user' or 'assistant'
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
```

### Add Rate Limiting

```python
from django.views.decorators.cache import cache_page

@cache_page(60)  # Cache responses for 1 minute
@csrf_exempt
def chatbot_api(request):
    ...
```

---

## 🐛 Troubleshooting

### Error: "ChatGPT API key not configured"

**Solution:**
- Check `.env` file exists in project root
- Verify `OPENAI_API_KEY=...` is set
- Restart Django server
- Check: `python manage.py shell` → `import os; print(os.getenv('OPENAI_API_KEY'))`

### Error: "401 Unauthorized"

**Solution:**
- API key is wrong or expired
- Go to https://platform.openai.com/account/api-keys
- Generate new key
- Update `.env` file
- Restart server

### Error: "Rate limit exceeded"

**Solution:**
- Too many requests to API
- Add delay between messages
- Increase `max_tokens` (less requests needed)
- Upgrade to paid tier

### Chatbot widget not showing

**Solution:**
- Clear browser cache (Ctrl+Shift+Delete)
- Check console for JavaScript errors (F12)
- Verify `chatbot.js` is loaded (check Network tab)
- Check base.html has `<script src="{% static 'js/chatbot.js' %}"></script>`

### Messages not sending

**Solution:**
- Check browser console (F12 → Console tab)
- Verify API endpoint is correct: `/api/chatbot/`
- Check Django logs for errors
- Verify CSRF token handling

---

## 📝 Quick Reference

### API Endpoint
```
POST /api/chatbot/
Content-Type: application/json

{
  "message": "Your question here"
}

Response:
{
  "success": true/false,
  "reply": "ChatGPT response",
  "error": "Error message (if any)"
}
```

### Files to Modify

1. **Add API Key:** `.env`
   ```env
   OPENAI_API_KEY=sk-...
   ```

2. **Change Colors:** `BmcBase/static/js/chatbot.js`
   - Search: `#39b54a` (BMC Green)
   - Replace with your color

3. **Change System Prompt:** `BmcBase/views_chatbot.py`
   - Line with `'system_content': 'You are...'`

4. **Change Icon:** `BmcBase/templates/BmcBase/base.html`
   - Search: `icon-chatbot.png`
   - Replace with your icon path

---

## 🚨 Security Notes

⚠️ **NEVER:**
- Commit `.env` file with API key
- Share API key in code/logs
- Expose API key to frontend
- Use same key in production as development

✅ **DO:**
- Use environment variables
- Rotate API keys regularly
- Monitor usage for suspicious activity
- Set spending limits on OpenAI account
- Review conversation logs

---

## 📞 Getting Help

- **OpenAI Docs:** https://platform.openai.com/docs
- **API Status:** https://status.openai.com/
- **Contact Support:** https://help.openai.com/

---

## 📦 Deployment Checklist

Before deploying to production:

- [ ] API key set in environment variables (not hardcoded)
- [ ] `.env` file in `.gitignore`
- [ ] CSRF protection enabled (`csrf_exempt` only for testing!)
- [ ] Rate limiting configured
- [ ] Spending limits set on OpenAI account
- [ ] Error messages don't expose sensitive info
- [ ] User authentication added (optional)
- [ ] Database logging of conversations (optional)
- [ ] Terms of service updated mentioning ChatGPT
- [ ] Privacy policy updated for data handling

---

## 🎓 Learn More

- Full Django Integration: [Django REST Framework](https://www.django-rest-framework.org/)
- OpenAI API: [Official Documentation](https://platform.openai.com/docs/api-reference)
- Frontend: Pure JavaScript, no dependencies required

---

**Status:** ✅ Production Ready  
**Last Updated:** April 18, 2026  
**API:** OpenAI ChatGPT 3.5 Turbo / GPT-4
