searxng.py 3.03 KB
Newer Older
1
2
3
import logging
import requests

4
5
from typing import List

6
from apps.rag.search.main import SearchResult
Timothy J. Baek's avatar
Timothy J. Baek committed
7
from config import SRC_LOG_LEVELS
8
9
10
11
12

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])


13
14
15
def search_searxng(
    query_url: str, query: str, count: int, **kwargs
) -> List[SearchResult]:
16
17
    """
    Search a SearXNG instance for a given query and return the results as a list of SearchResult objects.
18

19
    The function allows passing additional parameters such as language or time_range to tailor the search result.
20
21

    Args:
22
        query_url (str): The base URL of the SearXNG server.
23
24
        query (str): The search term or question to find in the SearXNG database.
        count (int): The maximum number of results to retrieve from the search.
25

26
27
    Keyword Args:
        language (str): Language filter for the search results; e.g., "en-US". Defaults to an empty string.
28
        safesearch (int): Safe search filter for safer web results; 0 = off, 1 = moderate, 2 = strict. Defaults to 1 (moderate).
29
30
        time_range (str): Time range for filtering results by date; e.g., "2023-04-05..today" or "all-time". Defaults to ''.
        categories: (Optional[List[str]]): Specific categories within which the search should be performed, defaulting to an empty string if not provided.
31

32
33
    Returns:
        List[SearchResult]: A list of SearchResults sorted by relevance score in descending order.
34

35
36
    Raise:
        requests.exceptions.RequestException: If a request error occurs during the search process.
37
    """
38

39
    # Default values for optional parameters are provided as empty strings or None when not specified.
40
    language = kwargs.get("language", "en-US")
41
    safesearch = kwargs.get("safesearch", "1")
42
43
    time_range = kwargs.get("time_range", "")
    categories = "".join(kwargs.get("categories", []))
44
45
46
47
48

    params = {
        "q": query,
        "format": "json",
        "pageno": 1,
49
        "safesearch": safesearch,
50
51
52
53
54
        "language": language,
        "time_range": time_range,
        "categories": categories,
        "theme": "simple",
        "image_proxy": 0,
55
56
    }

57
58
59
60
61
    # Legacy query format
    if "<query>" in query_url:
        # Strip all query parameters from the URL
        query_url = query_url.split("?")[0]

Lyuboslav Petrov's avatar
Lyuboslav Petrov committed
62
    log.debug(f"searching {query_url}")
63
64
65

    response = requests.get(
        query_url,
66
67
68
69
70
71
72
        headers={
            "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
            "Accept": "text/html",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "en-US,en;q=0.5",
            "Connection": "keep-alive",
        },
73
        params=params,
74
75
    )

76
77
78
    response.raise_for_status()  # Raise an exception for HTTP errors.

    json_response = response.json()
79
80
81
82
83
84
    results = json_response.get("results", [])
    sorted_results = sorted(results, key=lambda x: x.get("score", 0), reverse=True)
    return [
        SearchResult(
            link=result["url"], title=result.get("title"), snippet=result.get("content")
        )
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
85
        for result in sorted_results[:count]
86
    ]