Author : Georgios Ioannou
Copyright © 2024 by Georgios Ioannou
Setting Up API Tokens for Hugging Face & OpenAI in Hugging Face Space
1. Create Required Tokens
Hugging Face Token:
- Log in to Hugging Face
- Go to Settings → Access Tokens
- Click "New token"
- Name your token and select permissions
- Copy the token
OpenAI API Key:
- Log in to OpenAI
- Go to API settings
- Create new API key
- Copy the key
2. Add Tokens to Space Settings
- Go to your Hugging Face Space settings (⚙️ icon)
- Find "Variables and secrets" section
- Add both tokens as "New secret" one by one:
MONGO_URI = "your_mongo_uri"
HUGGINGFACEHUB_API_TOKEN = "your_huggingface_token_here"
OPENAI_API_KEY = "your_openai_key_here"
3. Access Tokens in app.py
import os
# Load environment variable(s)
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
Alternative Methods
Using Streamlit secrets.toml
# .streamlit/secrets.toml
HUGGINGFACEHUB_API_TOKEN = "your_token_here"
OPENAI_API_KEY = "your_key_here"
Security Best Practices
- Never commit tokens to version control
- Add
.env
orsecrets.toml
to.gitignore
- Use read-only tokens when possible
- Regularly reresh your API keys
- Set appropriate token permissions