dataset_docstore.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. from typing import Any, Dict, Optional, Sequence
  2. from langchain.schema import Document
  3. from sqlalchemy import func
  4. from core.model_providers.model_factory import ModelFactory
  5. from extensions.ext_database import db
  6. from models.dataset import Dataset, DocumentSegment
  7. class DatesetDocumentStore:
  8. def __init__(
  9. self,
  10. dataset: Dataset,
  11. user_id: str,
  12. document_id: Optional[str] = None,
  13. ):
  14. self._dataset = dataset
  15. self._user_id = user_id
  16. self._document_id = document_id
  17. @classmethod
  18. def from_dict(cls, config_dict: Dict[str, Any]) -> "DatesetDocumentStore":
  19. return cls(**config_dict)
  20. def to_dict(self) -> Dict[str, Any]:
  21. """Serialize to dict."""
  22. return {
  23. "dataset_id": self._dataset.id,
  24. }
  25. @property
  26. def dateset_id(self) -> Any:
  27. return self._dataset.id
  28. @property
  29. def user_id(self) -> Any:
  30. return self._user_id
  31. @property
  32. def docs(self) -> Dict[str, Document]:
  33. document_segments = db.session.query(DocumentSegment).filter(
  34. DocumentSegment.dataset_id == self._dataset.id
  35. ).all()
  36. output = {}
  37. for document_segment in document_segments:
  38. doc_id = document_segment.index_node_id
  39. output[doc_id] = Document(
  40. page_content=document_segment.content,
  41. metadata={
  42. "doc_id": document_segment.index_node_id,
  43. "doc_hash": document_segment.index_node_hash,
  44. "document_id": document_segment.document_id,
  45. "dataset_id": document_segment.dataset_id,
  46. }
  47. )
  48. return output
  49. def add_documents(
  50. self, docs: Sequence[Document], allow_update: bool = True
  51. ) -> None:
  52. max_position = db.session.query(func.max(DocumentSegment.position)).filter(
  53. DocumentSegment.document_id == self._document_id
  54. ).scalar()
  55. if max_position is None:
  56. max_position = 0
  57. embedding_model = ModelFactory.get_embedding_model(
  58. tenant_id=self._dataset.tenant_id
  59. )
  60. for doc in docs:
  61. if not isinstance(doc, Document):
  62. raise ValueError("doc must be a Document")
  63. segment_document = self.get_document(doc_id=doc.metadata['doc_id'], raise_error=False)
  64. # NOTE: doc could already exist in the store, but we overwrite it
  65. if not allow_update and segment_document:
  66. raise ValueError(
  67. f"doc_id {doc.metadata['doc_id']} already exists. "
  68. "Set allow_update to True to overwrite."
  69. )
  70. # calc embedding use tokens
  71. tokens = embedding_model.get_num_tokens(doc.page_content)
  72. if not segment_document:
  73. max_position += 1
  74. segment_document = DocumentSegment(
  75. tenant_id=self._dataset.tenant_id,
  76. dataset_id=self._dataset.id,
  77. document_id=self._document_id,
  78. index_node_id=doc.metadata['doc_id'],
  79. index_node_hash=doc.metadata['doc_hash'],
  80. position=max_position,
  81. content=doc.page_content,
  82. word_count=len(doc.page_content),
  83. tokens=tokens,
  84. created_by=self._user_id,
  85. )
  86. if 'answer' in doc.metadata and doc.metadata['answer']:
  87. segment_document.answer = doc.metadata.pop('answer', '')
  88. db.session.add(segment_document)
  89. else:
  90. segment_document.content = doc.page_content
  91. if 'answer' in doc.metadata and doc.metadata['answer']:
  92. segment_document.answer = doc.metadata.pop('answer', '')
  93. segment_document.index_node_hash = doc.metadata['doc_hash']
  94. segment_document.word_count = len(doc.page_content)
  95. segment_document.tokens = tokens
  96. db.session.commit()
  97. def document_exists(self, doc_id: str) -> bool:
  98. """Check if document exists."""
  99. result = self.get_document_segment(doc_id)
  100. return result is not None
  101. def get_document(
  102. self, doc_id: str, raise_error: bool = True
  103. ) -> Optional[Document]:
  104. document_segment = self.get_document_segment(doc_id)
  105. if document_segment is None:
  106. if raise_error:
  107. raise ValueError(f"doc_id {doc_id} not found.")
  108. else:
  109. return None
  110. return Document(
  111. page_content=document_segment.content,
  112. metadata={
  113. "doc_id": document_segment.index_node_id,
  114. "doc_hash": document_segment.index_node_hash,
  115. "document_id": document_segment.document_id,
  116. "dataset_id": document_segment.dataset_id,
  117. }
  118. )
  119. def delete_document(self, doc_id: str, raise_error: bool = True) -> None:
  120. document_segment = self.get_document_segment(doc_id)
  121. if document_segment is None:
  122. if raise_error:
  123. raise ValueError(f"doc_id {doc_id} not found.")
  124. else:
  125. return None
  126. db.session.delete(document_segment)
  127. db.session.commit()
  128. def set_document_hash(self, doc_id: str, doc_hash: str) -> None:
  129. """Set the hash for a given doc_id."""
  130. document_segment = self.get_document_segment(doc_id)
  131. if document_segment is None:
  132. return None
  133. document_segment.index_node_hash = doc_hash
  134. db.session.commit()
  135. def get_document_hash(self, doc_id: str) -> Optional[str]:
  136. """Get the stored hash for a document, if it exists."""
  137. document_segment = self.get_document_segment(doc_id)
  138. if document_segment is None:
  139. return None
  140. return document_segment.index_node_hash
  141. def get_document_segment(self, doc_id: str) -> DocumentSegment:
  142. document_segment = db.session.query(DocumentSegment).filter(
  143. DocumentSegment.dataset_id == self._dataset.id,
  144. DocumentSegment.index_node_id == doc_id
  145. ).first()
  146. return document_segment