Spaces:
Sleeping
Sleeping
| 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 PIL import Image | |
| import io | |
| def web_researcher(query: str, max_results: int = 3) -> str: | |
| """A tool that performs web research using DuckDuckGo search. | |
| Args: | |
| query: The search query string | |
| max_results: Maximum number of results to return (default 3) | |
| Returns: | |
| A formatted string containing search results | |
| """ | |
| try: | |
| search_results = DuckDuckGoSearchTool().search(query, max_results=max_results) | |
| if not search_results: | |
| return "No results found for your query." | |
| formatted_results = [] | |
| for i, result in enumerate(search_results, 1): | |
| formatted_results.append( | |
| f"Result {i}:\n" | |
| f"Title: {result.get('title', 'No title')}\n" | |
| f"URL: {result.get('link', 'No URL')}\n" | |
| f"Snippet: {result.get('snippet', 'No description')}\n" | |
| f"{'-'*50}" | |
| ) | |
| return "\n".join(formatted_results) | |
| except Exception as e: | |
| return f"Error performing search: {str(e)}" | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """A tool that 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)}" | |
| # Custom Final Answer Processor | |
| class CustomFinalAnswerTool: | |
| def __init__(self): | |
| self.tool = FinalAnswerTool() | |
| def __call__(self, answer): | |
| # Handle different answer types | |
| if hasattr(answer, '_image'): # If it's an image | |
| return self._process_image_answer(answer) | |
| elif isinstance(answer, str): # Regular text answer | |
| return answer | |
| else: # Fallback for other types | |
| return str(answer) | |
| def _process_image_answer(self, image_answer): | |
| """Process image answers to display properly""" | |
| try: | |
| # Convert the image to displayable format | |
| img = image_answer._image | |
| if isinstance(img, Image.Image): | |
| return img | |
| elif isinstance(img, bytes): | |
| return Image.open(io.BytesIO(img)) | |
| return f"Generated image: {image_answer}" | |
| except Exception as e: | |
| return f"Image processing error: {str(e)}" | |
| # Initialize tools | |
| final_answer = CustomFinalAnswerTool() | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruct', | |
| custom_role_conversions=None, | |
| ) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[final_answer.tool, web_researcher, get_current_time_in_timezone, image_generation_tool], | |
| max_steps=10, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| # Custom UI processor | |
| class CustomGradioUI(GradioUI): | |
| def process_final_answer(self, final_answer): | |
| """Override to handle different answer types""" | |
| if isinstance(final_answer, Image.Image): | |
| return final_answer | |
| return super().process_final_answer(final_answer) | |
| CustomGradioUI(agent).launch() |