musabAjr/First_agent_template
0
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7from Gradio_UI import GradioUI8import requests9from PIL import Image10from io import BytesIO11from smolagents import tool12 13@tool14def generate_waifu_image(tags: str = "maid") -> Image.Image:15 """Generate a waifu image with specified tags.16 17 Args:18 tags: Comma-separated tags (e.g., 'maid', 'raiden-shogun,maid')19 Available tags: maid, waifu, marin-kitagawa, etc.20 """21 # Convert string to list if multiple tags provided22 if ',' in tags:23 tag_list = [tag.strip() for tag in tags.split(',')]24 else:25 tag_list = [tags]26 27 url = 'https://api.waifu.im/search'28 params = {29 'included_tags': tag_list,30 'height': '>=2000'31 }32 33 try:34 response = requests.get(url, params=params)35 print()36 37 if response.status_code == 200:38 data = response.json()39 40 # Check if we got images41 if 'images' in data and len(data['images']) > 0:42 first_image = data['images'][0]43 44 # Get the URL (try different possible keys)45 image_url = first_image.get('url') or first_image.get('image_url')46 47 if not image_url:48 return "Error: No image URL found in response"49 50 # Download the image from the URL51 img_response = requests.get(image_url, timeout=10)52 img_response.raise_for_status() # Raise an exception for bad status53 54 # Convert to PIL Image55 img = Image.open(BytesIO(img_response.content))56 return img57 else:58 return "Error: No images returned from API"59 else:60 return f"Error: API request failed with status {response.status_code}"61 62 except requests.exceptions.RequestException as e:63 return f"Error: Failed to fetch image - {str(e)}"64 except Exception as e:65 return f"Error: {str(e)}"66 67@tool68def get_current_time_in_timezone(timezone: str) -> str:69 """A tool that fetches the current local time in a specified timezone.70 Args:71 timezone: A string representing a valid timezone (e.g., 'America/New_York').72 """73 try:74 # Create timezone object75 tz = pytz.timezone(timezone)76 # Get current time in that timezone77 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")78 return f"The current local time in {timezone} is: {local_time}"79 except Exception as e:80 return f"Error fetching time for timezone '{timezone}': {str(e)}"81 82@tool83def display_image(img: Image.Image) -> Image.Image:84 """85 Useful to ensure an image is correctly formatted for the UI.86 Args:87 img: The image object to display.88 """89 return img # Let the Gradio template handle the rendering90 91import requests92import json93from typing import Dict, List, Any94 95@tool96def search_remote_job(count: str, geo: str='', industry: str='') -> str:97 """Search for remote jobs using the Jobicy API.98 99 Args:100 count: Number of jobs to return (e.g., '10', '20')101 geo: Geographic preference (e.g., 'europe', 'usa', '') leave it empty if not specified102 industry: Industry (e.g., 'technology', 'marketing', '') leave it empty if not specified103 104 Returns:105 A formatted string listing remote jobs, or an error message.106 """107 108 109 url = 'https://jobicy.com/api/v2/remote-jobs'110 if not geo and not industry:111 params = {112 'count': count,113 }114 if not geo:115 params = {116 'count': count,117 'industry': industry,118 }119 if not industry:120 params = {121 'count': count,122 'geo': geo,123 124 }125 126 try:127 response = requests.get(url=url, params=params)128 # Check if the request was successful129 response.raise_for_status() 130 131 # Parse the JSON data132 data = response.json()133 jobs = data.get('jobs', [])134 if not jobs:135 return f"No remote jobs found for: geo='{geo}', industry='{indu}'"136 137 # Format the response as a readable string138 result = f"๐ Found {len(jobs)} remote job(s):\n\n"139 140 for i, job in enumerate(jobs[:5], 1): # Show first 5 jobs max141 result += f"{i}. **{job.get('jobTitle', 'N/A')}**\n"142 result += f" Company: {job.get('companyName', 'N/A')}\n"143 result += f" Location: {job.get('jobGeo', 'Remote')}\n"144 result += f" Industry: {job.get('jobIndustry', [])}\n"145 146 # Format salary if available147 salary = job.get('salaryRange')148 if salary:149 result += f" Salary: {salary}\n"150 151 # Add job URL152 apply_url = job.get('url')153 if apply_url:154 result += f" Apply: {apply_url}\n"155 156 result += "\n"157 158 if len(jobs) > 5:159 result += f"... and {len(jobs) - 5} more jobs. Use a higher 'count' parameter to see more."160 161 return result 162 163 except Exception as e:164 return f"Unexpected Error: {str(e)}"165final_answer = FinalAnswerTool()166 167 168# 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:169# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 170 171model = HfApiModel(172max_tokens=2096,173temperature=0.5,174model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded175custom_role_conversions=None,176)177 178 179# Import tool from Hub180image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)181 182with open("prompts.yaml", 'r') as stream:183 prompt_templates = yaml.safe_load(stream)184 185agent = CodeAgent(186 model=model,187 tools=[final_answer,generate_waifu_image,display_image,search_remote_job], ## add your tools here (don't remove final answer)188 max_steps=6,189 verbosity_level=1,190 grammar=None,191 planning_interval=None,192 name=None,193 description=None,194 prompt_templates=prompt_templates195)196 197 198GradioUI(agent).launch()199result = agent.run("Generate a waifu ")200# result will be an AgentImage; calling it at the end of a cell displays it201result 