keywords.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """
  2. 关键词提取和处理工具
  3. """
  4. import re
  5. from typing import List, Dict, Any
  6. from .api_client import LLMClient
  7. async def extract_keywords(
  8. research_topic: str,
  9. llm_client: LLMClient
  10. ) -> List[str]:
  11. """
  12. 从研究主题中提取关键词
  13. Args:
  14. research_topic: 用户输入的研究主题
  15. llm_client: LLM客户端实例
  16. Returns:
  17. 关键词列表
  18. """
  19. prompt = f"""
  20. 作为一个科研助手,请从以下研究主题中提取5-8个关键的检索词,这些词应该能够用于学术文献检索。
  21. 请考虑主题的核心概念、方法论、应用领域等方面。返回格式为逗号分隔的关键词列表,不要有编号或其他文本。
  22. 研究主题: {research_topic}
  23. 关键词:
  24. """
  25. response = await llm_client.generate_text(prompt, temperature=0.1)
  26. # 清理和解析响应
  27. # 移除多余的空格和标点
  28. response = re.sub(r'[\n\r]+', ',', response)
  29. response = re.sub(r'\s*,\s*', ',', response)
  30. response = re.sub(r'^\s+|\s+$', '', response)
  31. # 分割为关键词列表
  32. keywords = [kw.strip() for kw in response.split(',') if kw.strip()]
  33. return keywords
  34. async def expand_search_queries(
  35. keywords: List[str],
  36. llm_client: LLMClient
  37. ) -> List[str]:
  38. """
  39. 扩展搜索查询,生成更全面的检索语句
  40. Args:
  41. keywords: 关键词列表
  42. llm_client: LLM客户端实例
  43. Returns:
  44. 扩展后的搜索查询列表
  45. """
  46. kw_text = ", ".join(keywords)
  47. prompt = f"""
  48. 作为科研检索专家,我需要你帮助构建有效的学术文献检索语句。
  49. 基于以下关键词:{kw_text}
  50. 请生成3个不同的arXiv搜索查询语句,这些查询应当:
  51. 1. 使用布尔运算符(AND, OR)来组合关键词
  52. 2. 考虑同义词和相关概念
  53. 3. 针对不同的研究角度
  54. 只需返回这些查询语句,每行一个,不要有编号或其他文本。
  55. """
  56. response = await llm_client.generate_text(prompt, temperature=0.2)
  57. # 清理和解析响应
  58. queries = [q.strip() for q in response.splitlines() if q.strip()]
  59. # 确保至少有一个查询
  60. if not queries and keywords:
  61. queries = [" AND ".join(keywords[:3])]
  62. return queries