brave.py 1.19 KB
Newer Older
1
import logging
2
from typing import List
3
4
import requests

5
from apps.rag.search.main import SearchResult, filter_by_whitelist
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"])


12
def search_brave(api_key: str, query: str, whitelist:List[str], count: int) -> list[SearchResult]:
13
14
15
16
17
18
19
20
21
22
23
24
    """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
25
    params = {"q": query, "count": count}
26
27
28
29
30
31

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

    json_response = response.json()
    results = json_response.get("web", {}).get("results", [])
32
    filtered_results = filter_by_whitelist(results, whitelist)
33
34
35
36
    return [
        SearchResult(
            link=result["url"], title=result.get("title"), snippet=result.get("snippet")
        )
37
        for result in filtered_results[:count]
38
    ]