Performs a web search based on the user-provided query with pagination. Args: query (str): The keyword(s) to search for. page (int): The page number of the results to return. Defaults to 1. language (str): The language of the search results. Defaults to "en", can be
(query: str, page: int = 1, language: str = "en", country: str = "us")
| 2 | |
| 3 | |
| 4 | def web_search(query: str, page: int = 1, language: str = "en", country: str = "us") -> str: |
| 5 | """ |
| 6 | Performs a web search based on the user-provided query with pagination. |
| 7 | |
| 8 | Args: |
| 9 | query (str): The keyword(s) to search for. |
| 10 | page (int): The page number of the results to return. Defaults to 1. |
| 11 | language (str): The language of the search results. Defaults to "en", can be "en", "zh-cn", "zh-tw", "ja", "ko". |
| 12 | country (str): The country of the search results. Defaults to "us", can be "us", "cn", "jp", "kr". |
| 13 | |
| 14 | Returns: |
| 15 | str: A formatted string containing the title, link, and snippet of the search results for the specified page. |
| 16 | """ |
| 17 | import requests |
| 18 | import json |
| 19 | |
| 20 | url = "https://google.serper.dev/search" |
| 21 | |
| 22 | payload = json.dumps({ |
| 23 | "q": query, |
| 24 | "page": page, |
| 25 | "hl": language, |
| 26 | "gl": country |
| 27 | }) |
| 28 | headers = { |
| 29 | 'X-API-KEY': os.getenv("SERPER_DEV_API_KEY"), |
| 30 | 'Content-Type': 'application/json' |
| 31 | } |
| 32 | |
| 33 | response = requests.request("POST", url, headers=headers, data=payload) |
| 34 | |
| 35 | try: |
| 36 | data = response.json() |
| 37 | return __format_serper_results(data) |
| 38 | except json.JSONDecodeError: |
| 39 | return response.text |
| 40 | |
| 41 | |
| 42 | def __format_serper_results(data: dict) -> str: |
nothing calls this directly
no test coverage detected