File size: 25,724 Bytes
7110676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36ca344
7110676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c9d797
 
 
 
 
 
 
 
 
 
 
7110676
36ca344
7110676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env python
"""RAG Q&A with Citations β€” ask a question, get an answer grounded ONLY in a curated
construction & remodeling knowledge base, with inline [n] citations to the exact sources β€”
and an honest "I couldn't find that in the knowledge base" when the answer isn't there.

Real RAG: chunk -> embed (fastembed, ONNX/CPU, no torch) -> retrieve (cosine) -> Claude answers
from the retrieved sources only, citing each. No hallucinating past the sources.

  pip install flask requests anthropic fastembed numpy
  python app.py            # http://127.0.0.1:7860

Project #10 of the "30 Projects in 15 Days" challenge β€” GritAI.
"""
import os, re, json
import numpy as np
from flask import Flask, request, jsonify, Response

PORT = int(os.environ.get("PORT", "7860"))
ANTHROPIC_KEY = (os.environ.get("ANTHROPIC_API_KEY") or "").strip() or None
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5")
TOP_K = 4

# ============================ Construction & Remodeling KB ============================
# General, public industry knowledge (no proprietary data). Each entry is a citable source.
KB = [
 {"t": "Do I need a building permit?",
  "x": "Most structural, electrical, plumbing, and mechanical work requires a permit from your local "
       "building department β€” including additions, removing or moving walls, new circuits, water-heater "
       "replacement, decks over a certain height, and re-roofing in many areas. Cosmetic work (paint, "
       "flooring, cabinets, fixtures that reuse existing connections) usually does not. Permits exist to "
       "ensure work meets code and passes inspection; unpermitted work can cause problems when you sell. "
       "When unsure, call your local building department and ask β€” it's free."},
 {"t": "How permits and inspections work",
  "x": "You (or your licensed contractor) submit plans and pay a fee; the department issues the permit; "
       "work is done in phases with inspections at key points β€” typically a rough-in inspection (framing, "
       "electrical, plumbing before walls are closed) and a final inspection when complete. Don't cover "
       "walls until the rough-in passes. Keep the permit posted on site. Final sign-off closes the permit."},
 {"t": "Hiring a contractor: licenses and insurance",
  "x": "Verify the contractor holds a current state license for the trade and carries liability insurance "
       "and workers' compensation. Ask for the license number and confirm it with your state licensing "
       "board. Uninsured workers injured on your property can become your liability. For larger jobs, a "
       "general contractor coordinates subcontractors and pulls permits."},
 {"t": "Getting and comparing bids",
  "x": "Get at least three written bids for the same defined scope so they're comparable. A good bid itemizes "
       "labor, materials, permits, timeline, and payment schedule. Be wary of a bid far below the others β€” it "
       "often means missing scope or corners cut. Don't automatically pick the lowest; weigh reputation, "
       "references, and clarity."},
 {"t": "Contracts, deposits, and payment schedules",
  "x": "Always use a written contract listing scope, materials, price, start/finish dates, and a payment "
       "schedule tied to milestones. A common structure is a modest deposit, progress payments as phases "
       "complete, and a final payment after the work passes inspection and you're satisfied. Avoid paying "
       "large sums up front; never pay in full before work is done."},
 {"t": "Mechanic's liens and lien waivers",
  "x": "If a contractor or supplier isn't paid, they can file a mechanic's lien against your property even if "
       "you paid your general contractor. Protect yourself by requesting lien waivers from subcontractors and "
       "suppliers as they're paid, confirming the money reached them."},
 {"t": "Budgeting and the contingency fund",
  "x": "Set aside a contingency of 10–20% of the project budget for surprises β€” older homes especially hide "
       "problems (outdated wiring, water damage, non-code framing) behind the walls. Renovations frequently "
       "run over when hidden conditions surface; the contingency keeps a surprise from stalling the job."},
 {"t": "Kitchen remodel: scope, cost drivers, and timeline",
  "x": "Kitchens are among the most expensive rooms to remodel because they combine cabinetry, countertops, "
       "appliances, plumbing, electrical, and often flooring. Cabinetry and countertops are usually the "
       "biggest line items. Moving plumbing or gas lines and relocating walls adds significant cost. A typical "
       "mid-range kitchen remodel runs several weeks to a couple of months depending on scope and lead times "
       "on custom cabinets."},
 {"t": "Bathroom remodel basics",
  "x": "Bathrooms pack plumbing, waterproofing, tile, ventilation, and electrical into a small space, so labor "
       "per square foot is high. Proper waterproofing behind tile in showers is critical to prevent hidden "
       "rot and mold. A quality exhaust fan vented outside (not into the attic) prevents moisture damage. "
       "Moving the toilet, tub, or shower drain locations raises cost because it means opening the floor."},
 {"t": "Flooring options compared",
  "x": "Common choices: hardwood (durable, refinishable, higher cost, sensitive to moisture); engineered wood "
       "(more moisture-stable, thinner wear layer); luxury vinyl plank/LVP (waterproof, budget-friendly, great "
       "for kitchens/baths/basements); tile (very durable and waterproof, harder and colder underfoot); and "
       "carpet (soft and cheap, wears faster). Match the material to the room's moisture and traffic."},
 {"t": "Interior painting: prep and product",
  "x": "A lasting paint job is 80% prep: clean surfaces, fill and sand holes, caulk gaps, and prime bare or "
       "patched areas and stains. Use the right sheen β€” flat/matte hides wall flaws, eggshell/satin is a good "
       "durable middle for most walls, and semi-gloss resists moisture on trim, kitchens, and baths. One "
       "gallon covers roughly 350–400 square feet per coat; most jobs need two coats."},
 {"t": "Drywall: hanging, taping, and patching",
  "x": "Standard wall drywall is Β½ inch; ceilings often use 5/8 inch to resist sagging. Screw to the studs, "
       "then tape and apply three coats of joint compound, sanding between coats for a smooth, feathered seam. "
       "Small holes are patched with mesh or a patch kit and compound; large holes need a backed drywall "
       "patch. Use moisture-resistant board in wet areas."},
 {"t": "Framing and load-bearing walls",
  "x": "Walls are framed with studs spaced 16 inches on-center (sometimes 24). A load-bearing wall carries "
       "weight from above (roof, upper floors) down to the foundation; removing or altering one requires a "
       "properly sized beam and usually an engineer and a permit. Never remove a wall without confirming "
       "whether it's load-bearing β€” getting this wrong is dangerous."},
 {"t": "Roofing: materials and when to replace",
  "x": "Asphalt shingles are the most common and last roughly 15–30 years depending on quality; metal roofs "
       "last longer at a higher cost. Signs you need a new roof include curling or missing shingles, granules "
       "collecting in gutters, daylight or leaks in the attic, and sagging. Re-roofing usually needs a permit "
       "and an inspection."},
 {"t": "Insulation and energy efficiency (R-value)",
  "x": "Insulation is rated by R-value β€” higher means more resistance to heat flow. Attics benefit most from "
       "added insulation and are usually the cheapest place to improve efficiency. Air-sealing gaps and leaks "
       "before insulating matters as much as the insulation itself. Common types include fiberglass batts, "
       "blown-in cellulose, and spray foam (higher cost, also air-seals)."},
 {"t": "Electrical basics and when to call a pro",
  "x": "Simple like-for-like swaps (a switch or outlet) are often DIY, but new circuits, panel work, and "
       "anything you're unsure about should go to a licensed electrician and be permitted. Kitchens, baths, "
       "garages, and outdoors require GFCI protection; many circuits now require AFCI breakers. Never work on "
       "a live circuit β€” shut off the breaker and verify it's dead."},
 {"t": "Plumbing basics and rough-in",
  "x": "Plumbing is installed in two stages: the rough-in (supply and drain lines inside the walls and floor, "
       "inspected before closing up) and the finish (fixtures and trim). Proper drain slope (about ΒΌ inch per "
       "foot) and venting are required for drains to flow and to keep sewer gas out. Relocating fixtures means "
       "opening walls or floors, which drives cost."},
 {"t": "Decks: footings, materials, and permits",
  "x": "Decks generally need a permit and rest on footings dug below the local frost line so they don't heave. "
       "Materials range from pressure-treated lumber (cheapest) to cedar to composite (low-maintenance, higher "
       "cost). Proper flashing where the deck ledger meets the house prevents rot and is a common failure "
       "point. Railings and stair dimensions are code-regulated for safety."},
 {"t": "Concrete and foundation cracks",
  "x": "Thin, hairline cracks in concrete are common from normal curing and shrinkage and are usually cosmetic. "
       "Warning signs that need a professional include cracks wider than about ΒΌ inch, horizontal cracks in "
       "foundation walls, cracks that are growing, or doors and windows that suddenly stick β€” these can signal "
       "settlement or structural movement."},
 {"t": "HVAC sizing and maintenance",
  "x": "Heating and cooling equipment must be correctly sized for the home β€” an oversized system short-cycles "
       "and controls humidity poorly, while undersized struggles to keep up. Sizing is done with a load "
       "calculation (Manual J), not a rule of thumb. Basic maintenance β€” changing filters regularly and an "
       "annual service β€” extends equipment life and efficiency."},
 {"t": "Older homes: lead paint and asbestos",
  "x": "Homes built before 1978 may contain lead-based paint, and homes from roughly the 1980s and earlier may "
       "contain asbestos in flooring, popcorn ceilings, insulation, and duct wrap. Disturbing these during a "
       "remodel releases hazardous dust. Testing before demolition and using certified abatement pros for "
       "removal is the safe, and often legally required, path."},
 {"t": "Project phases and realistic timelines",
  "x": "A typical renovation flows through phases: design and permitting, demolition, rough-in (framing, "
       "electrical, plumbing, HVAC) with inspections, insulation and drywall, then finishes (paint, flooring, "
       "cabinets, trim, fixtures) and a final inspection. Material lead times β€” especially custom cabinets, "
       "windows, and specialty tile β€” often drive the schedule more than the labor does."},
 {"t": "Return on investment of common projects",
  "x": "Not all projects return equal value at resale. Curb-appeal and maintenance items (a new front door, "
       "garage door, fresh paint, and minor kitchen and bath updates) tend to recoup a larger share of their "
       "cost than high-end additions. Over-improving beyond the neighborhood's price range rarely pays back "
       "the full investment."},
]

