brave.py 1.23 KB
Newer Older
1
import logging
Michael Poluektov's avatar
Michael Poluektov committed
2
from typing import Optional
3
4
import requests

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

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


Timothy J. Baek's avatar
Timothy J. Baek committed
12
def search_brave(
Michael Poluektov's avatar
Michael Poluektov committed
13
    api_key: str, query: str, count: int, filter_list: Optional[list[str]] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
14
) -> list[SearchResult]:
15
16
17
18
19
20
21
22
23
24
25
26
    """Search using Brave's Search API and return the results as a list of SearchResult objects.

    Args:
        api_key (str): A Brave Search API key
        query (str): The query to search for
    """
    url = "https://api.search.brave.com/res/v1/web/search"
    headers = {
        "Accept": "application/json",
        "Accept-Encoding": "gzip",
        "X-Subscription-Token": api_key,
    }
Timothy J. Baek's avatar
Timothy J. Baek committed
27
    params = {"q": query, "count": count}
28
29
30
31
32
33

    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()

    json_response = response.json()
    results = json_response.get("web", {}).get("results", [])
34
35
    if filter_list:
        results = get_filtered_results(results, filter_list)
Timothy J. Baek's avatar
Timothy J. Baek committed
36

37
38
39
40
    return [
        SearchResult(
            link=result["url"], title=result.get("title"), snippet=result.get("snippet")
        )
41
        for result in results[:count]
42
    ]