bonita2026 Claude Fable 5 commited on
Commit
b61b1bd
·
verified ·
1 Parent(s): 7fd88a5

v21: server-side agentic analysis (Opus 5 analyst + Opus 4.6 writer), Spanish-only UI, daily budget fallback

Browse files
Files changed (3) hide show
  1. requirements.txt +1 -0
  2. web/agent_analysis.py +316 -0
  3. web/ui.py +63 -32
requirements.txt CHANGED
@@ -8,3 +8,4 @@
8
  requests>=2.31,<3
9
  xlrd>=2.0,<3
10
  boto3>=1.34,<2
 
 
8
  requests>=2.31,<3
9
  xlrd>=2.0,<3
10
  boto3>=1.34,<2
11
+ anthropic>=1
web/agent_analysis.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agentic analysis layer (v21): the narrative half the deterministic routes reserve.
2
+
3
+ ``routes.py`` says it in its own docstring: "the narrative parts … are produced
4
+ by the LLM agent". This module is that agent, run server-side so a website
5
+ visitor gets it by filling the same form as always:
6
+
7
+ 1. The deterministic route runs first (unchanged, statuses verbatim).
8
+ 2. An **analyst** (Claude Opus 5) reviews the deterministic result with the
9
+ route's own system prompt (``app.build_system_prompt``) and may call the
10
+ other routes as tools for cross-checks (e.g. viability pulling market data).
11
+ 3. A **writer** (Claude Opus 4.6) renders the client-facing report, 100 % in
12
+ Spanish, from the analyst's findings. The deterministic document is always
13
+ appended verbatim as an annex — statuses are never re-labelled here either.
14
+
15
+ Fail-honest states (mirroring ``email_delivery``): ``NOT_CONFIGURED`` (no
16
+ ``ANTHROPIC_API_KEY`` — the site behaves exactly as before this module
17
+ existed), ``CAPPED`` (our own daily budget spent), ``EXHAUSTED`` (the API
18
+ itself refuses for billing reasons), ``FAILED`` (any other error, shown, never
19
+ masked). Nothing about the request is stored; the in-memory spend counter
20
+ holds only date + dollars.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ from datetime import datetime, timezone
28
+ from typing import Any
29
+
30
+ from web import routes
31
+
32
+ # ─── Models & effort (task-Agentic Loop.md, 2026-09-17, Jade) ────────────────
33
+
34
+ ANALYST_MODEL = "claude-opus-5"
35
+ WRITER_MODEL = "claude-opus-4-6"
36
+
37
+ EFFORT_BY_ROUTE = {
38
+ "viability": "high",
39
+ "check": "high",
40
+ "opposition": "xhigh", # deliberate upgrade — adversarial review
41
+ "market": "medium",
42
+ "monitor": "medium",
43
+ }
44
+ WRITER_EFFORT = "high"
45
+
46
+ MAX_TOOL_ROUNDS = 4
47
+ ANALYST_MAX_TOKENS = 16000
48
+ WRITER_MAX_TOKENS = 12000
49
+
50
+ # ─── Pricing (USD per token; Opus 5 and Opus 4.6 share $5/$25 per MTok) ─────
51
+ _IN = 5.0 / 1e6
52
+ _OUT = 25.0 / 1e6
53
+ _CACHE_WRITE = _IN * 1.25
54
+ _CACHE_READ = _IN * 0.10
55
+
56
+ FALLBACK_ES = (
57
+ "«Hemos alcanzado la capacidad de análisis gratuitos de hoy. Su consulta no se ha "
58
+ "perdido: escríbanos a connect@railnexus.io y la atenderemos, o pregúntenos por "
59
+ "nuestro plan empresarial con capacidad dedicada y respuesta prioritaria.»"
60
+ )
61
+
62
+ # ─── Daily budget (in-memory; resets on UTC date change or process restart) ──
63
+
64
+ _spend = {"date": "", "usd": 0.0}
65
+
66
+
67
+ def _today() -> str:
68
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")
69
+
70
+
71
+ def daily_budget_usd() -> float:
72
+ try:
73
+ return float(os.environ.get("DAILY_BUDGET_USD", "10"))
74
+ except ValueError:
75
+ return 10.0
76
+
77
+
78
+ def _spent_today() -> float:
79
+ if _spend["date"] != _today():
80
+ _spend["date"] = _today()
81
+ _spend["usd"] = 0.0
82
+ return _spend["usd"]
83
+
84
+
85
+ def _record_usage(usage: Any) -> float:
86
+ cost = (getattr(usage, "input_tokens", 0) or 0) * _IN
87
+ cost += (getattr(usage, "output_tokens", 0) or 0) * _OUT
88
+ cost += (getattr(usage, "cache_creation_input_tokens", 0) or 0) * _CACHE_WRITE
89
+ cost += (getattr(usage, "cache_read_input_tokens", 0) or 0) * _CACHE_READ
90
+ _spent_today() # roll the date if needed
91
+ _spend["usd"] += cost
92
+ return cost
93
+
94
+
95
+ def analysis_status() -> dict:
96
+ """Mirror of ``email_delivery.delivery_status`` for the analysis banner."""
97
+ if not os.environ.get("ANTHROPIC_API_KEY"):
98
+ return {"configured": False, "reason": "falta ANTHROPIC_API_KEY"}
99
+ return {"configured": True, "analyst": ANALYST_MODEL, "writer": WRITER_MODEL,
100
+ "budget_usd": daily_budget_usd(), "spent_usd": round(_spent_today(), 4)}
101
+
102
+
103
+ # ─── Cross-check tools the analyst may call ──────────────────────────────────
104
+
105
+ def _trim(result: routes.RouteResult) -> dict:
106
+ """RouteResult as JSON the model reads — drop the bulky raw snapshot."""
107
+ data = result.to_dict()
108
+ payload = dict(data.get("payload") or {})
109
+ payload.pop("snapshot", None)
110
+ data["payload"] = payload
111
+ return data
112
+
113
+
114
+ def _tool_run(name: str, args: dict) -> dict:
115
+ if name == "run_check":
116
+ return _trim(routes.run_check(args.get("description", ""),
117
+ args.get("asset_type", "commercial"),
118
+ args.get("project_type", "") or ""))
119
+ if name == "run_viability":
120
+ return _trim(routes.run_viability(args.get("description", ""),
121
+ args.get("asset_type", "commercial"),
122
+ args.get("noi"), args.get("debt_service"),
123
+ args.get("loan"), args.get("value")))
124
+ if name == "run_market":
125
+ return _trim(routes.run_market(args.get("lat"), args.get("lon"),
126
+ args.get("province", ""), args.get("municipality", ""),
127
+ args.get("street", ""), args.get("number", ""),
128
+ int(args.get("radius", 1000)), 8, "es"))
129
+ if name == "run_monitor":
130
+ return _trim(routes.run_monitor(list(args.get("ccaa") or ["madrid"]),
131
+ int(args.get("days", 30)), "es"))
132
+ if name == "run_opposition":
133
+ return _trim(routes.run_opposition(args.get("pack_json", "") or "{}"))
134
+ return {"error": f"unknown tool {name}"}
135
+
136
+
137
+ _NUM = {"type": ["number", "null"]}
138
+
139
+ TOOLS = [
140
+ {"name": "run_check", "description":
141
+ "Jurisdiction gate + Spanish visado pre-validation for a property description. "
142
+ "Deterministic; returns the script's verbatim status (OK/BLOCKED/UNKNOWN_JURISDICTION).",
143
+ "input_schema": {"type": "object", "properties": {
144
+ "description": {"type": "string"}, "asset_type": {"type": "string"},
145
+ "project_type": {"type": "string"}}, "required": ["description"]}},
146
+ {"name": "run_viability", "description":
147
+ "Jurisdiction gate + deterministic DSCR / LTV calculators (GREEN/YELLOW/RED).",
148
+ "input_schema": {"type": "object", "properties": {
149
+ "description": {"type": "string"}, "asset_type": {"type": "string"},
150
+ "noi": _NUM, "debt_service": _NUM, "loan": _NUM, "value": _NUM},
151
+ "required": ["description"]}},
152
+ {"name": "run_market", "description":
153
+ "LIVE Spanish market snapshot (Catastro, INE, price sources) + Opposition Tierra "
154
+ "review. Give coordinates OR full address, never both. Takes 30s-2min.",
155
+ "input_schema": {"type": "object", "properties": {
156
+ "lat": _NUM, "lon": _NUM, "province": {"type": "string"},
157
+ "municipality": {"type": "string"}, "street": {"type": "string"},
158
+ "number": {"type": "string"}, "radius": {"type": "integer"}}}},
159
+ {"name": "run_monitor", "description":
160
+ "LIVE BOE + regional gazette legal monitor. ccaa: list of region keys "
161
+ "(e.g. ['madrid','cataluña']); days: lookback window.",
162
+ "input_schema": {"type": "object", "properties": {
163
+ "ccaa": {"type": "array", "items": {"type": "string"}},
164
+ "days": {"type": "integer"}}}},
165
+ {"name": "run_opposition", "description":
166
+ "Deterministic Opposition Tierra adversarial review of an evidence-pack JSON string.",
167
+ "input_schema": {"type": "object", "properties": {
168
+ "pack_json": {"type": "string"}}, "required": ["pack_json"]}},
169
+ ]
170
+
171
+ ANALYST_INSTRUCTIONS = (
172
+ "You are the analyst stage of the RailNexus Value web service. A client filled the "
173
+ "'{route}' form; the deterministic validators already ran and their result (statuses "
174
+ "verbatim, never re-label them) is in the user message. Your job: analyse it as the "
175
+ "route's methodology above requires, decide whether cross-checks are warranted "
176
+ "(call the tools; at most {rounds} rounds), and then output STRUCTURED FINDINGS as "
177
+ "plain text sections: HALLAZGOS (numbered findings, each tied to evidence and its "
178
+ "verbatim status), RIESGOS, LIMITACIONES (anything degraded, missing or not live — "
179
+ "state it plainly), CONCLUSION (conditioned on the statuses; a degraded status can "
180
+ "never support an unconditional conclusion). Do not write the client report; the "
181
+ "writer stage does that. Findings may be in English or Spanish."
182
+ )
183
+
184
+ WRITER_SYSTEM = (
185
+ "Eres el redactor final de RailNexus Value. Recibes (1) los hallazgos estructurados "
186
+ "del analista y (2) el documento determinista con los estados verbatim. Redacta el "
187
+ "informe para el cliente, íntegramente en español, con este contrato: título con la "
188
+ "ruta y la fecha; resumen ejecutivo honesto (si hay estados degradados, se dicen en "
189
+ "la primera línea, nunca se maquillan); hallazgos; riesgos y limitaciones; conclusión "
190
+ "condicionada a los estados; y cierre indicando que el anexo determinista forma parte "
191
+ "del informe. Estilo: profesional bancario, claro, sin jerga innecesaria, sin "
192
+ "anglicismos evitables. No inventes datos: todo número o estado procede de los "
193
+ "hallazgos o del documento determinista. No incluyas el anexo (se adjunta aparte)."
194
+ )
195
+
196
+
197
+ # ─── The loop ────────────────────────────────────────────────────────────────
198
+
199
+ def _billing_exhausted(exc: Exception) -> bool:
200
+ text = str(exc).lower()
201
+ return "credit balance" in text or "billing" in text or "insufficient" in text
202
+
203
+
204
+ def run_analysis(route: str, result: routes.RouteResult, form_context: dict) -> dict:
205
+ """Analyst + writer over a deterministic result. Returns a fail-honest dict:
206
+ ``{"state": OK|NOT_CONFIGURED|CAPPED|EXHAUSTED|FAILED, "report": str,
207
+ "message": str, "cost_usd": float}``.
208
+ """
209
+ if not os.environ.get("ANTHROPIC_API_KEY"):
210
+ return {"state": "NOT_CONFIGURED", "report": "", "cost_usd": 0.0,
211
+ "message": "Análisis con IA no configurado (falta ANTHROPIC_API_KEY)."}
212
+ if _spent_today() >= daily_budget_usd():
213
+ return {"state": "CAPPED", "report": "", "cost_usd": 0.0, "message": FALLBACK_ES}
214
+
215
+ try:
216
+ import anthropic
217
+ except ImportError:
218
+ return {"state": "NOT_CONFIGURED", "report": "", "cost_usd": 0.0,
219
+ "message": "Análisis con IA no configurado (paquete `anthropic` ausente)."}
220
+
221
+ import app as prompt_builder # route-selective system prompt (scripts/ already on path)
222
+
223
+ jurisdiction = None
224
+ jur = (result.payload or {}).get("jurisdiction")
225
+ if isinstance(jur, dict):
226
+ jurisdiction = jur.get("jurisdiction_detected")
227
+ project_type = (form_context or {}).get("project_type") or None
228
+
229
+ try:
230
+ system_text = prompt_builder.build_system_prompt(route, jurisdiction, project_type)
231
+ except Exception: # noqa: BLE001 — prompt builder must never take the site down
232
+ system_text = prompt_builder.build_system_prompt(route)
233
+
234
+ client = anthropic.Anthropic()
235
+ cost = 0.0
236
+ messages: list[dict] = [{
237
+ "role": "user",
238
+ "content": (
239
+ ANALYST_INSTRUCTIONS.format(route=route, rounds=MAX_TOOL_ROUNDS)
240
+ + "\n\nFORM CONTEXT (what the client entered):\n"
241
+ + json.dumps(form_context or {}, ensure_ascii=False, default=str)
242
+ + "\n\nDETERMINISTIC RESULT (statuses verbatim):\n"
243
+ + json.dumps(_trim(result), ensure_ascii=False, default=str)
244
+ ),
245
+ }]
246
+
247
+ try:
248
+ # Analyst loop (Opus 5, adaptive thinking, per-route effort).
249
+ for _ in range(MAX_TOOL_ROUNDS + 1):
250
+ with client.messages.stream(
251
+ model=ANALYST_MODEL,
252
+ max_tokens=ANALYST_MAX_TOKENS,
253
+ system=[{"type": "text", "text": system_text,
254
+ "cache_control": {"type": "ephemeral"}}],
255
+ thinking={"type": "adaptive"},
256
+ output_config={"effort": EFFORT_BY_ROUTE.get(route, "high")},
257
+ tools=TOOLS,
258
+ messages=messages,
259
+ ) as stream:
260
+ response = stream.get_final_message()
261
+ cost += _record_usage(response.usage)
262
+ if response.stop_reason != "tool_use":
263
+ break
264
+ messages.append({"role": "assistant", "content": response.content})
265
+ tool_results = []
266
+ for block in response.content:
267
+ if block.type == "tool_use":
268
+ try:
269
+ out = _tool_run(block.name, dict(block.input or {}))
270
+ except Exception as exc: # noqa: BLE001 — surfaced to the model
271
+ out = {"error": f"{type(exc).__name__}: {exc}"}
272
+ tool_results.append({"type": "tool_result", "tool_use_id": block.id,
273
+ "content": json.dumps(out, ensure_ascii=False,
274
+ default=str)[:20000]})
275
+ messages.append({"role": "user", "content": tool_results})
276
+
277
+ findings = "\n".join(b.text for b in response.content if b.type == "text").strip()
278
+ if not findings:
279
+ return {"state": "FAILED", "report": "", "cost_usd": cost,
280
+ "message": f"El analista no produjo hallazgos (stop: {response.stop_reason})."}
281
+
282
+ # Writer (Opus 4.6, effort high, informe 100 % en español).
283
+ with client.messages.stream(
284
+ model=WRITER_MODEL,
285
+ max_tokens=WRITER_MAX_TOKENS,
286
+ system=WRITER_SYSTEM,
287
+ thinking={"type": "adaptive"},
288
+ output_config={"effort": WRITER_EFFORT},
289
+ messages=[{"role": "user", "content":
290
+ "HALLAZGOS DEL ANALISTA:\n" + findings
291
+ + "\n\nDOCUMENTO DETERMINISTA (estados verbatim):\n"
292
+ + routes.render_document(result)}],
293
+ ) as stream:
294
+ written = stream.get_final_message()
295
+ cost += _record_usage(written.usage)
296
+ report = "\n".join(b.text for b in written.content if b.type == "text").strip()
297
+ if not report:
298
+ return {"state": "FAILED", "report": "", "cost_usd": cost,
299
+ "message": "El redactor no produjo informe."}
300
+ return {"state": "OK", "report": report, "cost_usd": cost, "message": ""}
301
+
302
+ except anthropic.AuthenticationError:
303
+ return {"state": "FAILED", "report": "", "cost_usd": cost,
304
+ "message": "Clave de API inválida (AuthenticationError)."}
305
+ except anthropic.RateLimitError:
306
+ return {"state": "EXHAUSTED", "report": "", "cost_usd": cost, "message": FALLBACK_ES}
307
+ except anthropic.BadRequestError as exc:
308
+ if _billing_exhausted(exc):
309
+ return {"state": "EXHAUSTED", "report": "", "cost_usd": cost, "message": FALLBACK_ES}
310
+ return {"state": "FAILED", "report": "", "cost_usd": cost,
311
+ "message": f"BadRequestError: {exc}"}
312
+ except Exception as exc: # noqa: BLE001 — shown, never masked; deterministic doc survives
313
+ if _billing_exhausted(exc):
314
+ return {"state": "EXHAUSTED", "report": "", "cost_usd": cost, "message": FALLBACK_ES}
315
+ return {"state": "FAILED", "report": "", "cost_usd": cost,
316
+ "message": f"{type(exc).__name__}: {exc}"}
web/ui.py CHANGED
@@ -13,27 +13,22 @@ from __future__ import annotations
13
  import json
