import faiss
from google import genai
from sentence_transformers import SentenceTransformer
# 1. Load the embedding model
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
# 2. Create sample documents
documents = [
"FAISS is a library used for efficient similarity search over vector embeddings.",
"Embeddings are numerical representations of text, images, or other data.",
"Retrieval-Augmented Generation, or RAG, retrieves relevant information before sending context to a language model.",
"A vector database stores embeddings and allows similarity search between vectors.",
"Chunking divides large documents into smaller pieces before generating embeddings.",
"The Gemini API allows developers to interact with language models programmatically.",
]
# 3. Convert documents into embeddings
document_embeddings = embedding_model.encode(documents, normalize_embeddings=True)
# 4. Get the embedding dimension
dimension = document_embeddings.shape[1]
# 5. Create a FAISS index
index = faiss.IndexFlatIP(dimension)
# 6. Add document embeddings to the index
index.add(document_embeddings)
print("Number of documents in the index:", index.ntotal)
# 7. Get a query from the user
query = input("\nAsk a question: ")
# 8. Convert the query into an embedding
query_embedding = embedding_model.encode([query], normalize_embeddings=True)
# 9. Retrieve the top-k relevant documents
k = 3
scores, indices = index.search(query_embedding, k=k)
# 10. Get the retrieved documents
retrieved_documents = []
for rank, document_index in enumerate(indices[0]):
document = documents[document_index]
score = scores[0][rank]
retrieved_documents.append(document)
print(f"\nRank {rank + 1}")
print("Document:", document)
print(f"Similarity Score: {score:.4f}")
# 11. Combine retrieved documents into context
context = "\n\n".join(retrieved_documents)
# 12. Create the RAG prompt
prompt = f"""
Answer the user's 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:
{query}
"""
# 13. Create the Gemini client
client = genai.Client()
# 14. Send the context and query to Gemini
response = client.interactions.create(model="gemini-3.7-flash", input=prompt)
# 15. Print the final answer
print("\nFinal Answer:")
print(response.output_text)