Spaces:
Sleeping
Sleeping
Create vector_handler.py
Browse files- vector_handler.py +38 -0
vector_handler.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pinecone
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import threading
|
| 5 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
| 6 |
+
from langchain.vectorstores.pinecone import Pinecone as LangchainPinecone
|
| 7 |
+
|
| 8 |
+
pinecone.init(api_key=os.getenv("PINECONE_API_KEY"), environment=os.getenv("PINECONE_ENV"))
|
| 9 |
+
|
| 10 |
+
embedding_model = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
| 11 |
+
|
| 12 |
+
def create_vector_store(session_id, texts):
|
| 13 |
+
index_name = session_id
|
| 14 |
+
if index_name not in pinecone.list_indexes():
|
| 15 |
+
pinecone.create_index(index_name, dimension=768)
|
| 16 |
+
index = pinecone.Index(index_name)
|
| 17 |
+
vectorstore = LangchainPinecone.from_texts(texts, embedding_model, index_name=index_name)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def query_vector_store(session_id, question):
|
| 21 |
+
index_name = session_id
|
| 22 |
+
vectorstore = LangchainPinecone.from_existing_index(index_name, embedding_model)
|
| 23 |
+
chain = get_chain()
|
| 24 |
+
docs = vectorstore.similarity_search(question)
|
| 25 |
+
result = chain({"input_documents": docs, "question": question}, return_only_outputs=True)
|
| 26 |
+
return result["output_text"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def delete_vector_store(index_name, delay=0):
|
| 30 |
+
def delayed_delete():
|
| 31 |
+
if delay:
|
| 32 |
+
time.sleep(delay)
|
| 33 |
+
try:
|
| 34 |
+
pinecone.delete_index(index_name)
|
| 35 |
+
print(f"Deleted index {index_name}")
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"Error deleting index {index_name}: {e}")
|
| 38 |
+
threading.Thread(target=delayed_delete).start()
|