Getting started overview
This guide provides a rapid onboarding path for developers to begin using Hugging Face. It focuses on the essential steps required to set up an account, obtain credentials, and execute a basic API call using the Hugging Face Inference API, primarily through the Python transformers library. The process typically involves creating a Hugging Face Hub account, generating an API access token, and then utilizing this token for authentication when interacting with models programmatically or through hosted inference endpoints.
Hugging Face offers various ways to interact with its ecosystem, including the Hugging Face Hub for model and dataset management, the open-source transformers library for local model execution, and the Inference API for hosted model inference. This guide will focus on the Inference API for a quick, authenticated first request.
Quick Reference Guide
| Step | What to do | Where |
|---|---|---|
| 1. Account Creation | Register for a free Hugging Face Hub account. | Hugging Face Join Page |
| 2. Generate API Token | Create a new API token with 'write' access for full functionality. | Hugging Face Tokens Settings |
| 3. Install SDK | Install the transformers Python library. |
Terminal (pip install transformers) |
| 4. Make Request | Send an authenticated request to the Inference API. | Python script or Jupyter notebook |
Create an account and get keys
To access most Hugging Face services, including the Inference API and the ability to upload models or datasets to the Hub, you need a Hugging Face account and an API access token. The API token serves as your authentication credential.
1. Create a Hugging Face account
- Navigate to the Hugging Face join page.
- Sign up using your email address, a Google account, or a GitHub account.
- Follow the on-screen prompts to complete the registration process, including email verification if you used an email address.
2. Generate an API access token
Once your account is created and verified, you can generate an API token:
- Log in to your Hugging Face account.
- Access your API Tokens settings page.
- Click the "New token" button.
- Provide a descriptive name for your token (e.g., "API Spine Test").
- Select the "Role" for the token. For most development purposes, including making inference requests and potentially pushing models, select
write. Areadtoken is sufficient only for public model inference or viewing public Hub resources without modification. - Click "Generate a token".
- Crucially, copy the generated token immediately. This token is sensitive and will only be fully displayed once upon creation. Store it securely, as you will need it for authenticating your API requests. Treat this token like a password; do not expose it in public repositories or client-side code.
Your first request
This section demonstrates how to make an authenticated request to the Hugging Face Inference API using the Python transformers library. The example will use a text classification model.
1. Install the transformers library
If you haven't already, install the necessary Python library. It is recommended to use a virtual environment.
pip install transformers
2. Prepare your environment and API token
Store your Hugging Face API token securely. It is best practice to load it from an environment variable rather than hardcoding it into your script.
import os
from transformers import pipeline
# Set your Hugging Face API token as an environment variable
# Example (replace 'hf_YOUR_TOKEN_HERE' with your actual token):
# export HF_TOKEN="hf_YOUR_TOKEN_HERE"
# or set it directly in your script for testing (not recommended for production)
# os.environ["HF_TOKEN"] = "hf_YOUR_TOKEN_HERE"
# Retrieve the token from an environment variable
hf_token = os.getenv("HF_TOKEN")
if not hf_token:
print("Error: Hugging Face API token not found. Please set the HF_TOKEN environment variable.")
exit()
3. Make an authenticated Inference API request
Now, use the pipeline function from the transformers library, which handles interaction with the Inference API directly when a token is provided and the model is not available locally. For this example, we'll use a sentiment analysis model.
# Initialize a sentiment analysis pipeline
# The 'model' parameter can specify any model available on the Hugging Face Hub.
# 'device=-1' implies using CPU; use 'device=0' for GPU if available and configured.
# The 'token' argument ensures the request is authenticated.
pipeline_classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", token=hf_token)
# Define the text to analyze
text_to_classify = "I love using Hugging Face for machine learning projects!"
# Perform inference
results = pipeline_classifier(text_to_classify)
# Print the results
print(f"Input Text: '{text_to_classify}'")
print(f"Sentiment Analysis Results: {results}")
# Example with another input
text_to_classify_negative = "This API response was unexpectedly slow."
results_negative = pipeline_classifier(text_to_classify_negative)
print(f"Input Text: '{text_to_classify_negative}'")
print(f"Sentiment Analysis Results: {results_negative}")
When you run this code, the pipeline function will send your text to the specified model hosted on Hugging Face's Inference API, authenticated with your token, and return the predicted sentiment. The initial call might take longer as the model is loaded.
Common next steps
After successfully making your first request, consider these common next steps to further your integration and development with Hugging Face:
- Explore the Hugging Face Hub: Browse the vast collection of models, datasets, and Spaces. The Hub hosts models for various tasks, including natural language processing, computer vision, and audio, often with accompanying documentation and example usage.
- Experiment with different models: Modify your Python script to use other models from the Hub. The
pipelinefunction supports many tasks, and you can find compatible models by searching the Hugging Face pipelines documentation. - Local Inference: For performance or privacy reasons, you might want to run models locally. The
transformerslibrary allows you to download models and run inference without relying on the Inference API. This typically involves loading a model and tokenizer directly. - Fine-tuning models: Hugging Face provides tools and guides for fine-tuning pre-trained models on your custom datasets. This can improve model performance for domain-specific tasks.
- Deploy Inference Endpoints: For production-grade deployments, Hugging Face offers Inference Endpoints. These are managed, scalable, and dedicated deployments of your models, providing a robust API for your applications.
- Utilize Hugging Face Spaces: Spaces allow you to build and host interactive machine learning applications directly on the Hugging Face Hub, often using Streamlit or Gradio. This is useful for demonstrating models or creating prototypes. For examples, consult the Hugging Face Spaces overview.
- Explore open standards: Understand how machine learning models are often shared and versioned. For instance, the use of Git and Git LFS for large files is common in ML workflows, as detailed in Git Large File Storage documentation.
Troubleshooting the first call
If your first API call encounters issues, consider the following common troubleshooting steps:
- API Token Validation: Ensure your
HF_TOKENenvironment variable is correctly set and contains the exact token copied from the Hugging Face settings. Verify there are no leading or trailing spaces. If you regenerated the token, update your environment variable. - Network Connectivity: Confirm your system has an active internet connection and can reach
huggingface.co. Proxy settings or firewalls might block access. - Model Name Accuracy: Double-check the model identifier in your code (e.g.,
"distilbert-base-uncased-finetuned-sst-2-english"). A typo will result in a "model not found" error. Verify the model exists and is public (or you have access if it's private) on the Hugging Face Models Hub. - Library Installation: Confirm the
transformerslibrary is installed correctly in your active Python environment. Runpip list | grep transformersto verify its presence and version. - Python Environment: Ensure you are running your script in the correct Python environment where
transformersis installed. If using a virtual environment, activate it before running your script. - Rate Limits: The free tier of the Inference API has rate limits. If you make many requests quickly, you might temporarily hit these limits. The error message will typically indicate a rate limit exceeded status.
- Error Messages: Carefully read any error messages returned by the API or the
transformerslibrary. They often provide specific clues about the problem, such as authentication failures, invalid model names, or network issues. - Check Hugging Face Status: In rare cases, there might be a service outage. Check the Hugging Face status page for any ongoing issues.