Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesimport re in visit_webpage.py and new custom joke picker tool is added to the agent
- app.py +86 -65
- tools/final_answer.py +14 -14
- tools/visit_webpage.py +49 -45
- tools/web_search.py +27 -27
app.py
CHANGED
|
@@ -1,65 +1,86 @@
|
|
| 1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
| 2 |
-
import datetime
|
| 3 |
-
import requests
|
| 4 |
-
import pytz
|
| 5 |
-
import yaml
|
| 6 |
-
from tools.final_answer import FinalAnswerTool
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
"""
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
| 2 |
+
import datetime
|
| 3 |
+
import requests
|
| 4 |
+
import pytz
|
| 5 |
+
import yaml
|
| 6 |
+
from tools.final_answer import FinalAnswerTool
|
| 7 |
+
from tools.visit_webpage import VisitWebpageTool
|
| 8 |
+
from tools.web_search import DuckDuckGoSearchTool
|
| 9 |
+
from Gradio_UI import GradioUI
|
| 10 |
+
from huggingface_hub import login
|
| 11 |
+
|
| 12 |
+
login()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 16 |
+
@tool
|
| 17 |
+
def joke_picker(arg1: str, arg2: int) -> str: # it's import to specify the return type
|
| 18 |
+
# Keep this format for the description / args / args description but feel free to modify the tool
|
| 19 |
+
"""A tool that does nothing yet
|
| 20 |
+
Args:
|
| 21 |
+
arg1: the first argument
|
| 22 |
+
arg2: the second argument
|
| 23 |
+
"""
|
| 24 |
+
# Example tool that fetches a random joke from an API
|
| 25 |
+
response = requests.get("https://official-joke-api.appspot.com/random_joke")
|
| 26 |
+
if response.status_code == 200:
|
| 27 |
+
joke = response.json()
|
| 28 |
+
return f"{joke['setup']} - {joke['punchline']}"
|
| 29 |
+
else:
|
| 30 |
+
return "Failed to fetch a joke."
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@tool
|
| 34 |
+
def get_current_time_in_timezone(timezone: str) -> str:
|
| 35 |
+
"""A tool that fetches the current local time in a specified timezone.
|
| 36 |
+
Args:
|
| 37 |
+
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
# Create timezone object
|
| 41 |
+
tz = pytz.timezone(timezone)
|
| 42 |
+
# Get current time in that timezone
|
| 43 |
+
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 44 |
+
return f"The current local time in {timezone} is: {local_time}"
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
final_answer = FinalAnswerTool()
|
| 50 |
+
visit_webpage = VisitWebpageTool()
|
| 51 |
+
web_search = DuckDuckGoSearchTool()
|
| 52 |
+
model = HfApiModel(
|
| 53 |
+
max_tokens=2096,
|
| 54 |
+
temperature=0.5,
|
| 55 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct", # it is possible that this model may be overloaded
|
| 56 |
+
custom_role_conversions=None,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Import tool from Hub
|
| 61 |
+
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 62 |
+
|
| 63 |
+
with open("prompts.yaml", "r") as stream:
|
| 64 |
+
prompt_templates = yaml.safe_load(stream)
|
| 65 |
+
|
| 66 |
+
agent = CodeAgent(
|
| 67 |
+
model=model,
|
| 68 |
+
tools=[
|
| 69 |
+
final_answer,
|
| 70 |
+
image_generation_tool,
|
| 71 |
+
get_current_time_in_timezone,
|
| 72 |
+
visit_webpage,
|
| 73 |
+
web_search,
|
| 74 |
+
joke_picker,
|
| 75 |
+
], ## add your tools here (don't remove final answer)
|
| 76 |
+
max_steps=6,
|
| 77 |
+
verbosity_level=1,
|
| 78 |
+
grammar=None,
|
| 79 |
+
planning_interval=None,
|
| 80 |
+
name=None,
|
| 81 |
+
description=None,
|
| 82 |
+
prompt_templates=prompt_templates,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
GradioUI(agent).launch()
|
tools/final_answer.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
-
from typing import Any, Optional
|
| 2 |
-
from smolagents.tools import Tool
|
| 3 |
-
|
| 4 |
-
class FinalAnswerTool(Tool):
|
| 5 |
-
name = "final_answer"
|
| 6 |
-
description = "Provides a final answer to the given problem."
|
| 7 |
-
inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
|
| 8 |
-
output_type = "any"
|
| 9 |
-
|
| 10 |
-
def forward(self, answer: Any) -> Any:
|
| 11 |
-
return answer
|
| 12 |
-
|
| 13 |
-
def __init__(self, *args, **kwargs):
|
| 14 |
-
self.is_initialized = False
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
|
| 4 |
+
class FinalAnswerTool(Tool):
|
| 5 |
+
name = "final_answer"
|
| 6 |
+
description = "Provides a final answer to the given problem."
|
| 7 |
+
inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
|
| 8 |
+
output_type = "any"
|
| 9 |
+
|
| 10 |
+
def forward(self, answer: Any) -> Any:
|
| 11 |
+
return answer
|
| 12 |
+
|
| 13 |
+
def __init__(self, *args, **kwargs):
|
| 14 |
+
self.is_initialized = False
|
tools/visit_webpage.py
CHANGED
|
@@ -1,45 +1,49 @@
|
|
| 1 |
-
from typing import Any, Optional
|
| 2 |
-
from smolagents.tools import Tool
|
| 3 |
-
import requests
|
| 4 |
-
import markdownify
|
| 5 |
-
import smolagents
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
except
|
| 42 |
-
return
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
import requests
|
| 4 |
+
import markdownify
|
| 5 |
+
import smolagents
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class VisitWebpageTool(Tool):
|
| 10 |
+
name = "visit_webpage"
|
| 11 |
+
description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
|
| 12 |
+
inputs = {
|
| 13 |
+
"url": {"type": "string", "description": "The url of the webpage to visit."}
|
| 14 |
+
}
|
| 15 |
+
output_type = "string"
|
| 16 |
+
|
| 17 |
+
def forward(self, url: str) -> str:
|
| 18 |
+
try:
|
| 19 |
+
import requests
|
| 20 |
+
from markdownify import markdownify
|
| 21 |
+
from requests.exceptions import RequestException
|
| 22 |
+
|
| 23 |
+
from smolagents.utils import truncate_content
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
raise ImportError(
|
| 26 |
+
"You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
|
| 27 |
+
) from e
|
| 28 |
+
try:
|
| 29 |
+
# Send a GET request to the URL with a 20-second timeout
|
| 30 |
+
response = requests.get(url, timeout=20)
|
| 31 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
| 32 |
+
|
| 33 |
+
# Convert the HTML content to Markdown
|
| 34 |
+
markdown_content = markdownify(response.text).strip()
|
| 35 |
+
|
| 36 |
+
# Remove multiple line breaks
|
| 37 |
+
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
| 38 |
+
|
| 39 |
+
return truncate_content(markdown_content, 10000)
|
| 40 |
+
|
| 41 |
+
except requests.exceptions.Timeout:
|
| 42 |
+
return "The request timed out. Please try again later or check the URL."
|
| 43 |
+
except RequestException as e:
|
| 44 |
+
return f"Error fetching the webpage: {str(e)}"
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"An unexpected error occurred: {str(e)}"
|
| 47 |
+
|
| 48 |
+
def __init__(self, *args, **kwargs):
|
| 49 |
+
self.is_initialized = False
|
tools/web_search.py
CHANGED
|
@@ -1,27 +1,27 @@
|
|
| 1 |
-
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:
|
| 15 |
-
from duckduckgo_search import DDGS
|
| 16 |
-
except ImportError as e:
|
| 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)
|
|
|
|
| 1 |
+
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:
|
| 15 |
+
from duckduckgo_search import DDGS
|
| 16 |
+
except ImportError as e:
|
| 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)
|