Spaces:
Running
Running
#9 Tool-Using Agent — Flask + Claude ReAct loop (private validation build)
Browse files- .env.example +4 -0
- .gitignore +6 -0
- Dockerfile +9 -0
- README.md +43 -5
- app.py +262 -0
- requirements.txt +3 -0
.env.example
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Claude API key — required (the whole app is a function-calling / tool-use loop).
|
| 2 |
+
ANTHROPIC_API_KEY=sk-ant-...
|
| 3 |
+
ANTHROPIC_MODEL=claude-haiku-4-5
|
| 4 |
+
# The tools themselves (weather, Wikipedia) are keyless — no other secrets needed.
|
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.venv/
|
| 5 |
+
venv/
|
| 6 |
+
*.log
|
Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tool-Using Agent — runs on Hugging Face Spaces, Render, Railway, Fly.io, etc.
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
COPY . .
|
| 7 |
+
ENV PORT=7860
|
| 8 |
+
EXPOSE 7860
|
| 9 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
|
@@ -1,10 +1,48 @@
|
|
| 1 |
---
|
| 2 |
-
title: Tool
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Tool-Using Agent
|
| 3 |
+
emoji: 🛠️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
+
short_description: An AI agent that calls live tools (ReAct) · 30-in-15 #9
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Tool-Using Agent 🛠️
|
| 13 |
+
|
| 14 |
+
Ask a question and watch the AI **call real, live tools** to answer it — a calculator, the current
|
| 15 |
+
date/time, live **weather**, and **Wikipedia** — running the **ReAct** loop (decide → call a tool →
|
| 16 |
+
read the result → repeat) and showing every tool call it made.
|
| 17 |
+
|
| 18 |
+
> Project **#9** of my *"30 AI Projects in 15 Days"* build-in-public challenge.
|
| 19 |
+
|
| 20 |
+
**▶ Live demo: https://agent.gritai.solutions**
|
| 21 |
+
|
| 22 |
+

