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.

duckduckgo.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. from duckduckgo_search import DDGS
  21. from agent.tools.base import ToolMeta, ToolParamBase, ToolBase
  22. from api.utils.api_utils import timeout
  23. class DuckDuckGoParam(ToolParamBase):
  24. """
  25. Define the DuckDuckGo component parameters.
  26. """
  27. def __init__(self):
  28. self.meta:ToolMeta = {
  29. "name": "duckduckgo_search",
  30. "description": "DuckDuckGo is a search engine focused on privacy. It offers search capabilities for web pages, images, and provides translation services. DuckDuckGo also features a private AI chat interface, providing users with an AI assistant that prioritizes data protection.",
  31. "parameters": {
  32. "query": {
  33. "type": "string",
  34. "description": "The search keywords to execute with DuckDuckGo. The keywords should be the most important words/terms(includes synonyms) from the original request.",
  35. "default": "{sys.query}",
  36. "required": True
  37. },
  38. "channel": {
  39. "type": "string",
  40. "description": "default:general. The category of the search. `news` is useful for retrieving real-time updates, particularly about politics, sports, and major current events covered by mainstream media sources. `general` is for broader, more general-purpose searches that may include a wide range of sources.",
  41. "enum": ["general", "news"],
  42. "default": "general",
  43. "required": False,
  44. },
  45. }
  46. }
  47. super().__init__()
  48. self.top_n = 10
  49. self.channel = "text"
  50. def check(self):
  51. self.check_positive_integer(self.top_n, "Top N")
  52. self.check_valid_value(self.channel, "Web Search or News", ["text", "news"])
  53. def get_input_form(self) -> dict[str, dict]:
  54. return {
  55. "query": {
  56. "name": "Query",
  57. "type": "line"
  58. },
  59. "channel": {
  60. "name": "Channel",
  61. "type": "options",
  62. "value": "general",
  63. "options": ["general", "news"]
  64. }
  65. }
  66. class DuckDuckGo(ToolBase, ABC):
  67. component_name = "DuckDuckGo"
  68. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))
  69. def _invoke(self, **kwargs):
  70. if not kwargs.get("query"):
  71. self.set_output("formalized_content", "")
  72. return ""
  73. last_e = ""
  74. for _ in range(self._param.max_retries+1):
  75. try:
  76. if kwargs.get("topic", "general") == "general":
  77. with DDGS() as ddgs:
  78. # {'title': '', 'href': '', 'body': ''}
  79. duck_res = ddgs.text(kwargs["query"], max_results=self._param.top_n)
  80. self._retrieve_chunks(duck_res,
  81. get_title=lambda r: r["title"],
  82. get_url=lambda r: r.get("href", r.get("url")),
  83. get_content=lambda r: r["body"])
  84. self.set_output("json", duck_res)
  85. return self.output("formalized_content")
  86. else:
  87. with DDGS() as ddgs:
  88. # {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''}
  89. duck_res = ddgs.news(kwargs["query"], max_results=self._param.top_n)
  90. self._retrieve_chunks(duck_res,
  91. get_title=lambda r: r["title"],
  92. get_url=lambda r: r.get("href", r.get("url")),
  93. get_content=lambda r: r["body"])
  94. self.set_output("json", duck_res)
  95. return self.output("formalized_content")
  96. except Exception as e:
  97. last_e = e
  98. logging.exception(f"DuckDuckGo error: {e}")
  99. time.sleep(self._param.delay_after_error)
  100. if last_e:
  101. self.set_output("_ERROR", str(last_e))
  102. return f"DuckDuckGo error: {last_e}"
  103. assert False, self.output()
  104. def thoughts(self) -> str:
  105. return """
  106. Keywords: {}
  107. Looking for the most relevant articles.
  108. """.format(self.get_input().get("query", "-_-!"))