Download app/search.py from ShadowTEM/Chatbot: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/ShadowTEM/Chatbot/resolve/main/app/search.py
- Command line
-
hf download hf://spaces/ShadowTEM/Chatbot/app/search.py
-
curl -L -o search.py https://huggingface.co/spaces/ShadowTEM/Chatbot/resolve/main/app/search.py
1.16 kB
| # search.py | |
| import requests | |
| def search_query(query): | |
| """ | |
| Perform a search using the DuckDuckGo Instant Answer API. | |
| Parameters: | |
| query (str): The search query. | |
| Returns: | |
| dict: A dictionary with the JSON response from the API. | |
| Raises: | |
| Exception: If the API call fails. | |
| """ | |
| url = "https://api.duckduckgo.com/" | |
| params = { | |
| "q": query, | |
| "format": "json", | |
| "no_html": 1, | |
| "skip_disambig": 1 | |
| } | |
| response = requests.get(url, params=params) | |
| if response.status_code == 200: | |
| return response.json() | |
| else: | |
| raise Exception(f"Search API error: {response.status_code}") | |
| if __name__ == "__main__": | |
| # Example usage: | |
| query = "latest cancer research news" | |
| try: | |
| results = search_query(query) | |
| # Print the title and abstract (if available) from the response. | |
| # DuckDuckGo Instant Answer API returns a variety of keys depending on the query. | |
| print("Search Results:") | |
| print(results) | |
| except Exception as e: | |
| print("Error during search:", e) | |