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
MongoDB URI:
- Follow here
2. Add Tokens to Hugging Face Space Settings
- Go INTO your Hugging Face Space settings (⚙️ icon)
- Find "Variables and secrets" section
- Add tokens as "New secret" one by one:
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 gives access to load_dotenv, find_dotenv
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 Method
import streamlit as st
# Load environment variable(s)
HUGGINGFACEHUB_API_TOKEN = st.secrets["HUGGINGFACEHUB_API_TOKEN"]
OPENAI_API_KEY = st.secrets["OPENAI_API_KEY"]
MONGO_URI = st.secrets["MONGO_URI"]
Security Best Practices
- Never commit tokens to version control
- Add
.env
to.gitignore
- Use read-only tokens when possible
- Regularly refresh your API keys
- Set appropriate token permissions