from transformers import pipeline
from langchain_core.documents import Document
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline
# 1. create sample documents
documents = [
Document(
page_content=(
"FAISS is a library used for efficient similarity "
"search over vector embeddings."
)
),
Document(
page_content=(
"Embeddings are numerical representations of text, images, or other data."
)
),
Document(
page_content=(
"Retrieval-Augmented Generation, or RAG, retrieves "
"relevant information before sending context to a "
"language model."
)
),
Document(
page_content=(
"A vector database stores embeddings and allows "
"similarity search between vectors."
)
),
Document(
page_content=(
"Chunking divides large documents into smaller pieces "
"before generating embeddings."
)
),
Document(
page_content=(
"LangChain is a framework for building applications "
"powered by language models."
)
),
]
# 2. load the embedding model
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# 3. create the FAISS vector store
vector_store = FAISS.from_documents(documents, embeddings)
# 4. create a retriever
retriever = vector_store.as_retriever(search_kwargs={"k": 3})
# 5. Create a local Hugging Face pipeline
hf_pipeline = pipeline(
task="text-generation", model="distilgpt2", max_new_tokens=100, do_sample=False
)
# 6. Convert the Hugging Face pipeline into a LangChain LLM
llm = HuggingFacePipeline(pipeline=hf_pipeline)
# 6. create the RAG prompt
prompt = PromptTemplate.from_template("""
Answer the question using only the provided context.
If the answer is not available in the context, say:
I could not find the answer in the provided documents.
Context:
{context}
Question:
{question}
Answer:
""")
# 7. creating an output parser
output_parser = StrOutputParser()
# 8. get a question from the user
question = input("\nAsk a question: ")
# 9. retrieve relevant documents
retrieved_documents = retriever.invoke(question)
# 10. Display retriever documents
print("\n Retrieved Documents:")
for rank, document in enumerate(retrieved_documents, start=1):
print(f"\nRank {rank}")
print(document.page_content)
# 11. combine documents into context
context = "\n\n".join(document.page_content for document in retrieved_documents)
# 12. building the RAG chain
chain = prompt | llm | output_parser
# 13. generate the answer
response = chain.invoke({"context": context, "question": question})
# 14. printing the final answer
print("\n Final answer: ")
print(response)