|
# Author : Georgios Ioannou |
|
# |
|
# Copyright © 2024 by Georgios Ioannou |
|
|
|
# Setting Up API Tokens for Hugging Face & OpenAI in Hugging Face Space |
|
|
|
## 1. Create Required Tokens |
|
1. **Hugging Face Token**: |
|
- Log in to [Hugging Face](https://huggingface.co) |
|
- Go to Settings → Access Tokens |
|
- Click "New token" |
|
- Name your token and select permissions |
|
- Copy the token |
|
|
|
2. **OpenAI API Key**: |
|
- Log in to [OpenAI](https://platform.openai.com) |
|
- Go to API settings |
|
- Create new API key |
|
- Copy the key |
|
|
|
3. **MongoDB URI**: |
|
- Follow [here](https://huggingface.co/spaces/GeorgiosIoannouCoder/cuny-tech-prep-tutorial-5/blob/main/mongodb_atlas_vector_search_setup.md#connection-string) |
|
|
|
## 2. Add Tokens to Hugging Face Space Settings |
|
1. Go INTO your Hugging Face Space settings (⚙️ icon) |
|
2. Find "Variables and secrets" section |
|
3. Add tokens as "New secret" one by one: |
|
```toml |
|
HUGGINGFACEHUB_API_TOKEN = "your_huggingface_token_here" |
|
OPENAI_API_KEY = "your_openai_key_here" |
|
MONGO_URI = "your_mongo_uri" |
|
``` |
|
|
|
## 3. Add Access Tokens in app.py |
|
|
|
### NOTE: pip install python-dotenv |
|
|
|
#### [python-dotenv](https://pypi.org/project/python-dotenv/) gives access to load_dotenv, find_dotenv |
|
```python |
|
import os |
|
from dotenv import load_dotenv, find_dotenv |
|
|
|
# Load environment variable(s) |
|
load_dotenv(find_dotenv()) |
|
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN") |
|
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") |
|
MONGO_URI = os.getenv("MONGO_URI") |
|
``` |
|
|
|
## Alternative Methods |
|
### Using Streamlit secrets.toml |
|
```toml |
|
# .streamlit/secrets.toml |
|
HUGGINGFACEHUB_API_TOKEN = "your_token_here" |
|
OPENAI_API_KEY = "your_key_here" |
|
MONGO_URI = "your_mongodb_uri_here" |
|
``` |
|
|
|
## Security Best Practices |
|
- Never commit tokens to version control |
|
- Add `.env` or `secrets.toml` to `.gitignore` |
|
- Use read-only tokens when possible |
|
- Regularly reresh your API keys |
|
- Set appropriate token permissions |
|
|