rociozalla/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 ai_policy_tracker(country_or_region: str, ai_topic: str) -> str:13 """Tracks recent AI policy and geopolitical developments for a given region and topic.14 Searches for news and returns a classified summary of events from the past week.15 16 Args:17 country_or_region: the country or region to monitor (e.g. 'European Union', 'China', 'United States')18 ai_topic: the AI policy topic to track (e.g. 'chip export controls', 'frontier model regulation', 'AI Act', 'sovereign AI')19 """20 search_tool = DuckDuckGoSearchTool()21 22 EVENT_TYPES = {23 "regulation": ["law", "regulation", "ban", "policy", "act", "directive", "compliance"],24 "geopolitics": ["sanction", "export control", "alliance", "agreement", "treaty", "tension", "rivalry"],25 "technical": ["model", "chip", "compute", "benchmark", "deployment", "safety", "open source"],26 }27 28 queries = [29 f"{country_or_region} {ai_topic} AI policy 2025",30 f"{country_or_region} artificial intelligence regulation news",31 f"{ai_topic} geopolitics international {country_or_region}",32 ]33 34 all_results = []35 for q in queries:36 try:37 result = search_tool(q)38 all_results.append(result)39 except Exception:40 continue41 42 if not all_results:43 return f"No results found for '{country_or_region}' + '{ai_topic}'."44 45 combined = "\n\n---\n\n".join(all_results)46 47 # Classify events by type48 lines = combined.split("\n")49 classified = {"regulation": [], "geopolitics": [], "technical": [], "other": []}50 51 for line in lines:52 line = line.strip()53 if not line or len(line) < 30:54 continue55 categorized = False56 for event_type, keywords in EVENT_TYPES.items():57 if any(kw.lower() in line.lower() for kw in keywords):58 classified[event_type].append(line)59 categorized = True60 break61 if not categorized:62 classified["other"].append(line)63 64 # Build report65 report_lines = [66 f"=== AI Policy Tracker ===",67 f"Region: {country_or_region} | Topic: {ai_topic}",68 "",69 ]70 71 icons = {"regulation": "🔴", "geopolitics": "🟡", "technical": "🔵", "other": "⚪"}72 labels = {"regulation": "Regulation", "geopolitics": "Geopolitics", "technical": "Technical", "other": "Other"}73 74 for category, items in classified.items():75 if items:76 report_lines.append(f"{icons[category]} {labels[category]}:")77 for item in items[:3]: # top 3 per category78 report_lines.append(f" • {item[:200]}")79 report_lines.append("")80 81 if all(len(v) == 0 for v in classified.values()):82 return f"No structured developments found for '{country_or_region}' + '{ai_topic}' this week."83 84 return "\n".join(report_lines)85 86@tool87def get_current_time_in_timezone(timezone: str) -> str:88 """A tool that fetches the current local time in a specified timezone.89 Args:90 timezone: A string representing a valid timezone (e.g., 'America/New_York').91 """92 try:93 # Create timezone object94 tz = pytz.timezone(timezone)95 # Get current time in that timezone96 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")97 return f"The current local time in {timezone} is: {local_time}"98 except Exception as e:99 return f"Error fetching time for timezone '{timezone}': {str(e)}"100 101 102final_answer = FinalAnswerTool()103 104# 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:105# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 106 107model = HfApiModel(108max_tokens=2096,109temperature=0.5,110model_id='Qwen/Qwen2.5-Coder-7B-Instruct',# it is possible that this model may be overloaded111custom_role_conversions=None,112)113 114 115# Import tool from Hub116image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)117 118with open("prompts.yaml", 'r') as stream:119 prompt_templates = yaml.safe_load(stream)120 121agent = CodeAgent(122 model=model,123 tools=[DuckDuckGoSearchTool(), ai_policy_tracker, final_answer], ## add your tools here (don't remove final answer)124 max_steps=6,125 verbosity_level=1,126 grammar=None,127 planning_interval=None,128 name=None,129 description=None,130 prompt_templates=prompt_templates131)132 133 134GradioUI(agent).launch()