trunks_service.py 7.2 KB

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