14
  from typing import Any
15
 
16
- from web import AGENT_VERSION
17
- from web import email_delivery, routes
18
 
19
- TITLE = f"RailNexus Value v{AGENT_VERSION.split('.')[0]} — Real Estate & Infrastructure Agent"
20
 
21
  INTRO = (
22
- f"**Versión {AGENT_VERSION}.** Cinco rutas sobre los mismos validadores y colectores que "
23
- "usa la CLI del programa: nada se reimplementa aquí. **El estado que ves es el que "
24
- "reporta el propio script** (`LIVE` / `PARTIAL_LIVE` / `NO_LIVE_MARKET_DATA`, "
25
- "`COMPLETE` / `PARTIAL` / `FAILED`, `PASS` / `CONDITIONAL` / `BLOCKED`…): un estado "
26
- "degradado se muestra como tal, nunca se maquilla. Las rutas *market* y *monitor* "
27
- "consultan servicios públicos en vivo (Catastro, SIU/MUC, INE, Registradores, MIVAU, "
28
- "BOE y boletines CCAA) y pueden tardar de 30 s a 2 min."
29
  )
30
 
31
  ROUTE_LABELS = {
32
- "viability": "Viability — jurisdicción + DSCR / LTV",
33
- "check": "Check — jurisdicción + pre-visado (España)",
34
- "market": "Market — Catastro + suelo + precios (España, en vivo)",
35
- "monitor": "Monitor — BOE + boletines CCAA (en vivo)",
36
- "opposition": "Opposition Tierra — revisión adversarial de un evidence pack",
37
  }
