|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +import httpx |
| 5 | +import llm |
| 6 | + |
| 7 | + |
| 8 | +class SearXNG: |
| 9 | + """A tool for searching the web using SearXNG search engine""" |
| 10 | + |
| 11 | + def __init__(self, base_url: str = None): |
| 12 | + self.base_url = base_url or os.getenv("SEARXNG_URL") |
| 13 | + if not self.base_url: |
| 14 | + raise ValueError("SEARXNG_URL environment variable is required") |
| 15 | + self.method = os.getenv("SEARXNG_METHOD", "POST").upper() |
| 16 | + |
| 17 | + def search( |
| 18 | + self, |
| 19 | + query: str, |
| 20 | + format: str = "json", |
| 21 | + categories: str = None, |
| 22 | + engines: str = None, |
| 23 | + language: str = "en", |
| 24 | + pageno: int = 1, |
| 25 | + time_range: str = None, |
| 26 | + safesearch: int = 1, |
| 27 | + ) -> str: |
| 28 | + """ |
| 29 | + Search the web using SearXNG. |
| 30 | +
|
| 31 | + Args: |
| 32 | + query: The search query (required) |
| 33 | + format: Output format (json, csv, rss) - default: json |
| 34 | + categories: Comma separated list of search categories (optional) |
| 35 | + engines: Comma separated list of search engines (optional) |
| 36 | + language: Language code - default: en |
| 37 | + pageno: Search page number - default: 1 |
| 38 | + time_range: Time range (day, month, year) - optional |
| 39 | + safesearch: Safe search level (0, 1, 2) - default: 1 |
| 40 | + """ |
| 41 | + search_url = f"{self.base_url.rstrip('/')}/search" |
| 42 | + |
| 43 | + params = { |
| 44 | + "q": query, |
| 45 | + "format": format, |
| 46 | + "language": language, |
| 47 | + "pageno": pageno, |
| 48 | + "safesearch": safesearch, |
| 49 | + } |
| 50 | + |
| 51 | + if categories: |
| 52 | + params["categories"] = categories |
| 53 | + if engines: |
| 54 | + params["engines"] = engines |
| 55 | + if time_range: |
| 56 | + params["time_range"] = time_range |
| 57 | + |
| 58 | + try: |
| 59 | + # TODO: Set user agent? |
| 60 | + headers = None |
| 61 | + |
| 62 | + with httpx.Client(follow_redirects=True, timeout=30.0, headers=headers) as client: |
| 63 | + if self.method == "POST": |
| 64 | + response = client.post(search_url, data=params) |
| 65 | + else: |
| 66 | + response = client.get(search_url, params=params) |
| 67 | + response.raise_for_status() |
| 68 | + |
| 69 | + if format == "json": |
| 70 | + result = response.json() |
| 71 | + if "results" in result: |
| 72 | + formatted_results = [] |
| 73 | + for item in result["results"][:10]: |
| 74 | + formatted_result = { |
| 75 | + "title": item.get("title", ""), |
| 76 | + "url": item.get("url", ""), |
| 77 | + "snippet": item.get("content", ""), |
| 78 | + "engine": item.get("engine", ""), |
| 79 | + } |
| 80 | + formatted_results.append(formatted_result) |
| 81 | + |
| 82 | + summary = { |
| 83 | + "query": query, |
| 84 | + "number_of_results": len(result.get("results", [])), |
| 85 | + "results": formatted_results, |
| 86 | + } |
| 87 | + return json.dumps(summary, indent=2) |
| 88 | + else: |
| 89 | + return json.dumps(result, indent=2) |
| 90 | + else: |
| 91 | + return response.text |
| 92 | + |
| 93 | + except httpx.HTTPError as e: |
| 94 | + raise Exception(f"HTTP error occurred: {e}") |
| 95 | + except json.JSONDecodeError as e: |
| 96 | + raise Exception(f"Error parsing JSON response: {e}") |
| 97 | + except Exception as e: |
| 98 | + raise Exception(f"Error performing search: {e}") |
| 99 | + |
| 100 | + |
| 101 | +def searxng_search(query: str) -> str: |
| 102 | + """ |
| 103 | + Search the web using SearXNG. Returns a JSON string with results including |
| 104 | + title, URL, snippet, and search engine used. |
| 105 | +
|
| 106 | + Args: |
| 107 | + query: Search query to search for. SearxNG search syntax (https://docs.searxng.org/user/search-syntax.html) is supported. |
| 108 | + """ |
| 109 | + searxng = SearXNG() |
| 110 | + return searxng.search(query) |
| 111 | + |
| 112 | + |
| 113 | +@llm.hookimpl |
| 114 | +def register_tools(register): |
| 115 | + if not os.environ.get("SEARXNG_URL"): |
| 116 | + raise RuntimeError("SEARXNG_URL environment variable is not set.") |
| 117 | + register(searxng_search) |
0 commit comments