bing_search.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import requests
  2. from ..base import BaseTool
  3. from typing import List
  4. # from pydantic import root_validator
  5. from pyopenagi.utils.utils import get_from_env
  6. class BingSearch(BaseTool):
  7. """Bing Search Tool, refactored from langchain.
  8. In order to set this up, follow instructions at:
  9. https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
  10. """
  11. def __init__(self):
  12. super().__init__()
  13. self.url = "https://api.bing.microsoft.com/v7.0/search" # temporarily
  14. self.bing_subscription_key = get_from_env("BING_SUBSCRIPTION_KEY")
  15. self.k: int = 10 # topk searched results
  16. # search_kwargs: dict
  17. def _bing_search_results(self, search_term: str, count: int) -> List[dict]:
  18. headers = {"Ocp-Apim-Subscription-Key": self.bing_subscription_key}
  19. params = {
  20. "q": search_term,
  21. "count": count,
  22. "textDecorations": True,
  23. "textFormat": "HTML",
  24. # **self.search_kwargs,
  25. }
  26. response = requests.get(
  27. self.bing_search_url,
  28. headers=headers,
  29. params=params, # type: ignore
  30. )
  31. response.raise_for_status()
  32. search_results = response.json()
  33. if "webPages" in search_results:
  34. return search_results["webPages"]["value"]
  35. return []
  36. def run(self, query: str) -> str:
  37. """Run query through BingSearch and parse result."""
  38. response = self._bing_search_results(query, count=self.k)
  39. result = self.parse_result(response)
  40. return result
  41. def parse_result(self, response):
  42. snippets = []
  43. if len(response) == 0:
  44. return "No good Bing Search Result was found"
  45. for result in response:
  46. snippets.append(result["snippet"])
  47. return " ".join(snippets)