""" tools.py — three real tools the agent can call. 1) calculator (pure compute) 2) get_weather (real public API, no key needed: open-meteo) 3) save_note / list_notes (stateful: local SQLite) Each tool validates its arguments and returns a helpful error string on failure, never raising into the agent loop. """ import sqlite3 import math import requests DB = "agent_notes.db" def _db(): conn = sqlite3.connect(DB) conn.execute("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT)") return conn def calculator(expression: str) -> str: """Safely evaluate a maths expression using a restricted namespace.""" if not isinstance(expression, str) or not expression.strip(): return "Error: expression must be a non-empty string." allowed = {k: getattr(math, k) for k in dir(math) if not k.startswith("_")} allowed.update({"abs": abs, "round": round, "min": min, "max": max}) try: # No builtins → cannot call open(), import, etc. return str(eval(expression, {"__builtins__": {}}, allowed)) except Exception as e: return f"Error evaluating expression: {e}" def get_weather(latitude: float, longitude: float) -> str: """Current temperature for a lat/lon via the free open-meteo API.""" try: lat, lon = float(latitude), float(longitude) except (TypeError, ValueError): return "Error: latitude and longitude must be numbers." try: r = requests.get( "https://api.open-meteo.com/v1/forecast", params={"latitude": lat, "longitude": lon, "current_weather": True}, timeout=20, ) r.raise_for_status() cw = r.json().get("current_weather", {}) return f"{cw.get('temperature', '?')}°C, wind {cw.get('windspeed', '?')} km/h." except Exception as e: return f"Error fetching weather: {e}" def save_note(text: str) -> str: """Persist a note to the local database.""" if not isinstance(text, str) or not text.strip(): return "Error: note text must be a non-empty string." conn = _db() conn.execute("INSERT INTO notes (text) VALUES (?)", (text.strip(),)) conn.commit() nid = conn.execute("SELECT last_insert_rowid()").fetchone()[0] conn.close() return f"Saved note #{nid}." def list_notes() -> str: """Return all saved notes.""" conn = _db() rows = conn.execute("SELECT id, text FROM notes ORDER BY id").fetchall() conn.close() if not rows: return "No notes saved yet." return "\n".join(f"#{i}: {t}" for i, t in rows) # Registry the agent uses to dispatch by name. TOOLS = { "calculator": calculator, "get_weather": get_weather, "save_note": save_note, "list_notes": list_notes, }