From eefe6c4b808a4332bc719ced03409f46ae207777 Mon Sep 17 00:00:00 2001 From: MohamedAlawakey Date: Tue, 30 Sep 2025 01:22:52 +0300 Subject: [PATCH] this directory have our services, this file used to search on the internet --- services/search.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 services/search.py diff --git a/services/search.py b/services/search.py new file mode 100644 index 0000000..4872874 --- /dev/null +++ b/services/search.py @@ -0,0 +1,34 @@ +import httpx +import json +import os +from config import SERPER_URL, USER_AGENT + + +# Function: search docs via Google Serper API +async def search_web(query: str) -> dict | None: + # search query, 2 results only + payload = json.dumps({"q": query, "num": 2}) + + headers = { + "X-API-KEY": os.getenv("SERPER_API_KEY"), + "Content-Type": "application/json", + "User-Agent": USER_AGENT, + } + + # Send POST request to Serper API + async with httpx.AsyncClient() as client: + try: + response = await client.post( + SERPER_URL, + headers=headers, + data=payload, + timeout=30.0 + ) + response.raise_for_status() + # return search results + return response.json() + except httpx.TimeoutException: + # return empty if timeout + return { + "organic": [] + }