bocha.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import logging
  2. from typing import Optional
  3. import requests
  4. import json
  5. from open_webui.retrieval.web.main import SearchResult, get_filtered_results
  6. from open_webui.env import SRC_LOG_LEVELS
  7. log = logging.getLogger(__name__)
  8. log.setLevel(SRC_LOG_LEVELS["RAG"])
  9. def _parse_response(response):
  10. result = {}
  11. if "data" in response:
  12. data = response["data"]
  13. if "webPages" in data:
  14. webPages = data["webPages"]
  15. if "value" in webPages:
  16. result["webpage"] = [
  17. {
  18. "id": item.get("id", ""),
  19. "name": item.get("name", ""),
  20. "url": item.get("url", ""),
  21. "snippet": item.get("snippet", ""),
  22. "summary": item.get("summary", ""),
  23. "siteName": item.get("siteName", ""),
  24. "siteIcon": item.get("siteIcon", ""),
  25. "datePublished": item.get("datePublished", "") or item.get("dateLastCrawled", ""),
  26. }
  27. for item in webPages["value"]
  28. ]
  29. return result
  30. def search_bocha(
  31. api_key: str, query: str, count: int, filter_list: Optional[list[str]] = None
  32. ) -> list[SearchResult]:
  33. """Search using Bocha's Search API and return the results as a list of SearchResult objects.
  34. Args:
  35. api_key (str): A Bocha Search API key
  36. query (str): The query to search for
  37. """
  38. url = "https://api.bochaai.com/v1/web-search?utm_source=ollama"
  39. headers = {
  40. "Authorization": f"Bearer {api_key}",
  41. "Content-Type": "application/json"
  42. }
  43. payload = json.dumps({
  44. "query": query,
  45. "summary": True,
  46. "freshness": "noLimit",
  47. "count": count
  48. })
  49. response = requests.post(url, headers=headers, data=payload, timeout=5)
  50. response.raise_for_status()
  51. results = _parse_response(response.json())
  52. print(results)
  53. if filter_list:
  54. results = get_filtered_results(results, filter_list)
  55. return [
  56. SearchResult(
  57. link=result["url"],
  58. title=result.get("name"),
  59. snippet=result.get("summary")
  60. )
  61. for result in results.get("webpage", [])[:count]
  62. ]