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": [] + }