Change this python code so that it uses a free embedding model from hugging face: from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langchain_mistralai import MistralAIEmbeddings
To change the Python code so that it uses a free embedding model from Hugging Face, we will replace the MistralAIEmbeddings with an embedding model from the transformers library provided by Hugging Face. One popular choice for embeddings is the sentence-transformers/all-MiniLM-L6-v2 model, which provides a good balance between performance and speed. However, please note that using Hugging Face's models requires you to have the library installed.
User
ERROR: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in <cell line: 28>()
26
27 # Embed and index
---> 28 vectorstore = Chroma.from_documents(
29 documents=all_splits,
30 collection_name="rag-chroma",
It appears that the Chroma vector store is not compatible with using just any embedding function directly. The class seems to expect a specific type of embedding object rather than an arbitrary function. Since Chroma may be designed to work with the , we need to create an adapter for the Hugging Face embeddings that match the expected interface.
User
TypeError: HuggingFaceEmbeddingWrapper() takes no arguments
Assistant
I apologize for the confusion; the example code I provided was meant to illustrate how you might wrap a Hugging Face embedding model to work with the Chroma vector store. Since you received an error indicating that the HuggingFaceEmbeddingWrapper constructor should not take arguments, it suggests I included an incorrect example.
Let's correct the code by ensuring the HuggingFaceEmbeddingWrapper takes an argument in its constructor:
from sentence_transformers import SentenceTransformer
class HuggingFaceEmbeddingWrapper:
def __init__(self, model_name):
self.model = SentenceTransformer(model_name)
def encode(self, documents):
return self.model.encode(documents, show_progress_bar=True)
# Initialize the embedding wrapper with the model name
embedding_wrapper = HuggingFaceEmbeddingWrapper('sentence-transformers/all-MiniLM-L6-v2')
User
Create the SentenceTransformer model
embeddings_model = SentenceTransformer('BAAI/bge-m3') GIVER ERROR: TypeError Traceback (most recent call last)
in <cell line: 2>()
1 # Create the SentenceTransformer model
----> 2 embeddings_model = SentenceTransformer('BAAI/bge-m3')
5 frames
/usr/local/lib/python3.10/dist-packages/transformers/tokenization_utils_base.py in _from_pretrained(cls, resolved_vocab_files, pretrained_model_name_or_path, init_configuration, token, cache_dir, local_files_only, _commit_hash, _is_local, *init_inputs, **kwargs)
2247 if added_tokens_map != {} and init_kwargs[key] is not None:
2248 if key != "additional_special_tokens":
-> 2249 init_kwargs[key] = added_tokens_map.get(init_kwargs[key], init_kwargs[key])
2250
2251 init_kwargs["added_tokens_decoder"] = added_tokens_decoder
TypeError: unhashable type: 'dict'
Assistant
User
from transformers import AutoTokenizer, AutoModel
import torch
tokenizer = AutoTokenizer.from_pretrained("BAAI/bge-m3")
model = AutoModel.from_pretrained("BAAI/bge-m3")
Function to generate embeddings
def get_embeddings(texts):
# Tokenize input texts
encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
# Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling. For example, mean pooling (taking the mean of the token embeddings).
embeddings = model_output.last_hidden_state.mean(dim=1)
return embeddings
Usage example
texts = ["This is a sentence.", "This is another sentence."]
embeddings = get_embeddings(texts)
print(embeddings) - ERROR : ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in <cell line: 4>()
2 import torch
3
----> 4 tokenizer = AutoTokenizer.from_pretrained("BAAI/bge-m3")
5 model = AutoModel.from_pretrained("BAAI/bge-m3")
6
Assistant
The error you are encountering seems to be internal to the transformers library when trying to load the pretrained model BAAI/bge-m3. The error message suggests there may be an issue with the model's tokenizer configuration file, where a dictionary is being used in a context that expects a hashable type.
To troubleshoot this issue, you can try the following steps:
Make sure that you have the latest version of the transformers library installed. Outdated versions might have compatibility issues with certain models. You can update it using pip:
pip install --upgrade transformers
Check the Hugging Face model hub to ensure that BAAI/bge-m3 is the correct model identifier and that it has tokenizer files available.
User
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langchain_mistralai import MistralAIEmbeddings
JB:
from sentence_transformers import SentenceTransformer
embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key) # ORIGINAL # NameError: name 'mistral_api_key' is not defined
Assistant
Based on the error message you encountered, it seems that the method expects the parameter to be an object with a method called , which the class apparently doesn't have.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
First, ensure you have the transformers and sentence-transformers libraries installed:
pip install transformers sentence-transformers
Then you can modify the code like this:
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from sentence_transformers import SentenceTransformer
# Load the document
url = "https://lilianweng.github.io/posts/2023-06-23-agent/"
loader = WebBaseLoader(url)
docs = loader.load()
# Split the document
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=500, chunk_overlap=100
)
all_splits = text_splitter.split_documents(docs)
# Load a free embedding model from Hugging Face
embedding_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
# Function to calculate embeddings for a batch of texts
def get_embeddings(texts):
embeddings = embedding_model.encode(texts, show_progress_bar=True)
return embeddings
# Embed and index
vectorstore = Chroma.from_documents(
documents=all_splits,
collection_name="rag-chroma",
embedding_function=get_embeddings, # Use the custom embedding function here
)
retriever = vectorstore.as_retriever()
This code utilizes the SentenceTransformer class to encode the text splits. You can choose a different free embedding model if you want to experiment with different results. Just make sure that the embeddings you compute with the model are compatible with whatever downstream tasks you have for the vectors (e.g., retrieval, similarity measures, etc.).
Chroma
MistralAIEmbeddings
However, without the implementation details of the Chroma class and its from_documents method, it is difficult to advise precisely how to adapt the Hugging Face model output to fit. If Chroma is a custom implementation, you would need to refer to its documentation or source code to understand its interface requirements.
Assuming from_documents has similar arguments to from_texts, it is possible the class doesn't accept an embedding_function parameter but rather expects an embedding object with a particular interface.
One possible way to fix it is to create a wrapper class around the Hugging Face model that fulfills the expected interface. Below is a hypothetical example of how such a wrapper class might look:
from sentence_transformers import SentenceTransformer
class HuggingFaceEmbeddingWrapper:
def __init__(self, model_name):
self.model = SentenceTransformer(model_name)
def encode(self, documents):
# Assuming `documents` is a list of strings and that the Hugging Face model accepts a list of strings.
# You might need to adapt this if your documents are in a different format.
return self.model.encode(documents, show_progress_bar=True)
# Initialize the embedding wrapper with a free Hugging Face model
embedding_wrapper = HuggingFaceEmbeddingWrapper('sentence-transformers/all-MiniLM-L6-v2')
# Chroma.from_documents now receives the embedding wrapper instance
vectorstore = Chroma.from_documents(
documents=all_splits,
collection_name="rag-chroma",
embedding=embedding_wrapper, # Pass the wrapper instance here
)
If there are actually arguments such as embedding_function, metadatas, ids, etc., you need to ensure they are passed correctly according to the Chroma interface.
Please substitute the actual code with the solution that fits the interface requirements of the Chroma class you are using. If you have access to the documentation or the source of the Chroma class, please refer to that for the correct usage of the from_documents method. If issues persist, consider reaching out to the maintainers of the langchain_community library for additional support.
This code assumes that Chroma.from_documents expects an embedding object that has an encode method similar to the method of the SentenceTransformer class.
Please note that the interface of the Chroma class and its methods like from_documents needs to be compatible with this approach. Unfortunately, without having the actual implementation details of the Chroma class, I can't provide a precise solution. It's crucial to check the documentation or source code for the Chroma class to understand what type of object it expects for the embedding parameter. If you're still encountering errors, please verify if the Chroma class is designed to be used with other embedding models, or reach out to the maintainers for guidance on how to use it with external embeddings.
If the Chroma class is not flexible to be used with any embedding model, you might need to refactor larger parts of your code to work with the Sentence Transformers model or, if suitable, choose another vector store that's compatible with the Hugging Face model you wish to use.
The error message you're encountering indicates that there's an issue with the SentenceTransformer initialization with the model 'BAAI/bge-m3'. The TypeError: unhashable type: 'dict' likely arises because something unexpected is being passed where a hashable type (such as a string or integer) is expected.
The BAAI/bge-m3 model may not be directly compatible with the SentenceTransformer class from the sentence-transformers library. Generally, models that are designed to be used with the SentenceTransformer class have their specific model structure, which includes a tokenizer and a pooling layer to handle sentence embeddings.
Here's what you can try to resolve this issue:
First, ensure that the model you're trying to use is compatible with the sentence-transformers library. This library expects models that output sentence-level embeddings and are formatted in a certain way.
If the model BAAI/bge-m3 is a native Hugging Face transformer model and not a custom Sentence Transformer model, you may need to use the transformers library directly instead of sentence-transformers.
Assuming that the model can be loaded using the transformers library, here's how you can create a function to generate embeddings:
from transformers import AutoTokenizer, AutoModel
import torch
tokenizer = AutoTokenizer.from_pretrained('BAAI/bge-m3')
model = AutoModel.from_pretrained('BAAI/bge-m3')
# Function to generate embeddings
def get_embeddings(texts):
# Tokenize input texts
encoded_input = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
# Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling. For example, mean pooling (taking the mean of the token embeddings).
embeddings = model_output.last_hidden_state.mean(dim=1)
return embeddings
# Usage example
texts = ["This is a sentence.", "This is another sentence."]
embeddings = get_embeddings(texts)
print(embeddings)
In the above example, last_hidden_state is the output corresponding to the last layer of the transformer model, and you would perform a mean pooling operation to obtain sentence-level embeddings. The model and tokenizer should match whatever the model 'BAAI/bge-m3' is designed for.
Please note that the pooling strategy I used (mean pooling) is a simplification, and depending on your application or the specifics of the model, you might want to use a different strategy.
Finally, remember that any embeddings generated with these models should be compatible with the downstream components of your system, such as Chroma or other vector stores, databases, or search engines. If Chroma and SentenceTransformer libraries are not compatible, consider an alternative approach or reach out to the developers of these libraries for further support.
2 frames
/usr/local/lib/python3.10/dist-packages/transformers/tokenization_utils_base.py in _from_pretrained(cls, resolved_vocab_files, pretrained_model_name_or_path, init_configuration, token, cache_dir, local_files_only, _commit_hash, _is_local, *init_inputs, **kwargs)
2247 if added_tokens_map != {} and init_kwargs[key] is not None:
2248 if key != "additional_special_tokens":
-> 2249 init_kwargs[key] = added_tokens_map.get(init_kwargs[key], init_kwargs[key])
2250
2251 init_kwargs["added_tokens_decoder"] = added_tokens_decoder
TypeError: unhashable type: 'dict'
If the above steps do not resolve the issue, as a temporary workaround, you can try to manually download the model and tokenizer files from the Hugging Face model hub and load them locally, bypassing the from_pretrained method. However, this should be a last resort after ensuring that the transformers library is up to date and that the model identifier is correct.
If the issue continues to persist, it could be an issue specific to the model or the transformers library. In that case, you might want to report this issue to the Hugging Face transformers repository or check the repository issues to see if others have encountered a similar problem.
Remember, some models are trained and intended to be used with specific versions of libraries or have special requirements. Always check the model's page on the Hugging Face model hub for instructions and requirements.
3 frames
/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py in getattr(self, name)
1693 if name in modules:
1694 return modules[name]
-> 1695 raise AttributeError(f"'{type(self).name}' object has no attribute '{name}'")
1696
1697 def setattr(self, name: str, value: Union[Tensor, 'Module']) -> None:
AttributeError: 'SentenceTransformer' object has no attribute 'embed_documents'
Chroma.from_documents
embedding
embed_documents
SentenceTransformer
To resolve this, we need to adapt the SentenceTransformer object to fit the interface that Chroma is expecting. Since SentenceTransformer has an encode method to generate embeddings, we may need to wrap it in a class that provides an embed_documents method.
Below is an example of a wrapper class you can create to adapt the SentenceTransformer object:
class SentenceTransformerWrapper:
def __init__(self, model_name):
self.model = SentenceTransformer(model_name)
def encode(self, sentences, batch_size=32):
return self.model.encode(sentences, batch_size=batch_size, show_progress_bar=True)
# Assuming that the Chroma class expects an embed_documents method
def embed_documents(self, documents, batch_size=32):
# In case documents is a list of lists (chunks of text)
# Flatten the list: [['chunk1', 'chunk2'], ['chunk3']] -> ['chunk1', 'chunk2', 'chunk3']
flat_list = [item for sublist in documents for item in sublist]
return self.encode(flat_list, batch_size=batch_size)
Now, use this wrapper to create an instance that can be passed to the Chroma.from_documents method:
This code assumes that Chroma.from_documents can accept an embedding object with a method embed_documents which takes a list of documents and returns their embeddings. However, without the documentation or implementation details of Chroma.from_documents, this is the best guess I can provide.
If the Chroma class or from_documents method has specific requirements that aren't met by this adaptation, you may need to modify the wrapper class further or use a different approach. It's essential to refer to the documentation of these libraries or contact the developers for guidance on compatible embeddings. It's also possible that Chroma was specifically designed to work only with MistralAIEmbeddings and may not easily interoperate with SentenceTransformer. If that's the case, an alternative approach may be necessary, such as using a different vector storage or retrieval system.