Dumoura's picture
Update app.py
55e6a0c verified
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
from transformers import pipeline
# 0. Tool to get the topic from the user
@tool
def get_topic() -> str:
"""A tool to prompt the user for a topic.
Returns:
str: The topic entered by the user.
"""
# For demonstration purposes, we use input(). In a production UI this might be replaced by a text field.
topic = input("Enter the topic you want to explore: ")
return topic
# 1. Tool to search the web using DuckDuckGo
@tool
def search_web(query: str) -> str:
"""A tool that searches the web for the provided query.
Args:
query: The search query.
Returns:
str: A snippet from the top search result.
"""
# Leverage the built-in DuckDuckGo search functionality
results = DuckDuckGoSearchTool.search(query=query)
if results and len(results) > 0:
# Return a snippet from the first result for brevity.
return results[0].get('snippet', "No snippet available.")
return "No results found."
# 2. Tool to summarize content using a Hugging Face summarization pipeline
@tool
def summarise_content(text: str) -> str:
"""A tool that summarizes text content.
Args:
text: The content to summarize.
Returns:
str: The summarized text.
"""
summarizer = pipeline("summarization")
# Adjust max/min length as needed
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
return summary[0]['summary_text']
# 3. Tool to generate a social media post based on the summary
@tool
def write_social_media_post(summary: str) -> str:
"""A tool that crafts a social media post using the provided summary.
Args:
summary: The summary text to base the post on.
Returns:
str: A drafted social media post.
"""
# Using a simple template; feel free to enhance with hashtags or formatting as needed.
post = f"Check this out: {summary} #news #update"
return post
final_answer = FinalAnswerTool()
# Define our Hugging Face model for the CodeAgent
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
)
# Optional: Load an image generation tool if you wish to expand functionality
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Load prompt templates from a YAML file
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Instantiate the agent with our custom tools (plus final_answer to ensure a response)
agent = CodeAgent(
model=model,
tools=[
final_answer,
get_topic,
search_web,
summarise_content,
write_social_media_post
],
max_steps=6,
verbosity_level=1,
prompt_templates=prompt_templates
)
# Launch the Gradio UI to interact with the agent
GradioUI(agent).launch()