# ============================ embeddings + retrieval ============================
_EMB = None
_MAT = None  # normalized KB embedding matrix


def emb_model():
    global _EMB
    if _EMB is None:
        from fastembed import TextEmbedding
        _EMB = TextEmbedding("BAAI/bge-small-en-v1.5")
    return _EMB


def _norm(m):
    n = np.linalg.norm(m, axis=-1, keepdims=True)
    return m / np.clip(n, 1e-8, None)


def build_index():
    global _MAT
    texts = [f"{d['t']}. {d['x']}" for d in KB]
    vecs = np.array(list(emb_model().passage_embed(texts)), dtype=np.float32)
    _MAT = _norm(vecs)


if os.environ.get("SPACE_ID"):     # warm the index at startup on the Space
    try:
        build_index()
        print("[startup] KB index built", flush=True)
    except Exception as _e:
        print(f"[startup] index build failed (will retry on first ask): {_e}", flush=True)


def retrieve(question, k=TOP_K):
    if _MAT is None:
        build_index()
    q = _norm(np.array(list(emb_model().query_embed([question]))[0], dtype=np.float32).reshape(1, -1))[0]
    sims = _MAT @ q
    idx = np.argsort(-sims)[:k]
    return [(int(i), float(sims[i])) for i in idx]


TOOL = {
    "name": "answer",
    "description": "Answer the question using ONLY the provided sources.",
    "input_schema": {"type": "object", "properties": {
        "found": {"type": "boolean", "description": "true only if the sources actually answer the question."},
        "answer": {"type": "string", "description": "The answer, grounded in the sources, with inline citations "
                   "like [1] or [2] pointing to the source numbers used. If found is false, briefly say the "
                   "knowledge base doesn't cover it."},
        "used": {"type": "array", "items": {"type": "integer"}, "description": "Source numbers actually cited."}},
        "required": ["found", "answer", "used"]},
}


