documentation
Browse files- tools/web_search.py +5 -4
tools/web_search.py
CHANGED
|
@@ -2,13 +2,14 @@ from typing import Any, Optional
|
|
| 2 |
from smolagents.tools import Tool
|
| 3 |
import duckduckgo_search
|
| 4 |
|
| 5 |
-
class DuckDuckGoSearchTool(Tool):
|
| 6 |
name = "web_search"
|
| 7 |
description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."
|
| 8 |
inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}
|
| 9 |
output_type = "string"
|
| 10 |
|
| 11 |
def __init__(self, max_results=10, **kwargs):
|
|
|
|
| 12 |
super().__init__()
|
| 13 |
self.max_results = max_results
|
| 14 |
try:
|
|
@@ -17,11 +18,11 @@ class DuckDuckGoSearchTool(Tool):
|
|
| 17 |
raise ImportError(
|
| 18 |
"You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."
|
| 19 |
) from e
|
| 20 |
-
self.ddgs = DDGS(**kwargs)
|
| 21 |
|
| 22 |
def forward(self, query: str) -> str:
|
| 23 |
-
results = self.ddgs.text(query, max_results=self.max_results)
|
| 24 |
if len(results) == 0:
|
| 25 |
raise Exception("No results found! Try a less restrictive/shorter query.")
|
| 26 |
postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
|
| 27 |
-
return "## Search Results\n\n" + "\n\n".join(postprocessed_results)
|
|
|
|
| 2 |
from smolagents.tools import Tool
|
| 3 |
import duckduckgo_search
|
| 4 |
|
| 5 |
+
class DuckDuckGoSearchTool(Tool): #inherits from smolagents tool class
|
| 6 |
name = "web_search"
|
| 7 |
description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."
|
| 8 |
inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}
|
| 9 |
output_type = "string"
|
| 10 |
|
| 11 |
def __init__(self, max_results=10, **kwargs):
|
| 12 |
+
"""prepares the tool for searching"""
|
| 13 |
super().__init__()
|
| 14 |
self.max_results = max_results
|
| 15 |
try:
|
|
|
|
| 18 |
raise ImportError(
|
| 19 |
"You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."
|
| 20 |
) from e
|
| 21 |
+
self.ddgs = DDGS(**kwargs) # instance of search engine client
|
| 22 |
|
| 23 |
def forward(self, query: str) -> str:
|
| 24 |
+
results = self.ddgs.text(query, max_results=self.max_results) #API call to duckduckgo search
|
| 25 |
if len(results) == 0:
|
| 26 |
raise Exception("No results found! Try a less restrictive/shorter query.")
|
| 27 |
postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
|
| 28 |
+
return "## Search Results\n\n" + "\n\n".join(postprocessed_results) # markdown friendly result for UI
|