-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathknowledge_base_manager.py
216 lines (169 loc) · 7.91 KB
/
knowledge_base_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# import pickle
# import chromadb
# from chromadb.utils import embedding_functions
# from sentence_transformers import SentenceTransformer
# from typing import List, Dict, Any
# import os
# import shutil
# class KnowledgeBaseManager:
# def __init__(self, db_path: str = "./chroma_db"):
# self.db_path = db_path
# self.client = None
# self.model = SentenceTransformer("all-MiniLM-L6-v2")
# self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
# self.collection = None
# def load_documents(self, filename: str) -> List:
# if not os.path.exists(filename):
# raise FileNotFoundError(f"The file {filename} does not exist.")
# with open(filename, 'rb') as f:
# return pickle.load(f)
# def initialize_database(self, filename: str, collection_name: str):
# # Attempt to remove the entire database directory
# try:
# shutil.rmtree(self.db_path)
# print(f"Deleted existing database directory: {self.db_path}")
# except Exception as e:
# print(f"Error deleting database directory: {e}")
# # Reinitialize the client
# self.client = chromadb.PersistentClient(path=self.db_path)
# documents = self.load_documents(filename)
# # Create a new collection
# self.collection = self.client.create_collection(name=collection_name, embedding_function=self.embedding_function)
# # Batch add documents for better performance
# batch_size = 1000
# for i in range(0, len(documents), batch_size):
# batch = documents[i:i+batch_size]
# self.collection.add(
# documents=[doc.page_content for doc in batch],
# metadatas=[{"title": doc.metadata.get('title', '')} for doc in batch],
# ids=[f"doc_{j}" for j in range(i, i+len(batch))]
# )
# print(f"Initialized database with {len(documents)} documents from {filename}")
# def query_kb(self, prompt: str, top_k: int = 3) -> List[Dict[str, Any]]:
# if not self.collection:
# raise ValueError("Database not initialized. Please initialize a database first.")
# results = self.collection.query(
# query_texts=[prompt],
# n_results=top_k
# )
# retrieved_results = []
# for i in range(len(results['ids'][0])):
# doc_id = results['ids'][0][i]
# content = results['documents'][0][i]
# metadata = results['metadatas'][0][i]
# title = metadata['title']
# similarity = 1 - results['distances'][0][i] # Convert distance to similarity
# retrieved_results.append({
# "id": doc_id,
# "title": title,
# "content": content,
# "similarity": round(similarity, 4)
# })
# return retrieved_results
# def get_collection_info(self) -> Dict[str, Any]:
# if not self.collection:
# raise ValueError("Database not initialized. Please initialize a database first.")
# return {
# "name": self.collection.name,
# "count": self.collection.count()
# }
# # if __name__ == "__main__":
# # # Create an instance of the KnowledgeBaseManager
# # kb_manager = KnowledgeBaseManager()
# # # Load documents from a file (replace with your own file path)
# # filename = "data/Scraped_data/scraped_nextjs.pkl"
# # collection_name = "next_js"
# # # Initialize the database
# # kb_manager.initialize_database(filename, collection_name)
# # # Query the knowledge base
# # prompt = "What is rendering and routing"
# # top_k = 2
# # results = kb_manager.query_knowledge_base(prompt, top_k)
# # # Print the results
# # print("Results:")
# # for result in results:
# # print(f"Title: {result['title']}")
# # print(f"Content: {result['content'][:200]}...")
# # print(f"Similarity: {result['similarity']:.4f}")
# # print()
# # # Get collection info
# # collection_info = kb_manager.get_collection_info()
# # print("Collection Info:")
# # print(f"Name: {collection_info['name']}")
# # print(f"Count: {collection_info['count']}")
import os
import shutil
import pickle
import chromadb
from chromadb.utils import embedding_functions
from sentence_transformers import SentenceTransformer
from typing import List, Dict, Any
class KnowledgeBaseManager:
def __init__(self, db_path: str):
self.db_path = db_path
self.client = None
self.model = SentenceTransformer("all-MiniLM-L6-v2")
self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
self.collection = None
def load_documents(self, filename: str) -> List:
if not os.path.exists(filename):
raise FileNotFoundError(f"The file {filename} does not exist.")
with open(filename, 'rb') as f:
return pickle.load(f)
def initialize_database(self, filename: str, collection_name: str):
if self.client is None:
self.client = chromadb.PersistentClient(path=self.db_path)
# Check if collection already exists
existing_collections = self.client.list_collections()
if any(col.name == collection_name for col in existing_collections):
print(f"Collection {collection_name} already exists. Skipping initialization.")
self.collection = self.client.get_collection(name=collection_name, embedding_function=self.embedding_function)
return
documents = self.load_documents(filename)
# Create a new collection
self.collection = self.client.create_collection(name=collection_name, embedding_function=self.embedding_function)
# Batch add documents for better performance
batch_size = 1000
for i in range(0, len(documents), batch_size):
batch = documents[i:i+batch_size]
self.collection.add(
documents=[doc.page_content for doc in batch],
metadatas=[{"title": doc.metadata.get('title', '')} for doc in batch],
ids=[f"doc_{j}" for j in range(i, i+len(batch))]
)
print(f"Initialized database with {len(documents)} documents from {filename}")
def query_kb(self, prompt: str, top_k: int = 3) -> List[Dict[str, Any]]:
"""Use this function to get information from knowledge base
Args:
prompt (str): prompt to search in information base to get results.
top_k (int): Number of records of information to return. Defaults to 3.
Returns:
str: String of entire information in one string combined
"""
if not self.collection:
raise ValueError("Database not initialized. Please initialize a database first.")
results = self.collection.query(
query_texts=[prompt],
n_results=top_k
)
retrieved_results = []
for i in range(len(results['ids'][0])):
doc_id = results['ids'][0][i]
content = results['documents'][0][i]
metadata = results['metadatas'][0][i]
title = metadata['title']
similarity = 1 - results['distances'][0][i] # Convert distance to similarity
retrieved_results.append({
"id": doc_id,
"title": title,
"content": content,
"similarity": round(similarity, 4)
})
return retrieved_results
def get_collection_info(self) -> Dict[str, Any]:
if not self.collection:
raise ValueError("Database not initialized. Please initialize a database first.")
return {
"name": self.collection.name,
"count": self.collection.count()
}