citation_tool.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """引用格式化工具(返回 str)"""
  2. from typing import Any, Dict, List
  3. from hello_agents.tools import Tool, ToolParameter
  4. class CitationTool(Tool):
  5. """引用格式化工具(GB/T 7714-2015 与 APA 7th)"""
  6. def __init__(self):
  7. super().__init__(
  8. name="format_citation",
  9. description="将论文元数据格式化为标准引用格式(gb7714 或 apa)。",
  10. )
  11. def get_parameters(self) -> List[ToolParameter]:
  12. return [
  13. ToolParameter(name="title", type="string",
  14. description="论文标题", required=True),
  15. ToolParameter(name="authors", type="string",
  16. description="作者列表,逗号分隔", required=True),
  17. ToolParameter(name="year", type="string",
  18. description="年份", required=True),
  19. ToolParameter(name="venue", type="string",
  20. description="期刊/会议名", required=False),
  21. ToolParameter(name="volume", type="string",
  22. description="卷号", required=False),
  23. ToolParameter(name="issue", type="string",
  24. description="期号", required=False),
  25. ToolParameter(name="pages", type="string",
  26. description="页码", required=False),
  27. ToolParameter(name="doi", type="string",
  28. description="DOI", required=False),
  29. ToolParameter(name="style", type="string",
  30. description="gb7714 或 apa", required=False),
  31. ]
  32. def run(self, parameters: Dict[str, Any]) -> str:
  33. title = parameters.get("title", "")
  34. authors_raw = parameters.get("authors", "")
  35. year = parameters.get("year", "")
  36. venue = parameters.get("venue", "")
  37. volume = parameters.get("volume", "")
  38. issue = parameters.get("issue", "")
  39. pages = parameters.get("pages", "")
  40. doi = parameters.get("doi", "")
  41. style = parameters.get("style", "gb7714")
  42. if not title or not authors_raw:
  43. return "❌ title 与 authors 为必填字段"
  44. author_list = [a.strip() for a in authors_raw.split(",") if a.strip()]
  45. authors_str = ", ".join(author_list)
  46. if style == "gb7714":
  47. parts = [f"{authors_str}. {title}[J]."]
  48. if venue:
  49. parts.append(venue)
  50. if year:
  51. parts.append(f", {year}")
  52. if volume:
  53. parts.append(f", {volume}")
  54. if issue:
  55. parts.append(f"({issue})")
  56. if pages:
  57. parts.append(f": {pages}")
  58. citation = "".join(parts) + "."
  59. if doi:
  60. citation += f" DOI: {doi}."
  61. elif style == "apa":
  62. citation = f"{authors_str} ({year}). {title}."
  63. if venue:
  64. citation += f" {venue}"
  65. if volume:
  66. citation += f", {volume}"
  67. if issue:
  68. citation += f"({issue})"
  69. if pages:
  70. citation += f", {pages}"
  71. citation += "."
  72. if doi:
  73. citation += f" https://doi.org/{doi}"
  74. else:
  75. citation = f"{authors_str}. {title}. {venue}, {year}."
  76. return citation