When I use langchain’s RAG method to search local txt, some content cannot be searched

When I use langchain’s RAG method to search local txt, some content cannot be searched. Every time I change chunk_size, the content that cannot be searched will be different.The content in the file is Chinese. The TextLoader can successfully load all the content.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from langchain import hub
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain_community.llms import Ollama
from langchain_community.embeddings import HuggingFaceBgeEmbeddings
from langchain_core.prompts import PromptTemplate
import re
loader = TextLoader("knowledge.txt")
data = loader.load()
with open("geometry-knowledges-chinese.txt", 'r', encoding='utf-8') as file:
content = file.read()
lines = content.split('n')
titles = []
for line in lines:
match = re.search(r'"([^"]+)"', line)
if match:
titles.append(match.group(1))
model_name = "BAAI/bge-small-en"
model_kwargs = {"device": "cpu"}
encode_kwargs = {"normalize_embeddings": True}
hf=HuggingFaceBgeEmbeddings(model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs)
# Split
text_splitter = RecursiveCharacterTextSplitter(
separators=[
"nn",
"n",
"uff0e", # Fullwidth full stop
"u3002", # Ideographic full stop
],
chunk_size =300, chunk_overlap = 50,length_function = len,add_start_index = True)
all_splits = text_splitter.split_documents(data)
# Store splits
vectorstore = FAISS.from_documents(documents=all_splits, embedding=hf)
# RAG prompt
template = """Use the following context to search for answers to your questions.
If you don't know the answer, just say you don't know, don't try to make up an answer.
Don't add anything else.{context}
Question: {question}
Helpful Answer:"""
QA_CHAIN_PROMPT = PromptTemplate(
input_variables=["context", "question"],
template=template,
)
# LLM
llm = Ollama(model="llama3.1")
# RetrievalQA
qa_chain = RetrievalQA.from_chain_type(
llm,
retriever=vectorstore.as_retriever(),
chain_type_kwargs={"prompt":QA_CHAIN_PROMPT}
)
for title in titles:
specific_question = f"Definition of{title}"
result = qa_chain({"query": specific_question})
print(f"Definition of{title}:{result['result']}")
</code>
<code>from langchain import hub from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import FAISS from langchain.chains import RetrievalQA from langchain_community.llms import Ollama from langchain_community.embeddings import HuggingFaceBgeEmbeddings from langchain_core.prompts import PromptTemplate import re loader = TextLoader("knowledge.txt") data = loader.load() with open("geometry-knowledges-chinese.txt", 'r', encoding='utf-8') as file: content = file.read() lines = content.split('n') titles = [] for line in lines: match = re.search(r'"([^"]+)"', line) if match: titles.append(match.group(1)) model_name = "BAAI/bge-small-en" model_kwargs = {"device": "cpu"} encode_kwargs = {"normalize_embeddings": True} hf=HuggingFaceBgeEmbeddings(model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs) # Split text_splitter = RecursiveCharacterTextSplitter( separators=[ "nn", "n", "uff0e", # Fullwidth full stop "u3002", # Ideographic full stop ], chunk_size =300, chunk_overlap = 50,length_function = len,add_start_index = True) all_splits = text_splitter.split_documents(data) # Store splits vectorstore = FAISS.from_documents(documents=all_splits, embedding=hf) # RAG prompt template = """Use the following context to search for answers to your questions. If you don't know the answer, just say you don't know, don't try to make up an answer. Don't add anything else.{context} Question: {question} Helpful Answer:""" QA_CHAIN_PROMPT = PromptTemplate( input_variables=["context", "question"], template=template, ) # LLM llm = Ollama(model="llama3.1") # RetrievalQA qa_chain = RetrievalQA.from_chain_type( llm, retriever=vectorstore.as_retriever(), chain_type_kwargs={"prompt":QA_CHAIN_PROMPT} ) for title in titles: specific_question = f"Definition of{title}" result = qa_chain({"query": specific_question}) print(f"Definition of{title}:{result['result']}") </code>
from langchain import hub
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain_community.llms import Ollama
from langchain_community.embeddings import HuggingFaceBgeEmbeddings
from langchain_core.prompts import PromptTemplate
import re

loader = TextLoader("knowledge.txt")
data = loader.load()


with open("geometry-knowledges-chinese.txt", 'r', encoding='utf-8') as file:
    content = file.read()
lines = content.split('n')
titles = []
for line in lines:
    match = re.search(r'"([^"]+)"', line)
    if match:
        titles.append(match.group(1))



model_name = "BAAI/bge-small-en"
model_kwargs = {"device": "cpu"}
encode_kwargs = {"normalize_embeddings": True}
hf=HuggingFaceBgeEmbeddings(model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs)

# Split
text_splitter = RecursiveCharacterTextSplitter(
    separators=[
        "nn",
        "n",
        "uff0e",  # Fullwidth full stop
        "u3002",  # Ideographic full stop
    ],
    chunk_size =300, chunk_overlap = 50,length_function = len,add_start_index = True)
all_splits = text_splitter.split_documents(data)

# Store splits
vectorstore = FAISS.from_documents(documents=all_splits, embedding=hf)

# RAG prompt
template = """Use the following context to search for answers to your questions.
    If you don't know the answer, just say you don't know, don't try to make up an answer.
    Don't add anything else.{context}
    Question: {question}
    Helpful Answer:"""
QA_CHAIN_PROMPT = PromptTemplate(
    input_variables=["context", "question"],
    template=template,
)

# LLM
llm = Ollama(model="llama3.1")

# RetrievalQA
qa_chain = RetrievalQA.from_chain_type(
    llm,
    retriever=vectorstore.as_retriever(),
    chain_type_kwargs={"prompt":QA_CHAIN_PROMPT}
)
for title in titles:
    specific_question = f"Definition of{title}"
    result = qa_chain({"query": specific_question})
    print(f"Definition of{title}:{result['result']}")

How should I modify the code to allow the LLM to search for all the content?

Your code looks correct. I would advice three things to debug.

  1. Your chunking strategy may not be suitable for your dataset. Try play around with chunk size and overlap values to arrive at optimal retrieval.
  2. I can see you have two txt file. Ensure you have actual data in vector for your query.
  3. Try this below for now, and let me know what happens.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
qa_chain = RetrievalQA.from_chain_type(
llm,
retriever=vectorstore.as_retriever(
search_type="mmr",
search_kwargs={'k': 6, 'lambda_mult': 0.25}
),
chain_type_kwargs={"prompt":QA_CHAIN_PROMPT}
)
qa_chain = RetrievalQA.from_chain_type( llm, retriever=vectorstore.as_retriever( search_type="mmr", search_kwargs={'k': 6, 'lambda_mult': 0.25} ), chain_type_kwargs={"prompt":QA_CHAIN_PROMPT} )
qa_chain = RetrievalQA.from_chain_type(
        llm,
        retriever=vectorstore.as_retriever(
        search_type="mmr",
        search_kwargs={'k': 6, 'lambda_mult': 0.25}
        ),
        chain_type_kwargs={"prompt":QA_CHAIN_PROMPT}
)

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật