clintonvanry/First_agent_template
0
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7 8from Gradio_UI import GradioUI9 10# Below is an example of a tool that does nothing. Amaze us with your creativity !11@tool12def get_weather(city: str) -> str:13 """A tool that retrieves the current weather for a city using DuckDuckGoSearchTool14 15 Args:16 city: the name of the city17 18 Returns:19 str: Weather information for the specified city, or error message20 """21 try:22 # Create instance first, then call setup on the instance23 web_search_tool = DuckDuckGoSearchTool(max_results=3)24 web_search_tool.setup() # Call setup on instance, not class25 26 # Search for weather information27 search_query = f"current weather {city} temperature forecast"28 results = web_search_tool(search_query)29 30 # Debug: Print raw results to understand the structure31 print(f"Raw results type: {type(results)}")32 print(f"Raw results: {results}")33 34 # Process results based on different possible return types35 if results:36 weather_info = []37 38 # Handle different result formats39 if isinstance(results, list):40 for i, result in enumerate(results[:3]): # Use top 3 results41 print(f"Result {i}: {type(result)} - {result}")42 43 if isinstance(result, dict):44 # Handle dictionary results45 text = result.get('snippet', result.get('body', result.get('content', '')))46 title = result.get('title', '')47 url = result.get('url', '')48 49 # Combine title and text for better context50 combined = f"{title} {text}".strip()51 52 elif isinstance(result, str):53 # Handle string results54 combined = result55 56 else:57 # Handle object results with attributes58 combined = ""59 for attr in ['snippet', 'body', 'content', 'text', 'description']:60 if hasattr(result, attr):61 value = getattr(result, attr)62 if value:63 combined += f"{value} "64 65 # Also try title66 if hasattr(result, 'title'):67 title = getattr(result, 'title')68 if title:69 combined = f"{title} {combined}"70 71 # Filter for weather-related content72 if combined and any(keyword in combined.lower() for keyword in 73 ['temperature', 'weather', '°f', '°c', 'degrees', 'sunny', 74 'cloudy', 'rain', 'forecast', 'humidity', 'wind']):75 weather_info.append(combined[:200]) # Limit length76 77 elif isinstance(results, str):78 # Handle single string result79 weather_info = [results[:300]]80 81 else:82 # Handle other result types83 weather_info = [str(results)[:300]]84 85 # Format final response86 if weather_info:87 return f"Weather in {city}: {' | '.join(weather_info)}"88 else:89 return f"Found search results for {city} but no clear weather information. Raw results: {str(results)[:200]}"90 91 else:92 return f"No search results found for weather in {city}"93 94 except ImportError as e:95 return f"Error: DuckDuckGoSearchTool not available. Import error: {str(e)}"96 except AttributeError as e:97 return f"Error: Problem with DuckDuckGoSearchTool setup or usage: {str(e)}"98 except TypeError as e:99 return f"Error: Incorrect parameters for DuckDuckGoSearchTool: {str(e)}"100 except Exception as e:101 return f"Error fetching weather information for city '{city}': {str(e)}"102 103 104 105 106 107@tool108def get_current_time_in_timezone(timezone: str) -> str:109 """A tool that fetches the current local time in a specified timezone.110 Args:111 timezone: A string representing a valid timezone (e.g., 'America/New_York').112 """113 try:114 # Create timezone object115 tz = pytz.timezone(timezone)116 # Get current time in that timezone117 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")118 return f"The current local time in {timezone} is: {local_time}"119 except Exception as e:120 return f"Error fetching time for timezone '{timezone}': {str(e)}"121 122 123final_answer = FinalAnswerTool()124 125# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:126# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 127 128model = HfApiModel(129max_tokens=2096,130temperature=0.5,131model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded132custom_role_conversions=None,133)134 135 136# Import tool from Hub137image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)138 139with open("prompts.yaml", 'r') as stream:140 prompt_templates = yaml.safe_load(stream)141 142agent = CodeAgent(143 model=model,144 tools=[final_answer, get_weather, get_current_time_in_timezone], ## add your tools here (don't remove final answer)145 max_steps=6,146 verbosity_level=1,147 grammar=None,148 planning_interval=None,149 name=None,150 description=None,151 prompt_templates=prompt_templates152)153 154 155GradioUI(agent).launch()