MatheusPCSilva/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 11@tool12def jepa_weather_advisor(city: str = None) -> str:13 """14 Suggests whether you should take an umbrella using the JEPA (Joint Embedding Predictive Architecture) paradigm.15 Instead of predicting words (like an LLM), this tool:16 1. Automatically detects your location (if no city is provided).17 2. Fetches REAL weather data.18 3. Encodes this data into a LATENT VECTOR (embedding).19 4. Compares this vector against a MEMORY of known weather states.20 5. Chooses the most similar state via DOT PRODUCT (vector similarity).21 6. Returns the corresponding action (take or skip the umbrella).22 23 Args:24 city: (Optional) Name of the city (e.g., 'São Paulo', 'Rio de Janeiro').25 If not provided, the tool automatically detects your location via IP.26 """27 # ======================================================================28 # STEP 0: GET LOCATION (Automatic fallback via IP if city is None)29 # ======================================================================30 location_source = "provided"31 lat, lon, city_name = None, None, None32 33 if city and city.strip():34 # User provided a city → use Geocoding API35 geo_response = requests.get("https://geocoding-api.open-meteo.com/v1/search",36 params={"name": city.strip(), "count": 1, "format": "json"})37 geo_data = geo_response.json()38 if not geo_data.get("results"):39 return f"❌ City '{city}' not found. Please try a valid city name."40 lat = geo_data["results"][0]["latitude"]41 lon = geo_data["results"][0]["longitude"]42 city_name = geo_data["results"][0]["name"]43 location_source = f"provided ('{city_name}')"44 else:45 # No city provided → Automatically detect location via IP46 try:47 ip_response = requests.get("http://ip-api.com/json/", timeout=5)48 ip_data = ip_response.json()49 if ip_data.get("status") == "success":50 lat = ip_data["lat"]51 lon = ip_data["lon"]52 city_name = ip_data["city"]53 country = ip_data.get("countryCode", "")54 location_source = f"automatically detected via IP ({city_name}, {country})"55 else:56 # Fallback if IP detection fails57 city_name = "São Paulo"58 lat, lon = -23.5505, -46.633359 location_source = "fallback (defaulted to São Paulo - IP detection failed)"60 except Exception as e:61 # Fallback on any network error62 city_name = "São Paulo"63 lat, lon = -23.5505, -46.633364 location_source = f"fallback (defaulted to São Paulo - error: {str(e)})"65 66 # ======================================================================67 # STEP 1: FETCH REAL WEATHER DATA (Open-Meteo API)68 # ======================================================================69 weather_response = requests.get("https://api.open-meteo.com/v1/forecast",70 params={"latitude": lat, "longitude": lon,71 "current": ["temperature_2m", "precipitation", "cloud_cover", "wind_speed_10m"],72 "timezone": "America/Sao_Paulo"})73 weather_data = weather_response.json()74 current = weather_data["current"]75 76 temp = current["temperature_2m"]77 precip = current["precipitation"]78 clouds = current["cloud_cover"]79 wind = current["wind_speed_10m"]80 81 # ======================================================================82 # STEP 2: ENCODER → projects raw data into LATENT SPACE (4-dim vector)83 # ======================================================================84 latent_vector = {85 "rain": min(2.0, precip * 4), # precipitation (mm)86 "cloud": min(2.0, clouds / 50), # cloud cover (%)87 "sun": max(0.0, 2.0 - clouds / 50), # inverse of cloud cover88 "wind": min(2.0, wind / 20) # wind speed (km/h)89 }90 91 # ======================================================================92 # STEP 3: WORLD MODEL MEMORY (prior knowledge in latent space)93 # ======================================================================94 memory = {95 "rainy": {"rain": 2.0, "cloud": 1.0, "sun": 0.0, "wind": 0.5},96 "cloudy": {"rain": 0.0, "cloud": 2.0, "sun": 0.0, "wind": 0.0},97 "windy": {"rain": 0.5, "cloud": 0.0, "sun": 0.0, "wind": 2.0},98 "sunny": {"rain": 0.0, "cloud": 0.0, "sun": 2.0, "wind": 0.5}99 }100 101 # ======================================================================102 # STEP 4: PREDICTION BY VECTOR SIMILARITY (dot product)103 # ======================================================================104 similarities = {}105 for state, state_vec in memory.items():106 sim = sum(latent_vector[feature] * state_vec[feature] for feature in latent_vector)107 similarities[state] = round(sim, 3)108 109 predicted_state = max(similarities, key=similarities.get)110 111 # ======================================================================112 # STEP 5: POLICY TABLE (action based on the predicted state)113 # ======================================================================114 policy = {115 "rainy": "🌂 TAKE AN UMBRELLA! (Latent state: wet)",116 "cloudy": "☂️ Better take one, rain might come. (Latent state: humid)",117 "windy": "🧥 No umbrella needed, but grab a jacket. (Latent state: windy)",118 "sunny": "🕶️ No umbrella needed at all. (Latent state: dry)"119 }120 action = policy[predicted_state]121 122 # ======================================================================123 # DIDACTIC OUTPUT (explains JEPA step-by-step + location info)124 # ======================================================================125 return f"""126📍 **Location**: {city_name} ({location_source})127🌡️ **Raw data**: {temp}°C | {precip}mm rain | {clouds}% clouds | {wind}km/h wind128 129🧠 **HOW JEPA REASONED (step-by-step)**:130 1311. **Encoder** transformed raw data into a latent vector (embedding):132 `{latent_vector}`133 1342. **World Model** (memory) holds vectors representing known weather states:135 {', '.join(memory.keys())}136 1373. **Prediction** = calculating the similarity (dot product) between the input vector and each memory vector:138 {similarities}139 1404. **Most similar state** → `{predicted_state}` (chosen because it has the highest similarity score)141 1425. **Action** → {action}143 144💡 **THE CRUCIAL DIFFERENCE**:145- An **LLM** would predict the **next word** (e.g., 'rain', 'umbrella') based on text statistics.146- The **JEPA** predicted a **latent state** (a vector) and, through similarity, decided the action – without ever generating text during the reasoning process.147"""148 149 150@tool151def get_current_time_in_timezone(timezone: str) -> str:152 """A tool that fetches the current local time in a specified timezone.153 Args:154 timezone: A string representing a valid timezone (e.g., 'America/New_York').155 """156 try:157 # Create timezone object158 tz = pytz.timezone(timezone)159 # Get current time in that timezone160 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")161 return f"The current local time in {timezone} is: {local_time}"162 except Exception as e:163 return f"Error fetching time for timezone '{timezone}': {str(e)}"164 165 166final_answer = FinalAnswerTool()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, jepa_weather_advisor, get_current_time_in_timezone], ## 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()