hybrid_similarity.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/env python3
  2. """
  3. 混合相似度计算模块
  4. 结合向量模型(text_embedding)和LLM模型(semantic_similarity)的结果
  5. """
  6. from typing import Dict, Any, Optional
  7. import asyncio
  8. from lib.text_embedding import compare_phrases as compare_phrases_embedding
  9. from lib.semantic_similarity import compare_phrases as compare_phrases_semantic
  10. async def compare_phrases(
  11. phrase_a: str,
  12. phrase_b: str,
  13. weight_embedding: float = 0.5,
  14. weight_semantic: float = 0.5,
  15. embedding_model: str = "chinese",
  16. semantic_model: str = 'openai/gpt-4.1-mini',
  17. use_cache: bool = True,
  18. cache_dir_embedding: str = "cache/text_embedding",
  19. cache_dir_semantic: str = "cache/semantic_similarity",
  20. **semantic_kwargs
  21. ) -> Dict[str, Any]:
  22. """
  23. 混合相似度计算:同时使用向量模型和LLM模型,按权重组合结果
  24. Args:
  25. phrase_a: 第一个短语
  26. phrase_b: 第二个短语
  27. weight_embedding: 向量模型权重,默认 0.5
  28. weight_semantic: LLM模型权重,默认 0.5
  29. embedding_model: 向量模型名称,默认 "chinese"
  30. semantic_model: LLM模型名称,默认 'openai/gpt-4.1-mini'
  31. use_cache: 是否使用缓存,默认 True
  32. cache_dir_embedding: 向量模型缓存目录
  33. cache_dir_semantic: LLM模型缓存目录
  34. **semantic_kwargs: 其他传递给semantic_similarity的参数
  35. - temperature: 温度参数,默认 0.0
  36. - max_tokens: 最大token数,默认 65536
  37. - prompt_template: 自定义提示词模板
  38. - instructions: Agent系统指令
  39. - tools: Agent工具列表
  40. - name: Agent名称
  41. Returns:
  42. {
  43. "相似度": float, # 加权平均后的相似度 (0-1)
  44. "说明": str # 综合说明(包含各模型的分数和说明)
  45. }
  46. Examples:
  47. >>> # 使用默认权重 (0.5:0.5)
  48. >>> result = await compare_phrases("深度学习", "神经网络")
  49. >>> print(result['相似度']) # 加权平均后的相似度
  50. 0.82
  51. >>> # 自定义权重,更倾向向量模型
  52. >>> result = await compare_phrases(
  53. ... "深度学习", "神经网络",
  54. ... weight_embedding=0.7,
  55. ... weight_semantic=0.3
  56. ... )
  57. >>> # 使用不同的模型
  58. >>> result = await compare_phrases(
  59. ... "深度学习", "神经网络",
  60. ... embedding_model="multilingual",
  61. ... semantic_model="anthropic/claude-sonnet-4.5"
  62. ... )
  63. """
  64. # 验证权重
  65. total_weight = weight_embedding + weight_semantic
  66. if abs(total_weight - 1.0) > 0.001:
  67. raise ValueError(f"权重之和必须为1.0,当前为: {total_weight}")
  68. # 并发调用两个模型
  69. embedding_task = asyncio.to_thread(
  70. compare_phrases_embedding,
  71. phrase_a=phrase_a,
  72. phrase_b=phrase_b,
  73. model_name=embedding_model,
  74. use_cache=use_cache,
  75. cache_dir=cache_dir_embedding
  76. )
  77. semantic_task = compare_phrases_semantic(
  78. phrase_a=phrase_a,
  79. phrase_b=phrase_b,
  80. model_name=semantic_model,
  81. use_cache=use_cache,
  82. cache_dir=cache_dir_semantic,
  83. **semantic_kwargs
  84. )
  85. # 等待两个任务完成
  86. embedding_result, semantic_result = await asyncio.gather(
  87. embedding_task,
  88. semantic_task
  89. )
  90. # 提取相似度分数
  91. score_embedding = embedding_result.get("相似度", 0.0)
  92. score_semantic = semantic_result.get("相似度", 0.0)
  93. # 计算加权平均
  94. final_score = (
  95. score_embedding * weight_embedding +
  96. score_semantic * weight_semantic
  97. )
  98. # 生成综合说明(格式化为清晰的结构)
  99. explanation = (
  100. f"【混合相似度】{final_score:.3f}(向量模型权重{weight_embedding},LLM模型权重{weight_semantic})\n\n"
  101. f"【向量模型】相似度={score_embedding:.3f}\n"
  102. f"{embedding_result.get('说明', 'N/A')}\n\n"
  103. f"【LLM模型】相似度={score_semantic:.3f}\n"
  104. f"{semantic_result.get('说明', 'N/A')}"
  105. )
  106. # 构建返回结果(与原接口完全一致)
  107. return {
  108. "相似度": final_score,
  109. "说明": explanation
  110. }
  111. def compare_phrases_sync(
  112. phrase_a: str,
  113. phrase_b: str,
  114. weight_embedding: float = 0.5,
  115. weight_semantic: float = 0.5,
  116. **kwargs
  117. ) -> Dict[str, Any]:
  118. """
  119. 混合相似度计算的同步版本(内部创建事件循环)
  120. Args:
  121. phrase_a: 第一个短语
  122. phrase_b: 第二个短语
  123. weight_embedding: 向量模型权重,默认 0.5
  124. weight_semantic: LLM模型权重,默认 0.5
  125. **kwargs: 其他参数(同 compare_phrases)
  126. Returns:
  127. 同 compare_phrases
  128. Examples:
  129. >>> result = compare_phrases_sync("深度学习", "神经网络")
  130. >>> print(result['相似度'])
  131. """
  132. return asyncio.run(
  133. compare_phrases(
  134. phrase_a=phrase_a,
  135. phrase_b=phrase_b,
  136. weight_embedding=weight_embedding,
  137. weight_semantic=weight_semantic,
  138. **kwargs
  139. )
  140. )
  141. if __name__ == "__main__":
  142. async def main():
  143. print("=" * 80)
  144. print("混合相似度计算示例")
  145. print("=" * 80)
  146. print()
  147. # 示例 1: 默认权重 (0.5:0.5)
  148. print("示例 1: 默认权重 (0.5:0.5)")
  149. print("-" * 80)
  150. result = await compare_phrases("深度学习", "神经网络")
  151. print(f"相似度: {result['相似度']:.3f}")
  152. print(f"说明:\n{result['说明']}")
  153. print()
  154. # 示例 2: 不相关的短语
  155. print("示例 2: 不相关的短语")
  156. print("-" * 80)
  157. result = await compare_phrases("编程", "吃饭")
  158. print(f"相似度: {result['相似度']:.3f}")
  159. print(f"说明:\n{result['说明']}")
  160. print()
  161. # 示例 3: 自定义权重,更倾向向量模型
  162. print("示例 3: 自定义权重 (向量:0.7, LLM:0.3)")
  163. print("-" * 80)
  164. result = await compare_phrases(
  165. "人工智能", "机器学习",
  166. weight_embedding=0.7,
  167. weight_semantic=0.3
  168. )
  169. print(f"相似度: {result['相似度']:.3f}")
  170. print(f"说明:\n{result['说明']}")
  171. print()
  172. # 示例 4: 完整输出示例
  173. print("示例 4: 完整输出示例")
  174. print("-" * 80)
  175. result = await compare_phrases("宿命感", "余华的小说")
  176. print(f"相似度: {result['相似度']:.3f}")
  177. print(f"说明:\n{result['说明']}")
  178. print()
  179. # 示例 5: 同步版本
  180. print("示例 5: 同步版本调用")
  181. print("-" * 80)
  182. result = compare_phrases_sync("Python", "编程语言")
  183. print(f"相似度: {result['相似度']:.3f}")
  184. print(f"说明:\n{result['说明']}")
  185. print()
  186. print("=" * 80)
  187. asyncio.run(main())