from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_google_genai import ChatGoogleGenerativeAI
# 1. Create 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="The Gemini API allows developers to interact with language models programmatically."
),
]
# 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 the retriever
retriever = vector_store.as_retriever(
search_kwargs={"k": 3}
)
# 5. Load the Gemini LLM
llm = ChatGoogleGenerativeAI(
model="gemini-2.5-flash",
temperature=0
)
# 6. Create the prompt template
prompt = ChatPromptTemplate.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}
""")
# 7. Create the output parser
output_parser = StrOutputParser()
# 8. Get the question
question = input("Ask a question: ")
# 9. Retrieve relevant documents
retrieved_documents = retriever.invoke(question)
# 10. Combine documents into context
context = "\n\n".join(
document.page_content
for document in retrieved_documents
)
# 11. Build the chain
chain = prompt | llm | output_parser
# 12. Run the chain
response = chain.invoke(
{
"context": context,
"question": question
}
)
# 13. Print the result
print("\nFinal Answer:")
print(response)