def answer_question(question):
    hits = retrieve(question)
    sources = [{"n": i + 1, "title": KB[idx]["t"], "text": KB[idx]["x"], "score": round(sc, 3)}
               for i, (idx, sc) in enumerate(hits)]
    if not ANTHROPIC_KEY:
        return {"found": False, "answer": "Set ANTHROPIC_API_KEY on the server to generate answers.",
                "used": [], "sources": sources}
    block = "\n\n".join(f"[{s['n']}] {s['title']}\n{s['text']}" for s in sources)
    sysp = ("You answer questions about construction and home remodeling using ONLY the numbered SOURCES "
            "provided. Ground every claim in the sources and cite them inline as [n]. If the sources do not "
            "actually contain the answer, set found=false and say the knowledge base doesn't cover it β€” never "
            "guess or use outside knowledge. Be concise and practical.")
    try:
        import requests
        resp = requests.post("https://api.anthropic.com/v1/messages",
            headers={"x-api-key": ANTHROPIC_KEY, "anthropic-version": "2023-06-01",
                     "content-type": "application/json"},
            json={"model": ANTHROPIC_MODEL, "max_tokens": 900, "system": sysp,
                  "tools": [TOOL], "tool_choice": {"type": "tool", "name": "answer"},
                  "messages": [{"role": "user", "content": f"SOURCES:\n{block}\n\nQUESTION: {question}"}]},
            timeout=60)
        resp.raise_for_status()
        content = resp.json().get("content", [])
        data = next((b.get("input") for b in content if b.get("type") == "tool_use"), {}) or {}
    except Exception as e:
        import sys; print("answer error:", type(e).__name__, file=sys.stderr, flush=True)  # no repr β€” never log secrets
        return {"found": False, "answer": "Something went wrong β€” please try again.", "used": [], "sources": sources}
    used = set(data.get("used", []) or [])
    shown = [s for s in sources if s["n"] in used] or (sources if data.get("found") else [])
    return {"found": bool(data.get("found")), "answer": data.get("answer", ""), "used": sorted(used),
            "sources": shown}


