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 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. from abc import ABC
  17. from duckduckgo_search import DDGS
  18. import pandas as pd
  19. from agent.settings import DEBUG
  20. from agent.component.base import ComponentBase, ComponentParamBase
  21. class DuckDuckGoParam(ComponentParamBase):
  22. """
  23. Define the DuckDuckGo component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.top_n = 10
  28. self.channel = "text"
  29. def check(self):
  30. self.check_positive_integer(self.top_n, "Top N")
  31. self.check_valid_value(self.channel, "Web Search or News", ["text", "news"])
  32. class DuckDuckGo(ComponentBase, ABC):
  33. component_name = "DuckDuckGo"
  34. def _run(self, history, **kwargs):
  35. ans = self.get_input()
  36. ans = " - ".join(ans["content"]) if "content" in ans else ""
  37. if not ans:
  38. return DuckDuckGo.be_output("")
  39. try:
  40. if self._param.channel == "text":
  41. with DDGS() as ddgs:
  42. # {'title': '', 'href': '', 'body': ''}
  43. duck_res = [{"content": '<a href="' + i["href"] + '">' + i["title"] + '</a> ' + i["body"]} for i
  44. in ddgs.text(ans, max_results=self._param.top_n)]
  45. elif self._param.channel == "news":
  46. with DDGS() as ddgs:
  47. # {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''}
  48. duck_res = [{"content": '<a href="' + i["url"] + '">' + i["title"] + '</a> ' + i["body"]} for i
  49. in ddgs.news(ans, max_results=self._param.top_n)]
  50. except Exception as e:
  51. return DuckDuckGo.be_output("**ERROR**: " + str(e))
  52. if not duck_res:
  53. return DuckDuckGo.be_output("")
  54. df = pd.DataFrame(duck_res)
  55. if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
  56. return df