Re_Backend/ADMIN_AI_CONFIGURATION.md

427 lines
10 KiB
Markdown

# Admin Panel - AI Provider Configuration
## Overview
Admins can configure AI providers **directly through the admin panel** without touching code or `.env` files. The system supports three AI providers with automatic failover.
---
## 🎯 Quick Start for Admins
### Step 1: Access Admin Panel
Navigate to the admin configurations page in your workflow system.
### Step 2: Configure AI Provider
Look for the **AI Configuration** section with these settings:
| Setting | Description | Example Value |
|---------|-------------|---------------|
| **AI Provider** | Choose your AI provider | `claude`, `openai`, or `gemini` |
| **Claude API Key** | API key from Anthropic | `sk-ant-xxxxxxxxxxxxx` |
| **OpenAI API Key** | API key from OpenAI | `sk-proj-xxxxxxxxxxxxx` |
| **Gemini API Key** | API key from Google | `AIzaxxxxxxxxxxxxxxx` |
| **Enable AI Features** | Turn AI on/off | `true` or `false` |
### Step 3: Get Your API Key
Choose ONE provider and get an API key:
#### Option A: Claude (Recommended)
1. Go to https://console.anthropic.com
2. Create account / Sign in
3. Generate API key
4. Copy key (starts with `sk-ant-`)
#### Option B: OpenAI
1. Go to https://platform.openai.com
2. Create account / Sign in
3. Navigate to API keys
4. Create new key
5. Copy key (starts with `sk-proj-` or `sk-`)
#### Option C: Gemini (Free Tier Available!)
1. Go to https://ai.google.dev
2. Sign in with Google account
3. Get API key
4. Copy key
### Step 4: Configure in Admin Panel
**Example: Setting up Claude**
1. Set **AI Provider** = `claude`
2. Set **Claude API Key** = `sk-ant-api03-xxxxxxxxxxxxx`
3. Leave other API keys empty (optional)
4. Set **Enable AI Features** = `true`
5. Click **Save Configuration**
**Done!** The system will automatically initialize Claude.
---
## 🔄 How It Works
### Automatic Initialization
When you save the configuration:
```
Admin saves config
System clears cache
AI Service reads new config from database
Initializes selected provider (Claude/OpenAI/Gemini)
✅ AI features active
```
**You'll see in server logs:**
```
info: [Admin] AI configuration 'AI_PROVIDER' updated
info: [AI Service] Reinitializing AI provider from updated configuration...
info: [AI Service] Preferred provider from config: claude
info: [AI Service] ✅ Claude provider initialized
info: [AI Service] ✅ Active provider: Claude (Anthropic)
info: [Admin] AI service reinitialized with Claude (Anthropic)
```
### Automatic Failover
If your primary provider fails, the system automatically tries alternatives:
```sql
-- Example: Admin configured Claude, but API key is invalid
UPDATE admin_configurations
SET config_value = 'claude'
WHERE config_key = 'AI_PROVIDER';
UPDATE admin_configurations
SET config_value = 'sk-ant-INVALID'
WHERE config_key = 'CLAUDE_API_KEY';
```
**System Response:**
```
warn: [AI Service] Claude API key not configured.
warn: [AI Service] Preferred provider unavailable. Trying fallbacks...
info: [AI Service] ✅ OpenAI provider initialized
info: [AI Service] ✅ Using fallback provider: OpenAI (GPT-4)
```
**AI features still work!** (if OpenAI key is configured)
---
## 📋 Configuration Guide by Provider
### Claude (Anthropic) - Best for Production
**Pros:**
- ✅ High-quality, professional output
- ✅ Excellent instruction following
- ✅ Good for formal business documents
- ✅ Reliable and consistent
**Cons:**
- ⚠️ Paid service (no free tier)
- ⚠️ Requires account setup
**Configuration:**
```
AI_PROVIDER = claude
CLAUDE_API_KEY = sk-ant-api03-xxxxxxxxxxxxx
```
**Cost:** ~$0.004 per conclusion generation
---
### OpenAI (GPT-4) - Industry Standard
**Pros:**
- ✅ Fast response times
- ✅ Well-documented
- ✅ Widely used and trusted
- ✅ Good performance
**Cons:**
- ⚠️ Paid service
- ⚠️ Higher cost than alternatives
**Configuration:**
```
AI_PROVIDER = openai
OPENAI_API_KEY = sk-proj-xxxxxxxxxxxxx
```
**Cost:** ~$0.005 per conclusion generation
---
### Gemini (Google) - Cost-Effective
**Pros:**
-**Free tier available!**
- ✅ Good performance
- ✅ Easy Google integration
- ✅ Generous rate limits
**Cons:**
- ⚠️ Slightly lower quality than Claude/GPT-4
- ⚠️ Rate limits on free tier
**Configuration:**
```
AI_PROVIDER = gemini
GEMINI_API_KEY = AIzaxxxxxxxxxxxxxxx
```
**Cost:** **FREE** (up to rate limits), then $0.0001 per generation
---
## 🔐 Security Best Practices
### 1. API Key Storage
-**Stored in database** (encrypted in production)
-**Marked as sensitive** (hidden in UI by default)
-**Never exposed** to frontend
-**Admin access only**
### 2. Key Rotation
- Rotate API keys every 3-6 months
- Update in admin panel
- System automatically reinitializes
### 3. Access Control
- Only **Super Admins** can update AI configurations
- Regular users cannot view API keys
- All changes are logged in audit trail
---
## 🧪 Testing AI Configuration
### Method 1: Check Status via API
```bash
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
http://localhost:5000/api/v1/ai/status
```
**Response:**
```json
{
"success": true,
"data": {
"available": true,
"provider": "Claude (Anthropic)",
"status": "active"
}
}
```
### Method 2: Check Server Logs
Look for initialization logs when server starts:
```
info: [AI Service] Preferred provider from config: claude
info: [AI Service] ✅ Claude provider initialized
info: [AI Service] ✅ Active provider: Claude (Anthropic)
```
### Method 3: Test in Application
1. Create a workflow request
2. Complete all approvals
3. As initiator, click "Finalize & Close Request"
4. Click "Generate with AI"
5. Should see AI-generated conclusion
---
## 🔄 Switching Providers
### Example: Switching from Claude to Gemini
**Current Configuration:**
```
AI_PROVIDER = claude
CLAUDE_API_KEY = sk-ant-xxxxxxxxxxxxx
```
**Steps to Switch:**
1. **Get Gemini API key** from https://ai.google.dev
2. **Open Admin Panel** → AI Configuration
3. **Update settings:**
- Set **AI Provider** = `gemini`
- Set **Gemini API Key** = `AIzaxxxxxxxxxxxxxxx`
4. **Click Save**
**Result:**
```
info: [Admin] AI configuration 'AI_PROVIDER' updated
info: [AI Service] Reinitializing...
info: [AI Service] Preferred provider from config: gemini
info: [AI Service] ✅ Gemini provider initialized
info: [AI Service] ✅ Active provider: Gemini (Google)
```
**Done!** System now uses Gemini. **No server restart needed!**
---
## 💡 Pro Tips
### 1. Multi-Provider Setup (Recommended)
Configure ALL three providers for maximum reliability:
```
AI_PROVIDER = claude
CLAUDE_API_KEY = sk-ant-xxxxxxxxxxxxx
OPENAI_API_KEY = sk-proj-xxxxxxxxxxxxx
GEMINI_API_KEY = AIzaxxxxxxxxxxxxxxx
AI_ENABLED = true
```
**Benefits:**
- If Claude is down → automatically uses OpenAI
- If OpenAI is down → automatically uses Gemini
- **Zero downtime** for AI features!
### 2. Cost Optimization
**Development/Testing:**
- Use `gemini` (free tier)
- Switch to paid provider only for production
**Production:**
- Use `claude` for best quality
- Or use `openai` for fastest responses
### 3. Monitor Usage
Check which provider is being used:
```sql
SELECT
ai_model_used,
COUNT(*) as usage_count,
AVG(ai_confidence_score) as avg_confidence
FROM conclusion_remarks
WHERE created_at > NOW() - INTERVAL '30 days'
GROUP BY ai_model_used;
```
---
## ⚠️ Troubleshooting
### Issue: "AI Service not configured"
**Check:**
1. Is `AI_ENABLED` set to `true`?
2. Is at least one API key configured?
3. Is the API key valid?
**Fix:**
- Open Admin Panel
- Verify AI Provider setting
- Re-enter API key
- Click Save
### Issue: "Failed to generate conclusion"
**Check:**
1. API key still valid (not expired/revoked)?
2. Provider service available (check status.anthropic.com, etc.)?
3. Sufficient API quota/credits?
**Fix:**
- Test API key manually (use provider's playground)
- Check account balance/quota
- Try switching to different provider
### Issue: Provider keeps failing
**Fallback Strategy:**
1. Configure multiple providers
2. System will auto-switch
3. Check logs to see which one succeeded
---
## 📊 Admin Panel UI
The admin configuration page should show:
```
┌─────────────────────────────────────────────┐
│ AI Configuration │
├─────────────────────────────────────────────┤
│ │
│ AI Provider: [claude ▼] │
│ Options: claude, openai, gemini │
│ │
│ Claude API Key: [••••••••••••••] [Show] │
│ Enter Claude API key from console.anthr... │
│ │
│ OpenAI API Key: [••••••••••••••] [Show] │
│ Enter OpenAI API key from platform.open... │
│ │
│ Gemini API Key: [••••••••••••••] [Show] │
│ Enter Gemini API key from ai.google.dev │
│ │
│ Enable AI Features: [✓] Enabled │
│ │
│ Current Status: ✅ Active (Claude) │
│ │
│ [Save Configuration] [Test AI] │
└─────────────────────────────────────────────┘
```
---
## 🎯 Summary
**Key Advantages:**
-**No code changes** - Configure through UI
-**No server restart** - Hot reload on save
-**Automatic failover** - Multiple providers
-**Vendor flexibility** - Switch anytime
-**Audit trail** - All changes logged
-**Secure storage** - API keys encrypted
**Admin Actions Required:**
1. Choose AI provider
2. Enter API key
3. Click Save
4. Done!
**User Impact:**
- Zero - users just click "Generate with AI"
- System handles provider selection automatically
- Professional conclusions generated seamlessly
---
## 📞 Support
**Provider Documentation:**
- Claude: https://docs.anthropic.com
- OpenAI: https://platform.openai.com/docs
- Gemini: https://ai.google.dev/docs
**For System Issues:**
- Check `/api/v1/ai/status` endpoint
- Review server logs for initialization
- Verify admin_configurations table entries