Burr FSM coordinating nine specialists + agent.py CLI
Browse filesSingle sequential pass per query — geocode, then nine specialists
in dependency order (flood layers first because they're the cheap
spatial joins; live API calls grouped after; RAG last because it's
the slowest). State accumulates into a flat dict the reconciler
then turns into doc-role messages.
agent.py is the CLI entrypoint that runs the FSM end-to-end and
prints the reconciled paragraph + per-step trace, used as the
quickest end-to-end smoke test before bringing up the web layer.
- agent.py +52 -0
- app/fsm.py +394 -0
agent.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HeliOS-NYC agent CLI: address -> cited paragraph via the Burr FSM.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python agent.py "180 Beach 35 St, Queens"
|
| 5 |
+
python agent.py "280 Broome St, Manhattan" --json
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import sys
|
| 12 |
+
import warnings
|
| 13 |
+
|
| 14 |
+
warnings.filterwarnings("ignore")
|
| 15 |
+
|
| 16 |
+
from app.fsm import run # noqa: E402
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main() -> int:
|
| 20 |
+
ap = argparse.ArgumentParser()
|
| 21 |
+
ap.add_argument("query", help="NYC address or natural-language location")
|
| 22 |
+
ap.add_argument("--json", action="store_true", help="emit full JSON state")
|
| 23 |
+
args = ap.parse_args()
|
| 24 |
+
|
| 25 |
+
print(f"\n query: {args.query}", file=sys.stderr)
|
| 26 |
+
print(" running FSM... (Granite 4.1 + open data, all local)\n", file=sys.stderr)
|
| 27 |
+
|
| 28 |
+
result = run(args.query)
|
| 29 |
+
|
| 30 |
+
if args.json:
|
| 31 |
+
print(json.dumps(result, indent=2, default=str))
|
| 32 |
+
return 0
|
| 33 |
+
|
| 34 |
+
print("─── trace " + "─" * 56)
|
| 35 |
+
for step in result["trace"]:
|
| 36 |
+
ok = "✓" if step["ok"] else "✗"
|
| 37 |
+
line = f" {ok} {step['step']:22s} {step.get('elapsed_s', 0):>5.2f}s"
|
| 38 |
+
if step.get("result"):
|
| 39 |
+
line += " " + json.dumps(step["result"], default=str)
|
| 40 |
+
elif step.get("err"):
|
| 41 |
+
line += " ERR: " + step["err"]
|
| 42 |
+
print(line)
|
| 43 |
+
|
| 44 |
+
print("\n─── cited report " + "─" * 49)
|
| 45 |
+
print()
|
| 46 |
+
print(result["paragraph"])
|
| 47 |
+
print()
|
| 48 |
+
return 0
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
sys.exit(main())
|
app/fsm.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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pipeline; each action degrades gracefully (empty result -> no doc).
|
| 4 |
+
The reconciler (Granite 4.1) only sees documents from specialists that
|
| 5 |
+
actually produced data.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
import time
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import geopandas as gpd
|
| 14 |
+
from burr.core import ApplicationBuilder, State, action
|
| 15 |
+
from shapely.geometry import Point
|
| 16 |
+
|
| 17 |
+
from app.context import floodnet, microtopo, nyc311
|
| 18 |
+
from app.energy import estimate as energy_estimate
|
| 19 |
+
from app.flood_layers import dep_stormwater, ida_hwm, prithvi_water, sandy_inundation
|
| 20 |
+
from app.geocode import geocode_one
|
| 21 |
+
from app.rag import retrieve as rag_retrieve
|
| 22 |
+
from app.reconcile import reconcile as run_reconcile
|
| 23 |
+
|
| 24 |
+
log = logging.getLogger("helios_nyc.fsm")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _step(state: State, name: str) -> dict[str, Any]:
|
| 28 |
+
"""Append a step record to the trace; returns the dict so the action
|
| 29 |
+
can mutate timing/result fields."""
|
| 30 |
+
trace = list(state.get("trace", []))
|
| 31 |
+
rec = {"step": name, "started_at": time.time(), "ok": None}
|
| 32 |
+
trace.append(rec)
|
| 33 |
+
return rec, trace
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@action(reads=["query"], writes=["geocode", "lat", "lon", "trace"])
|
| 37 |
+
def step_geocode(state: State) -> State:
|
| 38 |
+
rec, trace = _step(state, "geocode")
|
| 39 |
+
try:
|
| 40 |
+
hit = geocode_one(state["query"])
|
| 41 |
+
if hit is None:
|
| 42 |
+
rec["ok"] = False
|
| 43 |
+
rec["err"] = "no geocoder match"
|
| 44 |
+
# Burr requires every declared write to be populated. Emit
|
| 45 |
+
# explicit None rather than leaving keys absent.
|
| 46 |
+
return state.update(geocode=None, lat=None, lon=None, trace=trace)
|
| 47 |
+
rec["ok"] = True
|
| 48 |
+
rec["result"] = {"address": hit.address, "lat": hit.lat, "lon": hit.lon}
|
| 49 |
+
return state.update(
|
| 50 |
+
geocode={"address": hit.address, "borough": hit.borough,
|
| 51 |
+
"lat": hit.lat, "lon": hit.lon,
|
| 52 |
+
"bbl": hit.bbl, "bin": hit.bin},
|
| 53 |
+
lat=hit.lat, lon=hit.lon, trace=trace,
|
| 54 |
+
)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
rec["ok"] = False
|
| 57 |
+
rec["err"] = str(e)
|
| 58 |
+
log.exception("geocode failed")
|
| 59 |
+
return state.update(geocode=None, lat=None, lon=None, trace=trace)
|
| 60 |
+
finally:
|
| 61 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@action(reads=["lat", "lon"], writes=["sandy", "trace"])
|
| 65 |
+
def step_sandy(state: State) -> State:
|
| 66 |
+
rec, trace = _step(state, "sandy_inundation")
|
| 67 |
+
try:
|
| 68 |
+
if state.get("lat") is None:
|
| 69 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 70 |
+
return state.update(trace=trace)
|
| 71 |
+
pt = gpd.GeoDataFrame(geometry=[Point(state["lon"], state["lat"])], crs="EPSG:4326").to_crs("EPSG:2263")
|
| 72 |
+
flag = bool(sandy_inundation.join(pt).iloc[0])
|
| 73 |
+
rec["ok"] = True; rec["result"] = {"inside": flag}
|
| 74 |
+
return state.update(sandy=flag, trace=trace)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 77 |
+
log.exception("sandy failed")
|
| 78 |
+
return state.update(trace=trace)
|
| 79 |
+
finally:
|
| 80 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@action(reads=["lat", "lon"], writes=["dep", "trace"])
|
| 84 |
+
def step_dep(state: State) -> State:
|
| 85 |
+
rec, trace = _step(state, "dep_stormwater")
|
| 86 |
+
try:
|
| 87 |
+
if state.get("lat") is None:
|
| 88 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 89 |
+
return state.update(trace=trace)
|
| 90 |
+
pt = gpd.GeoDataFrame(geometry=[Point(state["lon"], state["lat"])], crs="EPSG:4326").to_crs("EPSG:2263")
|
| 91 |
+
out: dict[str, Any] = {}
|
| 92 |
+
for scen in ["dep_extreme_2080", "dep_moderate_2050", "dep_moderate_current"]:
|
| 93 |
+
j = dep_stormwater.join(pt, scen).iloc[0]
|
| 94 |
+
out[scen] = {
|
| 95 |
+
"depth_class": int(j["depth_class"]),
|
| 96 |
+
"depth_label": j["depth_label"],
|
| 97 |
+
"citation": f"NYC DEP Stormwater Flood Map — {dep_stormwater.label(scen)}",
|
| 98 |
+
}
|
| 99 |
+
rec["ok"] = True; rec["result"] = {k: v["depth_label"] for k, v in out.items()}
|
| 100 |
+
return state.update(dep=out, trace=trace)
|
| 101 |
+
except Exception as e:
|
| 102 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 103 |
+
log.exception("dep failed")
|
| 104 |
+
return state.update(trace=trace)
|
| 105 |
+
finally:
|
| 106 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@action(reads=["lat", "lon"], writes=["floodnet", "trace"])
|
| 110 |
+
def step_floodnet(state: State) -> State:
|
| 111 |
+
rec, trace = _step(state, "floodnet")
|
| 112 |
+
try:
|
| 113 |
+
if state.get("lat") is None:
|
| 114 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 115 |
+
return state.update(trace=trace)
|
| 116 |
+
s = floodnet.summary_for_point(state["lat"], state["lon"], radius_m=600)
|
| 117 |
+
s["radius_m"] = 600
|
| 118 |
+
rec["ok"] = True
|
| 119 |
+
rec["result"] = {"n_sensors": s["n_sensors"],
|
| 120 |
+
"n_events_3y": s["n_flood_events_3y"]}
|
| 121 |
+
return state.update(floodnet=s, trace=trace)
|
| 122 |
+
except Exception as e:
|
| 123 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 124 |
+
log.exception("floodnet failed")
|
| 125 |
+
return state.update(trace=trace)
|
| 126 |
+
finally:
|
| 127 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@action(reads=["lat", "lon"], writes=["nyc311", "trace"])
|
| 131 |
+
def step_311(state: State) -> State:
|
| 132 |
+
rec, trace = _step(state, "nyc311")
|
| 133 |
+
try:
|
| 134 |
+
if state.get("lat") is None:
|
| 135 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 136 |
+
return state.update(trace=trace)
|
| 137 |
+
s = nyc311.summary_for_point(state["lat"], state["lon"], radius_m=200, years=5)
|
| 138 |
+
rec["ok"] = True; rec["result"] = {"n": s["n"]}
|
| 139 |
+
return state.update(nyc311=s, trace=trace)
|
| 140 |
+
except Exception as e:
|
| 141 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 142 |
+
log.exception("311 failed")
|
| 143 |
+
return state.update(trace=trace)
|
| 144 |
+
finally:
|
| 145 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@action(reads=["lat", "lon"], writes=["ida_hwm", "trace"])
|
| 149 |
+
def step_ida_hwm(state: State) -> State:
|
| 150 |
+
rec, trace = _step(state, "ida_hwm_2021")
|
| 151 |
+
try:
|
| 152 |
+
if state.get("lat") is None:
|
| 153 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 154 |
+
return state.update(trace=trace)
|
| 155 |
+
s = ida_hwm.summary_for_point(state["lat"], state["lon"], radius_m=800)
|
| 156 |
+
if s is None:
|
| 157 |
+
rec["ok"] = False; rec["err"] = "HWM data missing"
|
| 158 |
+
return state.update(ida_hwm=None, trace=trace)
|
| 159 |
+
rec["ok"] = True
|
| 160 |
+
rec["result"] = {
|
| 161 |
+
"n_within_800m": s.n_within_radius,
|
| 162 |
+
"max_height_above_gnd_ft": s.max_height_above_gnd_ft,
|
| 163 |
+
"nearest_m": s.nearest_dist_m,
|
| 164 |
+
}
|
| 165 |
+
return state.update(ida_hwm=vars(s), trace=trace)
|
| 166 |
+
except Exception as e:
|
| 167 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 168 |
+
log.exception("ida_hwm failed")
|
| 169 |
+
return state.update(ida_hwm=None, trace=trace)
|
| 170 |
+
finally:
|
| 171 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@action(reads=["lat", "lon"], writes=["prithvi_water", "trace"])
|
| 175 |
+
def step_prithvi(state: State) -> State:
|
| 176 |
+
rec, trace = _step(state, "prithvi_eo_v2")
|
| 177 |
+
try:
|
| 178 |
+
if state.get("lat") is None:
|
| 179 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 180 |
+
return state.update(prithvi_water=None, trace=trace)
|
| 181 |
+
s = prithvi_water.summary_for_point(state["lat"], state["lon"])
|
| 182 |
+
if s is None:
|
| 183 |
+
rec["ok"] = False; rec["err"] = "Prithvi mask missing"
|
| 184 |
+
return state.update(prithvi_water=None, trace=trace)
|
| 185 |
+
rec["ok"] = True
|
| 186 |
+
rec["result"] = {
|
| 187 |
+
"inside_water_polygon": s.inside_water_polygon,
|
| 188 |
+
"nearest_distance_m": s.nearest_distance_m,
|
| 189 |
+
"n_polygons_within_500m": s.n_polygons_within_500m,
|
| 190 |
+
}
|
| 191 |
+
return state.update(prithvi_water=vars(s), trace=trace)
|
| 192 |
+
except Exception as e:
|
| 193 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 194 |
+
log.exception("prithvi failed")
|
| 195 |
+
return state.update(prithvi_water=None, trace=trace)
|
| 196 |
+
finally:
|
| 197 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@action(reads=["lat", "lon"], writes=["microtopo", "trace"])
|
| 201 |
+
def step_microtopo(state: State) -> State:
|
| 202 |
+
rec, trace = _step(state, "microtopo_lidar")
|
| 203 |
+
try:
|
| 204 |
+
if state.get("lat") is None:
|
| 205 |
+
rec["ok"] = False; rec["err"] = "no coords"
|
| 206 |
+
return state.update(trace=trace)
|
| 207 |
+
m = microtopo.microtopo_at(state["lat"], state["lon"])
|
| 208 |
+
if m is None:
|
| 209 |
+
rec["ok"] = False; rec["err"] = "DEM fetch failed"
|
| 210 |
+
return state.update(microtopo=None, trace=trace)
|
| 211 |
+
rec["ok"] = True
|
| 212 |
+
rec["result"] = {
|
| 213 |
+
"elev_m": m.point_elev_m,
|
| 214 |
+
"pct_200m": m.rel_elev_pct_200m,
|
| 215 |
+
"relief_m": m.basin_relief_m,
|
| 216 |
+
}
|
| 217 |
+
return state.update(microtopo=vars(m), trace=trace)
|
| 218 |
+
except Exception as e:
|
| 219 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 220 |
+
log.exception("microtopo failed")
|
| 221 |
+
return state.update(microtopo=None, trace=trace)
|
| 222 |
+
finally:
|
| 223 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@action(reads=["geocode", "sandy", "dep", "floodnet", "nyc311", "microtopo", "ida_hwm", "prithvi_water"],
|
| 227 |
+
writes=["rag", "trace"])
|
| 228 |
+
def step_rag(state: State) -> State:
|
| 229 |
+
rec, trace = _step(state, "rag_granite_embedding")
|
| 230 |
+
try:
|
| 231 |
+
geo = state.get("geocode") or {}
|
| 232 |
+
sandy = state.get("sandy")
|
| 233 |
+
dep = state.get("dep") or {}
|
| 234 |
+
# Build a context-rich query so retrieval pulls policy paragraphs
|
| 235 |
+
# relevant to *this* address, not generic flood text.
|
| 236 |
+
bits = []
|
| 237 |
+
if geo.get("address"):
|
| 238 |
+
bits.append(f"address {geo['address']}")
|
| 239 |
+
if geo.get("borough"):
|
| 240 |
+
bits.append(f"in {geo['borough']}")
|
| 241 |
+
if sandy:
|
| 242 |
+
bits.append("inside Hurricane Sandy 2012 inundation zone")
|
| 243 |
+
for k, v in dep.items():
|
| 244 |
+
if v.get("depth_class", 0) > 0:
|
| 245 |
+
bits.append(f"in {v['depth_label']} pluvial scenario")
|
| 246 |
+
bits.append("flood resilience plan, vulnerability, hardening, mitigation")
|
| 247 |
+
q = "; ".join(bits)
|
| 248 |
+
hits = rag_retrieve(q, k=3, min_score=0.45)
|
| 249 |
+
rec["ok"] = True
|
| 250 |
+
rec["result"] = {"hits": len(hits),
|
| 251 |
+
"top": [(h["doc_id"], round(h["score"], 2)) for h in hits]}
|
| 252 |
+
return state.update(rag=hits, trace=trace)
|
| 253 |
+
except Exception as e:
|
| 254 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 255 |
+
log.exception("rag failed")
|
| 256 |
+
return state.update(rag=[], trace=trace)
|
| 257 |
+
finally:
|
| 258 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@action(reads=["geocode", "sandy", "dep", "floodnet", "nyc311", "microtopo",
|
| 262 |
+
"ida_hwm", "prithvi_water", "rag"],
|
| 263 |
+
writes=["paragraph", "audit", "trace"])
|
| 264 |
+
def step_reconcile(state: State) -> State:
|
| 265 |
+
rec, trace = _step(state, "reconcile_granite41")
|
| 266 |
+
try:
|
| 267 |
+
snap = {
|
| 268 |
+
"geocode": state.get("geocode"),
|
| 269 |
+
"sandy": state.get("sandy"),
|
| 270 |
+
"dep": state.get("dep"),
|
| 271 |
+
"floodnet": state.get("floodnet"),
|
| 272 |
+
"nyc311": state.get("nyc311"),
|
| 273 |
+
"microtopo": state.get("microtopo"),
|
| 274 |
+
"ida_hwm": state.get("ida_hwm"),
|
| 275 |
+
"prithvi_water": state.get("prithvi_water"),
|
| 276 |
+
"rag": state.get("rag"),
|
| 277 |
+
}
|
| 278 |
+
para, audit = run_reconcile(snap, return_audit=True)
|
| 279 |
+
rec["ok"] = True
|
| 280 |
+
rec["result"] = {
|
| 281 |
+
"paragraph_chars": len(para),
|
| 282 |
+
"dropped_sentences": len(audit["dropped"]),
|
| 283 |
+
}
|
| 284 |
+
return state.update(paragraph=para, audit=audit, trace=trace)
|
| 285 |
+
except Exception as e:
|
| 286 |
+
rec["ok"] = False; rec["err"] = str(e)
|
| 287 |
+
log.exception("reconcile failed")
|
| 288 |
+
return state.update(paragraph="", audit={"raw": "", "dropped": []}, trace=trace)
|
| 289 |
+
finally:
|
| 290 |
+
rec["elapsed_s"] = round(time.time() - rec["started_at"], 2)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def build_app(query: str):
|
| 294 |
+
return (
|
| 295 |
+
ApplicationBuilder()
|
| 296 |
+
.with_actions(
|
| 297 |
+
geocode=step_geocode,
|
| 298 |
+
sandy=step_sandy,
|
| 299 |
+
dep=step_dep,
|
| 300 |
+
floodnet=step_floodnet,
|
| 301 |
+
nyc311=step_311,
|
| 302 |
+
microtopo=step_microtopo,
|
| 303 |
+
ida_hwm=step_ida_hwm,
|
| 304 |
+
prithvi=step_prithvi,
|
| 305 |
+
rag=step_rag,
|
| 306 |
+
reconcile=step_reconcile,
|
| 307 |
+
)
|
| 308 |
+
.with_transitions(
|
| 309 |
+
("geocode", "sandy"),
|
| 310 |
+
("sandy", "dep"),
|
| 311 |
+
("dep", "floodnet"),
|
| 312 |
+
("floodnet", "nyc311"),
|
| 313 |
+
("nyc311", "microtopo"),
|
| 314 |
+
("microtopo", "ida_hwm"),
|
| 315 |
+
("ida_hwm", "prithvi"),
|
| 316 |
+
("prithvi", "rag"),
|
| 317 |
+
("rag", "reconcile"),
|
| 318 |
+
)
|
| 319 |
+
.with_state(query=query, trace=[])
|
| 320 |
+
.with_entrypoint("geocode")
|
| 321 |
+
.build()
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _summarize_energy(trace: list) -> dict | None:
|
| 326 |
+
rec_step = next((t for t in trace if t.get("step") == "reconcile_granite41"
|
| 327 |
+
and t.get("ok")), None)
|
| 328 |
+
if not rec_step:
|
| 329 |
+
return None
|
| 330 |
+
total_s = sum(t.get("elapsed_s", 0) or 0 for t in trace)
|
| 331 |
+
return energy_estimate(rec_step.get("elapsed_s", 0) or 0, total_s)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def run(query: str) -> dict[str, Any]:
|
| 335 |
+
app = build_app(query)
|
| 336 |
+
final_action, _, final_state = app.run(halt_after=["reconcile"])
|
| 337 |
+
trace = final_state.get("trace", [])
|
| 338 |
+
return {
|
| 339 |
+
"query": query,
|
| 340 |
+
"geocode": final_state.get("geocode"),
|
| 341 |
+
"sandy": final_state.get("sandy"),
|
| 342 |
+
"dep": final_state.get("dep"),
|
| 343 |
+
"floodnet": final_state.get("floodnet"),
|
| 344 |
+
"nyc311": final_state.get("nyc311"),
|
| 345 |
+
"microtopo": final_state.get("microtopo"),
|
| 346 |
+
"ida_hwm": final_state.get("ida_hwm"),
|
| 347 |
+
"prithvi_water": final_state.get("prithvi_water"),
|
| 348 |
+
"rag": final_state.get("rag"),
|
| 349 |
+
"paragraph": final_state.get("paragraph"),
|
| 350 |
+
"audit": final_state.get("audit"),
|
| 351 |
+
"energy": _summarize_energy(trace),
|
| 352 |
+
"trace": trace,
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def iter_steps(query: str):
|
| 357 |
+
"""Yield (action_name, partial_state_dict) after each Burr action.
|
| 358 |
+
|
| 359 |
+
Used by the web UI for SSE streaming — each yield is a "step lit up"
|
| 360 |
+
moment. The final yield carries the reconciled paragraph.
|
| 361 |
+
"""
|
| 362 |
+
app = build_app(query)
|
| 363 |
+
last_trace_len = 0
|
| 364 |
+
for action_obj, result, state in app.iterate(halt_after=["reconcile"]):
|
| 365 |
+
trace = list(state.get("trace", []))
|
| 366 |
+
# Yield only the new trace records since the prior step
|
| 367 |
+
new_records = trace[last_trace_len:]
|
| 368 |
+
last_trace_len = len(trace)
|
| 369 |
+
for rec in new_records:
|
| 370 |
+
yield {
|
| 371 |
+
"kind": "step",
|
| 372 |
+
"step": rec["step"],
|
| 373 |
+
"ok": rec.get("ok"),
|
| 374 |
+
"elapsed_s": rec.get("elapsed_s"),
|
| 375 |
+
"result": rec.get("result"),
|
| 376 |
+
"err": rec.get("err"),
|
| 377 |
+
}
|
| 378 |
+
# final
|
| 379 |
+
trace = state.get("trace", [])
|
| 380 |
+
yield {
|
| 381 |
+
"kind": "final",
|
| 382 |
+
"geocode": state.get("geocode"),
|
| 383 |
+
"sandy": state.get("sandy"),
|
| 384 |
+
"dep": state.get("dep"),
|
| 385 |
+
"floodnet": state.get("floodnet"),
|
| 386 |
+
"nyc311": state.get("nyc311"),
|
| 387 |
+
"microtopo": state.get("microtopo"),
|
| 388 |
+
"ida_hwm": state.get("ida_hwm"),
|
| 389 |
+
"prithvi_water": state.get("prithvi_water"),
|
| 390 |
+
"rag": state.get("rag"),
|
| 391 |
+
"paragraph": state.get("paragraph"),
|
| 392 |
+
"audit": state.get("audit"),
|
| 393 |
+
"energy": _summarize_energy(trace),
|
| 394 |
+
}
|