app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 256 * 1024


@app.route("/")
def home():
    return Response(PAGE, mimetype="text/html")


@app.route("/api/ask", methods=["POST"])
def api_ask():
    q = (request.get_json(force=True).get("question") or "").strip()[:600]
    if not q:
        return jsonify(error="Ask a question."), 400
    return jsonify(answer_question(q))


PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>GritAI Β· Cited Answers β€” Construction & Remodeling</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@700;800;900&family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root{--bg:#0a0b0e;--bg2:#0e1015;--panel:#111318;--ink:#eef0f4;--dim:#9aa1b0;--dim2:#5f6675;--line:#20242e;--line2:#2b303c;
 --grit:#ff5a2a;--grit2:#ff7d54;--grit-dim:#c9451f;--ok:#5fd08a;
 --disp:'Archivo',system-ui,sans-serif;--body:'IBM Plex Sans',system-ui,sans-serif;--mono:'IBM Plex Mono',ui-monospace,monospace}
*{box-sizing:border-box}html,body{height:100%}
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--body);font-size:15px;line-height:1.6;position:relative;overflow-x:hidden}
body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;background:linear-gradient(0deg,transparent 95%,rgba(255,90,42,.04) 100%),
 repeating-linear-gradient(90deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),repeating-linear-gradient(0deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),radial-gradient(120% 80% at 50% -10%,#141821 0%,var(--bg) 55%)}
.wrap{position:relative;z-index:1;max-width:900px;margin:0 auto;padding:0 28px 70px}
header{display:flex;align-items:center;gap:16px;padding:22px 0 18px;border-bottom:1px solid var(--line);animation:fade .6s .02s both}
.mark{width:38px;height:38px;flex:none}
.brand .co{font-family:var(--disp);font-weight:900;font-size:19px;letter-spacing:.5px}.brand .co b{color:var(--grit)}
.brand .sub{font-family:var(--mono);font-size:10.5px;letter-spacing:.28em;text-transform:uppercase;color:var(--dim2);margin-top:5px}
.tags{margin-left:auto;display:flex;gap:8px}
.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}
.tag.hot{color:var(--grit);border-color:var(--grit-dim)}
.hero{padding:32px 0 24px;animation:fade .6s .12s both}
.hero h1{font-family:var(--disp);font-weight:800;font-size:clamp(28px,4.8vw,46px);line-height:1.03;letter-spacing:-.02em;margin:0;max-width:18ch}
.hero h1 em{font-style:normal;color:var(--grit)}
.hero p{color:var(--dim);max-width:60ch;margin:14px 0 0}
.sec{display:flex;align-items:center;gap:14px;margin:26px 0 12px}
.sec .num{font-family:var(--mono);font-size:11px;font-weight:600;color:var(--grit)}
.sec .name{font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.26em;text-transform:uppercase;color:var(--dim)}
.sec .rule{flex:1;height:1px;background:linear-gradient(90deg,var(--line2),transparent)}
.ask{animation:fade .6s .2s both}
.field{display:flex;align-items:stretch;border:1px solid var(--line2);border-radius:3px;background:var(--panel);overflow:hidden;transition:border-color .18s}
.field:focus-within{border-color:var(--grit-dim)}
.field .car{font-family:var(--mono);color:var(--grit);padding:16px 0 16px 16px;user-select:none}
.field input{flex:1;background:transparent;border:0;outline:none;color:var(--ink);font-family:var(--body);font-size:15.5px;padding:16px 14px}
.field input::placeholder{color:var(--dim2)}
.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}
.run:hover{background:var(--grit2);box-shadow:0 0 26px -4px rgba(255,90,42,.55)}.run:disabled{opacity:.55;cursor:default}
.ex{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
.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}
.chip:hover{color:var(--grit);border-color:var(--grit-dim)}
.out{display:none}.out.show{display:block}
.ans{border:1px solid var(--line2);border-left:2px solid var(--grit);border-radius:3px;background:var(--panel);padding:20px 22px;font-size:16px;line-height:1.65}
.ans.miss{border-left-color:var(--dim2)}
.ans cite,.ct{color:var(--grit);font-family:var(--mono);font-size:.82em;font-weight:600;font-style:normal;vertical-align:super;cursor:pointer;text-decoration:none}
.src{border:1px solid var(--line);border-radius:3px;background:linear-gradient(180deg,var(--panel),var(--bg2))}
.srow{display:grid;grid-template-columns:30px 1fr;gap:0 12px;padding:13px 18px;border-bottom:1px solid var(--line)}
.srow:last-child{border-bottom:0}
.srow .sn{font-family:var(--mono);color:var(--grit);font-weight:600}
.srow .st{font-family:var(--mono);font-weight:600;color:var(--grit2);font-size:13px;margin-bottom:3px}
.srow .sx{color:var(--dim);font-size:13px;line-height:1.55}
.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}
.spin span:nth-child(2){animation-delay:.18s}.spin span:nth-child(3){animation-delay:.36s}
footer{margin-top:32px;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}
footer .sp{margin-left:auto}footer a{color:var(--dim);text-decoration:none}footer a:hover{color:var(--grit)}
@keyframes fade{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
@keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-6px);opacity:1}}
</style></head>
<body><div class="wrap">
<header>
 <div class="mark"><svg width="38" height="38" viewBox="0 0 38 38" fill="none"><rect x="1" y="1" width="36" height="36" rx="2" stroke="#2b303c"/><path d="M27 12.5A9 9 0 1 0 28 22H19" stroke="#ff5a2a" stroke-width="2.4" stroke-linecap="square"/><rect x="10.5" y="10.5" width="3" height="3" fill="#ff5a2a"/></svg></div>
 <div class="brand"><div class="co">GRIT<b>AI</b></div><div class="sub">Cited Answers</div></div>
 <div class="tags"><span class="tag hot">&#9656; Live</span><span class="tag">RAG</span><span class="tag">SDVOSB</span></div>
