trunks_service.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. from sqlalchemy import func
  2. from sqlalchemy.orm import Session
  3. from db.session import get_db
  4. from typing import List, Optional
  5. from model.trunks_model import Trunks
  6. from db.session import SessionLocal
  7. import logging
  8. from utils.vectorizer import Vectorizer
  9. logger = logging.getLogger(__name__)
  10. class TrunksService:
  11. def __init__(self):
  12. self.db = next(get_db())
  13. def create_trunk(self, trunk_data: dict) -> Trunks:
  14. # 自动生成向量和全文检索字段
  15. content = trunk_data.get('content')
  16. if 'embedding' in trunk_data and len(trunk_data['embedding']) != 1024:
  17. raise ValueError("向量维度必须为1024")
  18. trunk_data['embedding'] = Vectorizer.get_embedding(content)
  19. if 'type' not in trunk_data:
  20. trunk_data['type'] = 'default'
  21. if 'title' not in trunk_data:
  22. from pathlib import Path
  23. trunk_data['title'] = Path(trunk_data['file_path']).stem
  24. print("embedding length:", len(trunk_data['embedding']))
  25. logger.debug(f"生成的embedding长度: {len(trunk_data['embedding'])}, 内容摘要: {content[:20]}")
  26. # trunk_data['content_tsvector'] = func.to_tsvector('chinese', content)
  27. db = SessionLocal()
  28. try:
  29. trunk = Trunks(**trunk_data)
  30. db.add(trunk)
  31. db.commit()
  32. db.refresh(trunk)
  33. return trunk
  34. except Exception as e:
  35. db.rollback()
  36. logger.error(f"创建trunk失败: {str(e)}")
  37. raise
  38. finally:
  39. db.close()
  40. def get_trunk_by_id(self, trunk_id: int) -> Optional[dict]:
  41. db = SessionLocal()
  42. try:
  43. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  44. if trunk:
  45. return {
  46. 'id': trunk.id,
  47. 'file_path': trunk.file_path,
  48. 'content': trunk.content,
  49. 'embedding': trunk.embedding.tolist(),
  50. 'type': trunk.type,
  51. 'title':trunk.title
  52. }
  53. return None
  54. finally:
  55. db.close()
  56. def search_by_vector(self, text: str, limit: int = 10, metadata_condition: Optional[dict] = None, type: Optional[str] = None, conversation_id: Optional[str] = None) -> List[dict]:
  57. embedding = Vectorizer.get_embedding(text)
  58. db = SessionLocal()
  59. try:
  60. query = db.query(
  61. Trunks.id,
  62. Trunks.file_path,
  63. Trunks.content,
  64. Trunks.embedding.l2_distance(embedding).label('distance'),
  65. Trunks.title,
  66. Trunks.embedding,
  67. Trunks.referrence
  68. )
  69. if metadata_condition:
  70. query = query.filter_by(**metadata_condition)
  71. if type:
  72. query = query.filter(Trunks.type == type)
  73. results = query.order_by('distance').limit(limit).all()
  74. result_list = [{
  75. 'id': r.id,
  76. 'file_path': r.file_path,
  77. 'content': r.content,
  78. #保留小数点后三位
  79. 'distance': round(r.distance, 3),
  80. 'title': r.title,
  81. 'embedding': r.embedding.tolist(),
  82. 'referrence': r.referrence
  83. } for r in results]
  84. if conversation_id:
  85. self.set_cache(conversation_id, result_list)
  86. return result_list
  87. finally:
  88. db.close()
  89. def fulltext_search(self, query: str) -> List[Trunks]:
  90. db = SessionLocal()
  91. try:
  92. return db.query(Trunks).filter(
  93. Trunks.content_tsvector.match(query)
  94. ).all()
  95. finally:
  96. db.close()
  97. def update_trunk(self, trunk_id: int, update_data: dict) -> Optional[Trunks]:
  98. if 'content' in update_data:
  99. content = update_data['content']
  100. update_data['embedding'] = Vectorizer.get_embedding(content)
  101. if 'type' not in update_data:
  102. update_data['type'] = 'default'
  103. logger.debug(f"更新生成的embedding长度: {len(update_data['embedding'])}, 内容摘要: {content[:20]}")
  104. # update_data['content_tsvector'] = func.to_tsvector('chinese', content)
  105. db = SessionLocal()
  106. try:
  107. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  108. if trunk:
  109. for key, value in update_data.items():
  110. setattr(trunk, key, value)
  111. db.commit()
  112. db.refresh(trunk)
  113. return trunk
  114. except Exception as e:
  115. db.rollback()
  116. logger.error(f"更新trunk失败: {str(e)}")
  117. raise
  118. finally:
  119. db.close()
  120. def delete_trunk(self, trunk_id: int) -> bool:
  121. db = SessionLocal()
  122. try:
  123. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  124. if trunk:
  125. db.delete(trunk)
  126. db.commit()
  127. return True
  128. return False
  129. except Exception as e:
  130. db.rollback()
  131. logger.error(f"删除trunk失败: {str(e)}")
  132. raise
  133. finally:
  134. db.close()
  135. _cache = {}
  136. def get_cache(self, conversation_id: str) -> List[dict]:
  137. """
  138. 根据conversation_id获取缓存结果
  139. :param conversation_id: 会话ID
  140. :return: 结果列表
  141. """
  142. return self._cache.get(conversation_id, [])
  143. def set_cache(self, conversation_id: str, result: List[dict]) -> None:
  144. """
  145. 设置缓存结果
  146. :param conversation_id: 会话ID
  147. :param result: 要缓存的结果
  148. """
  149. self._cache[conversation_id] = result
  150. def get_cached_result(self, conversation_id: str) -> List[dict]:
  151. """
  152. 根据conversation_id获取缓存结果
  153. :param conversation_id: 会话ID
  154. :return: 结果列表
  155. """
  156. return self.get_cache(conversation_id)
  157. def paginated_search(self, search_params: dict) -> dict:
  158. """
  159. 分页查询方法
  160. :param search_params: 包含keyword, pageNo, limit的字典
  161. :return: 包含结果列表和分页信息的字典
  162. """
  163. keyword = search_params.get('keyword', '')
  164. page_no = search_params.get('pageNo', 1)
  165. limit = search_params.get('limit', 10)
  166. if page_no < 1:
  167. page_no = 1
  168. if limit < 1:
  169. limit = 10
  170. embedding = Vectorizer.get_embedding(keyword)
  171. offset = (page_no - 1) * limit
  172. db = SessionLocal()
  173. try:
  174. # 获取总条数
  175. total_count = db.query(func.count(Trunks.id)).filter(Trunks.type == search_params.get('type')).scalar()
  176. # 执行向量搜索
  177. results = db.query(
  178. Trunks.id,
  179. Trunks.file_path,
  180. Trunks.content,
  181. Trunks.embedding.l2_distance(embedding).label('distance'),
  182. Trunks.title
  183. ).filter(Trunks.type == search_params.get('type')).order_by('distance').offset(offset).limit(limit).all()
  184. return {
  185. 'data': [{
  186. 'id': r.id,
  187. 'file_path': r.file_path,
  188. 'content': r.content,
  189. #保留小数点后三位
  190. 'distance': round(r.distance, 3),
  191. 'title': r.title
  192. } for r in results],
  193. 'pagination': {
  194. 'total': total_count,
  195. 'pageNo': page_no,
  196. 'limit': limit,
  197. 'totalPages': (total_count + limit - 1) // limit
  198. }
  199. }
  200. finally:
  201. db.close()