/usr/local/lib/python3.10/dist-packages/transformers/tokenization_utils_base.py:1601: FutureWarning: clean_up_tokenization_spaces was not set. It will be set to True by default. This behavior will be depracted in transformers v4.45, and will be then set to False by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884
warnings.warn(
ERROR:main:Error during document splitting: TextSplitter.init() got an unexpected keyword argument 'tokenizer'
ERROR:main:RAG pipeline failed: TextSplitter.init() got an unexpected keyword argument 'tokenizer'
import logging
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Union
import multiprocessing
import sys
import torch
import datasets
from datasets import Dataset
from langchain.docstore.document import Document as LangchainDocument
from langchain.text_splitter import RecursiveCharacterTextSplitter
from transformers import AutoTokenizer
from langchain.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.utils import DistanceStrategy
import pandas as pd
from tqdm import tqdm
import numpy as np
import pacmap
import plotly.express as px
import plotly.graph_objects as go
def load_dataset(self) -> None:
"""
Load the dataset using Hugging Face datasets library.
"""
try:
logger.info(f"Loading dataset '{self.dataset_name}' with split '{self.split}'.")
self.dataset = datasets.load_dataset(self.dataset_name, split=self.split)
logger.info("Dataset loaded successfully.")
except Exception as e:
logger.error(f"Failed to load dataset '{self.dataset_name}': {e}")
raise
def identify_text_columns(self) -> List[str]:
"""
Identify columns in the dataset that contain text data.
"""
if self.dataset is None:
logger.error("Dataset not loaded. Call load_dataset() first.")
raise ValueError("Dataset not loaded.")
text_columns = [column for column, dtype in self.dataset.features.items() if dtype == datasets.Value('string')]
if not text_columns:
logger.warning("No text columns found in the dataset.")
else:
logger.info(f"Identified text columns: {text_columns}")
return text_columns
def run(self) -> None:
"""
Run the full RAG pipeline.
"""
try:
# Load data
data_loader = DataLoader(dataset_name=self.dataset_name, split=self.split)
data_loader.load_dataset()
text_columns = data_loader.identify_text_columns()
if not text_columns:
logger.error("No text columns available for processing.")
return
# Process documents
doc_processor = DocumentProcessor(text_columns=text_columns)
doc_processor.process_documents(data_loader.dataset)
# Generate embeddings and create FAISS index
embed_handler = EmbeddingHandler()
faiss_index = embed_handler.generate_embeddings(doc_processor.docs_processed)
# Embed user query
query_vector = embed_handler.embed_query(self.query)
# Visualization
visualizer = Visualization()
projection = visualizer.project_embeddings(faiss_index, query_vector)
df = visualizer.create_dataframe(faiss_index, self.query)
visualizer.visualize(df)
logger.info("RAG pipeline completed successfully.")
except Exception as e:
logger.error(f"RAG pipeline failed: {e}")
Example usage
if name == "main":
import torch
code
user_query = "How to create a pipeline object?"
dataset_name = "m-ric/huggingface_doc" # Replace with your desired dataset
pipeline = RAGPipeline(dataset_name=dataset_name, query=user_query)
pipeline.run()
The error you're encountering:
code
ERROR:__main__:Error during document splitting: TextSplitter.__init__() got an unexpected keyword argument 'tokenizer'
ERROR:__main__:RAG pipeline failed: TextSplitter.__init__() got an unexpected keyword argument 'tokenizer'
indicates that the RecursiveCharacterTextSplitter class from the langchain.text_splitter module does not accept a tokenizer keyword argument in its constructor. This mismatch is causing your code to fail during the document splitting phase.
Cause of the Error
In your DocumentProcessor class, within the split_documents method, you have:
Here, you're trying to pass a tokenizer object directly to RecursiveCharacterTextSplitter, but according to the latest langchain API, this class does not accept a tokenizer parameter. Instead, it uses an encoding_name parameter to specify which tokenizer to use internally.
Solution
Option 1: Use the encoding_name Parameter
Modify the split_documents method to use the encoding_name parameter, which specifies the name of the tokenizer to use (e.g., 'gpt2', 'cl100k_base', etc.):
python
from langchain.text_splitter import RecursiveCharacterTextSplitter
def split_documents(self, documents: List[LangchainDocument]) -> List[LangchainDocument]:
"""
Split documents into smaller chunks.
"""
logger.info("Splitting documents into smaller chunks.")
try:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
separators=["\n\n", "\n", " ", ""],
encoding_name="gpt2" # Replace with the appropriate encoding for your use case
)
if self.multi_process:
logger.info("Using multiprocessing for splitting documents.")
with multiprocessing.Pool() as pool:
results = list(tqdm(
pool.imap(text_splitter.split_documents, [documents[i:i + 1000] for i in range(0, len(documents), 1000)]),
total=(len(documents) // 1000) + 1,
desc="Splitting documents"))
split_docs = [doc for sublist in results for doc in sublist]
else:
split_docs = []
for doc in tqdm(documents, desc="Splitting documents"):
split_docs.extend(text_splitter.split_documents([doc]))
logger.info(f"Split into {len(split_docs)} document chunks.")
return split_docs
except Exception as e:
logger.error(f"Error during document splitting: {e}")
raise
Explanation:
Remove the tokenizer Argument: The RecursiveCharacterTextSplitter does not accept a tokenizer object. Instead, it uses the encoding_name parameter to select the tokenizer internally.
Set encoding_name: Specify the tokenizer encoding name that matches your requirements. Common options include 'gpt2', 'cl100k_base', etc.
Update Imports: Ensure that you have the correct import statement for RecursiveCharacterTextSplitter.
Option 2: Use TokenTextSplitter for Token-Based Splitting
If you prefer to split the documents based on tokens rather than characters, you can use the TokenTextSplitter class:
python
from langchain.text_splitter import TokenTextSplitter
def split_documents(self, documents: List[LangchainDocument]) -> List[LangchainDocument]:
"""
Split documents into smaller chunks using token count.
"""
logger.info("Splitting documents into smaller chunks based on tokens.")
try:
text_splitter = TokenTextSplitter(
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
encoding_name="gpt2" # Replace with the appropriate encoding for your use case
)
if self.multi_process:
logger.info("Using multiprocessing for splitting documents.")
with multiprocessing.Pool() as pool:
results = list(tqdm(
pool.imap(text_splitter.split_documents, [documents[i:i + 1000] for i in range(0, len(documents), 1000)]),
total=(len(documents) // 1000) + 1,
desc="Splitting documents"))
split_docs = [doc for sublist in results for doc in sublist]
else:
split_docs = []
for doc in tqdm(documents, desc="Splitting documents"):
split_docs.extend(text_splitter.split_documents([doc]))
logger.info(f"Split into {len(split_docs)} document chunks.")
return split_docs
except Exception as e:
logger.error(f"Error during document splitting: {e}")
raise
Explanation:
Use TokenTextSplitter: This class splits text based on the number of tokens, which can be more suitable when working with language models that have token limits.
Set encoding_name: Ensure that the encoding name matches the tokenizer used by your downstream models.
Additional Considerations
Update chunk_size and chunk_overlap: When using token-based splitting, you might need to adjust these parameters to reflect token counts instead of character counts.
Ensure Compatibility: Make sure that your version of langchain is up to date, as the library is actively developed and APIs can change.
You can update langchain using:
bash
pip install --upgrade langchain
Handle Warnings: The initial FutureWarning about clean_up_tokenization_spaces is a warning about future changes in the transformers library and does not cause the program to fail. However, to suppress the warning, you can specify the clean_up_tokenization_spaces parameter in your tokenizer calls if needed.
Revised Code Snippet
Here's the revised DocumentProcessor class with the corrected split_documents method:
python
@dataclass
class DocumentProcessor:
text_columns: List[str]
chunk_size: int = 512
chunk_overlap: int = 50
tokenizer_name: str = "bert-base-uncased"
multi_process: bool = True
knowledge_base: List[LangchainDocument] = field(init=False, default_factory=list)
docs_processed: List[LangchainDocument] = field(init=False, default_factory=list)
def create_documents(self, dataset: Dataset) -> List[LangchainDocument]:
"""
Convert dataset entries to LangChain documents.
"""
logger.info("Converting dataset entries to LangChain documents.")
documents = []
for record in tqdm(dataset, desc="Creating documents"):
# Concatenate all text columns
page_content = ' '.join([str(record[col]) for col in self.text_columns if record[col]])
metadata = {col: record[col] for col in self.text_columns if record[col]}
documents.append(LangchainDocument(page_content=page_content, metadata=metadata))
logger.info(f"Created {len(documents)} documents.")
return documents
def split_documents(self, documents: List[LangchainDocument]) -> List[LangchainDocument]:
"""
Split documents into smaller chunks.
"""
logger.info("Splitting documents into smaller chunks.")
try:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
separators=["\n\n", "\n", " ", ""],
encoding_name="gpt2" # Replace with the appropriate encoding for your use case
)
if self.multi_process:
logger.info("Using multiprocessing for splitting documents.")
with multiprocessing.Pool() as pool:
results = list(tqdm(
pool.imap(text_splitter.split_documents, [documents[i:i + 1000] for i in range(0, len(documents), 1000)]),
total=(len(documents) // 1000) + 1,
desc="Splitting documents"))
split_docs = [doc for sublist in results for doc in sublist]
else:
split_docs = []
for doc in tqdm(documents, desc="Splitting documents"):
split_docs.extend(text_splitter.split_documents([doc]))
logger.info(f"Split into {len(split_docs)} document chunks.")
return split_docs
except Exception as e:
logger.error(f"Error during document splitting: {e}")
raise
# Rest of your class methods
Testing the Fix
After making these changes, rerun your pipeline to see if the error is resolved:
bash
python your_script.py
Conclusion
By updating the split_documents method to align with the current langchain API and removing the unsupported tokenizer parameter, your document splitting process should work correctly. This change reflects the importance of keeping third-party libraries updated and adjusting your code to accommodate any API changes.