GeorgiosIoannouCoder's picture
Update tokens.md
7da5413 verified

A newer version of the Streamlit SDK is available: 1.40.2

Upgrade

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
    • 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
    • Go to API settings
    • Create new API key
    • Copy the key
  3. MongoDB URI:

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:
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