Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. from abc import ABC
  18. import requests
  19. import pandas as pd
  20. from agent.component.base import ComponentBase, ComponentParamBase
  21. class BingParam(ComponentParamBase):
  22. """
  23. Define the Bing component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.top_n = 10
  28. self.channel = "Webpages"
  29. self.api_key = "YOUR_ACCESS_KEY"
  30. self.country = "CN"
  31. self.language = "en"
  32. def check(self):
  33. self.check_positive_integer(self.top_n, "Top N")
  34. self.check_valid_value(self.channel, "Bing Web Search or Bing News", ["Webpages", "News"])
  35. self.check_empty(self.api_key, "Bing subscription key")
  36. self.check_valid_value(self.country, "Bing Country",
  37. ['AR', 'AU', 'AT', 'BE', 'BR', 'CA', 'CL', 'DK', 'FI', 'FR', 'DE', 'HK', 'IN', 'ID',
  38. 'IT', 'JP', 'KR', 'MY', 'MX', 'NL', 'NZ', 'NO', 'CN', 'PL', 'PT', 'PH', 'RU', 'SA',
  39. 'ZA', 'ES', 'SE', 'CH', 'TW', 'TR', 'GB', 'US'])
  40. self.check_valid_value(self.language, "Bing Languages",
  41. ['ar', 'eu', 'bn', 'bg', 'ca', 'ns', 'nt', 'hr', 'cs', 'da', 'nl', 'en', 'gb', 'et',
  42. 'fi', 'fr', 'gl', 'de', 'gu', 'he', 'hi', 'hu', 'is', 'it', 'jp', 'kn', 'ko', 'lv',
  43. 'lt', 'ms', 'ml', 'mr', 'nb', 'pl', 'br', 'pt', 'pa', 'ro', 'ru', 'sr', 'sk', 'sl',
  44. 'es', 'sv', 'ta', 'te', 'th', 'tr', 'uk', 'vi'])
  45. class Bing(ComponentBase, ABC):
  46. component_name = "Bing"
  47. def _run(self, history, **kwargs):
  48. ans = self.get_input()
  49. ans = " - ".join(ans["content"]) if "content" in ans else ""
  50. if not ans:
  51. return Bing.be_output("")
  52. try:
  53. headers = {"Ocp-Apim-Subscription-Key": self._param.api_key, 'Accept-Language': self._param.language}
  54. params = {"q": ans, "textDecorations": True, "textFormat": "HTML", "cc": self._param.country,
  55. "answerCount": 1, "promote": self._param.channel}
  56. if self._param.channel == "Webpages":
  57. response = requests.get("https://api.bing.microsoft.com/v7.0/search", headers=headers, params=params)
  58. response.raise_for_status()
  59. search_results = response.json()
  60. bing_res = [{"content": '<a href="' + i["url"] + '">' + i["name"] + '</a> ' + i["snippet"]} for i in
  61. search_results["webPages"]["value"]]
  62. elif self._param.channel == "News":
  63. response = requests.get("https://api.bing.microsoft.com/v7.0/news/search", headers=headers,
  64. params=params)
  65. response.raise_for_status()
  66. search_results = response.json()
  67. bing_res = [{"content": '<a href="' + i["url"] + '">' + i["name"] + '</a> ' + i["description"]} for i
  68. in search_results['news']['value']]
  69. except Exception as e:
  70. return Bing.be_output("**ERROR**: " + str(e))
  71. if not bing_res:
  72. return Bing.be_output("")
  73. df = pd.DataFrame(bing_res)
  74. logging.debug(f"df: {str(df)}")
  75. return df