HuggingFace Model Inference Service
Overview
This skill provides procedural guidance for setting up HuggingFace model inference services. It covers model downloading, caching strategies, Flask API creation, and service deployment patterns.
Workflow
Phase 1: Environment Setup
Verify package manager availability
- Check for
uv, pip, or conda before installing dependencies
- Prefer
uv for faster dependency resolution when available
Install required packages
- Core:
transformers, torch (or tensorflow)
- API:
flask for REST endpoints
- Set appropriate timeouts for large package installations (300+ seconds)
Create model cache directory
- Establish a dedicated directory for model storage (e.g.,
/app/model_cache/model_name)
- Create parent directories as needed before downloading
Phase 2: Model Download
Download the model separately from API startup
- Use a dedicated download script or inline download before starting the service
- This prevents timeout issues during API initialization
Specify cache directory explicitly
from transformers import pipeline
model = pipeline("task-type", model="model-name", cache_dir="/path/to/cache")
Verification step (commonly missed)
- After download, verify model files exist in the target directory
- List directory contents to confirm successful download
Phase 3: API Creation
Flask application structure
from flask import Flask, request, jsonify
from transformers import pipeline
app = Flask(__name__)
model = None # Load at startup
@app.route('/predict', methods=['POST'])
def predict():
# Handle inference
pass
Input validation requirements
- Check for required fields in request JSON
- Validate field types (string, number, etc.)
- Handle empty or whitespace-only inputs
- Return descriptive error messages with appropriate HTTP status codes
Error response format
- Use consistent JSON structure:
{"error": "message"}
- Return 400 for client errors, 500 for server errors
Phase 4: Service Deployment
Host and port configuration
- Bind to
0.0.0.0 for external accessibility
- Use specified port (commonly 5000)
- Example:
app.run(host='0.0.0.0', port=5000)
Background execution
- Start Flask in background mode for testing
- Allow startup time (2-3 seconds) before sending test requests
Verification Strategies
Model Download Verification
- List cache directory contents after download
- Confirm expected model files exist (config.json, model weights, tokenizer files)
API Functionality Testing
Test these scenarios in order:
Positive case: Valid input that should succeed
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"text": "valid input text"}'
Negative case: Different valid input to verify varied responses
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"text": "different input text"}'
Error case: Missing required field
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{}'
Extended Edge Cases (Optional)
- Empty string input
- Very long text input
- Non-JSON content type
- Malformed JSON
- Wrong field type (number instead of string)
Common Pitfalls
Installation Issues
- Insufficient timeout: Large packages like
torch require extended timeouts (5+ minutes)
- Missing system dependencies: Some models require additional system packages
Model Loading Issues
- Cold start timeout: Loading models at first request causes timeouts; load at startup instead
- Memory constraints: Large models may exceed available RAM; check model requirements
API Issues
- Development server warning: Flask development server is not suitable for production; acceptable for testing but note the limitation
- No graceful shutdown: Consider signal handling for clean termination
- No health check endpoint: Adding
/health endpoint aids debugging
Process Management
- Background process verification: After starting in background, verify the process is running
- Port conflicts: Check if the specified port is already in use before starting
Task Planning Template
When approaching HuggingFace inference tasks, structure work as follows:
- Environment verification (package manager, system requirements)
- Dependency installation with appropriate timeouts
- Cache directory creation
- Model download with explicit cache path
- Model download verification
- API script creation with validation
- Service startup in background
- Functional testing (positive, negative, error cases)
- Edge case testing (if time permits)
1---2name: hf-model-inference3description: Guidance for setting up HuggingFace model inference services with Flask APIs. This skill applies when downloading HuggingFace models, creating inference endpoints, or building ML model serving APIs. Use for tasks involving transformers library, model caching, and REST API creation for ML models.4---56# HuggingFace Model Inference Service78## Overview910This skill provides procedural guidance for setting up HuggingFace model inference services. It covers model downloading, caching strategies, Flask API creation, and service deployment patterns.1112## Workflow1314### Phase 1: Environment Setup15161. **Verify package manager availability**17 - Check for `uv`, `pip`, or `conda` before installing dependencies18 - Prefer `uv` for faster dependency resolution when available19202. **Install required packages**21 - Core: `transformers`, `torch` (or `tensorflow`)22 - API: `flask` for REST endpoints23 - Set appropriate timeouts for large package installations (300+ seconds)24253. **Create model cache directory**26 - Establish a dedicated directory for model storage (e.g., `/app/model_cache/model_name`)27 - Create parent directories as needed before downloading2829### Phase 2: Model Download30311. **Download the model separately from API startup**32 - Use a dedicated download script or inline download before starting the service33 - This prevents timeout issues during API initialization34352. **Specify cache directory explicitly**36 ```python37 from transformers import pipeline38 model = pipeline("task-type", model="model-name", cache_dir="/path/to/cache")39 ```40413. **Verification step** (commonly missed)42 - After download, verify model files exist in the target directory43 - List directory contents to confirm successful download4445### Phase 3: API Creation46471. **Flask application structure**48 ```python49 from flask import Flask, request, jsonify50 from transformers import pipeline5152 app = Flask(__name__)53 model = None # Load at startup5455 @app.route('/predict', methods=['POST'])56 def predict():57 # Handle inference58 pass59 ```60612. **Input validation requirements**62 - Check for required fields in request JSON63 - Validate field types (string, number, etc.)64 - Handle empty or whitespace-only inputs65 - Return descriptive error messages with appropriate HTTP status codes66673. **Error response format**68 - Use consistent JSON structure: `{"error": "message"}`69 - Return 400 for client errors, 500 for server errors7071### Phase 4: Service Deployment72731. **Host and port configuration**74 - Bind to `0.0.0.0` for external accessibility75 - Use specified port (commonly 5000)76 - Example: `app.run(host='0.0.0.0', port=5000)`77782. **Background execution**79 - Start Flask in background mode for testing80 - Allow startup time (2-3 seconds) before sending test requests8182## Verification Strategies8384### Model Download Verification85- List cache directory contents after download86- Confirm expected model files exist (config.json, model weights, tokenizer files)8788### API Functionality Testing89Test these scenarios in order:90911. **Positive case**: Valid input that should succeed92 ```bash93 curl -X POST http://localhost:5000/predict \94 -H "Content-Type: application/json" \95 -d '{"text": "valid input text"}'96 ```97982. **Negative case**: Different valid input to verify varied responses99 ```bash100 curl -X POST http://localhost:5000/predict \101 -H "Content-Type: application/json" \102 -d '{"text": "different input text"}'103 ```1041053. **Error case**: Missing required field106 ```bash107 curl -X POST http://localhost:5000/predict \108 -H "Content-Type: application/json" \109 -d '{}'110 ```111112### Extended Edge Cases (Optional)113- Empty string input114- Very long text input115- Non-JSON content type116- Malformed JSON117- Wrong field type (number instead of string)118119## Common Pitfalls120121### Installation Issues122- **Insufficient timeout**: Large packages like `torch` require extended timeouts (5+ minutes)123- **Missing system dependencies**: Some models require additional system packages124125### Model Loading Issues126- **Cold start timeout**: Loading models at first request causes timeouts; load at startup instead127- **Memory constraints**: Large models may exceed available RAM; check model requirements128129### API Issues130- **Development server warning**: Flask development server is not suitable for production; acceptable for testing but note the limitation131- **No graceful shutdown**: Consider signal handling for clean termination132- **No health check endpoint**: Adding `/health` endpoint aids debugging133134### Process Management135- **Background process verification**: After starting in background, verify the process is running136- **Port conflicts**: Check if the specified port is already in use before starting137138## Task Planning Template139140When approaching HuggingFace inference tasks, structure work as follows:1411421. Environment verification (package manager, system requirements)1432. Dependency installation with appropriate timeouts1443. Cache directory creation1454. Model download with explicit cache path1465. Model download verification1476. API script creation with validation1487. Service startup in background1498. Functional testing (positive, negative, error cases)1509. Edge case testing (if time permits)