|
| 23 |
+
|
| 24 |
+
## Try
|
| 25 |
+
- *"What's a 15% tip on $47.80, and what's the weather in Paris?"* → calculator + weather
|
| 26 |
+
- *"Who invented the World Wide Web, and how many days ago was Jan 1 2000?"* → Wikipedia + date + calc
|
| 27 |
+
|
| 28 |
+
## How it works
|
| 29 |
+
- The model is given four **keyless** tools (Open-Meteo for weather, MediaWiki for Wikipedia, plus a
|
| 30 |
+
safe calculator and a clock). It decides which to call — possibly several — and the server executes
|
| 31 |
+
them and feeds results back, looping until the model can answer (capped at a few steps).
|
| 32 |
+
- **Transparency:** the UI shows the exact tool calls and their live results, so you can see the
|
| 33 |
+
reasoning, not just the answer.
|
| 34 |
+
- The calculator is a **safe AST evaluator** (no `eval`), limited to arithmetic + a few math functions.
|
| 35 |
+
|
| 36 |
+
## Run locally
|
| 37 |
+
```bash
|
| 38 |
+
pip install -r requirements.txt
|
| 39 |
+
export ANTHROPIC_API_KEY=sk-ant-...
|
| 40 |
+
python app.py # http://127.0.0.1:7860
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Deploy (always-on)
|
| 44 |
+
Ships with a `Dockerfile` — works on **Hugging Face Spaces**, Render, Railway, or Fly.io.
|
| 45 |
+
Set `ANTHROPIC_API_KEY` as a secret. The tools need no other keys.
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
Built by **Robert Lucyk** · [GritAI Solutions](https://gritai.solutions) · part of the 30-in-15 challenge.
|
app.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""
|
| 13 |
+
import os, ast, json, math, operator, datetime, urllib.parse
|
| 14 |
+
from flask import Flask, request, jsonify, Response
|
| 15 |
+
import requests
|
| 16 |
+
|
| 17 |
+
PORT = int(os.environ.get("PORT", "7860"))
|
| 18 |
+
ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY")
|
| 19 |
+
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5")
|
| 20 |
+
MAX_STEPS = 6
|
| 21 |
+
UA = {"User-Agent": "GritAI-ToolAgent/1.0 (https://gritai.solutions)"}
|
| 22 |
+
|
| 23 |
+
# --------------------------------------------------------------------------- tools
|
| 24 |
+
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
| 25 |
+
ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Mod: operator.mod,
|
| 26 |
+
ast.FloorDiv: operator.floordiv, ast.USub: operator.neg, ast.UAdd: operator.pos}
|
| 27 |
+
_FUNCS = {"sqrt": math.sqrt, "abs": abs, "round": round, "log": math.log, "log10": math.log10,
|
| 28 |
+
"sin": math.sin, "cos": math.cos, "tan": math.tan, "pi": math.pi, "e": math.e,
|
| 29 |
+
"floor": math.floor, "ceil": math.ceil, "exp": math.exp, "min": min, "max": max}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _safe_eval(node):
|
| 33 |
+
if isinstance(node, ast.Constant):
|
| 34 |
+
if isinstance(node.value, (int, float)):
|
| 35 |
+
return node.value
|
| 36 |
+
raise ValueError("only numbers")
|
| 37 |
+
if isinstance(node, ast.BinOp):
|
| 38 |
+
return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
| 39 |
+
if isinstance(node, ast.UnaryOp):
|
| 40 |
+
return _OPS[type(node.op)](_safe_eval(node.operand))
|
| 41 |
+
if isinstance(node, ast.Name):
|
| 42 |
+
if node.id in _FUNCS:
|
| 43 |
+
return _FUNCS[node.id]
|
| 44 |
+
raise ValueError(f"unknown name {node.id}")
|
| 45 |
+
if isinstance(node, ast.Call):
|
| 46 |
+
fn = _FUNCS.get(getattr(node.func, "id", ""))
|
| 47 |
+
if not callable(fn):
|
| 48 |
+
raise ValueError("unknown function")
|
| 49 |
+
return fn(*[_safe_eval(a) for a in node.args])
|
| 50 |
+
raise ValueError("unsupported expression")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def tool_calculator(expression):
|
| 54 |
+
try:
|
| 55 |
+
val = _safe_eval(ast.parse(str(expression), mode="eval").body)
|
| 56 |
+
return f"{expression} = {val}"
|
| 57 |
+
except Exception as e:
|
| 58 |
+
return f"Could not evaluate '{expression}': {e}"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def tool_datetime(timezone="UTC"):
|
| 62 |
+
now = datetime.datetime.now(datetime.timezone.utc)
|
| 63 |
+
return f"Current UTC date/time: {now.strftime('%A, %d %B %Y, %H:%M UTC')}"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
_WMO = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "rime fog",
|
| 67 |
+
51: "light drizzle", 53: "drizzle", 55: "dense drizzle", 61: "light rain", 63: "rain",
|
| 68 |
+
65: "heavy rain", 71: "light snow", 73: "snow", 75: "heavy snow", 80: "rain showers",
|
| 69 |
+
81: "rain showers", 82: "violent rain showers", 95: "thunderstorm", 96: "thunderstorm w/ hail"}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def tool_weather(location):
|
| 73 |
+
try:
|
| 74 |
+
g = requests.get("https://geocoding-api.open-meteo.com/v1/search",
|
| 75 |
+
params={"name": location, "count": 1}, headers=UA, timeout=15).json()
|
| 76 |
+
if not g.get("results"):
|
| 77 |
+
return f"No location found for '{location}'."
|
| 78 |
+
r = g["results"][0]
|
| 79 |
+
lat, lon = r["latitude"], r["longitude"]
|
| 80 |
+
place = ", ".join(filter(None, [r.get("name"), r.get("admin1"), r.get("country")]))
|
| 81 |
+
w = requests.get("https://api.open-meteo.com/v1/forecast",
|
| 82 |
+
params={"latitude": lat, "longitude": lon,
|
| 83 |
+
"current": "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m"},
|
| 84 |
+
headers=UA, timeout=15).json()
|
| 85 |
+
c = w.get("current", {})
|
| 86 |
+
desc = _WMO.get(c.get("weather_code"), "unknown")
|
| 87 |
+
return (f"Weather in {place}: {c.get('temperature_2m')}°C, {desc}, "
|
| 88 |
+
f"humidity {c.get('relative_humidity_2m')}%, wind {c.get('wind_speed_10m')} km/h.")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
return f"Weather lookup failed: {e}"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def tool_wikipedia(query):
|
| 94 |
+
try:
|
| 95 |
+
s = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 96 |
+
params={"action": "query", "list": "search", "srsearch": query,
|
| 97 |
+
"format": "json", "srlimit": 1}).json()
|
| 98 |
+
hits = s.get("query", {}).get("search", [])
|
| 99 |
+
if not hits:
|
| 100 |
+
return f"No Wikipedia article found for '{query}'."
|
| 101 |
+
title = hits[0]["title"]
|
| 102 |
+
e = requests.get("https://en.wikipedia.org/w/api.php", headers=UA, timeout=15,
|
| 103 |
+
params={"action": "query", "prop": "extracts", "exintro": 1, "explaintext": 1,
|
| 104 |
+
"titles": title, "format": "json"}).json()
|
| 105 |
+
pages = e.get("query", {}).get("pages", {})
|
| 106 |
+
extract = next(iter(pages.values()), {}).get("extract", "")
|
| 107 |
+
return f"Wikipedia — {title}: {extract[:800]}" if extract else f"Found '{title}' but no summary."
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return f"Wikipedia lookup failed: {e}"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
TOOLS_SPEC = [
|
| 113 |
+
{"name": "calculator", "description": "Evaluate an arithmetic expression. Supports + - * / ** % and "
|
| 114 |
+
"sqrt, log, sin, cos, tan, floor, ceil, abs, round, pi, e.",
|
| 115 |
+
"input_schema": {"type": "object", "properties": {"expression": {"type": "string"}},
|
| 116 |
+
"required": ["expression"]}},
|
| 117 |
+
{"name": "current_datetime", "description": "Get the current date and time (UTC).",
|
| 118 |
+
"input_schema": {"type": "object", "properties": {"timezone": {"type": "string"}}}},
|
| 119 |
+
{"name": "weather", "description": "Get the current weather for a city/place name (live).",
|
| 120 |
+
"input_schema": {"type": "object", "properties": {"location": {"type": "string"}},
|
| 121 |
+
"required": ["location"]}},
|
| 122 |
+
{"name": "wikipedia", "description": "Look up a topic on Wikipedia and get a summary (live).",
|
| 123 |
+
"input_schema": {"type": "object", "properties": {"query": {"type": "string"}},
|
| 124 |
+
"required": ["query"]}},
|
| 125 |
+
]
|
| 126 |
+
EXECUTORS = {"calculator": tool_calculator, "current_datetime": tool_datetime,
|
| 127 |
+
"weather": tool_weather, "wikipedia": tool_wikipedia}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def run_agent(question):
|
| 131 |
+
import anthropic
|
| 132 |
+
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
| 133 |
+
sysp = ("You are a helpful assistant that answers using the provided tools whenever they help. "
|
| 134 |
+
"Call tools to get live/precise data instead of guessing. You may call multiple tools. "
|
| 135 |
+
"When you have enough, give a clear, concise final answer.")
|
| 136 |
+
msgs = [{"role": "user", "content": question}]
|
| 137 |
+
trace = []
|
| 138 |
+
for _ in range(MAX_STEPS):
|
| 139 |
+
r = client.messages.create(model=ANTHROPIC_MODEL, max_tokens=1024, system=sysp,
|
| 140 |
+
tools=TOOLS_SPEC, messages=msgs)
|
| 141 |
+
if r.stop_reason == "tool_use":
|
| 142 |
+
msgs.append({"role": "assistant", "content": r.content})
|
| 143 |
+
results = []
|
| 144 |
+
for b in r.content:
|
| 145 |
+
if b.type == "tool_use":
|
| 146 |
+
out = EXECUTORS.get(b.name, lambda **k: "unknown tool")(**b.input)
|
| 147 |
+
trace.append({"tool": b.name, "input": b.input, "result": out[:400]})
|
| 148 |
+
results.append({"type": "tool_result", "tool_use_id": b.id, "content": out})
|
| 149 |
+
msgs.append({"role": "user", "content": results})
|
| 150 |
+
else:
|
| 151 |
+
text = "".join(b.text for b in r.content if b.type == "text")
|
| 152 |
+
return text.strip(), trace
|
| 153 |
+
return "I reached the step limit before finishing — try a simpler question.", trace
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
app = Flask(__name__)
|
| 157 |
+
app.config["MAX_CONTENT_LENGTH"] = 512 * 1024
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@app.route("/")
|
| 161 |
+
def home():
|
| 162 |
+
return Response(PAGE, mimetype="text/html")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@app.route("/api/ask", methods=["POST"])
|
| 166 |
+
def api_ask():
|
| 167 |
+
q = (request.get_json(force=True).get("question") or "").strip()[:1000]
|
| 168 |
+
if not q:
|
| 169 |
+
return jsonify(error="Ask a question."), 400
|
| 170 |
+
if not ANTHROPIC_KEY:
|
| 171 |
+
return jsonify(error="Set ANTHROPIC_API_KEY on the server to run the agent."), 200
|
| 172 |
+
try:
|
| 173 |
+
answer, trace = run_agent(q)
|
| 174 |
+
except Exception as e:
|
| 175 |
+
import sys; print("agent error:", repr(e), file=sys.stderr, flush=True)
|
| 176 |
+
return jsonify(error="The agent hit an error — please try again."), 200
|
| 177 |
+
return jsonify(answer=answer, trace=trace)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
|
| 181 |
+
<title>Tool-Using Agent</title>
|
| 182 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 183 |
+
<style>
|
| 184 |
+
:root{--primary:#4f46e5;--accent:#7c3aed;--ink:#171633;--bg:#f1f0fb;--card:#fff;--muted:#6b6a89;--line:#e5e3f5}
|
| 185 |
+
*{box-sizing:border-box}html,body{height:100%}
|
| 186 |
+
body{margin:0;font-family:'Segoe UI',system-ui,-apple-system,sans-serif;color:var(--ink);
|
| 187 |
+
background:radial-gradient(140% 90% at 50% 0%,#fff,var(--bg) 60%);display:flex;justify-content:center}
|
| 188 |
+
.app{width:100%;max-width:820px;min-height:100dvh;display:flex;flex-direction:column;padding:0 16px}
|
| 189 |
+
header{padding:26px 4px 12px;display:flex;align-items:center;gap:13px}
|
| 190 |
+
.hic{width:46px;height:46px;border-radius:13px;display:grid;place-items:center;font-size:23px;flex:none;color:#fff;
|
| 191 |
+
background:linear-gradient(135deg,var(--primary),var(--accent));box-shadow:0 10px 26px -10px rgba(79,70,229,.6)}
|
| 192 |
+
header h1{margin:0;font-size:23px;font-weight:800;letter-spacing:-.4px}
|
| 193 |
+
header p{margin:2px 0 0;color:var(--muted);font-size:13.5px}
|
| 194 |
+
.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:16px;box-shadow:0 6px 22px rgba(23,22,51,.05)}
|
| 195 |
+
.inrow{display:flex;gap:10px}
|
| 196 |
+
#q{flex:1;border:0;outline:none;font-size:15px;color:var(--ink);font-family:inherit;background:transparent;padding:4px}
|
| 197 |
+
.go{border:0;border-radius:12px;padding:11px 22px;font-size:15px;font-weight:600;cursor:pointer;color:#fff;background:linear-gradient(135deg,var(--primary),var(--accent));transition:.15s}
|
| 198 |
+
.go:hover{filter:brightness(1.08)}.go:disabled{opacity:.5;cursor:default}
|
| 199 |
+
.ex{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
|
| 200 |
+
.chip{background:var(--card);border:1px solid var(--line);border-radius:20px;padding:7px 12px;font-size:12px;cursor:pointer;transition:.15s;color:var(--muted)}
|
| 201 |
+
.chip:hover{border-color:var(--accent);color:var(--accent)}
|
| 202 |
+
.out{margin:18px 0;display:none}.out.show{display:block}
|
| 203 |
+
.trace{margin-bottom:14px}
|
| 204 |
+
.step{display:flex;gap:10px;align-items:flex-start;font-size:13px;padding:9px 12px;border:1px solid var(--line);border-radius:11px;margin-bottom:8px;background:#faf9ff}
|
| 205 |
+
.step .tn{font-weight:700;color:var(--primary);font-family:ui-monospace,monospace;font-size:12px;white-space:nowrap}
|
| 206 |
+
.step .ta{color:var(--ink)}.step .tr{color:var(--muted);margin-top:3px}
|
| 207 |
+
.answer{font-size:16px;line-height:1.6;white-space:pre-wrap}
|
| 208 |
+
.lbl{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);font-weight:600;margin:0 2px 8px}
|
| 209 |
+
.spin{display:inline-flex;gap:6px;padding:14px 2px}.spin span{width:9px;height:9px;border-radius:50%;background:var(--accent);opacity:.5;animation:bd 1.2s infinite}
|
| 210 |
+
.spin span:nth-child(2){animation-delay:.2s}.spin span:nth-child(3){animation-delay:.4s}
|
| 211 |
+
@keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-6px);opacity:1}}
|
| 212 |
+
.foot{text-align:center;font-size:10.5px;color:var(--muted);padding:16px 0 22px}.foot b{color:#4a487a}
|
| 213 |
+
</style></head>
|
| 214 |
+
<body><div class="app">
|
| 215 |
+
<header><div class="hic">🛠️</div><div><h1>Tool-Using Agent</h1>
|
| 216 |
+
<p>Ask anything — it calls live tools (calculator, weather, Wikipedia, clock) and shows its work.</p></div></header>
|
| 217 |
+
<div class="card">
|
| 218 |
+
<div class="inrow">
|
| 219 |
+
<input id="q" placeholder="e.g. What's a 15% tip on $47.80, and the weather in Paris?" autofocus>
|
| 220 |
+
<button class="go" id="go" onclick="ask()">Ask →</button>
|
| 221 |
+
</div>
|
| 222 |
+
<div class="ex" id="ex"></div>
|
| 223 |
+
</div>
|
| 224 |
+
<div class="out" id="out">
|
| 225 |
+
<div class="trace" id="trace"></div>
|
| 226 |
+
<div class="lbl">Answer</div>
|
| 227 |
+
<div class="card"><div class="answer" id="answer"></div></div>
|
| 228 |
+
</div>
|
| 229 |
+
<div class="foot">ReAct loop · live keyless tools (Open-Meteo + Wikipedia) · <b>GritAI</b></div>
|
| 230 |
+
</div><script>
|
| 231 |
+
const EXAMPLES=["What's a 15% tip on $47.80, and what's the weather in Paris?",
|
| 232 |
+
"Who invented the World Wide Web, and how many days ago was Jan 1 2000?",
|
| 233 |
+
"What's the square root of 20736, and what's the weather in Tokyo?",
|
| 234 |
+
"Summarize what an octopus is, then tell me the current UTC time."];
|
| 235 |
+
const TICON={calculator:'🧮',current_datetime:'🕐',weather:'🌦️',wikipedia:'📚'};
|
| 236 |
+
const $=id=>document.getElementById(id);
|
| 237 |
+
const q=$('q'),go=$('go'),out=$('out');
|
| 238 |
+
function esc(s){return String(s==null?'':s).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]));}
|
| 239 |
+
$('ex').innerHTML=EXAMPLES.map(e=>'<span class="chip">'+esc(e)+'</span>').join('');
|
| 240 |
+
$('ex').querySelectorAll('.chip').forEach(c=>c.onclick=()=>{q.value=c.textContent;ask();});
|
| 241 |
+
function ask(){if(go.disabled)return;const text=q.value.trim();if(!text){q.focus();return;}
|
| 242 |
+
go.disabled=true;go.textContent='Thinking…';out.classList.add('show');
|
| 243 |
+
$('trace').innerHTML='<span class="spin"><span></span><span></span><span></span></span>';$('answer').textContent='';
|
| 244 |
+
fetch('/api/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:text})})
|
| 245 |
+
.then(r=>r.json()).then(d=>{
|
| 246 |
+
if(d.error){$('trace').innerHTML='';$('answer').textContent=d.error;return;}
|
| 247 |
+
$('trace').innerHTML=(d.trace||[]).map(s=>{const ic=TICON[s.tool]||'🔧';
|
| 248 |
+
return '<div class="step"><div class="tn">'+ic+' '+esc(s.tool)+'</div><div><div class="ta">'+
|
| 249 |
+
esc(JSON.stringify(s.input))+'</div><div class="tr">→ '+esc(s.result)+'</div></div></div>';}).join('')||
|
| 250 |
+
'<div class="step"><div class="tr">(answered directly, no tools needed)</div></div>';
|
| 251 |
+
$('answer').textContent=d.answer;
|
| 252 |
+
}).catch(()=>{$('trace').innerHTML='';$('answer').textContent='Something went wrong — please try again.';})
|
| 253 |
+
.finally(()=>{go.disabled=false;go.textContent='Ask →';});
|
| 254 |
+
}
|
| 255 |
+
q.addEventListener('keydown',e=>{if(e.key==='Enter')ask();});
|
| 256 |
+
</script></body></html>"""
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
backend = "Claude API" if ANTHROPIC_KEY else "NO KEY (set ANTHROPIC_API_KEY)"
|
| 261 |
+
print(f"Tool-Using Agent on http://127.0.0.1:{PORT} [backend: {backend}]", flush=True)
|
| 262 |
+
app.run(host="0.0.0.0", port=PORT, threaded=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask>=3.0
|
| 2 |
+
requests>=2.31
|
| 3 |
+
anthropic>=0.40
|