Spaces:
Runtime error
Runtime error
File size: 9,457 Bytes
330b6e4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | # Environment Setup Guide
This guide walks you through setting up the Multi-Language Chat Agent application in different environments.
## Quick Start
For the fastest setup, use the automated setup script:
```bash
# Development environment
python scripts/setup_environment.py --environment development
# Production environment
python scripts/setup_environment.py --environment production
# Testing environment
python scripts/setup_environment.py --environment testing
```
## Manual Setup
### 1. Prerequisites
#### System Requirements
- **Python 3.8+**: Check with `python --version`
- **PostgreSQL 12+**: For persistent data storage
- **Redis 6+**: For caching and sessions (optional but recommended)
- **Git**: For version control
#### Install System Dependencies
**Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install python3 python3-pip python3-venv postgresql postgresql-contrib redis-server
```
**macOS (with Homebrew):**
```bash
brew install python postgresql redis
```
**Windows:**
- Install Python from python.org
- Install PostgreSQL from postgresql.org
- Install Redis from GitHub releases or use WSL
### 2. Project Setup
#### Clone Repository
```bash
git clone <repository-url>
cd chat-agent
```
#### Create Virtual Environment
```bash
python -m venv venv
# Activate virtual environment
# Linux/macOS:
source venv/bin/activate
# Windows:
venv\Scripts\activate
```
#### Install Python Dependencies
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
### 3. Database Setup
#### PostgreSQL Setup
**Create Database and User:**
```sql
-- Connect to PostgreSQL as superuser
sudo -u postgres psql
-- Create database and user
CREATE DATABASE chat_agent_db;
CREATE USER chatuser WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE chat_agent_db TO chatuser;
-- For development, you might want to create separate databases
CREATE DATABASE chat_agent_dev;
CREATE DATABASE chat_agent_test;
GRANT ALL PRIVILEGES ON DATABASE chat_agent_dev TO chatuser;
GRANT ALL PRIVILEGES ON DATABASE chat_agent_test TO chatuser;
\q
```
**Test Connection:**
```bash
psql -h localhost -U chatuser -d chat_agent_db -c "SELECT version();"
```
#### Redis Setup
**Start Redis:**
```bash
# Linux (systemd)
sudo systemctl start redis
sudo systemctl enable redis
# macOS
brew services start redis
# Manual start
redis-server
```
**Test Connection:**
```bash
redis-cli ping
# Should return: PONG
```
### 4. Environment Configuration
#### Create Environment File
Copy the appropriate environment template:
```bash
# Development
cp config/development.env .env
# Production
cp config/production.env .env
# Testing
cp config/testing.env .env
```
#### Configure Environment Variables
Edit `.env` file with your actual values:
```bash
# Required Configuration
GROQ_API_KEY=your_groq_api_key_here
SECRET_KEY=your_secure_secret_key_here
# Database Configuration
DATABASE_URL=postgresql://chatuser:your_password@localhost:5432/chat_agent_db
# Redis Configuration (optional)
REDIS_URL=redis://localhost:6379/0
# Application Configuration
FLASK_ENV=development # or production
FLASK_DEBUG=True # False for production
```
#### Generate Secret Key
```python
# Generate a secure secret key
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
### 5. Database Initialization
#### Run Migrations
```bash
# Initialize database with schema
python scripts/init_db.py init --config development
# Check migration status
python scripts/init_db.py status --config development
# Seed with sample data (optional)
python scripts/init_db.py seed --config development
```
#### Manual Migration (Alternative)
```bash
python migrations/migrate.py migrate --config development
```
### 6. Application Startup
#### Development Server
```bash
python app.py
```
The application will be available at `http://localhost:5000`
#### Production Server
```bash
# Install production server
pip install gunicorn
# Start with Gunicorn
gunicorn --bind 0.0.0.0:5000 --workers 4 --worker-class eventlet app:app
```
### 7. Verification
#### Test Health Endpoints
```bash
# Basic health check
curl http://localhost:5000/health/
# Detailed health check
curl http://localhost:5000/health/detailed
# Expected response:
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"service": "chat-agent",
"version": "1.0.0"
}
```
#### Test Chat Interface
1. Open browser to `http://localhost:5000`
2. You should see the chat interface
3. Try sending a message
4. Verify WebSocket connection works
#### Test API Endpoints
```bash
# Test session creation
curl -X POST http://localhost:5000/api/sessions \
-H "Content-Type: application/json" \
-d '{"user_id": "test_user", "language": "python"}'
# Test language switching
curl -X PUT http://localhost:5000/api/sessions/SESSION_ID/language \
-H "Content-Type: application/json" \
-d '{"language": "javascript"}'
```
## Environment-Specific Configuration
### Development Environment
**Features:**
- Debug mode enabled
- Detailed logging
- Hot reload
- Development database
- Relaxed security settings
**Configuration:**
```bash
FLASK_ENV=development
FLASK_DEBUG=True
LOG_LEVEL=DEBUG
DATABASE_URL=postgresql://chatuser:password@localhost:5432/chat_agent_dev
```
**Additional Tools:**
```bash
# Install development tools
pip install flask-debugtoolbar ipdb watchdog
# Enable debug toolbar
export FLASK_DEBUG_TB_ENABLED=True
```
### Production Environment
**Features:**
- Debug mode disabled
- Optimized logging
- Production database
- Enhanced security
- Performance monitoring
**Configuration:**
```bash
FLASK_ENV=production
FLASK_DEBUG=False
LOG_LEVEL=INFO
DATABASE_URL=postgresql://user:pass@prod-host:5432/chat_agent_prod
SECRET_KEY=very_secure_secret_key
```
**Security Considerations:**
- Use environment variables for secrets
- Enable HTTPS
- Configure firewall
- Set up monitoring
- Regular backups
### Testing Environment
**Features:**
- In-memory database
- Isolated test data
- Fast execution
- Minimal logging
**Configuration:**
```bash
FLASK_ENV=testing
TESTING=True
DATABASE_URL=sqlite:///:memory:
REDIS_URL=redis://localhost:6379/1
LOG_LEVEL=WARNING
```
**Running Tests:**
```bash
# Set testing environment
export FLASK_ENV=testing
# Run tests
python -m pytest tests/
python -m pytest tests/ --cov=chat_agent
```
## Troubleshooting
### Common Issues
#### 1. Import Errors
```bash
# Ensure virtual environment is activated
source venv/bin/activate
# Reinstall dependencies
pip install -r requirements.txt
```
#### 2. Database Connection Issues
```bash
# Check PostgreSQL service
sudo systemctl status postgresql
# Test connection manually
psql -h localhost -U chatuser -d chat_agent_db
# Check environment variables
echo $DATABASE_URL
```
#### 3. Redis Connection Issues
```bash
# Check Redis service
sudo systemctl status redis
# Test connection
redis-cli ping
# Check Redis URL
echo $REDIS_URL
```
#### 4. Permission Issues
```bash
# Fix file permissions
chmod +x scripts/*.py
# Fix directory permissions
sudo chown -R $USER:$USER .
```
#### 5. Port Already in Use
```bash
# Find process using port 5000
lsof -i :5000
# Kill process
kill -9 PID
# Use different port
export PORT=5001
python app.py
```
### Logging and Debugging
#### Enable Debug Logging
```bash
export LOG_LEVEL=DEBUG
export FLASK_DEBUG=True
python app.py
```
#### View Logs
```bash
# Application logs
tail -f logs/chat_agent.log
# System logs
journalctl -f -u postgresql
journalctl -f -u redis
```
#### Database Debugging
```bash
# Connect to database
psql -h localhost -U chatuser -d chat_agent_db
# Check tables
\dt
# Check migrations
SELECT * FROM schema_migrations;
# Check sample data
SELECT * FROM chat_sessions LIMIT 5;
```
## Performance Optimization
### Database Optimization
```sql
-- Create indexes for better performance
CREATE INDEX CONCURRENTLY idx_messages_session_timestamp
ON messages(session_id, timestamp);
CREATE INDEX CONCURRENTLY idx_sessions_user_active
ON chat_sessions(user_id, is_active);
```
### Redis Optimization
```bash
# Configure Redis for production
# Edit /etc/redis/redis.conf
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000
```
### Application Optimization
```python
# Use connection pooling
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 10,
'pool_recycle': 120,
'pool_pre_ping': True
}
# Configure Redis connection pool
REDIS_CONNECTION_POOL = {
'max_connections': 20,
'retry_on_timeout': True
}
```
## Next Steps
After successful setup:
1. **Configure Groq API**: Add your actual API key
2. **Set up monitoring**: Configure health checks and logging
3. **Security hardening**: Review security settings
4. **Performance testing**: Test with expected load
5. **Backup strategy**: Set up database backups
6. **Documentation**: Document your specific configuration
For deployment to production, see [DEPLOYMENT.md](DEPLOYMENT.md). |