</header>
<section class="hero">
 <h1>Answers you can <em>trust</em> β€” every claim cited.</h1>
 <p>Ask about construction and home remodeling. The answer is grounded only in a curated knowledge base and cites the exact sources β€” and it says <b>"I don't know"</b> when the answer isn't there. No made-up facts.</p>
</section>
<div class="sec"><span class="num">01</span><span class="name">Ask</span><span class="rule"></span></div>
<div class="ask">
 <div class="field"><span class="car">&gt;_</span>
  <input id="q" placeholder="Do I need a permit to remove a wall?" autofocus>
  <button class="run" id="go" onclick="ask()">Ask &#9656;</button></div>
 <div class="ex" id="ex"></div>
</div>
<div class="out" id="out">
 <div class="sec"><span class="num">02</span><span class="name" id="anslabel">Answer</span><span class="rule"></span></div>
 <div class="ans" id="answer"></div>
 <div class="sec" id="srchead" style="display:none"><span class="num">03</span><span class="name">Sources</span><span class="rule"></span></div>
 <div class="src" id="sources"></div>
</div>
<footer><span>RAG Β· fastembed + Claude Β· grounded, cited, honest</span>
 <span class="sp"><a href="https://gritai.solutions">GRITAI SOLUTIONS</a> Β· 30-in-15 &#8470;10</span></footer>
