File size: 1,774 Bytes
9cc4f9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import json

import gradio as gr
import pandas as pd
from langchain_community.tools import BraveSearch

from utils.helpers import map_results

from .base import BaseInterfaceWrapper


async def brave_search(query: str, api_key: str, max_results: int = 5) -> pd.DataFrame:
    """
    Given a search query, returns the search results from Brave.

    Args:
        query (str): The search query.
        api_key (str): The API key for Brave Search.
        max_results (int, optional): The number of maximum results to return. Defaults to 5.

    Returns:
        dict: The search results from Brave Search Engine. Fields:
            headers (list): The headers of the columns in the search results. Contains "title", "link", "body".
            data (list): The data in the search results. Each row contains the title, link, and body of the search result.
    """
    brave = BraveSearch.from_api_key(
        api_key=api_key,
        search_kwargs={
            "max_results": max_results,
        },
    )
    results = await brave.arun(query)
    results = json.loads(results)
    mapping = {
        "title": "title",
        "link": "link",
        "snippet": "body",
    }
    results = await map_results(results, mapping)
    return results


class BraveInterfaceWrapper(BaseInterfaceWrapper):
    def __init__(self):
        super().__init__(
            fn=brave_search,
            inputs=[
                gr.Textbox(label="Search Query"),
                gr.Textbox(label="API Key", type="password"),
                gr.Slider(
                    minimum=1, maximum=10, step=1, value=5, label="Number of Results"
                ),
            ],
            title="Brave Search",
            description="Search the web using Brave Search Engine.",
        )