Overview
RAG Chat requires environment variables to authenticate with external services. All variables should be stored in a.env file in the project root directory.
Required Variables
OPENAI_API_KEY
Your OpenAI API key for accessing GPT models and embedding services.
- Generating text embeddings via
OpenAIEmbeddings() - Powering chat responses through
ChatOpenAI() - Both embedding and chat functionality require a valid API key
Setup Instructions
1. Obtain an OpenAI API Key
Create OpenAI Account
Visit platform.openai.com and sign up or log in to your account.
Navigate to API Keys
Go to Settings → API Keys or visit platform.openai.com/api-keys directly.
Create New Key
Click “Create new secret key” and give it a descriptive name (e.g., “RAG Chat Development”).
2. Configure Your Project
Security Best Practices
Protect Your API Key
Add .env to .gitignore
Add .env to .gitignore
Ensure The project includes
.env is listed in your .gitignore file:.gitignore
.env.example as a template with empty values.Use Separate Keys for Different Environments
Use Separate Keys for Different Environments
Create different API keys for:
- Development and testing
- Production deployments
- Team members (if applicable)
Monitor API Usage
Monitor API Usage
Regularly check your OpenAI dashboard for:
- Unexpected usage spikes
- API calls from unknown sources
- Cost tracking and budget alerts
Rotate Keys Regularly
Rotate Keys Regularly
For production applications:
- Rotate API keys every 90 days
- Immediately rotate if a key may have been exposed
- Delete unused keys from the OpenAI dashboard
Deployment Configuration
When deploying RAG Chat, configure environment variables through your hosting platform:- Streamlit Cloud
- Docker
- Cloud Platforms
- Go to your app settings in Streamlit Cloud
- Navigate to Secrets
- Add your environment variables in TOML format:
Troubleshooting
AuthenticationError: Invalid API Key
AuthenticationError: Invalid API Key
Symptoms: Application crashes with OpenAI authentication errorSolutions:
- Verify your API key is correctly copied (no extra spaces)
- Check that
.envis in the project root directory - Ensure the key starts with
sk-proj-orsk- - Verify the key hasn’t been revoked in OpenAI dashboard
Environment Variable Not Loading
Environment Variable Not Loading
Symptoms: Application can’t find
OPENAI_API_KEYSolutions:- Restart the application after creating
.env - Check that
python-dotenvis installed:pip install python-dotenv - Verify
.envfile is not named.env.txtor similar - Check file permissions (should be readable)
Rate Limit Errors
Rate Limit Errors
Symptoms:
RateLimitError from OpenAI APISolutions:- Check your API usage limits in OpenAI dashboard
- Upgrade to a paid OpenAI account if on free tier
- Implement rate limiting in your application
- Consider using a lower-tier model (e.g.,
gpt-3.5-turbo)