</div><script>
const EXAMPLES=["Do I need a permit to remove a wall?","How much contingency should I budget for a remodel?",
 "What flooring is best for a bathroom?","How do I vet a contractor before hiring?","When should I replace my roof?",
 "What's the best paint color for resale?"];
const $=id=>document.getElementById(id);const q=$('q'),go=$('go'),out=$('out');
function esc(s){return String(s==null?'':s).replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));}
$('ex').innerHTML=EXAMPLES.map(e=>'<span class="chip">'+esc(e)+'</span>').join('');
$('ex').querySelectorAll('.chip').forEach(c=>c.onclick=()=>{q.value=c.textContent;ask();});
function citelink(s){return esc(s).replace(/\\[(\\d+)\\]/g,'<a class="ct" href="#src$1">[$1]</a>');}
function ask(){if(go.disabled)return;const text=q.value.trim();if(!text){q.focus();return;}
 go.disabled=true;go.textContent='…';out.classList.add('show');$('srchead').style.display='none';
 $('answer').innerHTML='<span class="spin"><span></span><span></span><span></span></span>';$('sources').innerHTML='';
 fetch('/api/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:text})})
 .then(r=>r.json()).then(d=>{
  if(d.error){$('answer').textContent=d.error;return;}
  const miss=!d.found;$('answer').className='ans'+(miss?' miss':'');
  $('anslabel').textContent=miss?'Not in the knowledge base':'Answer';
  $('answer').innerHTML=citelink(d.answer||'');
  const src=d.sources||[];
  if(src.length){$('srchead').style.display='flex';
   $('sources').innerHTML=src.map(s=>'<div class="srow" id="src'+s.n+'"><span class="sn">['+s.n+']</span>'+
     '<div><div class="st">'+esc(s.title)+'</div><div class="sx">'+esc(s.text)+'</div></div></div>').join('');}
 }).catch(()=>{$('answer').textContent='Something went wrong β€” please try again.';})
 .finally(()=>{go.disabled=false;go.textContent='Ask \\u25b8';});
}
q.addEventListener('keydown',e=>{if(e.key==='Enter')ask();});
</script></body></html>"""


if __name__ == "__main__":
    backend = "Claude API" if ANTHROPIC_KEY else "NO KEY (retrieval only)"
    print(f"RAG Q&A with Citations on http://127.0.0.1:{PORT}  [backend: {backend}]", flush=True)
    app.run(host="0.0.0.0", port=PORT, threaded=True)