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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 wikipedia
  21. from agent.tools.base import ToolMeta, ToolParamBase, ToolBase
  22. from api.utils.api_utils import timeout
  23. class WikipediaParam(ToolParamBase):
  24. """
  25. Define the Wikipedia component parameters.
  26. """
  27. def __init__(self):
  28. self.meta:ToolMeta = {
  29. "name": "wikipedia_search",
  30. "description": """A wide range of how-to and information pages are made available in wikipedia. Since 2001, it has grown rapidly to become the world's largest reference website. From Wikipedia, the free encyclopedia.""",
  31. "parameters": {
  32. "query": {
  33. "type": "string",
  34. "description": "The search keyword to execute with wikipedia. The keyword MUST be a specific subject that can match the title.",
  35. "default": "{sys.query}",
  36. "required": True
  37. }
  38. }
  39. }
  40. super().__init__()
  41. self.top_n = 10
  42. self.language = "en"
  43. def check(self):
  44. self.check_positive_integer(self.top_n, "Top N")
  45. self.check_valid_value(self.language, "Wikipedia languages",
  46. ['af', 'pl', 'ar', 'ast', 'az', 'bg', 'nan', 'bn', 'be', 'ca', 'cs', 'cy', 'da', 'de',
  47. 'et', 'el', 'en', 'es', 'eo', 'eu', 'fa', 'fr', 'gl', 'ko', 'hy', 'hi', 'hr', 'id',
  48. 'it', 'he', 'ka', 'lld', 'la', 'lv', 'lt', 'hu', 'mk', 'arz', 'ms', 'min', 'my', 'nl',
  49. 'ja', 'nb', 'nn', 'ce', 'uz', 'pt', 'kk', 'ro', 'ru', 'ceb', 'sk', 'sl', 'sr', 'sh',
  50. 'fi', 'sv', 'ta', 'tt', 'th', 'tg', 'azb', 'tr', 'uk', 'ur', 'vi', 'war', 'zh', 'yue'])
  51. def get_input_form(self) -> dict[str, dict]:
  52. return {
  53. "query": {
  54. "name": "Query",
  55. "type": "line"
  56. }
  57. }
  58. class Wikipedia(ToolBase, ABC):
  59. component_name = "Wikipedia"
  60. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 60))
  61. def _invoke(self, **kwargs):
  62. if not kwargs.get("query"):
  63. self.set_output("formalized_content", "")
  64. return ""
  65. last_e = ""
  66. for _ in range(self._param.max_retries+1):
  67. try:
  68. wikipedia.set_lang(self._param.language)
  69. wiki_engine = wikipedia
  70. pages = []
  71. for p in wiki_engine.search(kwargs["query"], results=self._param.top_n):
  72. try:
  73. pages.append(wikipedia.page(p))
  74. except Exception:
  75. pass
  76. self._retrieve_chunks(pages,
  77. get_title=lambda r: r.title,
  78. get_url=lambda r: r.url,
  79. get_content=lambda r: r.summary)
  80. return self.output("formalized_content")
  81. except Exception as e:
  82. last_e = e
  83. logging.exception(f"Wikipedia error: {e}")
  84. time.sleep(self._param.delay_after_error)
  85. if last_e:
  86. self.set_output("_ERROR", str(last_e))
  87. return f"Wikipedia error: {last_e}"
  88. assert False, self.output()
  89. def thoughts(self) -> str:
  90. return """
  91. Keywords: {}
  92. Looking for the most relevant articles.
  93. """.format(self.get_input().get("query", "-_-!"))