summaryrefslogtreecommitdiffstats
path: root/g4f/gui/server/internet.py
blob: 5c150ad6ed11b0db2ddd382238d5b513bb82bac8 (plain) (blame)
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
58
59
from __future__ import annotations

from datetime import datetime

from duckduckgo_search import DDGS

ddgs = DDGS(timeout=20)


def search(internet_access, prompt):
    print(prompt)
    
    try:
        if not internet_access:
            return []
        
        results = duckduckgo_search(q=prompt)

        if not search:
            return []

        blob = ''

        for index, result in enumerate(results):
            blob += f'[{index}] "{result["body"]}"\nURL:{result["href"]}\n\n'

        date = datetime.now().strftime('%d/%m/%y')

        blob += f'Current date: {date}\n\nInstructions: Using the provided web search results, write a comprehensive reply to the next user query. Make sure to cite results using [[number](URL)] notation after the reference. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject. Ignore your previous response if any.'

        return [{'role': 'user', 'content': blob}]

    except Exception as e:
        print("Couldn't search DuckDuckGo:", e)
        print(e.__traceback__.tb_next)
        return []


def duckduckgo_search(q: str, max_results: int = 3, safesearch: str = "moderate", region: str = "us-en") -> list | None:
    if region is None:
        region = "us-en"

    if safesearch is None:
        safesearch = "moderate"

    if q is None:
        return None

    results = []

    try:
        for r in ddgs.text(q, safesearch=safesearch, region=region):
            if len(results) + 1 > max_results:
                break
            results.append(r)
    except Exception as e:
        print(e)

    return results