kostas696's picture
Update app.py
24a1752 verified
Raw History Blame Contribute Delete
2.49 kB
from smolagents import CodeAgent, HfApiModel, tool
import datetime
import requests
import pytz
import yaml
from bs4 import BeautifulSoup
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@tool
def web_scraper(url: str, element: str = "p") -> str:
"""
Extracts content from a webpage.
Args:
url: The URL of the webpage to scrape. Must be a valid HTTP or HTTPS URL.
element: The HTML element to extract. Defaults to "p" (paragraphs).
Other valid values include "h1" (headings), "div" (divisions), etc.
"""
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
elements = soup.find_all(element)
if not elements:
return f"No '{element}' elements found on the page."
content = "\n".join([elem.get_text().strip() for elem in elements])
return f"Scraped content from {url}:\n{content}"
except requests.exceptions.RequestException as e:
return f"Error fetching the webpage: {str(e)}"
except Exception as e:
return f"An error occurred while scraping: {str(e)}"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""
Fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
# Load Final Answer Tool
final_answer = FinalAnswerTool()
# Initialize the LLaMA-3 Model
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='meta-llama/Meta-Llama-3-8B-Instruct',
custom_role_conversions=None,
)
# Load Prompts
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Initialize Code Agent with Meta-Llama-3 System Prompt
agent = CodeAgent(
model=model,
tools=[final_answer, get_current_time_in_timezone, web_scraper],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name="First Agent",
description="A code execution agent with web scraping capabilities",
prompt_templates=prompt_templates
)
# Launch UI
GradioUI(agent).launch()