File size: 1,544 Bytes
c16e1c9
 
 
 
 
 
 
 
b86e5c9
c16e1c9
 
 
b86e5c9
 
 
c16e1c9
 
 
b86e5c9
c16e1c9
 
b86e5c9
 
 
 
c16e1c9
 
b86e5c9
c16e1c9
b86e5c9
 
 
 
 
c16e1c9
 
 
 
 
 
 
b86e5c9
 
 
 
 
 
 
 
 
c16e1c9
 
 
 
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
import os
import httpx
from dotenv import load_dotenv

load_dotenv()

class WebClient:
    """
    Communicates with the Google Custom Search API.
    """

    def __init__(self):
        self.api_key = os.getenv("GOOGLE_SEARCH_API_KEY")
        self.cx_id = os.getenv("GOOGLE_SEARCH_CX_ID")
        self.search_endpoint = "https://www.googleapis.com/customsearch/v1"

    async def search(self, query: str):
        """
        Sends the query to Google Custom Search and returns search results.
        """

        if not self.api_key or not self.cx_id:
            print("Web Client Error: Google Custom Search credentials not configured.")
            return []

        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    self.search_endpoint,
                    params={
                        "key": self.api_key,
                        "cx": self.cx_id,
                        "q": query,
                        "num": 5,
                    }
                )

            if response.status_code != 200:
                return []

            data = response.json()
            items = data.get("items", [])
            return [
                {
                    "title": item.get("title"),
                    "link": item.get("link"),
                    "snippet": item.get("snippet"),
                }
                for item in items
            ]

        except Exception as e:
            print("Web Client Error:", e)
            return []