Files
opendan/rootfs/knowledge_pipelines/Mia/query.py
T

96 lines
4.4 KiB
Python
Raw Normal View History

2023-10-20 14:19:41 +08:00
import os
import logging
import json
2023-12-05 18:50:32 +08:00
from aios import *
2023-10-19 10:05:08 +08:00
2023-12-05 18:50:32 +08:00
class EmbeddingEnvironment(SimpleEnvironment):
def __init__(self, workspace: str) -> None:
super().__init__(workspace)
2023-10-20 14:19:41 +08:00
self.path = os.path.join(AIStorage.get_instance().get_myai_dir(), "knowledge/indices/embedding")
self._default_text_model = "all-MiniLM-L6-v2"
self._default_image_model = "clip-ViT-B-32"
2023-10-19 10:05:08 +08:00
query_param = {
"tokens": "key words to query",
"types": "prefered knowledge types, one or more of [text, image]",
"index": "index of query result"
}
self.add_ai_function(SimpleAIFunction("query_knowledge",
"vector query content from local knowledge base",
self._query,
query_param))
2023-10-20 14:19:41 +08:00
def __get_vector_store(self, model_name: str) -> ChromaVectorStore:
return ChromaVectorStore(self.path, model_name)
2023-10-19 10:05:08 +08:00
async def query_objects(self, tokens: str, types: list[str], topk: int) -> [ObjectID]:
texts = []
if "text" in types:
2023-10-20 14:19:41 +08:00
vector = await ComputeKernel.get_instance().do_text_embedding(tokens, self._default_text_model)
texts = await self.__get_vector_store(self._default_text_model).query(vector, topk)
2023-10-19 10:05:08 +08:00
images = []
if "image" in types:
2023-10-20 14:19:41 +08:00
vector = await ComputeKernel.get_instance().do_text_embedding(tokens, self._default_image_model)
images = await self.__get_vector_store(self._default_image_model).query(vector, topk)
2023-10-19 10:05:08 +08:00
return texts + images
def tokens_from_objects(self, object_ids: [ObjectID]) -> list[str]:
results = dict()
for object_id in object_ids:
2023-10-20 14:19:41 +08:00
parents = KnowledgeStore().get_relation_store().get_related_root_objects(object_id)
2023-10-19 10:05:08 +08:00
# last parent is the root object
root_object_id = parents[0] if parents else object_id
logging.info(f"object_id: {str(object_id)} root_object_id: {str(root_object_id)}")
if str(root_object_id) in results:
results[str(root_object_id)].append(object_id)
else:
results[str(root_object_id)] = [root_object_id, object_id]
content = ""
result_desc = []
for result in results.values():
# first element in result is the root object
root_object_id = result[0]
if root_object_id.get_object_type() == ObjectType.Email:
2023-10-20 14:19:41 +08:00
email = KnowledgeStore().load_object(root_object_id)
2023-10-19 10:05:08 +08:00
desc = email.get_desc()
desc["type"] = "email"
desc["contents"] = []
result_desc.append(desc)
upper_list = desc["contents"]
result = result[1:]
else:
upper_list = result_desc
for object_id in result:
if object_id.get_object_type() == ObjectType.Chunk:
2023-10-20 14:19:41 +08:00
upper_list.append({"type": "text", "content": KnowledgeStore().get_chunk_reader().get_chunk(object_id).read().decode("utf-8")})
2023-10-19 10:05:08 +08:00
if object_id.get_object_type() == ObjectType.Image:
# image = self.load_object(object_id)
desc = dict()
desc["id"] = str(object_id)
desc["type"] = "image"
upper_list.append(desc)
if object_id.get_object_type() == ObjectType.Video:
2023-10-20 14:19:41 +08:00
video = KnowledgeStore().load_object(object_id)
2023-10-19 10:05:08 +08:00
desc = video.get_desc()
desc["type"] = "video"
upper_list.append(desc)
else:
pass
content += json.dumps(result_desc)
content += ".\n"
return content
async def _query(self, tokens: str, types: list[str] = ["text"], index: str=0):
index = int(index)
2023-10-20 14:19:41 +08:00
object_ids = await self.query_objects(tokens, types, 4)
2023-10-19 10:05:08 +08:00
if len(object_ids) <= index:
return "*** I have no more information for your reference.\n"
else:
content = "*** I have provided the following known information for your reference with json format:\n"
2023-10-20 14:19:41 +08:00
return content + self.tokens_from_objects(object_ids[index:index+1])
2023-12-05 18:50:32 +08:00
def init(workspace: str) -> EmbeddingEnvironment:
return EmbeddingEnvironment(workspace)