KaranSood15's picture
Update app.py
159f47b verified
Raw
History Blame
2.43 kB
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# 🔧 Improved Custom Tool (Calculator)
@tool
def smart_calculator(expression: str) -> str:
"""Evaluates a mathematical expression safely.
Args:
expression: A math expression like '2+2*10'
"""
try:
result = eval(expression)
return f"Result: {result}"
except Exception as e:
return f"Error: {str(e)}"
# 🕒 Time Tool (unchanged but useful)
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Fetches current local time in a timezone.
Args:
timezone: e.g. 'Asia/Kolkata'
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"Time in {timezone}: {local_time}"
except Exception as e:
return f"Error: {str(e)}"
# 🌐 News Tool (NEW)
@tool
def get_latest_news(topic: str) -> str:
"""Fetch latest news on a topic.
Args:
topic: e.g. 'AI', 'India'
"""
try:
search = DuckDuckGoSearchTool()
return search.run(f"{topic} latest news")
except Exception as e:
return f"Error fetching news: {str(e)}"
# 🎯 Final Answer Tool (required)
final_answer = FinalAnswerTool()
# 🤖 Better Model (more general-purpose)
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-72B-Instruct', # upgraded model
custom_role_conversions=None,
)
# 🎨 Image Generation Tool
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# 📄 Load prompt templates
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# 🚀 Enhanced Agent
agent = CodeAgent(
model=model,
tools=[
final_answer,
smart_calculator,
get_current_time_in_timezone,
get_latest_news,
DuckDuckGoSearchTool(),
image_generation_tool
],
max_steps=6,
verbosity_level=2,
grammar=None,
planning_interval=None,
name="Smart AI Agent",
description="An AI agent that can search the web, calculate, fetch news, tell time, and generate images.",
prompt_templates=prompt_templates
)
# 🖥️ Launch UI
GradioUI(agent).launch()