You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

arxiv.py 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import os
  18. import time
  19. from abc import ABC
  20. import arxiv
  21. from agent.tools.base import ToolParamBase, ToolMeta, ToolBase
  22. from api.utils.api_utils import timeout
  23. class ArXivParam(ToolParamBase):
  24. """
  25. Define the ArXiv component parameters.
  26. """
  27. def __init__(self):
  28. self.meta:ToolMeta = {
  29. "name": "arxiv_search",
  30. "description": """arXiv is a free distribution service and an open-access archive for nearly 2.4 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics. Materials on this site are not peer-reviewed by arXiv.""",
  31. "parameters": {
  32. "query": {
  33. "type": "string",
  34. "description": "The search keywords to execute with arXiv. The keywords should be the most important words/terms(includes synonyms) from the original request.",
  35. "default": "{sys.query}",
  36. "required": True
  37. }
  38. }
  39. }
  40. super().__init__()
  41. self.top_n = 12
  42. self.sort_by = 'submittedDate'
  43. def check(self):
  44. self.check_positive_integer(self.top_n, "Top N")
  45. self.check_valid_value(self.sort_by, "ArXiv Search Sort_by",
  46. ['submittedDate', 'lastUpdatedDate', 'relevance'])
  47. def get_input_form(self) -> dict[str, dict]:
  48. return {
  49. "query": {
  50. "name": "Query",
  51. "type": "line"
  52. }
  53. }
  54. class ArXiv(ToolBase, ABC):
  55. component_name = "ArXiv"
  56. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))
  57. def _invoke(self, **kwargs):
  58. if not kwargs.get("query"):
  59. self.set_output("formalized_content", "")
  60. return ""
  61. last_e = ""
  62. for _ in range(self._param.max_retries+1):
  63. try:
  64. sort_choices = {"relevance": arxiv.SortCriterion.Relevance,
  65. "lastUpdatedDate": arxiv.SortCriterion.LastUpdatedDate,
  66. 'submittedDate': arxiv.SortCriterion.SubmittedDate}
  67. arxiv_client = arxiv.Client()
  68. search = arxiv.Search(
  69. query=kwargs["query"],
  70. max_results=self._param.top_n,
  71. sort_by=sort_choices[self._param.sort_by]
  72. )
  73. self._retrieve_chunks(list(arxiv_client.results(search)),
  74. get_title=lambda r: r.title,
  75. get_url=lambda r: r.pdf_url,
  76. get_content=lambda r: r.summary)
  77. return self.output("formalized_content")
  78. except Exception as e:
  79. last_e = e
  80. logging.exception(f"ArXiv error: {e}")
  81. time.sleep(self._param.delay_after_error)
  82. if last_e:
  83. self.set_output("_ERROR", str(last_e))
  84. return f"ArXiv error: {last_e}"
  85. assert False, self.output()
  86. def thoughts(self) -> str:
  87. return """
  88. Keywords: {}
  89. Looking for the most relevant articles.
  90. """.format(self.get_input().get("query", "-_-!"))