trunks_service.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. )
  68. if metadata_condition:
  69. query = query.filter_by(**metadata_condition)
  70. if type:
  71. query = query.filter(Trunks.type == type)
  72. results = query.order_by('distance').limit(limit).all()
  73. result_list = [{
  74. 'id': r.id,
  75. 'file_path': r.file_path,
  76. 'content': r.content,
  77. 'distance': r.distance,
  78. 'title': r.title,
  79. 'embedding': r.embedding.tolist()
  80. } for r in results]
  81. if conversation_id:
  82. self.set_cache(conversation_id, result_list)
  83. return result_list
  84. finally:
  85. db.close()
  86. def fulltext_search(self, query: str) -> List[Trunks]:
  87. db = SessionLocal()
  88. try:
  89. return db.query(Trunks).filter(
  90. Trunks.content_tsvector.match(query)
  91. ).all()
  92. finally:
  93. db.close()
  94. def update_trunk(self, trunk_id: int, update_data: dict) -> Optional[Trunks]:
  95. if 'content' in update_data:
  96. content = update_data['content']
  97. update_data['embedding'] = Vectorizer.get_embedding(content)
  98. if 'type' not in update_data:
  99. update_data['type'] = 'default'
  100. logger.debug(f"更新生成的embedding长度: {len(update_data['embedding'])}, 内容摘要: {content[:20]}")
  101. # update_data['content_tsvector'] = func.to_tsvector('chinese', content)
  102. db = SessionLocal()
  103. try:
  104. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  105. if trunk:
  106. for key, value in update_data.items():
  107. setattr(trunk, key, value)
  108. db.commit()
  109. db.refresh(trunk)
  110. return trunk
  111. except Exception as e:
  112. db.rollback()
  113. logger.error(f"更新trunk失败: {str(e)}")
  114. raise
  115. finally:
  116. db.close()
  117. def delete_trunk(self, trunk_id: int) -> bool:
  118. db = SessionLocal()
  119. try:
  120. trunk = db.query(Trunks).filter(Trunks.id == trunk_id).first()
  121. if trunk:
  122. db.delete(trunk)
  123. db.commit()
  124. return True
  125. return False
  126. except Exception as e:
  127. db.rollback()
  128. logger.error(f"删除trunk失败: {str(e)}")
  129. raise
  130. finally:
  131. db.close()
  132. _cache = {}
  133. def get_cache(self, conversation_id: str) -> List[dict]:
  134. """
  135. 根据conversation_id获取缓存结果
  136. :param conversation_id: 会话ID
  137. :return: 结果列表
  138. """
  139. return self._cache.get(conversation_id, [])
  140. def set_cache(self, conversation_id: str, result: List[dict]) -> None:
  141. """
  142. 设置缓存结果
  143. :param conversation_id: 会话ID
  144. :param result: 要缓存的结果
  145. """
  146. self._cache[conversation_id] = result
  147. def get_cached_result(self, conversation_id: str) -> List[dict]:
  148. """
  149. 根据conversation_id获取缓存结果
  150. :param conversation_id: 会话ID
  151. :return: 结果列表
  152. """
  153. return self.get_cache(conversation_id)
  154. def paginated_search(self, search_params: dict) -> dict:
  155. """
  156. 分页查询方法
  157. :param search_params: 包含keyword, pageNo, limit的字典
  158. :return: 包含结果列表和分页信息的字典
  159. """
  160. keyword = search_params.get('keyword', '')
  161. page_no = search_params.get('pageNo', 1)
  162. limit = search_params.get('limit', 10)
  163. if page_no < 1:
  164. page_no = 1
  165. if limit < 1:
  166. limit = 10
  167. embedding = Vectorizer.get_embedding(keyword)
  168. offset = (page_no - 1) * limit
  169. db = SessionLocal()
  170. try:
  171. # 获取总条数
  172. total_count = db.query(func.count(Trunks.id)).filter(Trunks.type == search_params.get('type')).scalar()
  173. # 执行向量搜索
  174. results = db.query(
  175. Trunks.id,
  176. Trunks.file_path,
  177. Trunks.content,
  178. Trunks.embedding.l2_distance(embedding).label('distance'),
  179. Trunks.title
  180. ).filter(Trunks.type == search_params.get('type')).order_by('distance').offset(offset).limit(limit).all()
  181. return {
  182. 'data': [{
  183. 'id': r.id,
  184. 'file_path': r.file_path,
  185. 'content': r.content,
  186. 'distance': r.distance,
  187. 'title': r.title
  188. } for r in results],
  189. 'pagination': {
  190. 'total': total_count,
  191. 'pageNo': page_no,
  192. 'limit': limit,
  193. 'totalPages': (total_count + limit - 1) // limit
  194. }
  195. }
  196. finally:
  197. db.close()