Spaces:
Sleeping
Sleeping
File size: 2,767 Bytes
2131907 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | """
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,
}
|