38
 
39
 
@@ -73,7 +68,33 @@ def on_run(route: str, description: str, asset_type: str, project_type: str, col
73
  return (msg, "", {"error": f"{type(exc).__name__}: {exc}"}, "")
74
  document = routes.render_document(result)
75
  payload: dict[str, Any] = result.to_dict()
76
- return (_status_markdown(result), document, payload, document)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
 
79
  def on_send(name: str, email: str, consent: bool, document: str) -> tuple[str, str, str]:
@@ -82,13 +103,22 @@ def on_send(name: str, email: str, consent: bool, document: str) -> tuple[str, s
82
  state = outcome["state"]
83
  icon = {"SENT": "✅", "NOT_CONFIGURED": "⛔", "CONSENT_REQUIRED": "☐",
84
  "INVALID_INPUT": "✏️", "REJECTED_SANDBOX": "🧪", "FAILED": "❌"}.get(state, "•")
85
- md = f"### {icon} `{state}`\n\n{outcome['message']}\n\n*Nada se ha guardado / nothing stored.*"
86
  if state in ("SENT", "REJECTED_SANDBOX", "FAILED"):
87
  # The request is over: the name and e-mail leave the form (and memory).
88
  return md, "", ""
89
  return md, name, email
90
 
91
 
 
 
 
 
 
 
 
 
 
92
  def _delivery_banner() -> str:
93
  status = email_delivery.delivery_status()
94
  if status["configured"]:
@@ -107,15 +137,16 @@ def build_demo():
107
  with gr.Blocks(title=TITLE) as demo:
108
  gr.Markdown(f"# {TITLE}")
109
  gr.Markdown(INTRO)
 
110
 
111
  route = gr.Radio(choices=[(v, k) for k, v in ROUTE_LABELS.items()], value="check",
112
- label="Ruta / route")
113
 
114
  with gr.Group(visible=True) as grp_text:
115
  description = gr.Textbox(
116
- label="Propiedad / property (dirección o descripción con el país)",
117
- placeholder="Office building in Madrid, Spain", lines=2)
118
- asset_type = gr.Dropdown(routes.ASSET_TYPES, value="commercial", label="Asset type")
119
 
120
  with gr.Group(visible=True) as grp_check:
121
  project_type = gr.Dropdown([""] + routes.PROJECT_TYPES, value="",
@@ -150,32 +181,32 @@ def build_demo():
150
  ccaa = gr.CheckboxGroup(routes.CCAA_KEYS, value=["madrid"], label="CCAA")
151
  days = gr.Slider(1, 90, value=30, step=1, label="Días hacia atrás")
152
 
153
- language = gr.Radio(routes.LANGUAGES, value="es", label="Idioma del informe (market / monitor)")
154
 
155
  with gr.Group(visible=False) as grp_opposition:
156
- pack_json = gr.Code(label="Evidence pack (JSON)", language="json", lines=12,
157
  value='{\n "conclusion": "",\n "jurisdiction": "Spain",\n'
158
  ' "sources": [],\n "claims": []\n}')
159
  with gr.Row():
160
- max_age_hours = gr.Number(label="Max market retrieval age (h)", value=24)
161
- max_data_age_days = gr.Number(label="Max market data age (days)", value=180)
162
 
163
- run_btn = gr.Button("Ejecutar / run", variant="primary")
164
 
165
  status_md = gr.Markdown()
166
- document_box = gr.Textbox(label="Documento (texto)", lines=22, max_lines=80)
167
  payload_json = gr.JSON(label="Resultado estructurado (JSON)")
168
  document_state = gr.State("")
169
 
170
- gr.Markdown("---\n## Recibir este documento por correo / receive by e-mail")
171
  gr.Markdown(_delivery_banner())
172
  gr.Markdown(email_delivery.CONSENT_TEXT)
173
  with gr.Row():
174
- req_name = gr.Textbox(label="Nombre / name")
175
- req_email = gr.Textbox(label="Correo / e-mail")
176
- consent = gr.Checkbox(label="He leído y acepto lo anterior / I have read and accept the above",
177
  value=False)
178
- send_btn = gr.Button("Enviar / send", interactive=False)
179
  send_result = gr.Markdown()
180
 
181
  def _toggle(selected):
 
13
  import json
14
  from typing import Any
15
 
16
+ from web import AGENT_VERSION # noqa: F401 (kept: version still stamps the annex)
17
+ from web import agent_analysis, email_delivery, routes
18
 
19
+ TITLE = "RailNexus Value - Real Estate & Infrastructure Agent"
20
 
21
  INTRO = (
22
+ "Se utilizan datos públicos en vivo; el análisis puede tardar entre "
23
+ "30 segundos y 2 minutos."
 
 
 
 
 
24
  )
25
 
26
  ROUTE_LABELS = {
27
+ "viability": "Viabilidad — jurisdicción + DSCR / LTV",
28
+ "check": "Comprobación — jurisdicción + pre-visado (España)",
29
+ "market": "Mercado — Catastro + suelo + precios (España, en vivo)",
30
+ "monitor": "Monitor legal — BOE + boletines CCAA (en vivo)",
31
+ "opposition": "Opposition Tierra — revisión adversarial de un paquete de evidencias",
32
  }
33
 
34
 
 
68
  return (msg, "", {"error": f"{type(exc).__name__}: {exc}"}, "")
69
  document = routes.render_document(result)
70
  payload: dict[str, Any] = result.to_dict()
71
+
72
+ # Agentic analysis (analyst Opus 5 + redactor Opus 4.6). Fail-honest: any
73
+ # state other than OK leaves the deterministic document exactly as before.
74
+ form_context = {
75
+ "route": route, "description": description, "asset_type": asset_type,
76
+ "project_type": project_type, "noi": noi, "debt_service": debt_service,
77
+ "loan": loan, "value": value, "lat": lat, "lon": lon, "province": province,
78
+ "municipality": municipality, "street": street, "number": number,
79
+ "ccaa": list(ccaa or []), "days": days,
80
+ }
81
+ analysis = agent_analysis.run_analysis(route, result, form_context)
82
+ payload["ai_analysis"] = {"state": analysis["state"],
83
+ "cost_usd": round(analysis.get("cost_usd", 0.0), 4)}
84
+ status_text = _status_markdown(result)
85
+ if analysis["state"] == "OK":
86
+ document = (analysis["report"]
87
+ + "\n\n" + "=" * 72
88
+ + "\nANEXO — RESULTADO DETERMINISTA (estados verbatim)\n"
89
+ + "=" * 72 + "\n\n" + document)
90
+ status_text += "\n\n🧠 **Informe redactado con análisis de IA** (anexo determinista incluido)."
91
+ elif analysis["state"] in ("CAPPED", "EXHAUSTED"):
92
+ status_text += f"\n\n📮 {analysis['message']}"
93
+ elif analysis["state"] == "FAILED":
94
+ status_text += ("\n\n⚠️ Análisis con IA no disponible en esta consulta "
95
+ f"(`{analysis['message']}`). Se muestra el resultado determinista.")
96
+ # NOT_CONFIGURED: silently identical to the pre-agent behaviour.
97
+ return (status_text, document, payload, document)
98
 
99
 
100
  def on_send(name: str, email: str, consent: bool, document: str) -> tuple[str, str, str]:
 
103
  state = outcome["state"]
104
  icon = {"SENT": "✅", "NOT_CONFIGURED": "⛔", "CONSENT_REQUIRED": "☐",
105
  "INVALID_INPUT": "✏️", "REJECTED_SANDBOX": "🧪", "FAILED": "❌"}.get(state, "•")
106
+ md = f"### {icon} `{state}`\n\n{outcome['message']}\n\n*Nada se ha guardado.*"
107
  if state in ("SENT", "REJECTED_SANDBOX", "FAILED"):
108
  # The request is over: the name and e-mail leave the form (and memory).
109
  return md, "", ""
110
  return md, name, email
111
 
112
 
113
+ def _analysis_banner() -> str:
114
+ status = agent_analysis.analysis_status()
115
+ if status["configured"]:
116
+ return (f"Análisis con IA: **configurado** (analista `{status['analyst']}`, "
117
+ f"redactor `{status['writer']}`).")
118
+ return (f"Análisis con IA: **NO CONFIGURADO** — {status['reason']}. "
119
+ "Los formularios funcionan; el informe mostrará solo el resultado determinista.")
120
+
121
+
122
  def _delivery_banner() -> str:
123
  status = email_delivery.delivery_status()
124
  if status["configured"]:
 
137
  with gr.Blocks(title=TITLE) as demo:
138
  gr.Markdown(f"# {TITLE}")
139
  gr.Markdown(INTRO)
140
+ gr.Markdown(_analysis_banner())
141
 
142
  route = gr.Radio(choices=[(v, k) for k, v in ROUTE_LABELS.items()], value="check",
143
+ label="Tipo de análisis")
144
 
145
  with gr.Group(visible=True) as grp_text:
146
  description = gr.Textbox(
147
+ label="Propiedad (dirección o descripción, indicando el país)",
148
+ placeholder="Edificio de oficinas en Madrid, España", lines=2)
149
+ asset_type = gr.Dropdown(routes.ASSET_TYPES, value="commercial", label="Tipo de activo")
150
 
151
  with gr.Group(visible=True) as grp_check:
152
  project_type = gr.Dropdown([""] + routes.PROJECT_TYPES, value="",
 
181
  ccaa = gr.CheckboxGroup(routes.CCAA_KEYS, value=["madrid"], label="CCAA")
182
  days = gr.Slider(1, 90, value=30, step=1, label="Días hacia atrás")
183
 
184
+ language = gr.State("es") # informe 100 % en español (task 2026-09-17)
185
 
186
  with gr.Group(visible=False) as grp_opposition:
187
+ pack_json = gr.Code(label="Paquete de evidencias (JSON)", language="json", lines=12,
188
  value='{\n "conclusion": "",\n "jurisdiction": "Spain",\n'
189
  ' "sources": [],\n "claims": []\n}')
190
  with gr.Row():
191
+ max_age_hours = gr.Number(label="Antigüedad máx. de la consulta de mercado (h)", value=24)
192
+ max_data_age_days = gr.Number(label="Antigüedad máx. de los datos de mercado (días)", value=180)
193
 
194
+ run_btn = gr.Button("Ejecutar análisis", variant="primary")
195
 
196
  status_md = gr.Markdown()
197
+ document_box = gr.Textbox(label="Informe (texto)", lines=22, max_lines=80)
198
  payload_json = gr.JSON(label="Resultado estructurado (JSON)")
199
  document_state = gr.State("")
200
 
201
+ gr.Markdown("---\n## Recibir este documento por correo")
202
  gr.Markdown(_delivery_banner())
203
  gr.Markdown(email_delivery.CONSENT_TEXT)
204
  with gr.Row():
205
+ req_name = gr.Textbox(label="Nombre")
206
+ req_email = gr.Textbox(label="Correo electrónico")
207
+ consent = gr.Checkbox(label="He leído y acepto lo anterior",
208
  value=False)
209
+ send_btn = gr.Button("Enviar", interactive=False)
210
  send_result = gr.Markdown()
211
 
212
  def _toggle(selected):