Hugging Face Embeddings with Weaviate
Weaviate's integration with Hugging Face's APIs allows you to access their models' capabilities directly from Weaviate.
Configure a Weaviate vector index to use an Hugging Face Hub embedding model, and Weaviate will generate embeddings for various operations using the specified model and your Hugging Face API key. This feature is called the vectorizer.
At import time, Weaviate generates text object embeddings and saves them into the index. For vector and hybrid search operations, Weaviate converts text queries into embeddings.
Requirements
Weaviate configuration
Your Weaviate instance must be configured with the Hugging Face vectorizer integration (text2vec-huggingface
) module.
For Weaviate Cloud (WCD) users
This integration is enabled by default on Weaviate Cloud (WCD) serverless instances.
For self-hosted users
- Check the cluster metadata to verify if the module is enabled.
- Follow the how-to configure modules guide to enable the module in Weaviate.
API credentials
You must provide a valid Hugging Face API key to Weaviate for this integration. Go to Hugging Face to sign up and obtain an API key.
Provide the API key to Weaviate using one of the following methods:
- Set the
HUGGINGFACE_APIKEY
environment variable that is available to Weaviate. - Provide the API key at runtime, as shown in the examples below.
- Python API v4
- JS/TS API v3
- Go
import weaviate
from weaviate.classes.init import Auth
import os
# Recommended: save sensitive data as environment variables
huggingface_key = os.getenv("HUGGINGFACE_APIKEY")
headers = {
"X-HuggingFace-Api-Key": huggingface_key,
}
client = weaviate.connect_to_weaviate_cloud(
cluster_url=weaviate_url, # `weaviate_url`: your Weaviate URL
auth_credentials=Auth.api_key(weaviate_key), # `weaviate_key`: your Weaviate API key
headers=headers
)
# Work with Weaviate
client.close()
import weaviate from 'weaviate-client'
const huggingFaceApiKey = process.env.HUGGINGFACE_APIKEY || ''; // Replace with your inference API key
const client = await weaviate.connectToWeaviateCloud(
'WEAVIATE_INSTANCE_URL', // Replace with your instance URL
{
authCredentials: new weaviate.ApiKey('WEAVIATE_INSTANCE_APIKEY'),
headers: {
'X-HuggingFace-Api-Key': huggingFaceApiKey,
}
}
)
// Work with Weaviate
client.close()
// Set these environment variables
// WCD_HOSTNAME your Weaviate instance hostname, excluding the scheme (https://)
// WCD_API_KEY your Weaviate instance API key
// <PROVIDER>_APIKEY your model provider API key (or token)
package main
import (
"context"
"fmt"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
)
func main() {
cfg := weaviate.Config{
Host: os.Getenv("WCD_HOSTNAME"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WCD_API_KEY")},
Headers: map[string]string{
"X-HuggingFace-Api-Key": os.Getenv("HUGGINGFACE_APIKEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
// Work with Weaviate
}
Configure the vectorizer
Configure a Weaviate index as follows to use a Hugging Face embedding model:
- Python API v4
- JS/TS API v3
- Go
from weaviate.classes.config import Configure
client.collections.create(
"DemoCollection",
vectorizer_config=[
Configure.NamedVectors.text2vec_huggingface(
name="title_vector",
source_properties=["title"],
model="sentence-transformers/all-MiniLM-L6-v2",
)
],
# Additional parameters not shown
)
await client.collections.create({
name: 'DemoCollection',
properties: [
{
name: 'title',
dataType: 'text' as const,
},
],
vectorizers: [
weaviate.configure.vectorizer.text2VecHuggingFace({
name: 'title_vector',
sourceProperties: ['title'],
model: 'sentence-transformers/all-MiniLM-L6-v2',
}),
],
// Additional parameters not shown
});
// package, imports not shown
func main() {
// Instantiation not shown
ctx := context.Background()
// Define the collection
basicHuggingfaceVectorizerDef := &models.Class{
Class: "DemoCollection",
VectorConfig: map[string]models.VectorConfig{
"title_vector": {
Vectorizer: map[string]interface{}{
"text2vec-huggingface": map[string]interface{}{
"sourceProperties": []string{"title"},
"model": "sentence-transformers/all-MiniLM-L6-v2",
},
},
},
},
}
// add the collection
err = client.Schema().ClassCreator().WithClass(basicHuggingfaceVectorizerDef).Do(ctx)
if err != nil {
panic(err)
}
}
You must specify one of the available models for the vectorizer to use.
Vectorization behavior
Weaviate follows the collection configuration and a set of predetermined rules to vectorize objects.
Unless specified otherwise in the collection definition, the default behavior is to:
- Only vectorize properties that use the
text
ortext[]
data type (unless skipped) - Sort properties in alphabetical (a-z) order before concatenating values
- If
vectorizePropertyName
istrue
(false
by default) prepend the property name to each property value - Join the (prepended) property values with spaces
- Prepend the class name (unless
vectorizeClassName
isfalse
) - Convert the produced string to lowercase
Vectorizer parameters
The following examples show how to configure Hugging Face-specific options.
- Python API v4
- JS/TS API v3
- Go
from weaviate.classes.config import Configure
client.collections.create(
"DemoCollection",
vectorizer_config=[
Configure.NamedVectors.text2vec_huggingface(
name="title_vector",
source_properties=["title"],
# NOTE: Use only one of (`model`), (`passage_model` and `query_model`), or (`endpoint_url`)
model="sentence-transformers/all-MiniLM-L6-v2",
# passage_model="sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base", # Required if using `query_model`
# query_model="sentence-transformers/facebook-dpr-question_encoder-single-nq-base", # Required if using `passage_model`
# endpoint_url="<custom_huggingface_url>",
#
# wait_for_model=True,
# use_cache=True,
# use_gpu=True,
)
],
# Additional parameters not shown
)
await client.collections.create({
name: 'DemoCollection',
properties: [
{
name: 'title',
dataType: 'text' as const,
},
],
vectorizers: [
weaviate.configure.vectorizer.text2VecHuggingFace({
name: 'title_vector',
sourceProperties: ['title'],
model: 'sentence-transformers/all-MiniLM-L6-v2',
// passage_model: 'sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base', // Required if using `query_model`
// query_model: 'sentence-transformers/facebook-dpr-question_encoder-single-nq-base', // Required if using `passage_model`
// endpoint_url: '<custom_huggingface_url>',
//
// wait_for_model: true,
// use_cache: true,
// use_gpu: true,
}),
],
// Additional parameters not shown
});
// package, imports not shown
func main() {
// Instantiation not shown
ctx := context.Background()
// Define the collection
fullHuggingfaceVectorizerDef := &models.Class{
Class: "DemoCollection",
VectorConfig: map[string]models.VectorConfig{
"title_vector": {
Vectorizer: map[string]interface{}{
"text2vec-huggingface": map[string]interface{}{
"sourceProperties": []string{"title"},
// Note: Use only one of (`model`), (`passage_model` and `query_model`), or (`endpoint_url`)
"model": "sentence-transformers/all-MiniLM-L6-v2",
// "passage_model": "sentence-transformers/facebook-dpr-ctx_encoder-single-nq-base", // Required if using `query_model`
// "query_model": "sentence-transformers/facebook-dpr-question_encoder-single-nq-base", // Required if using `passage_model`
// "endpoint_url": "<custom_huggingface_url>",
// // Optional parameters
// "wait_for_model": true,
// "use_cache": true,
// "use_gpu": true,
},
},
},
},
}
// add the collection
err = client.Schema().ClassCreator().WithClass(fullHuggingfaceVectorizerDef).Do(ctx)
if err != nil {
panic(err)
}
}
Model selection parameters
Only select one of the following parameters to specify the model:
model
,passageModel
andqueryModel
, orendpointURL
model
, passageModel
/queryModel
and endpointURL
The passageModel
and queryModel
parameters are used together to specify a DPR passage and query model.
The endpointURL
parameter is used to specify a custom Hugging Face Inference Endpoint. This parameter overrides the model
, passageModel
, and queryModel
parameters.
Additional parameters
options.waitForModel
: If the model is not ready, wait for it rather than returning a503
error.options.useGPU
: Use a GPU for inference if your account plan supports it.options.useCache
: Use a cached result if available. (For non-deterministic models to prevent the caching mechanism from being used.)
Data import
After configuring the vectorizer, import data into Weaviate. Weaviate generates embeddings for text objects using the specified model.
- Python API v4
- JS/TS API v3
- Go
collection = client.collections.get("DemoCollection")
with collection.batch.dynamic() as batch:
for src_obj in source_objects:
weaviate_obj = {
"title": src_obj["title"],
"description": src_obj["description"],
}
# The model provider integration will automatically vectorize the object
batch.add_object(
properties=weaviate_obj,
# vector=vector # Optionally provide a pre-obtained vector
)
const collectionName = 'DemoCollection'
const myCollection = client.collections.get(collectionName)
let dataObjects = []
for (let srcObject of srcObjects) {
dataObject.push({
title: srcObject.title,
description: srcObject.description,
});
}
const response = await myCollection.data.insertMany(dataObjects);
console.log(response);
// package, imports not shown
func main() {
// Instantiation not shown
ctx := context.Background()
var sourceObjects = []map[string]string{
// Objects not shown
}
// Convert items into a slice of models.Object
objects := []models.PropertySchema{}
for i := range sourceObjects {
objects = append(objects, map[string]interface{}{
// Populate the object with the data
})
}
// Batch write items
batcher := client.Batch().ObjectsBatcher()
for _, dataObj := range objects {
batcher.WithObjects(&models.Object{
Class: "DemoCollection",
Properties: dataObj,
})
}
// Flush
batchRes, err := batcher.Do(ctx)
// Error handling
if err != nil {
panic(err)
}
for _, res := range batchRes {
if res.Result.Errors != nil {
for _, err := range res.Result.Errors.Error {
if err != nil {
fmt.Printf("Error details: %v\n", *err)
panic(err.Message)
}
}
}
}
}
If you already have a compatible model vector available, you can provide it directly to Weaviate. This can be useful if you have already generated embeddings using the same model and want to use them in Weaviate, such as when migrating data from another system.
Searches
Once the vectorizer is configured, Weaviate will perform vector and hybrid search operations using the specified Hugging Face model.
Vector (near text) search
When you perform a vector search, Weaviate converts the text query into an embedding using the specified model and returns the most similar objects from the database.
The query below returns the n
most similar objects from the database, set by limit
.
- Python API v4
- JS/TS API v3
- Go
collection = client.collections.get("DemoCollection")
response = collection.query.near_text(
query="A holiday film", # The model provider integration will automatically vectorize the query
limit=2
)
for obj in response.objects:
print(obj.properties["title"])
const collectionName = 'DemoCollection'
const myCollection = client.collections.get(collectionName)
let result;
result = await myCollection.query.nearText(
'A holiday film', // The model provider integration will automatically vectorize the query
{
limit: 2,
}
)
console.log(JSON.stringify(result.objects, null, 2));
// package, imports not shown
func main() {
// Instantiation not shown
ctx := context.Background()
nearTextResponse, err := client.GraphQL().Get().
WithClassName("DemoCollection").
WithFields(
graphql.Field{Name: "title"},
).
WithNearText(client.GraphQL().NearTextArgBuilder().
WithConcepts([]string{"A holiday film"})).
WithLimit(2).
Do(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%v", nearTextResponse)
}
Hybrid search
A hybrid search performs a vector search and a keyword (BM25) search, before combining the results to return the best matching objects from the database.
When you perform a hybrid search, Weaviate converts the text query into an embedding using the specified model and returns the best scoring objects from the database.
The query below returns the n
best scoring objects from the database, set by limit
.
- Python API v4
- JS/TS API v3
- Go
collection = client.collections.get("DemoCollection")
response = collection.query.hybrid(
query="A holiday film", # The model provider integration will automatically vectorize the query
limit=2
)
for obj in response.objects:
print(obj.properties["title"])
const collectionName = 'DemoCollection'
const myCollection = client.collections.get(collectionName)
result = await myCollection.query.hybrid(
'A holiday film', // The model provider integration will automatically vectorize the query
{
limit: 2,
}
)
console.log(JSON.stringify(result.objects, null, 2));
// package, imports not shown
func main() {
// Instantiation not shown
ctx := context.Background()
hybridResponse, err := client.GraphQL().Get().
WithClassName("DemoCollection").
WithFields(
graphql.Field{Name: "title"},
).
WithHybrid(client.GraphQL().HybridArgumentBuilder().
WithQuery("A holiday film")).
WithLimit(2).
Do(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%v", hybridResponse)
}
References
Available models
You can use any Hugging Face embedding model with text2vec-huggingface
, including public and private Hugging Face models. Sentence similarity models generally work best.
Further resources
Code examples
Once the integrations are configured at the collection, the data management and search operations in Weaviate work identically to any other collection. See the following model-agnostic examples:
- The how-to: manage data guides show how to perform data operations (i.e. create, update, delete).
- The how-to: search guides show how to perform search operations (i.e. vector, keyword, hybrid) as well as retrieval augmented generation.
External resources
- Hugging Face Inference API documentation
- Hugging Face Model Hub
Questions and feedback
If you have any questions or feedback, let us know in the user forum.