bocha.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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", "")
  26. or item.get("dateLastCrawled", ""),
  27. }
  28. for item in webPages["value"]
  29. ]
  30. return result
  31. def search_bocha(
  32. api_key: str, query: str, count: int, filter_list: Optional[list[str]] = None
  33. ) -> list[SearchResult]:
  34. """Search using Bocha's Search API and return the results as a list of SearchResult objects.
  35. Args:
  36. api_key (str): A Bocha Search API key
  37. query (str): The query to search for
  38. """
  39. url = "https://api.bochaai.com/v1/web-search?utm_source=ollama"
  40. headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
  41. payload = json.dumps(
  42. {"query": query, "summary": True, "freshness": "noLimit", "count": count}
  43. )
  44. response = requests.post(url, headers=headers, data=payload, timeout=5)
  45. response.raise_for_status()
  46. results = _parse_response(response.json())
  47. print(results)
  48. if filter_list:
  49. results = get_filtered_results(results, filter_list)
  50. return [
  51. SearchResult(
  52. link=result["url"], title=result.get("name"), snippet=result.get("summary")
  53. )
  54. for result in results.get("webpage", [])[:count]
  55. ]