CONSAI Site Intelligence
AI that reads years of construction-camera photos against the schedule and flags delays.
- Multi-agent systems
- Computer vision
- Role
- AI co-founder: architect and sole engineer of the AI service and the Site Intelligence layer
- Client
- CONSAI (own startup), reference deployment on an industrial construction site in Qatar
- Timeline
- Apr - Sep 2026
- Status
- Live in productionmvp.consai.app (login required)
43-second cut of the recorded walkthrough on the sandbox: stored detections on a frame, progress against plan with dated vision evidence, delay alerts, a daily AI report and two assistant answers. Navigation and project names are cropped out; some parts are sped up.
- camera photos in the reference archive
- 135,404
- camera photos in the reference archive
- objects located in 41,477 frames
- 110,711
- objects located in 41,477 frames
- vision reads of tasks against the archive
- 1,729
- vision reads of tasks against the archive
- tools in the Claude agent loop
- 14
- tools in the Claude agent loop
- pytest tests in the AI service
- 95
- pytest tests in the AI service
The problem
CONSAI installs solar-powered 4G timelapse cameras on construction sites. At the reference site, six cameras had taken 135,404 photos since October 2024, one frame every 20 minutes, and nobody read them. The plan lived in a schedule file, and the reasons for slippage were buried in RFI correspondence.
The goal was software that does what a site engineer would do with that material: which tasks are late, why, what is blocking them, and what the site looked like on a given day. It had to do that without confidently wrong claims in front of people who know the site.
Architecture
Frames become detections
The archive runner tiles each frame, runs YOLO-World and posts boxes to the app's /api/detections, the same contract the edge units use. 41,477 frames gave 110,711 objects.
- Service
- Data
- AI model
- External
Hard problems I solved
Seeing small trucks without inventing them
Trucks are 20 to 60 pixels wide in 3000 x 2000 frames, so a whole-frame 640 px pass missed them. Tiling fixed recall, but tile overlap made one frame report 17 trucks where there were 8 to 10, and open-vocabulary YOLO labelled pipe stacks as heavy vehicles at up to 0.62 confidence.
Approach. Per-class NMS across tiles, then a class-agnostic NMS so one object cannot match two prompts. Distractor prompts (stacked pipes, tarpaulin, containers) absorb false positives and are never reported; per-camera dead zones remove permanent ones. Fine-grained prompts produced 7 phantom concrete mixers, so the vocabulary was cut to truck, heavy plant, crane and worker, and the schedule's equipment keywords were aligned to exactly those classes.
The aligned vocabulary removed 5 permanent false alarms. 110,711 objects located across 41,477 frames.
An agent that cannot contradict the alerts
The first assistant was one Claude call with all site state stuffed into the prompt ('hi' returned a full status dump), next to a separate if-statement analyser. Chat could disagree with the alerts on the same page.
Approach. A redesign from one spec and four TDD plans: a deterministic engine writes the facts (alerts, forecasts) and the agent reads them through tools instead of recomputing them. Graph access goes through a curated library of Cypher intents, not free-form text-to-Cypher. Proposed actions wait for human approval, and a failed execution stays pending instead of showing as approved.
Reading progress from a photo archive
A task name like 'Tank foundation pour' is too thin to judge a photo against, and a vision model asked about progress will happily guess from the date or the task order.
Approach. The model first writes visual cues per task. Monthly frames are then read against all tasks in one call, with not_visible allowed and 'Do not infer from the date' in the prompt. Curves use a rolling median of three and then a running maximum, because buildings do not un-build. Scans backfill the archive when a new programme is uploaded and resume after restarts.
1,729 task reads across the reference archive.
Free-tier vision that holds up in a live demo
Gemini's free tier advertises 5 requests a minute, but a measured 4 per minute still drew 429s, and daily quotas differ by model (20 a day against 1,500). Describing every photo on ingest would have meant about 132,000 calls.
Approach. A sliding-window limiter at 3 requests a minute that parses retry-after from the error, and a thread-safe pool that rotates through 9 models when one reports its daily quota used, until the reset at Pacific midnight. The agent gets at most 3 vision calls per question and is told when the budget is spent. Descriptions are cached per photo and SDK calls run off the event loop.
A cached description returns in 0.1 s against 12 to 15 s fresh.
An archive that ends in the past
Every 'last N hours' query returned nothing, because the cameras had stopped 17 to 51 days earlier. Site state, scene observations, the daily report and the forecast table went silently empty, while the UI still drew boxes around the trucks the engine said were missing.
Approach. Time windows are anchored on the newest frame per installation, forecasts extrapolate from the date of the last observation instead of the wall clock, and the site-state window is sized to the data's cadence (60 days, documented as a demo-era setting).
A secure demo on a shared VPS in days
Debug mode served 1 MB error pages, /api/detections was unauthenticated with wildcard CORS, and the databases would be internet-facing if a VPS-only compose override went missing (an rsync --delete once removed it). Laravel's default API throttle silently stopped a 1,200-row backfill at 40 rows.
Approach. Detections moved behind an agent key, CORS pinned, debug off, a broken Sanctum stub removed, and the inbound routes given their own 1,200 per minute limit. Validation accepts frames with nothing detected, photo batches are bounded after a 3,000-photo map exhausted 16 GB, and deploys go through a git-only script because Docker images bake code. One gap stays documented as open: RFI search filters by task, not by installation.
Code
Each stage removes a specific failure seen on real frames: tile duplicates, one object matching two prompts, look-alike materials, and fixed false positives per camera.
def detect(model, im, device, installation_id: int = 0):
"""Tiled detection with cross-tile NMS, returning global-coordinate boxes."""
conf = PER_CAMERA_CONF.get(installation_id, CONF)
boxes, scores, classes = [], [], []
for crop, ox, oy in tile_boxes(im): # 3x2 overlapping tiles
r = model.predict(crop, imgsz=IMGSZ, conf=conf, device=device, verbose=False)[0]
... # shift by (ox, oy), stack into tensors
keep_all = []
for c in t_cls.unique(): # 1. dedupe within a class across tiles
idx = (t_cls == c).nonzero(as_tuple=True)[0]
keep = nms(t_boxes[idx], t_scores[idx], NMS_IOU)
keep_all.extend(idx[keep].tolist())
ka = torch.tensor(sorted(keep_all)) # 2. one object, two prompts: keep the strongest
keep_all = ka[nms(t_boxes[ka], t_scores[ka], CLASS_AGNOSTIC_IOU)].tolist()
out = []
for i in sorted(keep_all, key=lambda i: -scores[i]):
label = model.names[classes[i]]
if label not in REPORT: # 3. distractors absorb, never report
continue
if _in_dead_zone(installation_id, boxes[i], im.size[0], im.size[1]):
continue # 4. permanent per-camera false positive
out.append({"label": label, "equipment": EQUIPMENT_MAP.get(label),
"confidence": round(scores[i], 3), "bbox": [round(v) for v in boxes[i]]})
return outdef smooth(points: list[tuple[date, int]]) -> list[tuple[date, int]]:
"""Rolling median of three, then a running maximum: one odd frame cannot
swing the curve, and construction does not un-build itself."""
if not points:
return []
pts = sorted(points)
vals = [p[1] for p in pts]
med = []
for i in range(len(vals)):
# A full three-point window only; at the ends the raw value stands.
# A two-point median would average, inventing a value no frame showed.
med.append(int(median(vals[i - 1:i + 2])) if 0 < i < len(vals) - 1 else vals[i])
out, run = [], 0
for (d, _), v in zip(pts, med):
run = max(run, v)
out.append((d, run))
return outfor _ in range(MAX_ITERS): # MAX_ITERS = 6
resp = await client.messages.create(
model=MODEL, system=system, tools=TOOL_SCHEMAS, max_tokens=8000, messages=messages,
)
if resp.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": resp.content})
results = []
for block in resp.content:
if getattr(block, "type", None) == "tool_use":
if block.name in VISION_TOOLS:
if vision_calls >= settings.vision_max_calls_per_request:
out = {"error": f"vision budget for this question is used up "
f"({settings.vision_max_calls_per_request} images); "
f"answer from what you already have"}
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(out)})
continue
vision_calls += 1
out = await dispatch_tool(block.name, block.input or {}, installation_id, db)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(out, default=str)})
messages.append({"role": "user", "content": results})
continue
answer = "".join(getattr(b, "text", "") for b in resp.content if getattr(b, "type", None) == "text")
breakWhat I built
Perception
- Tiled YOLO-World detection on 3 x 2 overlapping tiles with two-stage NMS
- Distractor prompts, per-camera dead zones and confidence overrides
- Archive runner that posts to the same /api/detections contract as the Raspberry Pi edge units
- Detection overlay on the camera, compare and timelapse views
Schedule and documents
- Schedule XML parsed with lxml into a Neo4j graph: tasks, dependencies, required equipment
- RFI PDFs summarised by Claude Haiku 4.5, chunked and embedded into Qdrant
- RFIs linked to the tasks they affect, with impact days
- Per-task visual progress: cues written once per task, then monthly frames read against them
Deterministic engines
- Delay detection every 30 minutes: 4 rules plus critical-path escalation
- Idempotent alerts through a partial unique index and ON CONFLICT upsert
- Completion forecasts from observed pace, with a what-if pace simulator
- Activity analytics: daily index, weekday by hour heatmap, idle streaks, portfolio ranking
Agent and product
- Claude tool-use loop with 14 installation-scoped tools and at most 6 iterations
- Human-approved actions: draft an RFI, mark task status, notify a trade
- Daily AI site reports, stored once per site and day and delivered idempotently
- Laravel and Livewire pages: Site Intelligence, Project Intelligence, Data, Control Tower
Screens
Progress vs plan: observed percent per task from monthly camera reads, variance against the baseline, and the dated vision evidence behind each number.
Alerts from the deterministic engine: predecessor not finished, blocked by an open RFI, required equipment not on site, each with its critical-path impact.
The assistant answers from its tools (graph, alerts, camera reads) and flags when two sources disagree instead of picking one.
Daily site report: Claude writes the narrative from vision descriptions, detector counts, weather, live tasks, open alerts and RFIs.
Stack
AI service
- Python 3.11
- FastAPI
- SQLAlchemy async + asyncpg
- Docker Compose
- pytest
Models
- YOLO-World (yolov8s-world)
- Claude Sonnet 5 (agent, reports)
- Claude Haiku 4.5 (RFI extraction)
- Gemini Flash vision
- all-MiniLM-L6-v2 embeddings
Data
- PostgreSQL 16
- Neo4j 5
- Qdrant 1.9
- MariaDB
- Backblaze B2
Product UI
- Laravel 12
- Livewire 3.6
- Filament 3.3
- ApexCharts
How it was built
AI-native: I wrote the specs and plans (12,298 lines of Markdown in the product repo; the agent redesign was one spec and four TDD plans), Claude Code implemented, and pytest, end-to-end scripts and browser checks gated each change. Claude is co-author on 58 of the 69 AI-service commits and 59 of my 73 commits to the product repo. The camera hardware, the base Laravel app and the other 247 of its 320 commits belong to my co-founder and the company.
The site, the end client and the contractors are not named, the schedule and RFIs in the demo are illustrative, and the video and screenshots are cropped to remove project names and navigation.