Spaces:
Running
Running
security: log only exception type (never secrets); generic client errors
Browse files
app.py
CHANGED
|
@@ -1,314 +1,314 @@
|
|
| 1 |
-
#!/usr/bin/env python
|
| 2 |
-
"""Tool-Using Agent — ask a question and watch the AI call real, live tools to answer it:
|
| 3 |
-
a calculator, the current date/time, live weather, and Wikipedia. It runs the ReAct loop
|
| 4 |
-
(decide → call tool → read result → repeat) and shows every tool call it made.
|
| 5 |
-
|
| 6 |
-
All tools are keyless (Open-Meteo + MediaWiki), so the only secret is ANTHROPIC_API_KEY.
|
| 7 |
-
|
| 8 |
-
pip install flask requests anthropic
|
| 9 |
-
python app.py # http://127.0.0.1:7860
|
| 10 |
-
|
| 11 |
-
Project #9 of the "30 Projects in 15 Days" challenge — GritAI.
|
| 12 |
-
UI: GritAI engineered/industrial design system (dark, grit-orange, IBM Plex + Archivo).
|
| 13 |
-
"""
|
| 14 |
-
import os, ast, json, math, operator, datetime, urllib.parse
|
| 15 |
-
from flask import Flask, request, jsonify, Response
|
| 16 |
-
import requests
|
| 17 |
-
|
| 18 |
-
PORT = int(os.environ.get("PORT", "7860"))
|
| 19 |
-
ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY")
|
| 20 |
-
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5")
|
| 21 |
-
MAX_STEPS = 6
|
| 22 |
-
UA = {"User-Agent": "GritAI-ToolAgent/1.0 (https://gritai.solutions)"}
|
| 23 |
-
|
| 24 |
-
# --------------------------------------------------------------------------- tools
|
| 25 |
-
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
| 26 |
-
ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Mod: operator.mod,
|
| 27 |
-
ast.FloorDiv: operator.floordiv, ast.USub: operator.neg, ast.UAdd: operator.pos}
|
| 28 |
-
_FUNCS = {"sqrt": math.sqrt, "abs": abs, "round": round, "log": math.log, "log10": math.log10,
|
| 29 |
-
"sin": math.sin, "cos": math.cos, "tan": math.tan, "pi": math.pi, "e": math.e,
|
| 30 |
-
"floor": math.floor, "ceil": math.ceil, "exp": math.exp, "min": min, "max": max}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _safe_eval(node):
|
| 34 |
-
if isinstance(node, ast.Constant):
|
| 35 |
-
if isinstance(node.value, (int, float)):
|
| 36 |
-
return node.value
|
| 37 |
-
raise ValueError("only numbers")
|
| 38 |
-
if isinstance(node, ast.BinOp):
|
| 39 |
-
return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
| 40 |
-
if isinstance(node, ast.UnaryOp):
|
| 41 |
-
return _OPS[type(node.op)](_safe_eval(node.operand))
|
| 42 |
-
if isinstance(node, ast.Name):
|
| 43 |
-
if node.id in _FUNCS:
|
| 44 |
-
return _FUNCS[node.id]
|
| 45 |
-
raise ValueError(f"unknown name {node.id}")
|
| 46 |
-
if isinstance(node, ast.Call):
|
| 47 |
-
fn = _FUNCS.get(getattr(node.func, "id", ""))
|
| 48 |
-
if not callable(fn):
|
| 49 |
-
raise ValueError("unknown function")
|
| 50 |
-
return fn(*[_safe_eval(a) for a in node.args])
|
| 51 |
-
raise ValueError("unsupported expression")
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def tool_calculator(expression):
|
| 55 |
-
try:
|
| 56 |
-
val = _safe_eval(ast.parse(str(expression), mode="eval").body)
|
| 57 |
-
return f"{expression} = {val}"
|
| 58 |
-
except Exception as e:
|
| 59 |
-
return f"Could not evaluate '{expression}': {e}"
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def tool_datetime(timezone="UTC"):
|
| 63 |
-
now = datetime.datetime.now(datetime.timezone.utc)
|
| 64 |
-
return f"Current UTC date/time: {now.strftime('%A, %d %B %Y, %H:%M UTC')}"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
_WMO = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "rime fog",
|
| 68 |
-
51: "light drizzle", 53: "drizzle", 55: "dense drizzle", 61: "light rain", 63: "rain",
|
| 69 |
-
65: "heavy rain", 71: "light snow", 73: "snow", 75: "heavy snow", 80: "rain showers",
|
| 70 |
-
81: "rain showers", 82: "violent rain showers", 95: "thunderstorm", 96: "thunderstorm w/ hail"}
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def tool_weather(location):
|
| 74 |
-
try:
|
| 75 |
-
g = requests.get("https://geocoding-api.open-meteo.com/v1/search",
|
| 76 |
-
params={"name": location, "count": 1}, headers=UA, timeout=15).json()
|
| 77 |
-
if not g.get("results"):
|
| 78 |
-
return f"No location found for '{location}'."
|
| 79 |
-
r = g["results"][0]
|
| 80 |
-
lat, lon = r["latitude"], r["longitude"]
|
| 81 |
-
place = ", ".join(filter(None, [r.get("name"), r.get("admin1"), r.get("country")]))
|
| 82 |
-
w = requests.get("https://api.open-meteo.com/v1/forecast",
|
| 83 |
-
params={"latitude": lat, "longitude": lon,
|
| 84 |
-
"current": "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m"},
|
| 85 |
-
headers=UA, timeout=15).json()
|
| 86 |
-
c = w.get("current", {})
|
| 87 |
-
desc = _WMO.get(c.get("weather_code"), "unknown")
|
| 88 |
-
return (f"Weather in {place}: {c.get('temperature_2m')}°C, {desc}, "
|
| 89 |
-
f"humidity {c.get('relative_humidity_2m')}%, wind {c.get('wind_speed_10m')} km/h.")
|
| 90 |
-
except Exception as e:
|
| 91 |
-
return f"Weather lookup failed: {e}"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def tool_wikipedia(query):
|
| 95 |
-
try:
|
| 96 |
-
s = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 97 |
-
params={"action": "query", "list": "search", "srsearch": query,
|
| 98 |
-
"format": "json", "srlimit": 1}).json()
|
| 99 |
-
hits = s.get("query", {}).get("search", [])
|
| 100 |
-
if not hits:
|
| 101 |
-
return f"No Wikipedia article found for '{query}'."
|
| 102 |
-
title = hits[0]["title"]
|
| 103 |
-
e = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 104 |
-
params={"action": "query", "prop": "extracts", "exintro": 1, "explaintext": 1,
|
| 105 |
-
"titles": title, "format": "json"}).json()
|
| 106 |
-
pages = e.get("query", {}).get("pages", {})
|
| 107 |
-
extract = next(iter(pages.values()), {}).get("extract", "")
|
| 108 |
-
return f"Wikipedia — {title}: {extract[:800]}" if extract else f"Found '{title}' but no summary."
|
| 109 |
-
except Exception as e:
|
| 110 |
-
return f"Wikipedia lookup failed: {e}"
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
TOOLS_SPEC = [
|
| 114 |
-
{"name": "calculator", "description": "Evaluate an arithmetic expression. Supports + - * / ** % and "
|
| 115 |
-
"sqrt, log, sin, cos, tan, floor, ceil, abs, round, pi, e.",
|
| 116 |
-
"input_schema": {"type": "object", "properties": {"expression": {"type": "string"}},
|
| 117 |
-
"required": ["expression"]}},
|
| 118 |
-
{"name": "current_datetime", "description": "Get the current date and time (UTC).",
|
| 119 |
-
"input_schema": {"type": "object", "properties": {"timezone": {"type": "string"}}}},
|
| 120 |
-
{"name": "weather", "description": "Get the current weather for a city/place name (live).",
|
| 121 |
-
"input_schema": {"type": "object", "properties": {"location": {"type": "string"}},
|
| 122 |
-
"required": ["location"]}},
|
| 123 |
-
{"name": "wikipedia", "description": "Look up a topic on Wikipedia and get a summary (live).",
|
| 124 |
-
"input_schema": {"type": "object", "properties": {"query": {"type": "string"}},
|
| 125 |
-
"required": ["query"]}},
|
| 126 |
-
]
|
| 127 |
-
EXECUTORS = {"calculator": tool_calculator, "current_datetime": tool_datetime,
|
| 128 |
-
"weather": tool_weather, "wikipedia": tool_wikipedia}
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def run_agent(question):
|
| 132 |
-
import anthropic
|
| 133 |
-
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
| 134 |
-
sysp = ("You are a helpful assistant that answers using the provided tools whenever they help. "
|
| 135 |
-
"Call tools to get live/precise data instead of guessing. You may call multiple tools. "
|
| 136 |
-
"When you have enough, give a clear, concise final answer.")
|
| 137 |
-
msgs = [{"role": "user", "content": question}]
|
| 138 |
-
trace = []
|
| 139 |
-
for _ in range(MAX_STEPS):
|
| 140 |
-
r = client.messages.create(model=ANTHROPIC_MODEL, max_tokens=1024, system=sysp,
|
| 141 |
-
tools=TOOLS_SPEC, messages=msgs)
|
| 142 |
-
if r.stop_reason == "tool_use":
|
| 143 |
-
msgs.append({"role": "assistant", "content": r.content})
|
| 144 |
-
results = []
|
| 145 |
-
for b in r.content:
|
| 146 |
-
if b.type == "tool_use":
|
| 147 |
-
out = EXECUTORS.get(b.name, lambda **k: "unknown tool")(**b.input)
|
| 148 |
-
trace.append({"tool": b.name, "input": b.input, "result": out[:400]})
|
| 149 |
-
results.append({"type": "tool_result", "tool_use_id": b.id, "content": out})
|
| 150 |
-
msgs.append({"role": "user", "content": results})
|
| 151 |
-
else:
|
| 152 |
-
text = "".join(b.text for b in r.content if b.type == "text")
|
| 153 |
-
return text.strip(), trace
|
| 154 |
-
return "I reached the step limit before finishing — try a simpler question.", trace
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
app = Flask(__name__)
|
| 158 |
-
app.config["MAX_CONTENT_LENGTH"] = 512 * 1024
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
@app.route("/")
|
| 162 |
-
def home():
|
| 163 |
-
return Response(PAGE, mimetype="text/html")
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
@app.route("/api/ask", methods=["POST"])
|
| 167 |
-
def api_ask():
|
| 168 |
-
q = (request.get_json(force=True).get("question") or "").strip()[:1000]
|
| 169 |
-
if not q:
|
| 170 |
-
return jsonify(error="Ask a question."), 400
|
| 171 |
-
if not ANTHROPIC_KEY:
|
| 172 |
-
return jsonify(error="Set ANTHROPIC_API_KEY on the server to run the agent."), 200
|
| 173 |
-
try:
|
| 174 |
-
answer, trace = run_agent(q)
|
| 175 |
-
except Exception as e:
|
| 176 |
-
import sys; print("agent error:",
|
| 177 |
-
return jsonify(error="The agent hit an error — please try again."), 200
|
| 178 |
-
return jsonify(answer=answer, trace=trace)
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
# ===================== GritAI engineered/industrial design system =====================
|
| 182 |
-
PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
|
| 183 |
-
<title>GritAI · Tool-Using Agent</title>
|
| 184 |
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 185 |
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 186 |
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 187 |
-
<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@600;700;800;900&family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
| 188 |
-
<style>
|
| 189 |
-
:root{--bg:#0a0b0e;--bg2:#0e1015;--panel:#111318;--ink:#eef0f4;--dim:#9aa1b0;--dim2:#5f6675;--line:#20242e;--line2:#2b303c;
|
| 190 |
-
--grit:#ff5a2a;--grit2:#ff7d54;--grit-dim:#c9451f;
|
| 191 |
-
--disp:'Archivo',system-ui,sans-serif;--body:'IBM Plex Sans',system-ui,sans-serif;--mono:'IBM Plex Mono',ui-monospace,monospace}
|
| 192 |
-
*{box-sizing:border-box}html,body{height:100%}
|
| 193 |
-
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--body);font-size:15px;line-height:1.6;-webkit-font-smoothing:antialiased;position:relative;overflow-x:hidden}
|
| 194 |
-
body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;
|
| 195 |
-
background:linear-gradient(0deg,transparent 95%,rgba(255,90,42,.04) 100%),
|
| 196 |
-
repeating-linear-gradient(90deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
|
| 197 |
-
repeating-linear-gradient(0deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
|
| 198 |
-
radial-gradient(120% 80% at 50% -10%,#141821 0%,var(--bg) 55%)}
|
| 199 |
-
body::after{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;opacity:.05;mix-blend-mode:overlay;
|
| 200 |
-
background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
|
| 201 |
-
.wrap{position:relative;z-index:1;max-width:960px;margin:0 auto;padding:0 28px 70px}
|
| 202 |
-
header{display:flex;align-items:center;gap:16px;padding:22px 0 18px;border-bottom:1px solid var(--line);animation:fade .6s .02s both}
|
| 203 |
-
.mark{width:38px;height:38px;flex:none}.mark svg{display:block}
|
| 204 |
-
.brand{display:flex;flex-direction:column;line-height:1}
|
| 205 |
-
.brand .co{font-family:var(--disp);font-weight:900;font-size:19px;letter-spacing:.5px}.brand .co b{color:var(--grit)}
|
| 206 |
-
.brand .sub{font-family:var(--mono);font-size:10.5px;letter-spacing:.28em;text-transform:uppercase;color:var(--dim2);margin-top:5px}
|
| 207 |
-
.tags{margin-left:auto;display:flex;gap:8px}
|
| 208 |
-
.tag{font-family:var(--mono);font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);border:1px solid var(--line2);border-radius:2px;padding:5px 9px}
|
| 209 |
-
.tag.hot{color:var(--grit);border-color:var(--grit-dim)}
|
| 210 |
-
.hero{padding:34px 0 26px;animation:fade .6s .12s both}
|
| 211 |
-
.hero h1{font-family:var(--disp);font-weight:800;font-size:clamp(30px,5.4vw,52px);line-height:1.02;letter-spacing:-.02em;margin:0;max-width:16ch}
|
| 212 |
-
.hero h1 em{font-style:normal;color:var(--grit)}
|
| 213 |
-
.hero p{color:var(--dim);max-width:56ch;margin:16px 0 0;font-size:15.5px}
|
| 214 |
-
.sec{display:flex;align-items:center;gap:14px;margin:30px 0 14px}
|
| 215 |
-
.sec .num{font-family:var(--mono);font-size:11px;font-weight:600;color:var(--grit);letter-spacing:.1em}
|
| 216 |
-
.sec .name{font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.26em;text-transform:uppercase;color:var(--dim)}
|
| 217 |
-
.sec .rule{flex:1;height:1px;background:linear-gradient(90deg,var(--line2),transparent)}
|
| 218 |
-
.ask{animation:fade .6s .2s both}
|
| 219 |
-
.field{display:flex;align-items:stretch;border:1px solid var(--line2);border-radius:3px;background:var(--panel);overflow:hidden;transition:border-color .18s}
|
| 220 |
-
.field:focus-within{border-color:var(--grit-dim)}
|
| 221 |
-
.field .car{font-family:var(--mono);color:var(--grit);padding:16px 0 16px 16px;font-size:15px;user-select:none}
|
| 222 |
-
.field input{flex:1;background:transparent;border:0;outline:none;color:var(--ink);font-family:var(--body);font-size:15.5px;padding:16px 14px}
|
| 223 |
-
.field input::placeholder{color:var(--dim2)}
|
| 224 |
-
.run{border:0;background:var(--grit);color:#140a06;font-family:var(--mono);font-weight:600;font-size:13px;letter-spacing:.14em;text-transform:uppercase;padding:0 24px;cursor:pointer;transition:.16s;box-shadow:-1px 0 0 var(--grit-dim)}
|
| 225 |
-
.run:hover{background:var(--grit2);box-shadow:0 0 26px -4px rgba(255,90,42,.55)}
|
| 226 |
-
.run:disabled{opacity:.55;cursor:default;box-shadow:none}
|
| 227 |
-
.ex{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
|
| 228 |
-
.chip{font-family:var(--mono);font-size:12px;color:var(--dim);background:var(--panel);border:1px solid var(--line);border-radius:2px;padding:8px 11px;cursor:pointer;transition:.15s}
|
| 229 |
-
.chip:hover{color:var(--grit);border-color:var(--grit-dim)}
|
| 230 |
-
.chip .pt{color:var(--dim2);margin-right:7px}
|
| 231 |
-
.out{display:none}.out.show{display:block}
|
| 232 |
-
.trace{border:1px solid var(--line);border-radius:3px;background:linear-gradient(180deg,var(--panel),var(--bg2))}
|
| 233 |
-
.log{font-family:var(--mono);font-size:13px;line-height:1.75}
|
| 234 |
-
.row{display:grid;grid-template-columns:22px 100px 1fr;gap:0 12px;padding:13px 18px;border-bottom:1px solid var(--line);animation:slidein .45s both}
|
| 235 |
-
.row:last-child{border-bottom:0}
|
| 236 |
-
.row .mk{color:var(--grit);font-weight:600}
|
| 237 |
-
.row .tn{color:var(--grit2);text-transform:uppercase;letter-spacing:.06em;font-weight:500}
|
| 238 |
-
.row .rd{color:var(--ink);word-break:break-word}.row .rd .arg{color:var(--dim2)}
|
| 239 |
-
.row.none .rd{color:var(--dim)}
|
| 240 |
-
.ans{border:1px solid var(--line2);border-left:2px solid var(--grit);border-radius:3px;background:var(--panel);padding:22px 24px}
|
| 241 |
-
.ans p{margin:0 0 12px;font-size:16px;line-height:1.65}.ans p:last-child{margin-bottom:0}
|
| 242 |
-
.spin{display:inline-flex;gap:6px;padding:16px 18px}.spin span{width:8px;height:8px;border-radius:50%;background:var(--grit);opacity:.5;animation:bd 1.2s infinite}
|
| 243 |
-
.spin span:nth-child(2){animation-delay:.18s}.spin span:nth-child(3){animation-delay:.36s}
|
| 244 |
-
footer{margin-top:34px;padding-top:16px;border-top:1px solid var(--line);font-family:var(--mono);font-size:11px;letter-spacing:.06em;color:var(--dim2);display:flex;gap:16px;flex-wrap:wrap;animation:fade .6s .5s both}
|
| 245 |
-
footer .b{color:var(--dim)}footer .sp{margin-left:auto}
|
| 246 |
-
footer a{color:var(--dim);text-decoration:none}footer a:hover{color:var(--grit)}
|
| 247 |
-
@keyframes fade{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
|
| 248 |
-
@keyframes slidein{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
|
| 249 |
-
@keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-6px);opacity:1}}
|
| 250 |
-
</style></head>
|
| 251 |
-
<body><div class="wrap">
|
| 252 |
-
<header>
|
| 253 |
-
<div class="mark"><svg width="38" height="38" viewBox="0 0 38 38" fill="none">
|
| 254 |
-
<rect x="1" y="1" width="36" height="36" rx="2" stroke="#2b303c"/>
|
| 255 |
-
<path d="M27 12.5A9 9 0 1 0 28 22H19" stroke="#ff5a2a" stroke-width="2.4" stroke-linecap="square"/>
|
| 256 |
-
<rect x="10.5" y="10.5" width="3" height="3" fill="#ff5a2a"/>
|
| 257 |
-
</svg></div>
|
| 258 |
-
<div class="brand"><div class="co">GRIT<b>AI</b></div><div class="sub">Tool-Using Agent</div></div>
|
| 259 |
-
<div class="tags"><span class="tag hot">▸ Live</span><span class="tag">SDVOSB</span><span class="tag">Lawton OK</span></div>
|
| 260 |
-
</header>
|
| 261 |
-
<section class="hero">
|
| 262 |
-
<h1>Ask it anything. It <em>calls real tools</em> to answer.</h1>
|
| 263 |
-
<p>A calculator, a clock, live weather, and Wikipedia — the agent decides what to call, runs it, and shows its work. Not a chatbot guessing. An operator.</p>
|
| 264 |
-
</section>
|
| 265 |
-
<div class="sec"><span class="num">01</span><span class="name">Ask</span><span class="rule"></span></div>
|
| 266 |
-
<div class="ask">
|
| 267 |
-
<div class="field">
|
| 268 |
-
<span class="car">>_</span>
|
| 269 |
-
<input id="q" placeholder="What's a 15% tip on $47.80, and the current weather in Paris?" autofocus>
|
| 270 |
-
<button class="run" id="go" onclick="ask()">Run ▸</button>
|
| 271 |
-
</div>
|
| 272 |
-
<div class="ex" id="ex"></div>
|
| 273 |
-
</div>
|
| 274 |
-
<div class="out" id="out">
|
| 275 |
-
<div class="sec"><span class="num">02</span><span class="name">Trace — live tool calls</span><span class="rule"></span></div>
|
| 276 |
-
<div class="trace"><div class="log" id="trace"></div></div>
|
| 277 |
-
<div class="sec"><span class="num">03</span><span class="name">Answer</span><span class="rule"></span></div>
|
| 278 |
-
<div class="ans" id="answer"></div>
|
| 279 |
-
</div>
|
| 280 |
-
<footer>
|
| 281 |
-
<span class="b">ReAct loop</span><span>·</span><span>keyless tools — Open-Meteo + Wikipedia</span>
|
| 282 |
-
<span class="sp"><a href="https://gritai.solutions">GRITAI SOLUTIONS</a> · 30-in-15 №9</span>
|
| 283 |
-
</footer>
|
| 284 |
-
</div><script>
|
| 285 |
-
const EXAMPLES=["Who invented the World Wide Web, and what's the square root of 4096?",
|
| 286 |
-
"What's the weather in Tokyo, and the current UTC time?",
|
| 287 |
-
"Summarize what an octopus is, then give me a 12% tip on $86."];
|
| 288 |
-
const $=id=>document.getElementById(id);
|
| 289 |
-
const q=$('q'),go=$('go'),out=$('out');
|
| 290 |
-
function esc(s){return String(s==null?'':s).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]));}
|
| 291 |
-
$('ex').innerHTML=EXAMPLES.map(e=>'<span class="chip"><span class="pt">↳</span>'+esc(e)+'</span>').join('');
|
| 292 |
-
$('ex').querySelectorAll('.chip').forEach(c=>c.onclick=()=>{q.value=c.textContent.replace(/^↳\s*/,'');ask();});
|
| 293 |
-
function argStr(o){try{return Object.values(o).join(', ');}catch(e){return '';}}
|
| 294 |
-
function ask(){if(go.disabled)return;const text=q.value.trim();if(!text){q.focus();return;}
|
| 295 |
-
go.disabled=true;go.textContent='…';out.classList.add('show');
|
| 296 |
-
$('trace').innerHTML='<div class="spin"><span></span><span></span><span></span></div>';$('answer').innerHTML='';
|
| 297 |
-
fetch('/api/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:text})})
|
| 298 |
-
.then(r=>r.json()).then(d=>{
|
| 299 |
-
if(d.error){$('trace').innerHTML='<div class="row none"><span class="mk">!</span><span class="tn">error</span><span class="rd">'+esc(d.error)+'</span></div>';return;}
|
| 300 |
-
const t=d.trace||[];
|
| 301 |
-
$('trace').innerHTML=t.length?t.map(s=>'<div class="row"><span class="mk">»</span><span class="tn">'+esc(s.tool)+'</span><span class="rd"><span class="arg">'+esc(argStr(s.input))+'</span> → '+esc(s.result)+'</span></div>').join(''):
|
| 302 |
-
'<div class="row none"><span class="mk">·</span><span class="tn">direct</span><span class="rd">answered directly — no tools needed</span></div>';
|
| 303 |
-
$('answer').innerHTML=String(d.answer||'').split(/\\n\\n+/).map(p=>'<p>'+esc(p).replace(/\\n/g,'<br>')+'</p>').join('');
|
| 304 |
-
}).catch(()=>{$('trace').innerHTML='<div class="row none"><span class="mk">!</span><span class="tn">error</span><span class="rd">Something went wrong — please try again.</span></div>';})
|
| 305 |
-
.finally(()=>{go.disabled=false;go.textContent='Run ▸';});
|
| 306 |
-
}
|
| 307 |
-
q.addEventListener('keydown',e=>{if(e.key==='Enter')ask();});
|
| 308 |
-
</script></body></html>"""
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
if __name__ == "__main__":
|
| 312 |
-
backend = "Claude API" if ANTHROPIC_KEY else "NO KEY (set ANTHROPIC_API_KEY)"
|
| 313 |
-
print(f"Tool-Using Agent on http://127.0.0.1:{PORT} [backend: {backend}]", flush=True)
|
| 314 |
-
app.run(host="0.0.0.0", port=PORT, threaded=True)
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Tool-Using Agent — ask a question and watch the AI call real, live tools to answer it:
|
| 3 |
+
a calculator, the current date/time, live weather, and Wikipedia. It runs the ReAct loop
|
| 4 |
+
(decide → call tool → read result → repeat) and shows every tool call it made.
|
| 5 |
+
|
| 6 |
+
All tools are keyless (Open-Meteo + MediaWiki), so the only secret is ANTHROPIC_API_KEY.
|
| 7 |
+
|
| 8 |
+
pip install flask requests anthropic
|
| 9 |
+
python app.py # http://127.0.0.1:7860
|
| 10 |
+
|
| 11 |
+
Project #9 of the "30 Projects in 15 Days" challenge — GritAI.
|
| 12 |
+
UI: GritAI engineered/industrial design system (dark, grit-orange, IBM Plex + Archivo).
|
| 13 |
+
"""
|
| 14 |
+
import os, ast, json, math, operator, datetime, urllib.parse
|
| 15 |
+
from flask import Flask, request, jsonify, Response
|
| 16 |
+
import requests
|
| 17 |
+
|
| 18 |
+
PORT = int(os.environ.get("PORT", "7860"))
|
| 19 |
+
ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY")
|
| 20 |
+
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5")
|
| 21 |
+
MAX_STEPS = 6
|
| 22 |
+
UA = {"User-Agent": "GritAI-ToolAgent/1.0 (https://gritai.solutions)"}
|
| 23 |
+
|
| 24 |
+
# --------------------------------------------------------------------------- tools
|
| 25 |
+
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
| 26 |
+
ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Mod: operator.mod,
|
| 27 |
+
ast.FloorDiv: operator.floordiv, ast.USub: operator.neg, ast.UAdd: operator.pos}
|
| 28 |
+
_FUNCS = {"sqrt": math.sqrt, "abs": abs, "round": round, "log": math.log, "log10": math.log10,
|
| 29 |
+
"sin": math.sin, "cos": math.cos, "tan": math.tan, "pi": math.pi, "e": math.e,
|
| 30 |
+
"floor": math.floor, "ceil": math.ceil, "exp": math.exp, "min": min, "max": max}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _safe_eval(node):
|
| 34 |
+
if isinstance(node, ast.Constant):
|
| 35 |
+
if isinstance(node.value, (int, float)):
|
| 36 |
+
return node.value
|
| 37 |
+
raise ValueError("only numbers")
|
| 38 |
+
if isinstance(node, ast.BinOp):
|
| 39 |
+
return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
| 40 |
+
if isinstance(node, ast.UnaryOp):
|
| 41 |
+
return _OPS[type(node.op)](_safe_eval(node.operand))
|
| 42 |
+
if isinstance(node, ast.Name):
|
| 43 |
+
if node.id in _FUNCS:
|
| 44 |
+
return _FUNCS[node.id]
|
| 45 |
+
raise ValueError(f"unknown name {node.id}")
|
| 46 |
+
if isinstance(node, ast.Call):
|
| 47 |
+
fn = _FUNCS.get(getattr(node.func, "id", ""))
|
| 48 |
+
if not callable(fn):
|
| 49 |
+
raise ValueError("unknown function")
|
| 50 |
+
return fn(*[_safe_eval(a) for a in node.args])
|
| 51 |
+
raise ValueError("unsupported expression")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def tool_calculator(expression):
|
| 55 |
+
try:
|
| 56 |
+
val = _safe_eval(ast.parse(str(expression), mode="eval").body)
|
| 57 |
+
return f"{expression} = {val}"
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"Could not evaluate '{expression}': {e}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def tool_datetime(timezone="UTC"):
|
| 63 |
+
now = datetime.datetime.now(datetime.timezone.utc)
|
| 64 |
+
return f"Current UTC date/time: {now.strftime('%A, %d %B %Y, %H:%M UTC')}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
_WMO = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "rime fog",
|
| 68 |
+
51: "light drizzle", 53: "drizzle", 55: "dense drizzle", 61: "light rain", 63: "rain",
|
| 69 |
+
65: "heavy rain", 71: "light snow", 73: "snow", 75: "heavy snow", 80: "rain showers",
|
| 70 |
+
81: "rain showers", 82: "violent rain showers", 95: "thunderstorm", 96: "thunderstorm w/ hail"}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def tool_weather(location):
|
| 74 |
+
try:
|
| 75 |
+
g = requests.get("https://geocoding-api.open-meteo.com/v1/search",
|
| 76 |
+
params={"name": location, "count": 1}, headers=UA, timeout=15).json()
|
| 77 |
+
if not g.get("results"):
|
| 78 |
+
return f"No location found for '{location}'."
|
| 79 |
+
r = g["results"][0]
|
| 80 |
+
lat, lon = r["latitude"], r["longitude"]
|
| 81 |
+
place = ", ".join(filter(None, [r.get("name"), r.get("admin1"), r.get("country")]))
|
| 82 |
+
w = requests.get("https://api.open-meteo.com/v1/forecast",
|
| 83 |
+
params={"latitude": lat, "longitude": lon,
|
| 84 |
+
"current": "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m"},
|
| 85 |
+
headers=UA, timeout=15).json()
|
| 86 |
+
c = w.get("current", {})
|
| 87 |
+
desc = _WMO.get(c.get("weather_code"), "unknown")
|
| 88 |
+
return (f"Weather in {place}: {c.get('temperature_2m')}°C, {desc}, "
|
| 89 |
+
f"humidity {c.get('relative_humidity_2m')}%, wind {c.get('wind_speed_10m')} km/h.")
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"Weather lookup failed: {e}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def tool_wikipedia(query):
|
| 95 |
+
try:
|
| 96 |
+
s = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 97 |
+
params={"action": "query", "list": "search", "srsearch": query,
|
| 98 |
+
"format": "json", "srlimit": 1}).json()
|
| 99 |
+
hits = s.get("query", {}).get("search", [])
|
| 100 |
+
if not hits:
|
| 101 |
+
return f"No Wikipedia article found for '{query}'."
|
| 102 |
+
title = hits[0]["title"]
|
| 103 |
+
e = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 104 |
+
params={"action": "query", "prop": "extracts", "exintro": 1, "explaintext": 1,
|
| 105 |
+
"titles": title, "format": "json"}).json()
|
| 106 |
+
pages = e.get("query", {}).get("pages", {})
|
| 107 |
+
extract = next(iter(pages.values()), {}).get("extract", "")
|
| 108 |
+
return f"Wikipedia — {title}: {extract[:800]}" if extract else f"Found '{title}' but no summary."
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return f"Wikipedia lookup failed: {e}"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
TOOLS_SPEC = [
|
| 114 |
+
{"name": "calculator", "description": "Evaluate an arithmetic expression. Supports + - * / ** % and "
|
| 115 |
+
"sqrt, log, sin, cos, tan, floor, ceil, abs, round, pi, e.",
|
| 116 |
+
"input_schema": {"type": "object", "properties": {"expression": {"type": "string"}},
|
| 117 |
+
"required": ["expression"]}},
|
| 118 |
+
{"name": "current_datetime", "description": "Get the current date and time (UTC).",
|
| 119 |
+
"input_schema": {"type": "object", "properties": {"timezone": {"type": "string"}}}},
|
| 120 |
+
{"name": "weather", "description": "Get the current weather for a city/place name (live).",
|
| 121 |
+
"input_schema": {"type": "object", "properties": {"location": {"type": "string"}},
|
| 122 |
+
"required": ["location"]}},
|
| 123 |
+
{"name": "wikipedia", "description": "Look up a topic on Wikipedia and get a summary (live).",
|
| 124 |
+
"input_schema": {"type": "object", "properties": {"query": {"type": "string"}},
|
| 125 |
+
"required": ["query"]}},
|
| 126 |
+
]
|
| 127 |
+
EXECUTORS = {"calculator": tool_calculator, "current_datetime": tool_datetime,
|
| 128 |
+
"weather": tool_weather, "wikipedia": tool_wikipedia}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def run_agent(question):
|
| 132 |
+
import anthropic
|
| 133 |
+
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
| 134 |
+
sysp = ("You are a helpful assistant that answers using the provided tools whenever they help. "
|
| 135 |
+
"Call tools to get live/precise data instead of guessing. You may call multiple tools. "
|
| 136 |
+
"When you have enough, give a clear, concise final answer.")
|
| 137 |
+
msgs = [{"role": "user", "content": question}]
|
| 138 |
+
trace = []
|
| 139 |
+
for _ in range(MAX_STEPS):
|
| 140 |
+
r = client.messages.create(model=ANTHROPIC_MODEL, max_tokens=1024, system=sysp,
|
| 141 |
+
tools=TOOLS_SPEC, messages=msgs)
|
| 142 |
+
if r.stop_reason == "tool_use":
|
| 143 |
+
msgs.append({"role": "assistant", "content": r.content})
|
| 144 |
+
results = []
|
| 145 |
+
for b in r.content:
|
| 146 |
+
if b.type == "tool_use":
|
| 147 |
+
out = EXECUTORS.get(b.name, lambda **k: "unknown tool")(**b.input)
|
| 148 |
+
trace.append({"tool": b.name, "input": b.input, "result": out[:400]})
|
| 149 |
+
results.append({"type": "tool_result", "tool_use_id": b.id, "content": out})
|
| 150 |
+
msgs.append({"role": "user", "content": results})
|
| 151 |
+
else:
|
| 152 |
+
text = "".join(b.text for b in r.content if b.type == "text")
|
| 153 |
+
return text.strip(), trace
|
| 154 |
+
return "I reached the step limit before finishing — try a simpler question.", trace
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
app = Flask(__name__)
|
| 158 |
+
app.config["MAX_CONTENT_LENGTH"] = 512 * 1024
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@app.route("/")
|
| 162 |
+
def home():
|
| 163 |
+
return Response(PAGE, mimetype="text/html")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@app.route("/api/ask", methods=["POST"])
|
| 167 |
+
def api_ask():
|
| 168 |
+
q = (request.get_json(force=True).get("question") or "").strip()[:1000]
|
| 169 |
+
if not q:
|
| 170 |
+
return jsonify(error="Ask a question."), 400
|
| 171 |
+
if not ANTHROPIC_KEY:
|
| 172 |
+
return jsonify(error="Set ANTHROPIC_API_KEY on the server to run the agent."), 200
|
| 173 |
+
try:
|
| 174 |
+
answer, trace = run_agent(q)
|
| 175 |
+
except Exception as e:
|
| 176 |
+
import sys; print("agent error:", type(e).__name__, file=sys.stderr, flush=True)
|
| 177 |
+
return jsonify(error="The agent hit an error — please try again."), 200
|
| 178 |
+
return jsonify(answer=answer, trace=trace)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# ===================== GritAI engineered/industrial design system =====================
|
| 182 |
+
PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
|
| 183 |
+
<title>GritAI · Tool-Using Agent</title>
|
| 184 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 185 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 186 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 187 |
+
<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@600;700;800;900&family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
| 188 |
+
<style>
|
| 189 |
+
:root{--bg:#0a0b0e;--bg2:#0e1015;--panel:#111318;--ink:#eef0f4;--dim:#9aa1b0;--dim2:#5f6675;--line:#20242e;--line2:#2b303c;
|
| 190 |
+
--grit:#ff5a2a;--grit2:#ff7d54;--grit-dim:#c9451f;
|
| 191 |
+
--disp:'Archivo',system-ui,sans-serif;--body:'IBM Plex Sans',system-ui,sans-serif;--mono:'IBM Plex Mono',ui-monospace,monospace}
|
| 192 |
+
*{box-sizing:border-box}html,body{height:100%}
|
| 193 |
+
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--body);font-size:15px;line-height:1.6;-webkit-font-smoothing:antialiased;position:relative;overflow-x:hidden}
|
| 194 |
+
body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;
|
| 195 |
+
background:linear-gradient(0deg,transparent 95%,rgba(255,90,42,.04) 100%),
|
| 196 |
+
repeating-linear-gradient(90deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
|
| 197 |
+
repeating-linear-gradient(0deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
|
| 198 |
+
radial-gradient(120% 80% at 50% -10%,#141821 0%,var(--bg) 55%)}
|
| 199 |
+
body::after{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;opacity:.05;mix-blend-mode:overlay;
|
| 200 |
+
background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
|
| 201 |
+
.wrap{position:relative;z-index:1;max-width:960px;margin:0 auto;padding:0 28px 70px}
|
| 202 |
+
header{display:flex;align-items:center;gap:16px;padding:22px 0 18px;border-bottom:1px solid var(--line);animation:fade .6s .02s both}
|
| 203 |
+
.mark{width:38px;height:38px;flex:none}.mark svg{display:block}
|
| 204 |
+
.brand{display:flex;flex-direction:column;line-height:1}
|
| 205 |
+
.brand .co{font-family:var(--disp);font-weight:900;font-size:19px;letter-spacing:.5px}.brand .co b{color:var(--grit)}
|
| 206 |
+
.brand .sub{font-family:var(--mono);font-size:10.5px;letter-spacing:.28em;text-transform:uppercase;color:var(--dim2);margin-top:5px}
|
| 207 |
+
.tags{margin-left:auto;display:flex;gap:8px}
|
| 208 |
+
.tag{font-family:var(--mono);font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);border:1px solid var(--line2);border-radius:2px;padding:5px 9px}
|
| 209 |
+
.tag.hot{color:var(--grit);border-color:var(--grit-dim)}
|
| 210 |
+
.hero{padding:34px 0 26px;animation:fade .6s .12s both}
|
| 211 |
+
.hero h1{font-family:var(--disp);font-weight:800;font-size:clamp(30px,5.4vw,52px);line-height:1.02;letter-spacing:-.02em;margin:0;max-width:16ch}
|
| 212 |
+
.hero h1 em{font-style:normal;color:var(--grit)}
|
| 213 |
+
.hero p{color:var(--dim);max-width:56ch;margin:16px 0 0;font-size:15.5px}
|
| 214 |
+
.sec{display:flex;align-items:center;gap:14px;margin:30px 0 14px}
|
| 215 |
+
.sec .num{font-family:var(--mono);font-size:11px;font-weight:600;color:var(--grit);letter-spacing:.1em}
|
| 216 |
+
.sec .name{font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.26em;text-transform:uppercase;color:var(--dim)}
|
| 217 |
+
.sec .rule{flex:1;height:1px;background:linear-gradient(90deg,var(--line2),transparent)}
|
| 218 |
+
.ask{animation:fade .6s .2s both}
|
| 219 |
+
.field{display:flex;align-items:stretch;border:1px solid var(--line2);border-radius:3px;background:var(--panel);overflow:hidden;transition:border-color .18s}
|
| 220 |
+
.field:focus-within{border-color:var(--grit-dim)}
|
| 221 |
+
.field .car{font-family:var(--mono);color:var(--grit);padding:16px 0 16px 16px;font-size:15px;user-select:none}
|
| 222 |
+
.field input{flex:1;background:transparent;border:0;outline:none;color:var(--ink);font-family:var(--body);font-size:15.5px;padding:16px 14px}
|
| 223 |
+
.field input::placeholder{color:var(--dim2)}
|
| 224 |
+
.run{border:0;background:var(--grit);color:#140a06;font-family:var(--mono);font-weight:600;font-size:13px;letter-spacing:.14em;text-transform:uppercase;padding:0 24px;cursor:pointer;transition:.16s;box-shadow:-1px 0 0 var(--grit-dim)}
|
| 225 |
+
.run:hover{background:var(--grit2);box-shadow:0 0 26px -4px rgba(255,90,42,.55)}
|
| 226 |
+
.run:disabled{opacity:.55;cursor:default;box-shadow:none}
|
| 227 |
+
.ex{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
|
| 228 |
+
.chip{font-family:var(--mono);font-size:12px;color:var(--dim);background:var(--panel);border:1px solid var(--line);border-radius:2px;padding:8px 11px;cursor:pointer;transition:.15s}
|
| 229 |
+
.chip:hover{color:var(--grit);border-color:var(--grit-dim)}
|
| 230 |
+
.chip .pt{color:var(--dim2);margin-right:7px}
|
| 231 |
+
.out{display:none}.out.show{display:block}
|
| 232 |
+
.trace{border:1px solid var(--line);border-radius:3px;background:linear-gradient(180deg,var(--panel),var(--bg2))}
|
| 233 |
+
.log{font-family:var(--mono);font-size:13px;line-height:1.75}
|
| 234 |
+
.row{display:grid;grid-template-columns:22px 100px 1fr;gap:0 12px;padding:13px 18px;border-bottom:1px solid var(--line);animation:slidein .45s both}
|
| 235 |
+
.row:last-child{border-bottom:0}
|
| 236 |
+
.row .mk{color:var(--grit);font-weight:600}
|
| 237 |
+
.row .tn{color:var(--grit2);text-transform:uppercase;letter-spacing:.06em;font-weight:500}
|
| 238 |
+
.row .rd{color:var(--ink);word-break:break-word}.row .rd .arg{color:var(--dim2)}
|
| 239 |
+
.row.none .rd{color:var(--dim)}
|
| 240 |
+
.ans{border:1px solid var(--line2);border-left:2px solid var(--grit);border-radius:3px;background:var(--panel);padding:22px 24px}
|
| 241 |
+
.ans p{margin:0 0 12px;font-size:16px;line-height:1.65}.ans p:last-child{margin-bottom:0}
|
| 242 |
+
.spin{display:inline-flex;gap:6px;padding:16px 18px}.spin span{width:8px;height:8px;border-radius:50%;background:var(--grit);opacity:.5;animation:bd 1.2s infinite}
|
| 243 |
+
.spin span:nth-child(2){animation-delay:.18s}.spin span:nth-child(3){animation-delay:.36s}
|
| 244 |
+
footer{margin-top:34px;padding-top:16px;border-top:1px solid var(--line);font-family:var(--mono);font-size:11px;letter-spacing:.06em;color:var(--dim2);display:flex;gap:16px;flex-wrap:wrap;animation:fade .6s .5s both}
|
| 245 |
+
footer .b{color:var(--dim)}footer .sp{margin-left:auto}
|
| 246 |
+
footer a{color:var(--dim);text-decoration:none}footer a:hover{color:var(--grit)}
|
| 247 |
+
@keyframes fade{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
|
| 248 |
+
@keyframes slidein{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
|
| 249 |
+
@keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-6px);opacity:1}}
|
| 250 |
+
</style></head>
|
| 251 |
+
<body><div class="wrap">
|
| 252 |
+
<header>
|
| 253 |
+
<div class="mark"><svg width="38" height="38" viewBox="0 0 38 38" fill="none">
|
| 254 |
+
<rect x="1" y="1" width="36" height="36" rx="2" stroke="#2b303c"/>
|
| 255 |
+
<path d="M27 12.5A9 9 0 1 0 28 22H19" stroke="#ff5a2a" stroke-width="2.4" stroke-linecap="square"/>
|
| 256 |
+
<rect x="10.5" y="10.5" width="3" height="3" fill="#ff5a2a"/>
|
| 257 |
+
</svg></div>
|
| 258 |
+
<div class="brand"><div class="co">GRIT<b>AI</b></div><div class="sub">Tool-Using Agent</div></div>
|
| 259 |
+
<div class="tags"><span class="tag hot">▸ Live</span><span class="tag">SDVOSB</span><span class="tag">Lawton OK</span></div>
|
| 260 |
+
</header>
|
| 261 |
+
<section class="hero">
|
| 262 |
+
<h1>Ask it anything. It <em>calls real tools</em> to answer.</h1>
|
| 263 |
+
<p>A calculator, a clock, live weather, and Wikipedia — the agent decides what to call, runs it, and shows its work. Not a chatbot guessing. An operator.</p>
|
| 264 |
+
</section>
|
| 265 |
+
<div class="sec"><span class="num">01</span><span class="name">Ask</span><span class="rule"></span></div>
|
| 266 |
+
<div class="ask">
|
| 267 |
+
<div class="field">
|
| 268 |
+
<span class="car">>_</span>
|
| 269 |
+
<input id="q" placeholder="What's a 15% tip on $47.80, and the current weather in Paris?" autofocus>
|
| 270 |
+
<button class="run" id="go" onclick="ask()">Run ▸</button>
|
| 271 |
+
</div>
|
| 272 |
+
<div class="ex" id="ex"></div>
|
| 273 |
+
</div>
|
| 274 |
+
<div class="out" id="out">
|
| 275 |
+
<div class="sec"><span class="num">02</span><span class="name">Trace — live tool calls</span><span class="rule"></span></div>
|
| 276 |
+
<div class="trace"><div class="log" id="trace"></div></div>
|
| 277 |
+
<div class="sec"><span class="num">03</span><span class="name">Answer</span><span class="rule"></span></div>
|
| 278 |
+
<div class="ans" id="answer"></div>
|
| 279 |
+
</div>
|
| 280 |
+
<footer>
|
| 281 |
+
<span class="b">ReAct loop</span><span>·</span><span>keyless tools — Open-Meteo + Wikipedia</span>
|
| 282 |
+
<span class="sp"><a href="https://gritai.solutions">GRITAI SOLUTIONS</a> · 30-in-15 №9</span>
|
| 283 |
+
</footer>
|
| 284 |
+
</div><script>
|
| 285 |
+
const EXAMPLES=["Who invented the World Wide Web, and what's the square root of 4096?",
|
| 286 |
+
"What's the weather in Tokyo, and the current UTC time?",
|
| 287 |
+
"Summarize what an octopus is, then give me a 12% tip on $86."];
|
| 288 |
+
const $=id=>document.getElementById(id);
|
| 289 |
+
const q=$('q'),go=$('go'),out=$('out');
|
| 290 |
+
function esc(s){return String(s==null?'':s).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]));}
|
| 291 |
+
$('ex').innerHTML=EXAMPLES.map(e=>'<span class="chip"><span class="pt">↳</span>'+esc(e)+'</span>').join('');
|
| 292 |
+
$('ex').querySelectorAll('.chip').forEach(c=>c.onclick=()=>{q.value=c.textContent.replace(/^↳\s*/,'');ask();});
|
| 293 |
+
function argStr(o){try{return Object.values(o).join(', ');}catch(e){return '';}}
|
| 294 |
+
function ask(){if(go.disabled)return;const text=q.value.trim();if(!text){q.focus();return;}
|
| 295 |
+
go.disabled=true;go.textContent='…';out.classList.add('show');
|
| 296 |
+
$('trace').innerHTML='<div class="spin"><span></span><span></span><span></span></div>';$('answer').innerHTML='';
|
| 297 |
+
fetch('/api/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:text})})
|
| 298 |
+
.then(r=>r.json()).then(d=>{
|
| 299 |
+
if(d.error){$('trace').innerHTML='<div class="row none"><span class="mk">!</span><span class="tn">error</span><span class="rd">'+esc(d.error)+'</span></div>';return;}
|
| 300 |
+
const t=d.trace||[];
|
| 301 |
+
$('trace').innerHTML=t.length?t.map(s=>'<div class="row"><span class="mk">»</span><span class="tn">'+esc(s.tool)+'</span><span class="rd"><span class="arg">'+esc(argStr(s.input))+'</span> → '+esc(s.result)+'</span></div>').join(''):
|
| 302 |
+
'<div class="row none"><span class="mk">·</span><span class="tn">direct</span><span class="rd">answered directly — no tools needed</span></div>';
|
| 303 |
+
$('answer').innerHTML=String(d.answer||'').split(/\\n\\n+/).map(p=>'<p>'+esc(p).replace(/\\n/g,'<br>')+'</p>').join('');
|
| 304 |
+
}).catch(()=>{$('trace').innerHTML='<div class="row none"><span class="mk">!</span><span class="tn">error</span><span class="rd">Something went wrong — please try again.</span></div>';})
|
| 305 |
+
.finally(()=>{go.disabled=false;go.textContent='Run ▸';});
|
| 306 |
+
}
|
| 307 |
+
q.addEventListener('keydown',e=>{if(e.key==='Enter')ask();});
|
| 308 |
+
</script></body></html>"""
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
if __name__ == "__main__":
|
| 312 |
+
backend = "Claude API" if ANTHROPIC_KEY else "NO KEY (set ANTHROPIC_API_KEY)"
|
| 313 |
+
print(f"Tool-Using Agent on http://127.0.0.1:{PORT} [backend: {backend}]", flush=True)
|
| 314 |
+
app.run(host="0.0.0.0", port=PORT, threaded=True)
|