From f4e7c0858f2f46cd1ac7c279209c2c28aa078c92 Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 22:53:51 +0530 Subject: [PATCH 1/7] Add Phase 2 design spec and plan: smarter AI Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-11-08-phase2-smarter-ai.md | 59 +++++++++ .../2026-11-08-phase2-smarter-ai-design.md | 122 ++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-08-phase2-smarter-ai.md create mode 100644 docs/superpowers/specs/2026-11-08-phase2-smarter-ai-design.md diff --git a/docs/superpowers/plans/2026-11-08-phase2-smarter-ai.md b/docs/superpowers/plans/2026-11-08-phase2-smarter-ai.md new file mode 100644 index 0000000..f07b571 --- /dev/null +++ b/docs/superpowers/plans/2026-11-08-phase2-smarter-ai.md @@ -0,0 +1,59 @@ +# Phase 2: Smarter AI Implementation Plan + +> Executed inline (user-approved). Each task is test-first and ends with a commit on branch `phase2-smarter-ai`. + +**Goal:** Filter-aware SQL, an LLM router with keyword fallback and follow-ups, self-correcting SQL, step-by-step +streaming answers, Groq rate-limit retries, and a published evaluation score. + +**Spec:** `docs/superpowers/specs/2026-11-08-phase2-smarter-ai-design.md` + +## Global constraints + +- Phase 1 constraints still apply (Python 3.11, pinned dependencies, read-only DB role, rate limits, no secrets in code). +- `/query` stays backward compatible: existing fields unchanged; `history` (request) and `steps`, `filters` + (response) are optional additions. +- Filter keys are exactly those in `floatchat.search.FILTER_SQL`; values are always bound parameters. +- Every LLM call goes through the API's budgeted chat function; every LLM failure falls back to the keyword/data-only + path. +- Commit messages end with `Co-Authored-By: Claude Opus 5.5 `. + +## Tasks + +### Task 1: Filter-aware SQL templates +- `floatchat/filters.py`: `FILTER_KEYS`, `clean_filters(filters) -> dict` (drops unknown keys/values), + `sql_conditions(filters, alias="p") -> (list[str], dict)`; `search.py` reuses it. +- `sql_agent.TEMPLATES` rewritten to `FROM measurements m JOIN profiles p ... WHERE {where}`; + `SqlAgent.generate_sql(question, filters)` / `run(question, filters=None)`. +- Tests: unit for the condition builder; integration: Arabian-Sea-filtered `avg_by_depth` uses only Arabian Sea + measurements (row counts match a direct SQL count) and differs from the unfiltered result. + +### Task 2: Router with keyword fallback and follow-ups +- `floatchat/router.py`: `Route` dataclass; `keyword_route(question, history)`; `llm_route(question, history, chat)` + (JSON reply, validated); `route(question, history, chat, llm_available)`. +- `answer_question` uses the route (path, intent, filters, standalone question) instead of its own keyword checks. +- Tests: keyword routes for the Phase 1 questions unchanged; follow-up "now only the Arabian Sea" reuses the previous + intent; LLM route parsing (valid, invalid intent/region dropped, malformed → keywords). + +### Task 3: Self-correcting SQL and Groq 429 retry +- `SqlAgent.run` records attempts; on a database error for LLM SQL, ask the LLM to fix it (≤2 repairs). +- `llm.chat`: one retry on 429 honouring `Retry-After` (≤10 s); `llm.chat_stream` for token streaming. +- Tests: fake LLM returning broken then fixed SQL succeeds with 2 attempts; 3 broken attempts fail cleanly; 429 retry + with a fake HTTP layer. + +### Task 4: Steps and the streaming endpoint +- `answer_question(..., emit=None, history=None)` emits step events and returns `steps` and `filters` in the result. +- `/query` accepts `history`; questions with history are not cached. +- `/query/stream` (SSE): `step`, `token`, `result`, `error` events; same rate limits and query log. +- Tests: `/query` with history routes the follow-up; stream returns steps then a result whose payload equals + `/query`'s; cached stream replays steps. + +### Task 5: Streamlit stopgap updates +- `app.py` sends the last 3 turns as `history`; shows "How I answered" (steps) under each answer. + +### Task 6: Evaluation suite +- `eval/questions.json` (~30 cases), `eval/__main__.py` runner (`--api`, pacing, JSON + Markdown output), + `.github/workflows/eval.yml` (manual + weekly), README score section. +- Tests: runner scoring logic on canned responses. + +### Task 7: Ship +- PR, CI green, merge, Render redeploy, run the eval against the live API, record the score, verify the done criteria. diff --git a/docs/superpowers/specs/2026-11-08-phase2-smarter-ai-design.md b/docs/superpowers/specs/2026-11-08-phase2-smarter-ai-design.md new file mode 100644 index 0000000..5e68774 --- /dev/null +++ b/docs/superpowers/specs/2026-11-08-phase2-smarter-ai-design.md @@ -0,0 +1,122 @@ +# Phase 2: Smarter AI (design) + +**Date:** 2026-11-08 +**Status:** approved by the user ("I approve the design, keep building"); built in this phase + +## Context + +Phase 1 put the API live (Render + Neon + Groq) with a keyword router, fixed SQL templates and pgvector search. +Phase 2 makes the AI part worth showing: it understands questions better, shows its work step by step, handles +follow-ups, and proves its accuracy with a published benchmark. Phase 3 (the Next.js site) builds its chat page on +the streaming endpoint defined here. + +Problems found in the Phase 1 code that this phase fixes: + +- **Statistical questions ignore filters.** "Average temperature at different depths *in the Arabian Sea*" detects the + region but runs a whole-ocean template. +- **Routing is keyword-only.** Phrasings without trigger words go to the wrong path; "now only the Arabian Sea" has no + memory of the previous question. +- **LLM-written SQL gets one try.** A typo in a column name ends in a fallback answer. +- **Answers arrive all at once** with no visibility into what happened. +- **Groq rate limits** (HTTP 429) fail the LLM call immediately. + +## Goals + +1. Filters (region, month, year, sensor) apply to **both** SQL answers and profile search. +2. An **LLM router** returns a structured decision (path, intent, filters, standalone question); the keyword router + remains as the fallback when no LLM is available, the budget is spent, or the LLM's output is invalid. +3. **Follow-up questions** work: the client sends the last few turns; the router resolves "now only the Arabian Sea" + into a standalone question with merged filters. +4. **Self-correcting SQL:** LLM-written SQL that fails is sent back with the database error, up to 2 repair attempts. +5. **Glass-box answers:** every answer carries a list of steps; a new streaming endpoint sends those steps and the + answer text as they happen (Server-Sent Events). +6. **Evaluation suite:** a fixed set of benchmark questions with expected routing/filters and answer checks, a runner + that scores the live API or a local one, and a published score. + +## Non-goals + +- The Next.js UI (Phase 3). The Streamlit stopgap gets follow-ups and a "How I answered" step list only. +- Server-side conversation storage. History travels with each request (stateless API). +- New data sources or variables. + +## Design + +### 1. Filters everywhere + +`Filters` is a small dict with optional keys `region`, `month_num`, `year`, `has_oxygen`, `has_chlorophyll`, +`has_nitrate`, `has_ph` (the keys `floatchat/search.py` already understands). SQL templates become filter-aware: each +template reads `FROM measurements m JOIN profiles p ON p.profile_id = m.profile_id WHERE {conditions}` and the +conditions are built from the same whitelist as search (values always bound parameters). A template run with filters +answers only for the matching profiles; the answer title says so ("… in the Arabian Sea, March"). + +### 2. Router (`floatchat/router.py`) + +``` +Route(path: "analytical" | "semantic", intent: str, filters: dict, question: str, source: "llm" | "keywords") +route(question, history, chat, llm_available) -> Route +``` + +- **LLM router:** one JSON-mode chat call with a compact prompt: the list of intents (the templates plus `custom`), + the allowed filter keys and region names, the last ≤3 turns of history, and the question. The reply is validated: + unknown intents, regions or keys are dropped; a malformed reply falls back to keywords. +- **Keyword router:** today's `is_analytical_query` / `detect_query_intent` / `parse_filters`, plus a follow-up rule: + if the question has filters but no intent of its own and the previous turn was analytical, reuse the previous + intent with the new filters merged over the old ones ("now only the Arabian Sea"). +- The router's standalone question is what the rest of the pipeline uses. + +### 3. Self-correcting SQL + +`SqlAgent.run(question, filters)`: templates for known intents (with filters); for `custom`, the LLM writes SQL, it is +validated (read-only check), executed, and on a database error the SQL and the error message go back to the LLM for a +fix, at most 2 repairs. Each attempt is recorded as a step. The read-only database role and 5 s timeout stay the last +line of defence. + +### 4. Steps and streaming + +`answer_question(...)` takes an optional `emit(event)` callback and returns the final result with a `steps` list. +Steps: `understood` (path, intent, filters, router source), `sql` (query, attempt), `rows` (count, ms), `search` +(matches, filters used, fallback note), `answer` (whether the LLM wrote it). `llm.chat_stream` streams tokens from the +OpenAI-compatible endpoint. + +API: + +- `POST /query` (unchanged contract, plus optional `history` in the request and `steps`, `filters` in the response). +- `POST /query/stream` → `text/event-stream` with events `step`, `token` (answer text as the LLM writes it), + `result` (the same payload `/query` returns) and `error`. Rate-limited like `/query`; cached answers replay their + steps and send the whole answer as one token. +- Answers to questions with history are not cached (they depend on the conversation). + +### 5. Groq rate limits + +`llm.chat` / `llm.chat_stream` retry once on HTTP 429, waiting `Retry-After` (capped at 10 s). A second 429 returns +`None` (data-only answer, not cached — Phase 1 behaviour). + +### 6. Evaluation suite (`eval/`) + +- `eval/questions.json`: ~30 questions across intents, regions, months, sensors, follow-ups and descriptive search, + each with expectations: `path`, `intent` (analytical), `filters`, and answer checks (analytical: rows returned and, + where relevant, the expected filter values in the SQL; semantic: every retrieved profile satisfies the filters). +- `python -m eval --api ` runs against any deployment (respecting rate limits by pacing requests) and writes + `eval/results.json` plus a Markdown summary: routing accuracy, filter accuracy, answer-check pass rate, median + latency, and how many answers the LLM wrote. +- `.github/workflows/eval.yml`: manual trigger (and weekly) against the live API; uploads the summary as the job + summary. The README shows the latest score. + +### 7. Streamlit stopgap + +`app.py` sends the last 3 turns as `history` and shows the steps in a "How I answered" expander under each answer. + +## Testing + +Unit: filter-condition builder, router validation and keyword follow-ups, SQL repair loop (fake LLM returning bad then +good SQL), 429 retry, SSE event formatting. Integration: filter-aware templates against the fixture (region-filtered +averages differ from global ones and only use matching profiles), `/query` with history, `/query/stream` event order, +eval runner against a local app with a fake LLM. + +## Done criteria + +- [ ] "Average temperature at different depths in the Arabian Sea" returns Arabian-Sea-only results, live. +- [ ] A follow-up ("now only the Bay of Bengal") changes the filters and keeps the intent, live. +- [ ] `/query/stream` streams steps and tokens on the live API. +- [ ] The eval suite runs against the live API and its score is in the README. +- [ ] CI green; all Phase 1 behaviour unchanged. From e3d5e16673fe444ecc259cb987dd8e644546ae8c Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 22:57:35 +0530 Subject: [PATCH 2/7] Apply question filters to statistical answers "Average temperature at different depths in the Arabian Sea" used to run a whole-ocean template. Templates now join profiles and take the question's region/month/year/sensor filters as bound parameters (regional comparisons keep every region), and the answer title names the filters. Search and SQL share one filter validator, so invalid values are dropped everywhere. Co-Authored-By: Claude Opus 5.5 --- floatchat/answer.py | 19 +++-- floatchat/filters.py | 48 ++++++++++++ floatchat/search.py | 16 +--- floatchat/sql_agent.py | 104 +++++++++++++++---------- tests/integration/test_answer_db.py | 7 ++ tests/integration/test_search.py | 6 +- tests/integration/test_sql_agent_db.py | 38 ++++++++- tests/unit/test_filters.py | 23 ++++++ 8 files changed, 196 insertions(+), 65 deletions(-) create mode 100644 floatchat/filters.py create mode 100644 tests/unit/test_filters.py diff --git a/floatchat/answer.py b/floatchat/answer.py index 98a62b9..6ad46d3 100644 --- a/floatchat/answer.py +++ b/floatchat/answer.py @@ -6,6 +6,7 @@ from sqlalchemy.engine import Engine from floatchat.db.queries import df_records +from floatchat.filters import clean_filters from floatchat.regions import MONTHS, parse_filters from floatchat.search import search_profiles from floatchat.sql_agent import SqlAgent @@ -87,17 +88,23 @@ def fmt(row, col, unit, digits=2): return "\n".join(lines) -def _analytical_answer(question: str, agent: SqlAgent, chat) -> dict | None: - result, error = agent.run(question) +def _analytical_answer(question: str, agent: SqlAgent, chat, filters: dict) -> dict | None: + result, error = agent.run(question, filters) if error: return None df, intent = result["results"], result["intent"] + applied = clean_filters(filters) + if intent == "regional_comparison": + applied.pop("region", None) insight = chat( f"Question: {question}\n\nSQL result (first rows):\n{df.head(15).to_string(index=False)}\n\n" "In 2-3 sentences, explain the main oceanographic pattern in this result.", system=SYSTEM_PROMPT, ) - answer = f"**{INTENT_TITLES.get(intent, 'Query results')}**\n\n{format_results_for_display(df, intent)}" + title = INTENT_TITLES.get(intent, "Query results") + if applied and intent in INTENT_TITLES: + title += " " + describe_filters(applied) + answer = f"**{title}**\n\n{format_results_for_display(df, intent)}" if insight: answer += f"\n\n**What this means:** {insight}" return { @@ -105,8 +112,8 @@ def _analytical_answer(question: str, agent: SqlAgent, chat) -> dict | None: "query_type": "analytical", "context_documents": [result["sql_query"]], "retrieved_metadata": [{"query_type": "analytical", "intent": intent, "sql_query": result["sql_query"], - "row_count": int(len(df)), "columns": [str(c) for c in df.columns], - "summary_stats": result["summary_stats"]}], + "filters": applied, "row_count": int(len(df)), + "columns": [str(c) for c in df.columns], "summary_stats": result["summary_stats"]}], "sql_results": df_records(df.head(200)), "intent": intent, "llm_used": bool(insight) or intent == "custom", @@ -143,7 +150,7 @@ def _semantic_answer(question: str, engine: Engine, embedder, chat) -> dict: def answer_question(question: str, *, engine: Engine, embedder_factory: Callable, agent: SqlAgent, chat) -> dict: if agent.is_analytical_query(question): - analytical = _analytical_answer(question, agent, chat) + analytical = _analytical_answer(question, agent, chat, parse_filters(question)) if analytical: return analytical return _semantic_answer(question, engine, embedder_factory(), chat) diff --git a/floatchat/filters.py b/floatchat/filters.py new file mode 100644 index 0000000..64de7dc --- /dev/null +++ b/floatchat/filters.py @@ -0,0 +1,48 @@ +""" +Question filters (region, month, year, sensor) shared by profile search and the SQL templates. +Only these keys ever reach SQL, and values are always bound parameters. +""" + +from floatchat.regions import REGIONS + +REGION_NAMES = {name for name, _ in REGIONS} +SENSOR_KEYS = ("has_oxygen", "has_chlorophyll", "has_nitrate", "has_ph") +FILTER_KEYS = ("region", "month_num", "year") + SENSOR_KEYS + +# {a} is the alias of the profiles table in the surrounding query +_CONDITIONS = { + "region": "{a}.region = :region", + "month_num": "EXTRACT(MONTH FROM {a}.profile_date) = :month_num", + "year": "EXTRACT(YEAR FROM {a}.profile_date) = :year", + **{key: "{a}." + key for key in SENSOR_KEYS}, +} + + +def _as_int(value, low: int, high: int): + try: + number = int(value) + except (TypeError, ValueError): + return None + return number if low <= number <= high else None + + +def clean_filters(filters: dict | None) -> dict: + """Keep only known keys with valid values (an LLM or a client may send anything).""" + clean = {} + for key, value in (filters or {}).items(): + if key == "region" and value in REGION_NAMES: + clean[key] = value + elif key == "month_num" and (month := _as_int(value, 1, 12)) is not None: + clean[key] = month + elif key == "year" and (year := _as_int(value, 2000, 2100)) is not None: + clean[key] = year + elif key in SENSOR_KEYS and value is True: + clean[key] = True + return clean + + +def sql_conditions(filters: dict, alias: str) -> tuple[list[str], dict]: + """SQL conditions and bound parameters for already-clean filters.""" + conditions = [_CONDITIONS[key].format(a=alias) for key in FILTER_KEYS if key in filters] + params = {key: filters[key] for key in ("region", "month_num", "year") if key in filters} + return conditions, params diff --git a/floatchat/search.py b/floatchat/search.py index 47ab1cf..3041bc3 100644 --- a/floatchat/search.py +++ b/floatchat/search.py @@ -3,17 +3,7 @@ from sqlalchemy import text from sqlalchemy.engine import Engine -# Only these filter keys reach SQL; values are always bound parameters -FILTER_SQL = { - "region": "region = :region", - "month_num": "EXTRACT(MONTH FROM profile_date) = :month_num", - "year": "EXTRACT(YEAR FROM profile_date) = :year", - "has_oxygen": "has_oxygen", - "has_chlorophyll": "has_chlorophyll", - "has_nitrate": "has_nitrate", - "has_ph": "has_ph", -} -VALUE_FILTERS = ("region", "month_num", "year") +from floatchat.filters import clean_filters, sql_conditions def vector_literal(vector) -> str: @@ -21,8 +11,8 @@ def vector_literal(vector) -> str: def search_profiles(engine: Engine, query_vector, filters: dict, limit: int = 8, ef_search: int = 200) -> list[dict]: - clauses = ["embedding IS NOT NULL"] + [FILTER_SQL[key] for key in filters if key in FILTER_SQL] - params = {key: filters[key] for key in VALUE_FILTERS if key in filters} + conditions, params = sql_conditions(clean_filters(filters), alias="profiles") + clauses = ["embedding IS NOT NULL"] + conditions params.update(q=vector_literal(query_vector), limit=limit) columns = """profile_id, float_id, cycle_number, to_char(profile_date, 'YYYY-MM-DD') AS date, EXTRACT(YEAR FROM profile_date)::int AS year, EXTRACT(MONTH FROM profile_date)::int AS month_num, diff --git a/floatchat/sql_agent.py b/floatchat/sql_agent.py index 80eabdc..cece2a6 100644 --- a/floatchat/sql_agent.py +++ b/floatchat/sql_agent.py @@ -13,34 +13,38 @@ from sqlalchemy.engine import Engine from floatchat import llm +from floatchat.filters import clean_filters, sql_conditions logger = logging.getLogger(__name__) ChatFn = Callable[..., str | None] -ZONE_CASE = ("CASE WHEN depth < 200 THEN 'Euphotic Zone' WHEN depth < 1000 THEN 'Mesopelagic Zone' " +ZONE_CASE = ("CASE WHEN m.depth < 200 THEN 'Euphotic Zone' WHEN m.depth < 1000 THEN 'Mesopelagic Zone' " "ELSE 'Bathypelagic Zone' END") -LAYER_CASE = ("CASE WHEN depth < 100 THEN 'Surface (0-100m)' WHEN depth < 500 THEN 'Intermediate (100-500m)' " - "WHEN depth < 1000 THEN 'Deep (500-1000m)' ELSE 'Very Deep (>1000m)' END") +LAYER_CASE = ("CASE WHEN m.depth < 100 THEN 'Surface (0-100m)' WHEN m.depth < 500 THEN 'Intermediate (100-500m)' " + "WHEN m.depth < 1000 THEN 'Deep (500-1000m)' ELSE 'Very Deep (>1000m)' END") +JOIN_PROFILES = "FROM measurements m JOIN profiles p ON p.profile_id = m.profile_id" +# {where} receives the question's filters as " AND " clauses on the profiles table (alias p) TEMPLATES = { - "avg_by_depth": """ - SELECT depth, AVG(temperature) AS avg_temperature, AVG(salinity) AS avg_salinity, + "avg_by_depth": f""" + SELECT m.depth, AVG(m.temperature) AS avg_temperature, AVG(m.salinity) AS avg_salinity, COUNT(*) AS measurement_count - FROM measurements - WHERE temperature IS NOT NULL AND salinity IS NOT NULL - GROUP BY depth ORDER BY depth LIMIT 100""", - "regional_comparison": """ + {JOIN_PROFILES} + WHERE m.temperature IS NOT NULL AND m.salinity IS NOT NULL{{where}} + GROUP BY m.depth ORDER BY m.depth LIMIT 100""", + "regional_comparison": f""" SELECT p.region, AVG(m.temperature) AS avg_temperature, AVG(m.salinity) AS avg_salinity, AVG(m.oxygen) AS avg_oxygen, COUNT(DISTINCT p.profile_id) AS profile_count, COUNT(*) AS measurement_count - FROM measurements m JOIN profiles p ON m.profile_id = p.profile_id - WHERE m.temperature IS NOT NULL AND m.depth <= 100 + {JOIN_PROFILES} + WHERE m.temperature IS NOT NULL AND m.depth <= 100{{where}} GROUP BY p.region ORDER BY avg_temperature DESC""", "depth_ranges": f""" - SELECT {LAYER_CASE} AS depth_range, AVG(temperature) AS avg_temperature, AVG(salinity) AS avg_salinity, - AVG(oxygen) AS avg_oxygen, COUNT(*) AS measurement_count - FROM measurements WHERE temperature IS NOT NULL - GROUP BY 1 ORDER BY MIN(depth)""", + SELECT {LAYER_CASE} AS depth_range, AVG(m.temperature) AS avg_temperature, + AVG(m.salinity) AS avg_salinity, AVG(m.oxygen) AS avg_oxygen, COUNT(*) AS measurement_count + {JOIN_PROFILES} + WHERE m.temperature IS NOT NULL{{where}} + GROUP BY 1 ORDER BY MIN(m.depth)""", "float_summary": """ SELECT f.float_id, f.wmo_id, f.deployment_date, COUNT(DISTINCT p.profile_id) AS total_profiles, COUNT(m.id) AS total_measurements, AVG(m.temperature) AS avg_temperature, @@ -48,23 +52,33 @@ FROM floats f JOIN profiles p ON f.float_id = p.float_id JOIN measurements m ON p.profile_id = m.profile_id - WHERE m.temperature IS NOT NULL + WHERE m.temperature IS NOT NULL{where} GROUP BY f.float_id, f.wmo_id, f.deployment_date ORDER BY total_measurements DESC LIMIT 50""", - "temporal_trends": """ - SELECT DATE_TRUNC('month', time) AS month, AVG(temperature) AS avg_temperature, - AVG(salinity) AS avg_salinity, COUNT(*) AS measurement_count - FROM measurements WHERE temperature IS NOT NULL + "temporal_trends": f""" + SELECT DATE_TRUNC('month', m.time) AS month, AVG(m.temperature) AS avg_temperature, + AVG(m.salinity) AS avg_salinity, COUNT(*) AS measurement_count + {JOIN_PROFILES} + WHERE m.temperature IS NOT NULL{{where}} GROUP BY 1 ORDER BY month LIMIT 100""", "bgc_analysis": f""" - SELECT {ZONE_CASE} AS ocean_zone, AVG(oxygen) AS avg_oxygen, MIN(oxygen) AS min_oxygen, - MAX(oxygen) AS max_oxygen, AVG(chlorophyll) AS avg_chlorophyll, AVG(nitrate) AS avg_nitrate, - AVG(ph) AS avg_ph, COUNT(*) AS measurement_count - FROM measurements - WHERE oxygen IS NOT NULL OR chlorophyll IS NOT NULL OR nitrate IS NOT NULL OR ph IS NOT NULL - GROUP BY 1 ORDER BY MIN(depth)""", + SELECT {ZONE_CASE} AS ocean_zone, AVG(m.oxygen) AS avg_oxygen, MIN(m.oxygen) AS min_oxygen, + MAX(m.oxygen) AS max_oxygen, AVG(m.chlorophyll) AS avg_chlorophyll, AVG(m.nitrate) AS avg_nitrate, + AVG(m.ph) AS avg_ph, COUNT(*) AS measurement_count + {JOIN_PROFILES} + WHERE (m.oxygen IS NOT NULL OR m.chlorophyll IS NOT NULL OR m.nitrate IS NOT NULL OR m.ph IS NOT NULL){{where}} + GROUP BY 1 ORDER BY MIN(m.depth)""", } + +def render_template(intent: str, filters: dict | None = None) -> tuple[str, dict]: + """A template with the question's filters applied; returns the SQL and its bound parameters.""" + filters = clean_filters(filters) + if intent == "regional_comparison": + filters.pop("region", None) # the point is to compare every region + conditions, params = sql_conditions(filters, alias="p") + return TEMPLATES[intent].format(where="".join(f" AND {c}" for c in conditions)).strip(), params + SCHEMA_PROMPT = """ TABLES (PostgreSQL): floats(float_id text PK, wmo_id int, deployment_date date, deployment_lat float, deployment_lon float, last_contact date) @@ -129,10 +143,12 @@ def validate_sql(sql: str) -> bool: return False return ";" not in lowered.strip().rstrip(";") # exactly one statement - def generate_sql(self, question: str) -> tuple[str | None, str]: - intent = self.detect_query_intent(question) + def generate_sql(self, question: str, filters: dict | None = None, + intent: str | None = None) -> tuple[str | None, str, dict]: + intent = intent or self.detect_query_intent(question) if intent in TEMPLATES: - return TEMPLATES[intent].strip(), intent + sql, params = render_template(intent, filters) + return sql, intent, params prompt = ( "You are an expert PostgreSQL analyst for Argo ocean float data.\n" f"{SCHEMA_PROMPT}\n" @@ -143,18 +159,15 @@ def generate_sql(self, question: str) -> tuple[str | None, str]: ) sql = self.chat(prompt, temperature=0.0) if not sql: - return None, "error" - sql = re.sub(r"```(sql)?", "", sql).strip().rstrip(";") - if "limit" not in sql.lower(): - sql += " LIMIT 1000" - return sql, "custom" + return None, "error", {} + return _clean_llm_sql(sql), "custom", {} - def execute_sql_query(self, sql: str) -> tuple[pd.DataFrame, str]: + def execute_sql_query(self, sql: str, params: dict | None = None) -> tuple[pd.DataFrame, str]: if not self.validate_sql(sql): return pd.DataFrame(), "Invalid or unsafe SQL query" try: with self.engine.connect() as conn: - df = pd.read_sql_query(text(sql), conn) + df = pd.read_sql_query(text(sql), conn, params=params or {}) except Exception as e: logger.info("SQL failed: %s", e) return pd.DataFrame(), f"Database error: {e.__class__.__name__}" @@ -162,16 +175,25 @@ def execute_sql_query(self, sql: str) -> tuple[pd.DataFrame, str]: return df, "Query executed successfully but returned no results" return df, "success" - def run(self, question: str) -> tuple[dict | None, str | None]: - if not self.is_analytical_query(question): + def run(self, question: str, filters: dict | None = None, + intent: str | None = None) -> tuple[dict | None, str | None]: + if intent is None and not self.is_analytical_query(question): return None, "Not an analytical query" - sql, intent = self.generate_sql(question) + sql, intent, params = self.generate_sql(question, filters, intent) if not sql: return None, "Failed to generate SQL" - df, status = self.execute_sql_query(sql) + df, status = self.execute_sql_query(sql, params) if status != "success": return None, f"SQL execution failed: {status}" - return {"sql_query": sql, "results": df, "intent": intent, "summary_stats": _summary_stats(df)}, None + return {"sql_query": sql, "params": params, "results": df, "intent": intent, + "summary_stats": _summary_stats(df)}, None + + +def _clean_llm_sql(sql: str) -> str: + sql = re.sub(r"```(sql)?", "", sql).strip().rstrip(";") + if "limit" not in sql.lower(): + sql += " LIMIT 1000" + return sql def _summary_stats(df: pd.DataFrame) -> dict: diff --git a/tests/integration/test_answer_db.py b/tests/integration/test_answer_db.py index 2f64409..f3973c6 100644 --- a/tests/integration/test_answer_db.py +++ b/tests/integration/test_answer_db.py @@ -20,6 +20,13 @@ def test_analytical_answer(reader_engine): assert result["llm_used"] is False +def test_analytical_answer_applies_the_question_filters(reader_engine): + result = ask(reader_engine, "What is the average temperature at different depths in the Arabian Sea?") + assert result["answer"].startswith("**Average temperature and salinity at each depth in the Arabian Sea**") + assert result["retrieved_metadata"][0]["filters"] == {"region": "Arabian Sea"} + assert ":region" in result["retrieved_metadata"][0]["sql_query"] + + def test_semantic_answer_with_region_filter(reader_engine): result = ask(reader_engine, "Show me profiles in the Arabian Sea") assert result["query_type"] == "semantic" diff --git a/tests/integration/test_search.py b/tests/integration/test_search.py index 244cb60..47d7a36 100644 --- a/tests/integration/test_search.py +++ b/tests/integration/test_search.py @@ -50,5 +50,7 @@ def test_filtered_search_finds_every_match_even_when_the_index_would_miss(loaded forced_index.dispose() -def test_unknown_filter_keys_are_ignored_and_no_match_is_empty(reader_engine): - assert search_profiles(reader_engine, query_vector(), {"region": "Atlantis", "evil": "1; DROP"}) == [] +def test_invalid_filters_are_dropped_and_no_match_is_empty(reader_engine): + unfiltered = search_profiles(reader_engine, query_vector(), {}) + assert search_profiles(reader_engine, query_vector(), {"region": "Atlantis", "evil": "1; DROP"}) == unfiltered + assert search_profiles(reader_engine, query_vector(), {"year": 2030}) == [] diff --git a/tests/integration/test_sql_agent_db.py b/tests/integration/test_sql_agent_db.py index 0c0b093..133e93d 100644 --- a/tests/integration/test_sql_agent_db.py +++ b/tests/integration/test_sql_agent_db.py @@ -1,16 +1,48 @@ import pytest +from sqlalchemy import text -from floatchat.sql_agent import TEMPLATES, SqlAgent +from floatchat.sql_agent import TEMPLATES, SqlAgent, render_template pytestmark = pytest.mark.integration +def no_llm(*a, **k): + return None + + @pytest.mark.parametrize("intent", sorted(TEMPLATES)) def test_every_template_runs(reader_engine, intent): - df, status = SqlAgent(reader_engine, chat=lambda *a, **k: None).execute_sql_query(TEMPLATES[intent]) + sql, params = render_template(intent) + df, status = SqlAgent(reader_engine, chat=no_llm).execute_sql_query(sql, params) assert status == "success" and not df.empty +def test_region_filter_restricts_a_template(reader_engine, loaded_db): + agent = SqlAgent(reader_engine, chat=no_llm) + everywhere, _ = agent.run("What is the average temperature at different depths?") + arabian, error = agent.run("What is the average temperature at different depths?", filters={"region": "Arabian Sea"}) + assert error is None and ":region" in arabian["sql_query"] + with loaded_db.connect() as conn: + expected = conn.execute(text( + "SELECT COUNT(*) FROM measurements m JOIN profiles p ON p.profile_id = m.profile_id " + "WHERE p.region = 'Arabian Sea' AND m.temperature IS NOT NULL AND m.salinity IS NOT NULL")).scalar() + assert int(arabian["results"]["measurement_count"].sum()) == expected + assert int(everywhere["results"]["measurement_count"].sum()) > expected + + +def test_regional_comparison_ignores_the_region_filter(reader_engine): + # "Compare the Arabian Sea and the Bay of Bengal" names regions, but the answer must still compare them all + result, _ = SqlAgent(reader_engine, chat=no_llm).run("Compare surface temperature across ocean regions", + filters={"region": "Arabian Sea"}) + assert len(result["results"]) > 1 + + +def test_filters_with_no_matching_data_report_no_results(reader_engine): + result, error = SqlAgent(reader_engine, chat=no_llm).run("What is the average temperature at different depths?", + filters={"year": 2030}) + assert result is None and "no results" in error + + def test_custom_question_uses_llm_sql(reader_engine): agent = SqlAgent(reader_engine, chat=lambda *a, **k: "```sql\nSELECT region, COUNT(*) AS n FROM profiles GROUP BY region\n```") result, error = agent.run("How many profiles were recorded?") @@ -24,5 +56,5 @@ def test_unsafe_llm_sql_is_refused(reader_engine): def test_no_llm_means_no_custom_sql(reader_engine): - result, error = SqlAgent(reader_engine, chat=lambda *a, **k: None).run("How many profiles were recorded?") + result, error = SqlAgent(reader_engine, chat=no_llm).run("How many profiles were recorded?") assert result is None and error == "Failed to generate SQL" diff --git a/tests/unit/test_filters.py b/tests/unit/test_filters.py new file mode 100644 index 0000000..4ce9efa --- /dev/null +++ b/tests/unit/test_filters.py @@ -0,0 +1,23 @@ +from floatchat.filters import clean_filters, sql_conditions + + +def test_clean_filters_keeps_only_valid_values(): + raw = {"region": "Arabian Sea", "month_num": 3, "year": 2026, "has_oxygen": True, + "evil": "1; DROP", "has_ph": False} + assert clean_filters(raw) == {"region": "Arabian Sea", "month_num": 3, "year": 2026, "has_oxygen": True} + + +def test_clean_filters_rejects_out_of_range_values(): + assert clean_filters({"region": "Atlantis", "month_num": 13, "year": 1890}) == {} + assert clean_filters({"month_num": "4", "year": "2025"}) == {"month_num": 4, "year": 2025} + assert clean_filters(None) == {} + + +def test_sql_conditions_are_parameterised(): + conditions, params = sql_conditions({"region": "Bay of Bengal", "month_num": 2, "has_nitrate": True}, alias="p") + assert conditions == ["p.region = :region", "EXTRACT(MONTH FROM p.profile_date) = :month_num", "p.has_nitrate"] + assert params == {"region": "Bay of Bengal", "month_num": 2} + + +def test_sql_conditions_empty(): + assert sql_conditions({}, alias="p") == ([], {}) From 3c5b29f1ce6ce7f1f60e611dce7a9408819fc7e7 Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 22:59:08 +0530 Subject: [PATCH 3/7] Add LLM router with keyword fallback, follow-ups and Groq 429 retry - floatchat/router.py: the LLM returns a JSON route (path, intent, filters, standalone question), validated against the known intents and filters; the keyword router takes over when there is no LLM or its reply is unusable, and resolves cue-word follow-ups ("now only the Arabian Sea") - llm.chat: JSON mode, one retry on HTTP 429 honouring Retry-After (max 10 s) - llm.chat_stream: yields the answer text as the LLM writes it Co-Authored-By: Claude Opus 5.5 --- floatchat/llm.py | 75 +++++++++++++++++++++-------- floatchat/router.py | 99 +++++++++++++++++++++++++++++++++++++++ tests/unit/test_llm.py | 79 +++++++++++++++++++++++++++++++ tests/unit/test_router.py | 80 +++++++++++++++++++++++++++++++ 4 files changed, 314 insertions(+), 19 deletions(-) create mode 100644 floatchat/router.py create mode 100644 tests/unit/test_llm.py create mode 100644 tests/unit/test_router.py diff --git a/floatchat/llm.py b/floatchat/llm.py index 43a0d2b..63631d1 100644 --- a/floatchat/llm.py +++ b/floatchat/llm.py @@ -4,13 +4,18 @@ fall back to data-only answers. """ +import json import logging +import time +from collections.abc import Iterator import requests from floatchat import config logger = logging.getLogger(__name__) +MAX_RETRY_WAIT = 10.0 +_sleep = time.sleep # replaced in tests def is_configured() -> bool: @@ -22,38 +27,70 @@ def is_configured() -> bool: return True -def chat(prompt: str, system: str | None = None, temperature: float = 0.2, max_tokens: int = 600) -> str | None: - if not is_configured(): - return None - - messages = [] - if system: - messages.append({"role": "system", "content": system}) +def _payload(prompt: str, system: str | None, temperature: float, max_tokens: int, json_mode: bool, + stream: bool = False) -> dict: + messages = [{"role": "system", "content": system}] if system else [] messages.append({"role": "user", "content": prompt}) + payload = {"model": config.LLM_MODEL, "messages": messages, "temperature": temperature, "max_tokens": max_tokens} + if json_mode: + payload["response_format"] = {"type": "json_object"} + if stream: + payload["stream"] = True + return payload + +def _post(payload: dict, stream: bool = False): + """POST to the chat endpoint, retrying once on a rate limit (HTTP 429) after Retry-After (max 10 s).""" headers = {"Content-Type": "application/json"} if config.LLM_API_KEY: headers["Authorization"] = f"Bearer {config.LLM_API_KEY}" + for attempt in (1, 2): + resp = requests.post(f"{config.LLM_BASE_URL}/chat/completions", json=payload, headers=headers, + timeout=config.LLM_TIMEOUT, stream=stream) + if resp.status_code != 429 or attempt == 2: + resp.raise_for_status() + return resp + try: + wait = float(resp.headers.get("retry-after", 2)) + except ValueError: + wait = 2.0 + logger.info("LLM rate-limited; retrying in %.1f s", min(wait, MAX_RETRY_WAIT)) + _sleep(min(wait, MAX_RETRY_WAIT)) + +def chat(prompt: str, system: str | None = None, temperature: float = 0.2, max_tokens: int = 600, + json_mode: bool = False) -> str | None: + if not is_configured(): + return None try: - resp = requests.post( - f"{config.LLM_BASE_URL}/chat/completions", - json={ - "model": config.LLM_MODEL, - "messages": messages, - "temperature": temperature, - "max_tokens": max_tokens, - }, - headers=headers, - timeout=config.LLM_TIMEOUT, - ) - resp.raise_for_status() + resp = _post(_payload(prompt, system, temperature, max_tokens, json_mode)) return resp.json()["choices"][0]["message"]["content"].strip() except Exception as e: logger.warning(f"LLM call failed: {e}") return None +def chat_stream(prompt: str, system: str | None = None, temperature: float = 0.2, + max_tokens: int = 600) -> Iterator[str]: + """Yield the answer text as the LLM writes it; yields nothing if no LLM is available or the call fails.""" + if not is_configured(): + return + try: + resp = _post(_payload(prompt, system, temperature, max_tokens, json_mode=False, stream=True), stream=True) + for line in resp.iter_lines(decode_unicode=True): + if not line or not line.startswith("data: "): + continue + data = line[len("data: "):] + if data.strip() == "[DONE]": + break + text = (json.loads(data)["choices"][0].get("delta") or {}).get("content") + if text: + yield text + resp.close() + except Exception as e: + logger.warning(f"LLM stream failed: {e}") + + def status() -> dict: """Report whether the configured LLM endpoint is reachable.""" if not is_configured(): diff --git a/floatchat/router.py b/floatchat/router.py new file mode 100644 index 0000000..ed2fd9a --- /dev/null +++ b/floatchat/router.py @@ -0,0 +1,99 @@ +""" +Decide how to answer a question: SQL (and which kind) or profile search, with which filters. + +The LLM router understands free phrasing and follow-ups; its JSON reply is validated, and the keyword router +takes over whenever no LLM is available or its reply is unusable. +""" + +import json +import re +from dataclasses import dataclass, field + +from floatchat.filters import FILTER_KEYS, REGION_NAMES, clean_filters +from floatchat.regions import parse_filters +from floatchat.sql_agent import TEMPLATES, SqlAgent + +INTENTS = tuple(TEMPLATES) + ("custom",) +FOLLOW_UP_CUES = re.compile(r"^\s*(now|and|also|then|but|only|just|same|instead|what about|how about)\b", re.I) +HISTORY_TURNS = 3 + +INTENT_HELP = { + "avg_by_depth": "average temperature/salinity at each depth", + "regional_comparison": "compare the regions (upper 100 m)", + "depth_ranges": "averages by depth layer (surface, intermediate, deep)", + "temporal_trends": "monthly averages over time", + "float_summary": "statistics per float, most active floats", + "bgc_analysis": "oxygen, chlorophyll, nitrate or pH by ocean zone", + "custom": "any other statistical question that needs its own SQL", +} + + +@dataclass +class Route: + path: str # "analytical" (SQL) or "semantic" (profile search) + intent: str | None # one of INTENTS for SQL, None for search + filters: dict = field(default_factory=dict) + question: str = "" # standalone question (follow-ups resolved) + source: str = "keywords" # "llm" or "keywords" + + +def keyword_route(question: str, history: list[dict] | None = None) -> Route: + filters = clean_filters(parse_filters(question)) + if SqlAgent.is_analytical_query(question): + return Route("analytical", SqlAgent.detect_query_intent(question), filters, question) + previous = (history or [])[-1] if history else None + if previous and FOLLOW_UP_CUES.search(question) and (filters or previous.get("query_type") == "semantic"): + merged = {**clean_filters(previous.get("filters")), **filters} + standalone = f"{previous.get('question', '')} ({question.strip()})" + if previous.get("query_type") == "analytical" and previous.get("intent") in INTENTS: + return Route("analytical", previous["intent"], merged, standalone) + return Route("semantic", None, merged, standalone) + return Route("semantic", None, filters, question) + + +def _prompt(question: str, history: list[dict]) -> str: + turns = "\n".join( + f"- {t.get('question')} -> {t.get('query_type')}, intent={t.get('intent')}, filters={json.dumps(t.get('filters') or {})}" + for t in history[-HISTORY_TURNS:] + ) or "(none)" + intents = "\n".join(f"- {name}: {text}" for name, text in INTENT_HELP.items()) + return ( + "Route a question about Argo ocean-float data (Indian Ocean, temperature, salinity, oxygen, chlorophyll, " + "nitrate, pH). Reply with JSON only:\n" + '{"path": "analytical" | "semantic", "intent": , "filters": {...}, "question": }\n\n' + "path=analytical for statistics (averages, comparisons, counts, trends) answered with SQL; " + "path=semantic for finding or describing particular profiles or floats.\n" + f"Intents (analytical only):\n{intents}\n" + f"Filter keys: {', '.join(FILTER_KEYS)}. region is one of: {', '.join(sorted(REGION_NAMES))}. " + "month_num is 1-12; has_* filters are true when the question is about that sensor.\n" + "If the question follows up on the previous turn (e.g. 'now only the Arabian Sea'), keep its path and " + "intent, merge the filters, and write the full standalone question.\n\n" + f"Previous turns:\n{turns}\n\nQuestion: {question}" + ) + + +def llm_route(question: str, history: list[dict], chat) -> Route | None: + reply = chat(_prompt(question, history or []), temperature=0.0, max_tokens=300, json_mode=True) + if not reply: + return None + try: + data = json.loads(re.sub(r"^```(json)?|```$", "", reply.strip()).strip()) + except (json.JSONDecodeError, TypeError): + return None + if not isinstance(data, dict) or data.get("path") not in ("analytical", "semantic"): + return None + filters = clean_filters(data.get("filters") if isinstance(data.get("filters"), dict) else {}) + standalone = data.get("question") if isinstance(data.get("question"), str) and data["question"].strip() else question + if data["path"] == "analytical": + intent = data.get("intent") if data.get("intent") in INTENTS else "custom" + return Route("analytical", intent, filters, standalone, "llm") + return Route("semantic", None, filters, standalone, "llm") + + +def route(question: str, history: list[dict] | None, chat, use_llm: bool) -> Route: + history = (history or [])[-HISTORY_TURNS:] + if use_llm: + decided = llm_route(question, history, chat) + if decided: + return decided + return keyword_route(question, history) diff --git a/tests/unit/test_llm.py b/tests/unit/test_llm.py new file mode 100644 index 0000000..ade26fe --- /dev/null +++ b/tests/unit/test_llm.py @@ -0,0 +1,79 @@ +import json + +import pytest + +from floatchat import config, llm + + +class FakeResponse: + def __init__(self, status=200, body=None, headers=None, lines=None): + self.status_code, self.headers = status, headers or {} + self._body, self._lines = body or {}, lines or [] + self.ok = status < 400 + + def raise_for_status(self): + if not self.ok: + raise RuntimeError(f"HTTP {self.status_code}") + + def json(self): + return self._body + + def iter_lines(self, decode_unicode=True): + yield from self._lines + + def close(self): + pass + + +def reply(text): + return FakeResponse(body={"choices": [{"message": {"content": text}}]}) + + +@pytest.fixture(autouse=True) +def configured(monkeypatch): + monkeypatch.setattr(config, "LLM_BASE_URL", "https://llm.example/v1") + monkeypatch.setattr(config, "LLM_MODEL", "test-model") + monkeypatch.setattr(config, "LLM_API_KEY", "key") + + +def install(monkeypatch, responses): + sent, waits = [], [] + + def post(url, json=None, headers=None, timeout=None, stream=False): + sent.append(json) + return responses.pop(0) + + monkeypatch.setattr(llm.requests, "post", post) + monkeypatch.setattr(llm, "_sleep", waits.append) + return sent, waits + + +def test_json_mode_sets_response_format(monkeypatch): + sent, _ = install(monkeypatch, [reply('{"a": 1}')]) + assert llm.chat("q", json_mode=True) == '{"a": 1}' + assert sent[0]["response_format"] == {"type": "json_object"} + + +def test_rate_limit_is_retried_once_honouring_retry_after(monkeypatch): + sent, waits = install(monkeypatch, [FakeResponse(429, headers={"retry-after": "3"}), reply("ok")]) + assert llm.chat("q") == "ok" + assert len(sent) == 2 and waits == [3.0] + + +def test_retry_after_is_capped_and_second_429_gives_up(monkeypatch): + _, waits = install(monkeypatch, [FakeResponse(429, headers={"retry-after": "120"}), FakeResponse(429)]) + assert llm.chat("q") is None + assert waits == [10.0] + + +def test_stream_yields_tokens(monkeypatch): + chunk = lambda text: "data: " + json.dumps({"choices": [{"delta": {"content": text}}]}) # noqa: E731 + lines = [chunk("Hel"), "", chunk("lo"), "data: [DONE]"] + sent, _ = install(monkeypatch, [FakeResponse(lines=lines)]) + assert "".join(llm.chat_stream("q")) == "Hello" + assert sent[0]["stream"] is True + + +def test_stream_yields_nothing_without_an_llm(monkeypatch): + monkeypatch.setattr(config, "LLM_BASE_URL", "") + assert list(llm.chat_stream("q")) == [] diff --git a/tests/unit/test_router.py b/tests/unit/test_router.py new file mode 100644 index 0000000..d664a43 --- /dev/null +++ b/tests/unit/test_router.py @@ -0,0 +1,80 @@ +import json + +from floatchat.router import keyword_route, llm_route, route + +PREVIOUS_SQL = {"question": "What is the average temperature at different depths?", "query_type": "analytical", + "intent": "avg_by_depth", "filters": {"month_num": 3}} +PREVIOUS_SEARCH = {"question": "Show me salinity profiles near the equator", "query_type": "semantic", + "intent": None, "filters": {"region": "Equatorial Indian Ocean"}} + + +def test_keyword_route_matches_phase1_routing(): + r = keyword_route("What is the average temperature at different depths in the Arabian Sea?") + assert (r.path, r.intent, r.filters, r.source) == ("analytical", "avg_by_depth", {"region": "Arabian Sea"}, "keywords") + r = keyword_route("Show me salinity profiles near the equator in March 2024") + assert (r.path, r.intent) == ("semantic", None) + assert r.filters == {"region": "Equatorial Indian Ocean", "month_num": 3, "year": 2024} + + +def test_keyword_follow_up_reuses_the_previous_statistical_question(): + r = keyword_route("now only the Arabian Sea", [PREVIOUS_SQL]) + assert (r.path, r.intent) == ("analytical", "avg_by_depth") + assert r.filters == {"month_num": 3, "region": "Arabian Sea"} + assert r.question.startswith("What is the average temperature at different depths?") + + +def test_keyword_follow_up_on_a_search(): + r = keyword_route("what about February?", [PREVIOUS_SEARCH]) + assert r.path == "semantic" + assert r.filters == {"region": "Equatorial Indian Ocean", "month_num": 2} + + +def test_a_new_question_with_a_region_is_not_a_follow_up(): + r = keyword_route("Show me profiles in the Arabian Sea", [PREVIOUS_SQL]) + assert (r.path, r.filters) == ("semantic", {"region": "Arabian Sea"}) + + +def fake_llm(reply): + calls = [] + + def chat(prompt, **kwargs): + calls.append((prompt, kwargs)) + return reply if isinstance(reply, str) else json.dumps(reply) + + chat.calls = calls + return chat + + +def test_llm_route_is_validated(): + chat = fake_llm({"path": "analytical", "intent": "bgc_analysis", + "filters": {"region": "Arabian Sea", "has_oxygen": True, "month_num": 14, "bogus": 1}, + "question": "Average oxygen by ocean zone in the Arabian Sea"}) + r = llm_route("how's the oxygen doing in the arabian sea, by zone?", [], chat) + assert (r.path, r.intent, r.source) == ("analytical", "bgc_analysis", "llm") + assert r.filters == {"region": "Arabian Sea", "has_oxygen": True} + assert r.question == "Average oxygen by ocean zone in the Arabian Sea" + assert chat.calls[0][1].get("json_mode") is True + + +def test_llm_route_unknown_intent_becomes_custom_sql(): + r = llm_route("q", [], fake_llm({"path": "analytical", "intent": "teleport", "filters": {}, "question": "q"})) + assert (r.path, r.intent) == ("analytical", "custom") + + +def test_llm_route_gives_up_on_malformed_replies(): + assert llm_route("q", [], fake_llm("not json at all")) is None + assert llm_route("q", [], fake_llm({"path": "sideways"})) is None + assert llm_route("q", [], lambda *a, **k: None) is None + + +def test_route_falls_back_to_keywords(): + r = route("What is the average temperature at different depths?", [], fake_llm("garbage"), use_llm=True) + assert (r.source, r.intent) == ("keywords", "avg_by_depth") + chat = fake_llm({"path": "semantic", "filters": {}, "question": "x"}) + assert route("anything", [], chat, use_llm=False).source == "keywords" and not chat.calls + + +def test_llm_prompt_includes_history(): + chat = fake_llm({"path": "analytical", "intent": "avg_by_depth", "filters": {}, "question": "q"}) + llm_route("now only the Arabian Sea", [PREVIOUS_SQL], chat) + assert "What is the average temperature at different depths?" in chat.calls[0][0] From 04a4a3e55016fc84130a9403cb6771e8adb8d837 Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 23:00:42 +0530 Subject: [PATCH 4/7] Repair failed LLM-written SQL using the database error Custom SQL that fails is sent back to the LLM with the database's error message, up to 2 repairs; each attempt is reported as a step. Filters are passed to the LLM when it writes custom SQL. Co-Authored-By: Claude Opus 5.5 --- floatchat/sql_agent.py | 62 ++++++++++++++++++++------ tests/integration/test_sql_agent_db.py | 33 ++++++++++++++ 2 files changed, 82 insertions(+), 13 deletions(-) diff --git a/floatchat/sql_agent.py b/floatchat/sql_agent.py index cece2a6..035d550 100644 --- a/floatchat/sql_agent.py +++ b/floatchat/sql_agent.py @@ -4,8 +4,10 @@ database role is read-only as well, so a bad query can never change data. """ +import json import logging import re +import time from collections.abc import Callable import pandas as pd @@ -17,6 +19,7 @@ logger = logging.getLogger(__name__) ChatFn = Callable[..., str | None] +MAX_SQL_REPAIRS = 2 ZONE_CASE = ("CASE WHEN m.depth < 200 THEN 'Euphotic Zone' WHEN m.depth < 1000 THEN 'Mesopelagic Zone' " "ELSE 'Bathypelagic Zone' END") @@ -149,11 +152,15 @@ def generate_sql(self, question: str, filters: dict | None = None, if intent in TEMPLATES: sql, params = render_template(intent, filters) return sql, intent, params + filters = clean_filters(filters) + scope = (f"Only include profiles matching these filters (columns of profiles): {json.dumps(filters)}. " + "month_num/year refer to profiles.profile_date.\n" if filters else "") prompt = ( "You are an expert PostgreSQL analyst for Argo ocean float data.\n" f"{SCHEMA_PROMPT}\n" "Rules: one read-only SELECT statement; meaningful column aliases; handle NULLs; " - "at most 1000 rows; ORDER BY for readable output.\n\n" + "at most 1000 rows; ORDER BY for readable output.\n" + f"{scope}\n" f"Question: {question}\n" "Return ONLY the SQL, no explanation and no code fences." ) @@ -162,31 +169,60 @@ def generate_sql(self, question: str, filters: dict | None = None, return None, "error", {} return _clean_llm_sql(sql), "custom", {} - def execute_sql_query(self, sql: str, params: dict | None = None) -> tuple[pd.DataFrame, str]: + def _execute(self, sql: str, params: dict | None) -> tuple[pd.DataFrame, str, str]: + """Run SQL; returns (rows, status, database error text for the repair prompt).""" if not self.validate_sql(sql): - return pd.DataFrame(), "Invalid or unsafe SQL query" + return pd.DataFrame(), "Invalid or unsafe SQL query", "The query must be one read-only SELECT statement." try: with self.engine.connect() as conn: df = pd.read_sql_query(text(sql), conn, params=params or {}) except Exception as e: logger.info("SQL failed: %s", e) - return pd.DataFrame(), f"Database error: {e.__class__.__name__}" + detail = str(getattr(e, "orig", e)).strip().splitlines()[0][:300] + return pd.DataFrame(), f"Database error: {e.__class__.__name__}", detail if df.empty: - return df, "Query executed successfully but returned no results" - return df, "success" + return df, "Query executed successfully but returned no results", "" + return df, "success", "" + + def execute_sql_query(self, sql: str, params: dict | None = None) -> tuple[pd.DataFrame, str]: + df, status, _ = self._execute(sql, params) + return df, status + + def _repair(self, question: str, sql: str, error: str) -> str | None: + prompt = ( + "You are an expert PostgreSQL analyst for Argo ocean float data.\n" + f"{SCHEMA_PROMPT}\n" + f"This SQL, written for the question below, failed.\nQuestion: {question}\nSQL: {sql}\n" + f"Error: {error}\n\nReturn ONLY the corrected read-only SQL, no explanation and no code fences." + ) + fixed = self.chat(prompt, temperature=0.0) + return _clean_llm_sql(fixed) if fixed else None - def run(self, question: str, filters: dict | None = None, - intent: str | None = None) -> tuple[dict | None, str | None]: + def run(self, question: str, filters: dict | None = None, intent: str | None = None, + emit: Callable[[dict], None] | None = None) -> tuple[dict | None, str | None]: + emit = emit or (lambda event: None) if intent is None and not self.is_analytical_query(question): return None, "Not an analytical query" sql, intent, params = self.generate_sql(question, filters, intent) if not sql: return None, "Failed to generate SQL" - df, status = self.execute_sql_query(sql, params) - if status != "success": - return None, f"SQL execution failed: {status}" - return {"sql_query": sql, "params": params, "results": df, "intent": intent, - "summary_stats": _summary_stats(df)}, None + repairs_left = MAX_SQL_REPAIRS if intent == "custom" else 0 + for attempt in range(1, repairs_left + 2): + started = time.perf_counter() + df, status, error = self._execute(sql, params) + ok = status == "success" + emit({"step": "sql", "attempt": attempt, "sql": sql, "params": params, + "status": "success" if ok else ("empty" if not error else "error"), + "rows": int(len(df)), "ms": int((time.perf_counter() - started) * 1000)}) + if ok: + return {"sql_query": sql, "params": params, "results": df, "intent": intent, + "attempts": attempt, "summary_stats": _summary_stats(df)}, None + if not error or attempt > repairs_left: + break + sql = self._repair(question, sql, error) # LLM-written SQL failed: send the error back for a fix + if not sql: + break + return None, f"SQL execution failed: {status}" def _clean_llm_sql(sql: str) -> str: diff --git a/tests/integration/test_sql_agent_db.py b/tests/integration/test_sql_agent_db.py index 133e93d..9eb12c3 100644 --- a/tests/integration/test_sql_agent_db.py +++ b/tests/integration/test_sql_agent_db.py @@ -49,6 +49,39 @@ def test_custom_question_uses_llm_sql(reader_engine): assert error is None and result["intent"] == "custom" and "LIMIT 1000" in result["sql_query"] +def test_failed_llm_sql_is_repaired_with_the_database_error(reader_engine): + replies = ["SELECT regoin, COUNT(*) AS n FROM profiles GROUP BY regoin", + "SELECT region, COUNT(*) AS n FROM profiles GROUP BY region"] + prompts, steps = [], [] + + def chat(prompt, **kwargs): + prompts.append(prompt) + return replies.pop(0) + + result, error = SqlAgent(reader_engine, chat=chat).run("How many profiles were recorded?", emit=steps.append) + assert error is None and "region" in result["sql_query"] and len(result["results"]) > 1 + assert "regoin" in prompts[1] and "does not exist" in prompts[1] # the repair prompt carries the real error + assert [s["status"] for s in steps if s["step"] == "sql"] == ["error", "success"] + + +def test_sql_repairs_stop_after_two_attempts(reader_engine): + calls = [] + + def always_broken(prompt, **kwargs): + calls.append(prompt) + return "SELECT nonsense_column FROM profiles" + + result, error = SqlAgent(reader_engine, chat=always_broken).run("How many profiles were recorded?") + assert result is None and "Database error" in error + assert len(calls) == 3 # first try + 2 repairs + + +def test_template_answers_emit_sql_steps(reader_engine): + steps = [] + SqlAgent(reader_engine, chat=no_llm).run("What is the average temperature at different depths?", emit=steps.append) + assert [s["step"] for s in steps] == ["sql"] and steps[0]["status"] == "success" and steps[0]["rows"] > 0 + + def test_unsafe_llm_sql_is_refused(reader_engine): agent = SqlAgent(reader_engine, chat=lambda *a, **k: "DELETE FROM profiles") result, error = agent.run("How many profiles were recorded?") From 38a5e743becdd72fb6fa526a41b5b8e5a5bb63ee Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 23:04:04 +0530 Subject: [PATCH 5/7] Glass-box answers: router-driven pipeline, step trace and SSE streaming - answer_question routes through the LLM/keyword router, reports each step (understood, sql attempts, search, answer) and streams the answer text - /query accepts up to 3 history turns for follow-ups and returns intent, filters and steps; follow-up answers are not cached - POST /query/stream sends step, token and result events (Server-Sent Events); cached answers replay their steps; same rate limits as /query Co-Authored-By: Claude Opus 5.5 --- api/main.py | 85 +++++++++++++++--- floatchat/answer.py | 131 +++++++++++++++++++--------- tests/integration/test_answer_db.py | 40 ++++++++- tests/integration/test_api.py | 61 ++++++++++++- 4 files changed, 262 insertions(+), 55 deletions(-) diff --git a/api/main.py b/api/main.py index cbd092a..6f20f46 100644 --- a/api/main.py +++ b/api/main.py @@ -6,13 +6,16 @@ and caches so repeated questions and dashboard calls stay cheap. """ +import json import logging +import queue +import threading import time from typing import Annotated, Literal from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse, Response +from fastapi.responses import JSONResponse, Response, StreamingResponse from pydantic import BaseModel, Field, StringConstraints from api.cache import TTLCache, normalize_question @@ -33,8 +36,17 @@ ERROR_ANSWER = "Something went wrong while answering that question. Please try rephrasing it." +class HistoryTurn(BaseModel): + """One earlier turn of the conversation, as returned by /query (lets follow-ups be understood).""" + question: Annotated[str, StringConstraints(max_length=300)] + query_type: str | None = None + intent: str | None = None + filters: dict = Field(default_factory=dict) + + class QueryRequest(BaseModel): query_text: Question + history: list[HistoryTurn] = Field(default_factory=list, max_length=3) class QueryResponse(BaseModel): @@ -43,6 +55,9 @@ class QueryResponse(BaseModel): context_documents: list[str] retrieved_metadata: list[dict] sql_results: list[dict] | None = None + intent: str | None = None + filters: dict = Field(default_factory=dict) + steps: list[dict] = Field(default_factory=list) class ProfileRequest(BaseModel): @@ -58,7 +73,7 @@ class ExportRequest(BaseModel): def create_app(engine=None, get_embedder_fn=get_embedder, chat_fn=llm.chat, query_limits=None, other_limit_per_minute: int = 60, llm_budget: int | None = None, - llm_enabled=llm.is_configured) -> FastAPI: + llm_enabled=llm.is_configured, stream_chat_fn=llm.chat_stream) -> FastAPI: engine = engine or make_engine(config.DATABASE_URL) per_minute, per_day = query_limits or (config.QUERY_LIMIT_PER_MINUTE, config.QUERY_LIMIT_PER_DAY) query_limiter = RateLimiter(per_minute, per_day, noun="questions") @@ -73,6 +88,11 @@ def budgeted_chat(*args, **kwargs): return None return chat_fn(*args, **kwargs) + def budgeted_stream(*args, **kwargs): + if not budget.try_consume(): + return iter(()) + return stream_chat_fn(*args, **kwargs) + agent = SqlAgent(engine, chat=budgeted_chat) def cached(cache: TTLCache, key: str, compute): @@ -89,7 +109,7 @@ def cached(cache: TTLCache, key: str, compute): @app.middleware("http") async def rate_limit(request: Request, call_next): if request.method != "OPTIONS" and request.url.path not in UNLIMITED_PATHS: - limiter = query_limiter if request.url.path == "/query" else other_limiter + limiter = query_limiter if request.url.path.startswith("/query") else other_limiter allowed, message = limiter.check(client_ip(request, config.FRONTEND_TOKEN)) if not allowed: return JSONResponse(status_code=429, content={"error": "rate_limited", "message": message}) @@ -132,34 +152,73 @@ def stats(): def floats(): return cached(dashboard, "floats", lambda: queries.get_floats(engine)) - @app.post("/query", response_model=QueryResponse) - def query(request: QueryRequest): - question = request.query_text + def answer(question: str, history: list[HistoryTurn], emit=None, stream: bool = False) -> dict: + """Answer with caching and logging; `emit` receives step/token events (used by the stream endpoint).""" + emit = emit or (lambda event: None) started = time.perf_counter() try: run_id = cached(status, "data", lambda: queries.data_status(engine))["latest_run_id"] except Exception: run_id = 0 + cacheable = not history # a follow-up's answer depends on the conversation key = f"{normalize_question(question)}|{run_id}" # new data -> new key -> no stale answers - result = answers.get(key) + result = answers.get(key) if cacheable else None was_cached = result is not None - if not was_cached: + if was_cached: + for step in result.get("steps", []): + emit({"type": "step", **step}) + emit({"type": "token", "text": result["answer"]}) + else: + llm_expected = llm_enabled() and not budget.exhausted try: - result = answer_question(question, engine=engine, embedder_factory=get_embedder_fn, - agent=agent, chat=budgeted_chat) + result = answer_question(question, engine=engine, embedder_factory=get_embedder_fn, agent=agent, + chat=budgeted_chat, history=[turn.model_dump() for turn in history], + use_llm_router=llm_expected, emit=emit, + stream_chat=budgeted_stream if stream else None) except Exception: logger.exception("Failed to answer %r", question) result = {"answer": ERROR_ANSWER, "query_type": "error", "context_documents": [], "retrieved_metadata": [], "intent": None, "llm_used": False} + emit({"type": "token", "text": ERROR_ANSWER}) # Don't pin a data-only answer for 24 h when the LLM should have helped but failed (e.g. rate limit) - llm_expected = llm_enabled() and not budget.exhausted - if result["query_type"] != "error" and (result.get("llm_used") or not llm_expected): + if cacheable and result["query_type"] != "error" and (result.get("llm_used") or not llm_expected): answers.set(key, result) queries.log_query(engine, question=question, query_type=result["query_type"], intent=result.get("intent"), latency_ms=int((time.perf_counter() - started) * 1000), success=result["query_type"] != "error", cached=was_cached, llm_used=bool(result.get("llm_used")) and not was_cached) - return result + return QueryResponse(**result).model_dump() + + @app.post("/query", response_model=QueryResponse) + def query(request: QueryRequest): + return answer(request.query_text, request.history) + + @app.post("/query/stream") + def query_stream(request: QueryRequest): + """ + Server-Sent Events: `step` events as the answer is worked out, `token` events with the answer text as it + is written, then one `result` event with the same payload /query returns (or `error`). + """ + events: queue.Queue = queue.Queue() + + def work(): + try: + events.put({"type": "result", **answer(request.query_text, request.history, events.put, stream=True)}) + except Exception: + logger.exception("Streaming answer failed") + events.put({"type": "error", "message": ERROR_ANSWER}) + finally: + events.put(None) + + threading.Thread(target=work, daemon=True).start() + + def sse(): + while (event := events.get()) is not None: + kind = event.pop("type") + yield f"event: {kind}\ndata: {json.dumps(event, default=str)}\n\n" + + return StreamingResponse(sse(), media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) @app.post("/get_profiles") def get_profiles(request: ProfileRequest): diff --git a/floatchat/answer.py b/floatchat/answer.py index 6ad46d3..c6bca77 100644 --- a/floatchat/answer.py +++ b/floatchat/answer.py @@ -7,7 +7,8 @@ from floatchat.db.queries import df_records from floatchat.filters import clean_filters -from floatchat.regions import MONTHS, parse_filters +from floatchat.regions import MONTHS +from floatchat.router import Route, route from floatchat.search import search_profiles from floatchat.sql_agent import SqlAgent @@ -88,27 +89,57 @@ def fmt(row, col, unit, digits=2): return "\n".join(lines) -def _analytical_answer(question: str, agent: SqlAgent, chat, filters: dict) -> dict | None: - result, error = agent.run(question, filters) +class _Writer: + """Collects answer text and, when streaming, emits every piece as a token event as it is written.""" + + def __init__(self, emit, chat, stream_chat): + self.emit, self.chat, self.stream_chat = emit, chat, stream_chat + self.parts: list[str] = [] + + def write(self, text: str) -> None: + if text: + self.parts.append(text) + self.emit({"type": "token", "text": text}) + + def llm(self, prompt: str, prefix: str = "") -> bool: + """Write the LLM's reply (streamed when possible), preceded by `prefix`; False if the LLM gave nothing.""" + if self.stream_chat: + wrote = False + for piece in self.stream_chat(prompt, system=SYSTEM_PROMPT): + if not wrote: + self.write(prefix) + wrote = True + self.write(piece) + return wrote + text = self.chat(prompt, system=SYSTEM_PROMPT) + if text: + self.write(prefix + text) + return bool(text) + + @property + def text(self) -> str: + return "".join(self.parts) + + +def _analytical_answer(route: Route, agent: SqlAgent, writer: _Writer, step) -> dict | None: + result, error = agent.run(route.question, route.filters, route.intent, emit=step) if error: return None df, intent = result["results"], result["intent"] - applied = clean_filters(filters) + applied = clean_filters(route.filters) if intent == "regional_comparison": applied.pop("region", None) - insight = chat( - f"Question: {question}\n\nSQL result (first rows):\n{df.head(15).to_string(index=False)}\n\n" - "In 2-3 sentences, explain the main oceanographic pattern in this result.", - system=SYSTEM_PROMPT, - ) title = INTENT_TITLES.get(intent, "Query results") if applied and intent in INTENT_TITLES: title += " " + describe_filters(applied) - answer = f"**{title}**\n\n{format_results_for_display(df, intent)}" - if insight: - answer += f"\n\n**What this means:** {insight}" + writer.write(f"**{title}**\n\n{format_results_for_display(df, intent)}") + insight = writer.llm( + f"Question: {route.question}\n\nSQL result (first rows):\n{df.head(15).to_string(index=False)}\n\n" + "In 2-3 sentences, explain the main oceanographic pattern in this result.", + prefix="\n\n**What this means:** ", + ) return { - "answer": answer, + "answer": writer.text, "query_type": "analytical", "context_documents": [result["sql_query"]], "retrieved_metadata": [{"query_type": "analytical", "intent": intent, "sql_query": result["sql_query"], @@ -116,41 +147,63 @@ def _analytical_answer(question: str, agent: SqlAgent, chat, filters: dict) -> d "columns": [str(c) for c in df.columns], "summary_stats": result["summary_stats"]}], "sql_results": df_records(df.head(200)), "intent": intent, - "llm_used": bool(insight) or intent == "custom", + "filters": applied, + "llm_used": insight or intent == "custom", } -def _semantic_answer(question: str, engine: Engine, embedder, chat) -> dict: - filters = parse_filters(question) - vector = embedder.embed([question])[0] +def _semantic_answer(route: Route, engine: Engine, embedder, writer: _Writer, step) -> dict: + filters = clean_filters(route.filters) + vector = embedder.embed([route.question])[0] matches = search_profiles(engine, vector, filters) - note = "" - if not matches and filters: - note = (f"No profiles were recorded {describe_filters(filters)} in this dataset, " - "so these are the closest matches overall.\n\n") + fallback = not matches and bool(filters) + if fallback: matches = search_profiles(engine, vector, {}) + step({"step": "search", "matches": len(matches), "filters": filters, "fallback_without_filters": fallback}) if not matches: - return {"answer": "I couldn't find any matching Argo profiles.", "query_type": "semantic", - "context_documents": [], "retrieved_metadata": [], "intent": None, "llm_used": False} + writer.write("I couldn't find any matching Argo profiles.") + return {"answer": writer.text, "query_type": "semantic", "context_documents": [], "retrieved_metadata": [], + "intent": None, "filters": filters, "llm_used": False} + if fallback: + writer.write(f"No profiles were recorded {describe_filters(filters)} in this dataset, " + "so these are the closest matches overall.\n\n") documents = [m["description"] for m in matches] metadata = [{k: v for k, v in m.items() if k not in ("description", "distance")} for m in matches] context = "\n".join(f"- {doc}" for doc in documents) - answer = chat(f"Context:\n{context}\n\nQuestion: {question}", system=SYSTEM_PROMPT) - llm_used = bool(answer) - if not answer: - scope = f" {describe_filters(filters)}" if filters and not note else "" + llm_used = writer.llm(f"Context:\n{context}\n\nQuestion: {route.question}") + if not llm_used: + scope = f" {describe_filters(filters)}" if filters and not fallback else "" bullets = "\n".join(f"- **Float {m['float_id']}**, cycle {m['cycle_number']} · {m['date']} · " f"{format_position(m['lat'], m['lon'])} ({m['region']})" for m in metadata) - answer = (f"Here are the {len(metadata)} Argo profiles{scope} most relevant to your question:\n\n" - f"{bullets}\n\nTop match: {documents[0]}") - return {"answer": note + answer, "query_type": "semantic", "context_documents": documents, - "retrieved_metadata": metadata, "intent": None, "llm_used": llm_used} - - -def answer_question(question: str, *, engine: Engine, embedder_factory: Callable, agent: SqlAgent, chat) -> dict: - if agent.is_analytical_query(question): - analytical = _analytical_answer(question, agent, chat, parse_filters(question)) - if analytical: - return analytical - return _semantic_answer(question, engine, embedder_factory(), chat) + writer.write(f"Here are the {len(metadata)} Argo profiles{scope} most relevant to your question:\n\n" + f"{bullets}\n\nTop match: {documents[0]}") + return {"answer": writer.text, "query_type": "semantic", "context_documents": documents, + "retrieved_metadata": metadata, "intent": None, "filters": filters, "llm_used": llm_used} + + +def answer_question(question: str, *, engine: Engine, embedder_factory: Callable, agent: SqlAgent, chat, + history: list[dict] | None = None, use_llm_router: bool = False, + emit: Callable[[dict], None] | None = None, stream_chat=None) -> dict: + """ + Answer a question and report each step. `emit` receives {"type": "step", ...} and {"type": "token", "text"} + events as they happen; with `stream_chat`, the LLM's text arrives token by token. + """ + emit = emit or (lambda event: None) + steps: list[dict] = [] + + def step(event: dict) -> None: + steps.append(event) + emit({"type": "step", **event}) + + decided = route(question, history, chat, use_llm_router) + step({"step": "understood", "path": decided.path, "intent": decided.intent, "filters": decided.filters, + "question": decided.question, "router": decided.source}) + result = None + if decided.path == "analytical": + result = _analytical_answer(decided, agent, _Writer(emit, chat, stream_chat), step) + if result is None: + result = _semantic_answer(decided, engine, embedder_factory(), _Writer(emit, chat, stream_chat), step) + step({"step": "answer", "llm_used": bool(result["llm_used"])}) + result["steps"] = steps + return result diff --git a/tests/integration/test_answer_db.py b/tests/integration/test_answer_db.py index f3973c6..fc19da9 100644 --- a/tests/integration/test_answer_db.py +++ b/tests/integration/test_answer_db.py @@ -7,9 +7,9 @@ pytestmark = pytest.mark.integration -def ask(engine, question, chat=lambda *a, **k: None): +def ask(engine, question, chat=lambda *a, **k: None, **kwargs): return answer_question(question, engine=engine, embedder_factory=FakeEmbedder, - agent=SqlAgent(engine, chat=chat), chat=chat) + agent=SqlAgent(engine, chat=chat), chat=chat, **kwargs) def test_analytical_answer(reader_engine): @@ -24,6 +24,7 @@ def test_analytical_answer_applies_the_question_filters(reader_engine): result = ask(reader_engine, "What is the average temperature at different depths in the Arabian Sea?") assert result["answer"].startswith("**Average temperature and salinity at each depth in the Arabian Sea**") assert result["retrieved_metadata"][0]["filters"] == {"region": "Arabian Sea"} + assert result["filters"] == {"region": "Arabian Sea"} assert ":region" in result["retrieved_metadata"][0]["sql_query"] @@ -43,3 +44,38 @@ def test_semantic_answer_falls_back_when_filters_match_nothing(reader_engine): def test_llm_text_is_used_when_available(reader_engine): result = ask(reader_engine, "Show me profiles in the Arabian Sea", chat=lambda *a, **k: "MOCK ANSWER") assert result["answer"] == "MOCK ANSWER" and result["llm_used"] is True + + +def test_steps_describe_what_happened(reader_engine): + result = ask(reader_engine, "What is the average temperature at different depths in the Arabian Sea?") + steps = result["steps"] + assert [s["step"] for s in steps] == ["understood", "sql", "answer"] + assert steps[0]["path"] == "analytical" and steps[0]["router"] == "keywords" + assert steps[1]["status"] == "success" and steps[1]["rows"] > 0 + search_steps = ask(reader_engine, "Show me profiles in the Arabian Sea")["steps"] + assert [s["step"] for s in search_steps] == ["understood", "search", "answer"] + assert search_steps[1]["matches"] > 0 + + +def test_streamed_tokens_add_up_to_the_answer(reader_engine): + events = [] + + def stream_chat(prompt, **kwargs): + yield from ["Mock ", "streamed ", "insight."] + + for question in ("What is the average temperature at different depths?", "Show me profiles in the Arabian Sea"): + events.clear() + result = ask(reader_engine, question, emit=events.append, stream_chat=stream_chat) + tokens = "".join(e["text"] for e in events if e["type"] == "token") + assert tokens == result["answer"] and "Mock streamed insight." in result["answer"] + assert result["llm_used"] is True + assert [e["step"] for e in events if e["type"] == "step"] == [s["step"] for s in result["steps"]] + + +def test_follow_up_uses_the_history(reader_engine): + first = ask(reader_engine, "What is the average temperature at different depths?") + turn = {"question": "What is the average temperature at different depths?", "query_type": first["query_type"], + "intent": first["intent"], "filters": first["filters"]} + follow_up = ask(reader_engine, "now only the Arabian Sea", history=[turn]) + assert follow_up["intent"] == "avg_by_depth" and follow_up["filters"] == {"region": "Arabian Sea"} + assert follow_up["answer"].startswith("**Average temperature and salinity at each depth in the Arabian Sea**") diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py index d62c2c0..cd076d4 100644 --- a/tests/integration/test_api.py +++ b/tests/integration/test_api.py @@ -1,3 +1,5 @@ +import json + import pytest from fastapi.testclient import TestClient from sqlalchemy import text @@ -12,9 +14,22 @@ def make_client(engine, **kwargs): kwargs.setdefault("get_embedder_fn", FakeEmbedder) kwargs.setdefault("chat_fn", lambda *a, **k: None) kwargs.setdefault("llm_enabled", lambda: False) + kwargs.setdefault("stream_chat_fn", lambda *a, **k: iter(())) return TestClient(create_app(engine=engine, **kwargs)) +def stream(client, question, history=None, ip="1.1.1.1"): + """POST /query/stream and parse the Server-Sent Events into (event, data) pairs.""" + resp = client.post("/query/stream", json={"query_text": question, "history": history or []}, + headers={"X-Forwarded-For": ip}) + assert resp.status_code == 200 and resp.headers["content-type"].startswith("text/event-stream") + events = [] + for block in resp.text.strip().split("\n\n"): + lines = dict(line.split(": ", 1) for line in block.splitlines()) + events.append((lines["event"], json.loads(lines["data"]))) + return events + + def ask(client, question, ip="1.1.1.1"): return client.post("/query", json={"query_text": question}, headers={"X-Forwarded-For": ip}) @@ -44,12 +59,54 @@ def test_query_analytical_and_semantic(reader_engine): client = make_client(reader_engine) analytical = ask(client, "What is the average temperature at different depths?").json() assert analytical["query_type"] == "analytical" and analytical["sql_results"] - assert set(analytical) == {"answer", "query_type", "context_documents", "retrieved_metadata", "sql_results"} + assert set(analytical) == {"answer", "query_type", "context_documents", "retrieved_metadata", "sql_results", + "intent", "filters", "steps"} + assert analytical["intent"] == "avg_by_depth" and [s["step"] for s in analytical["steps"]][0] == "understood" semantic = ask(client, "Show me profiles in the Arabian Sea").json() assert semantic["query_type"] == "semantic" assert all(m["region"] == "Arabian Sea" for m in semantic["retrieved_metadata"]) +def test_follow_up_question_with_history(reader_engine): + client = make_client(reader_engine) + first = ask(client, "What is the average temperature at different depths?").json() + history = [{"question": "What is the average temperature at different depths?", + "query_type": first["query_type"], "intent": first["intent"], "filters": first["filters"]}] + resp = client.post("/query", json={"query_text": "now only the Arabian Sea", "history": history}, + headers={"X-Forwarded-For": "1.1.1.1"}).json() + assert resp["intent"] == "avg_by_depth" and resp["filters"] == {"region": "Arabian Sea"} + too_long = client.post("/query", json={"query_text": "x", "history": history * 4}) + assert too_long.status_code == 422 + + +def test_stream_sends_steps_tokens_then_the_result(reader_engine): + client = make_client(reader_engine, chat_fn=lambda *a, **k: None, + stream_chat_fn=lambda *a, **k: iter(["Streamed ", "answer."]), llm_enabled=lambda: True) + events = stream(client, "Show me profiles in the Arabian Sea") + kinds = [kind for kind, _ in events] + assert kinds[0] == "step" and kinds[-1] == "result" and "token" in kinds + assert kinds.index("token") > kinds.index("step") + result = events[-1][1] + assert result["answer"] == "".join(data["text"] for kind, data in events if kind == "token") + assert result["answer"] == "Streamed answer." and result["query_type"] == "semantic" + assert [data["step"] for kind, data in events if kind == "step"] == [s["step"] for s in result["steps"]] + + +def test_cached_stream_replays_steps(reader_engine): + client = make_client(reader_engine) + first = stream(client, "What is the average temperature at different depths?") + second = stream(client, "What is the average temperature at different depths?") + assert [k for k, _ in second] == [k for k, _ in first if k == "step"] + ["token", "result"] + assert second[-1][1]["answer"] == first[-1][1]["answer"] + + +def test_stream_is_rate_limited_with_query(reader_engine): + client = make_client(reader_engine, query_limits=(1, 100)) + stream(client, "Show me profiles in the Arabian Sea") + limited = client.post("/query", json={"query_text": "again"}, headers={"X-Forwarded-For": "1.1.1.1"}) + assert limited.status_code == 429 + + def test_query_validation(reader_engine): client = make_client(reader_engine) assert ask(client, " ").status_code == 422 @@ -80,6 +137,8 @@ def test_answers_are_not_cached_when_the_llm_failed(reader_engine, loaded_db): calls = [] def flaky_llm(*a, **k): + if k.get("json_mode"): + return None # router call: fall back to keywords calls.append(1) return None if len(calls) == 1 else "MOCK ANSWER" From cb52088191eb6acfae694ed442721dc3cb40e470 Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 23:07:27 +0530 Subject: [PATCH 6/7] Streamlit: send follow-up history and show how each answer was built The chat now sends the last three answered turns so questions like "now only the Arabian Sea" keep the earlier analysis, and every answer has a "How I answered" expander listing the router decision, SQL attempts, search matches and whether the LLM wrote the text. Example dates now match the rolling 12-month dataset. Co-Authored-By: Claude Opus 5.5 --- app.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/app.py b/app.py index 6d53c72..332b79b 100644 --- a/app.py +++ b/app.py @@ -31,7 +31,7 @@ SUGGESTIONS = [ # (icon, topic, question) ("🌡️", "Depth structure", "What is the average temperature at different depths?"), ("🗺️", "Regions", "Compare surface temperature across ocean regions"), - ("🔎", "Find profiles", "Show me salinity profiles near the equator in March 2024"), + ("🔎", "Find profiles", "Show me salinity profiles near the equator in March 2026"), ("🫧", "Oxygen minimum", "Which floats measured low oxygen in the Arabian Sea?"), ("🧪", "Biogeochemistry", "Average dissolved oxygen by ocean zone"), ("📅", "Trends", "Show the monthly temperature trend"), @@ -151,10 +151,23 @@ def export_profiles(profile_ids: tuple, fmt: str) -> bytes: return api_post("/export", {"format": fmt, "profile_ids": list(profile_ids)}).content +def conversation_history(turns: int = 3) -> list[dict]: + """The last few answered questions, so the API can understand follow-ups like "now only the Arabian Sea".""" + history, question = [], None + for msg in st.session_state.messages: + if msg["role"] == "user": + question = msg["content"] + elif question and (response := msg.get("response")) and response.get("query_type") in ("analytical", "semantic"): + history.append({"question": question, "query_type": response["query_type"], + "intent": response.get("intent"), "filters": response.get("filters") or {}}) + question = None + return history[-turns:] + + def ask_backend(question: str) -> dict: try: started = time.perf_counter() - response = api_post("/query", {"query_text": question}).json() + response = api_post("/query", {"query_text": question, "history": conversation_history()}).json() response["elapsed"] = time.perf_counter() - started return response except requests.exceptions.RequestException as e: @@ -485,11 +498,46 @@ def render_response(msg: dict, idx: int): for doc in response.get("context_documents", []): st.caption(doc) + render_steps(response.get("steps") or []) + + +def describe_step(step: dict) -> str: + kind = step.get("step") + if kind == "understood": + parts = [] + for key, value in (step.get("filters") or {}).items(): + parts.append(key.removeprefix("has_") if value is True else f"{key.replace('_num', '')}={value}") + filters = ", ".join(parts) or "none" + how = "SQL" if step.get("path") == "analytical" else "profile search" + intent = f" · {step['intent'].replace('_', ' ')}" if step.get("intent") else "" + return (f"**Understood** ({'AI router' if step.get('router') == 'llm' else 'keyword router'}): " + f"{how}{intent} · filters: {filters}") + if kind == "sql": + status = {"success": f"{step.get('rows', 0)} rows", "empty": "no rows", "error": "failed, repairing"} + return f"**SQL attempt {step.get('attempt', 1)}**: {status.get(step.get('status'), step.get('status'))} · {step.get('ms', 0)} ms" + if kind == "search": + note = " (no exact match, widened the search)" if step.get("fallback_without_filters") else "" + return f"**Searched profiles**: {step.get('matches', 0)} matches{note}" + if kind == "answer": + return "**Answer** written by the LLM" if step.get("llm_used") else "**Answer** built from the data" + return f"**{kind}**" + + +def render_steps(steps: list[dict]): + if not steps: + return + with st.expander("How I answered"): + for step in steps: + st.markdown(f"- {describe_step(step)}") + if step.get("step") == "sql" and step.get("status") != "success": + st.code(step.get("sql", ""), language="sql") + def render_chat(): st.markdown("## 💬 Ask FloatChat") - st.caption("Ask about temperature, salinity or oxygen in the Indian Ocean (Jan–Mar 2024). " - "Statistical questions run as SQL; descriptive ones search the profile index.") + st.caption("Ask about temperature, salinity or oxygen in the Indian Ocean over the last 12 months. " + "Statistical questions run as SQL; descriptive ones search the profile index. " + "Follow-ups work too, e.g. *now only the Arabian Sea*.") if not st.session_state.messages: st.markdown(""" @@ -512,7 +560,7 @@ def render_chat(): if msg["role"] == "assistant": render_response(msg, idx) - question = st.chat_input("e.g. Show me salinity profiles near the equator in March 2024") + question = st.chat_input("e.g. Show me salinity profiles near the equator in March 2026") question = question or st.session_state.pop("pending_question", None) if question: st.session_state.messages.append({"role": "user", "content": question}) From 81716cec777ec29b65051f4f29bfce463c53d5e6 Mon Sep 17 00:00:00 2001 From: CodexManvik Date: Sun, 8 Nov 2026 23:13:18 +0530 Subject: [PATCH 7/7] Add an evaluation suite that scores routing, filters and answers eval/questions.json holds 30 benchmark questions (every analysis, region, month/year, sensor, descriptive search and follow-up). python -m eval --api asks them with rate-limit pacing and scores routing, filter accuracy and answer checks (SQL rows that really apply the filters; searched profiles that match them), writing eval/latest.md and eval/latest.json. A weekly workflow runs it against the live API. The README documents Phase 2. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/eval.yml | 33 +++++ eval/__init__.py | 1 + eval/__main__.py | 87 ++++++++++++ eval/questions.json | 66 +++++++++ eval/runner.py | 214 +++++++++++++++++++++++++++++ readme.md | 65 +++++++-- tests/integration/test_eval_api.py | 26 ++++ tests/unit/test_eval.py | 144 +++++++++++++++++++ 8 files changed, 622 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/eval.yml create mode 100644 eval/__init__.py create mode 100644 eval/__main__.py create mode 100644 eval/questions.json create mode 100644 eval/runner.py create mode 100644 tests/integration/test_eval_api.py create mode 100644 tests/unit/test_eval.py diff --git a/.github/workflows/eval.yml b/.github/workflows/eval.yml new file mode 100644 index 0000000..17cfd47 --- /dev/null +++ b/.github/workflows/eval.yml @@ -0,0 +1,33 @@ +name: Evaluation + +on: + workflow_dispatch: + inputs: + api: + description: "API to evaluate" + default: "https://floatchat-ai-svjw.onrender.com" + schedule: + - cron: "0 4 * * 1" # Mondays 04:00 UTC, after the daily refresh + +permissions: + contents: read + +jobs: + eval: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: pip install "requests==2.34.2" + - name: Ask the benchmark questions and score the answers + run: python -m eval --api "${{ github.event.inputs.api || 'https://floatchat-ai-svjw.onrender.com' }}" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: eval-results + path: | + eval/latest.json + eval/latest.md diff --git a/eval/__init__.py b/eval/__init__.py new file mode 100644 index 0000000..7867570 --- /dev/null +++ b/eval/__init__.py @@ -0,0 +1 @@ +"""Benchmark questions and a runner that scores how well FloatChat understands and answers them.""" diff --git a/eval/__main__.py b/eval/__main__.py new file mode 100644 index 0000000..d2358ad --- /dev/null +++ b/eval/__main__.py @@ -0,0 +1,87 @@ +""" +Run the benchmark against a FloatChat API and write the scores. + + python -m eval --api https://floatchat-ai-svjw.onrender.com + python -m eval --api http://localhost:8000 --delay 0 --only depth-avg,regions +""" + +import argparse +import json +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +import requests + +from eval.runner import load_cases, run_eval, summarize, to_markdown + +HERE = Path(__file__).parent + + +def http_sender(api: str, timeout: float = 90): + session = requests.Session() + session.headers["User-Agent"] = "FloatChat-eval" + + def send(payload: dict) -> tuple[int, dict]: + try: + response = session.post(f"{api}/query", json=payload, timeout=timeout) + except requests.RequestException as e: + print(f" request failed: {e.__class__.__name__}") + return 0, {} + try: + return response.status_code, response.json() + except ValueError: + return response.status_code, {} + + return send + + +def wake(api: str) -> None: + """Free hosting sleeps when idle; wait for it so the first question's latency isn't a cold start.""" + try: + health = requests.get(f"{api}/health", timeout=180, headers={"User-Agent": "FloatChat-eval"}).json() + print(f"API {health.get('status')}: {health.get('indexed_profiles')} profiles, LLM {health.get('llm')}") + except (requests.RequestException, ValueError) as e: + print(f"Health check failed ({e.__class__.__name__}); trying the questions anyway") + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(prog="python -m eval", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--api", default=os.getenv("FLOATCHAT_API", "http://localhost:8000")) + parser.add_argument("--cases", default=str(HERE / "questions.json")) + parser.add_argument("--delay", type=float, default=6.5, + help="seconds between questions (the public API allows 10 per minute)") + parser.add_argument("--only", help="comma-separated case ids (their follow-up parents are added)") + parser.add_argument("--out", default=str(HERE / "latest.json")) + parser.add_argument("--markdown", default=str(HERE / "latest.md")) + args = parser.parse_args(argv) + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + + api = args.api.rstrip("/") + cases = load_cases(args.cases) + if args.only: + wanted = set(args.only.split(",")) + wanted |= {c["follow_up_of"] for c in cases if c["id"] in wanted and c.get("follow_up_of")} + cases = [c for c in cases if c["id"] in wanted] + + wake(api) + results = run_eval(cases, http_sender(api), delay=args.delay) + summary = summarize(results) + ran_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + markdown = to_markdown(summary, results, api, ran_at) + + Path(args.out).write_text(json.dumps({"api": api, "ran_at": ran_at, "summary": summary, "results": results}, + indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + Path(args.markdown).write_text(markdown, encoding="utf-8") + if os.getenv("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as f: + f.write(markdown) + print("\n" + markdown) + return 1 if summary["failed_requests"] == summary["cases"] else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/eval/questions.json b/eval/questions.json new file mode 100644 index 0000000..8db6fd6 --- /dev/null +++ b/eval/questions.json @@ -0,0 +1,66 @@ +[ + {"id": "depth-avg", "question": "What is the average temperature at different depths?", + "expect": {"path": "analytical", "intent": "avg_by_depth", "filters": {}}}, + {"id": "depth-avg-arabian", "question": "What is the average temperature at different depths in the Arabian Sea?", + "expect": {"path": "analytical", "intent": "avg_by_depth", "filters": {"region": "Arabian Sea"}}}, + {"id": "depth-avg-bengal-march", "question": "Average salinity by depth in the Bay of Bengal in March 2026", + "expect": {"path": "analytical", "intent": "avg_by_depth", + "filters": {"region": "Bay of Bengal", "month_num": 3, "year": 2026}}}, + {"id": "regions", "question": "Compare surface temperature across ocean regions", + "expect": {"path": "analytical", "intent": "regional_comparison", "filters": {}}}, + {"id": "regions-warmest", "question": "Which region has the highest average temperature in the upper ocean?", + "expect": {"path": "analytical", "intent": "regional_comparison", "filters": {}}}, + {"id": "layers", "question": "Show temperature and salinity by depth layer", + "expect": {"path": "analytical", "intent": "depth_ranges", "filters": {}}}, + {"id": "layers-southern", "question": "Compare surface and deep water in the Southern Indian Ocean", + "expect": {"path": "analytical", "intent": "depth_ranges", "filters": {"region": "Southern Indian Ocean"}}}, + {"id": "monthly", "question": "Show the monthly trend of surface temperature", + "expect": {"path": "analytical", "intent": "temporal_trends", "filters": {}}}, + {"id": "monthly-equator", "question": "How has the average temperature near the equator changed over time?", + "expect": {"path": "analytical", "intent": "temporal_trends", "filters": {"region": "Equatorial Indian Ocean"}}}, + {"id": "floats-active", "question": "Give me a summary of the most active floats", + "expect": {"path": "analytical", "intent": "float_summary", "filters": {}}}, + {"id": "floats-arabian", "question": "Summarize the floats operating in the Arabian Sea", + "expect": {"path": "analytical", "intent": "float_summary", "filters": {"region": "Arabian Sea"}}}, + {"id": "bgc-oxygen", "question": "Average dissolved oxygen by ocean zone", + "expect": {"path": "analytical", "intent": "bgc_analysis", "filters": {}, "optional_filters": ["has_oxygen"]}}, + {"id": "bgc-chlorophyll-bengal", "question": "Compare chlorophyll levels across zones in the Bay of Bengal", + "expect": {"path": "analytical", "intent": "bgc_analysis", "filters": {"region": "Bay of Bengal"}, + "optional_filters": ["has_chlorophyll"]}}, + {"id": "bgc-ph", "question": "What is the average pH in each ocean zone?", + "expect": {"path": "analytical", "intent": "bgc_analysis", "filters": {}, "optional_filters": ["has_ph"]}}, + {"id": "count-arabian", "question": "How many profiles were recorded in the Arabian Sea?", + "expect": {"path": "analytical", "intent": "custom", "filters": {"region": "Arabian Sea"}}}, + {"id": "max-bengal-2026", "question": "What was the maximum temperature recorded in the Bay of Bengal in 2026?", + "expect": {"path": "analytical", "intent": "custom", "filters": {"region": "Bay of Bengal", "year": 2026}}}, + {"id": "mean-salinity-1000m", "question": "What is the mean salinity at 1000 m?", + "expect": {"path": "analytical", "intent": ["custom", "avg_by_depth"], "filters": {}}}, + {"id": "find-equator-march", "question": "Show me salinity profiles near the equator in March 2026", + "expect": {"path": "semantic", + "filters": {"region": "Equatorial Indian Ocean", "month_num": 3, "year": 2026}}}, + {"id": "find-low-oxygen", "question": "Which floats measured low oxygen in the Arabian Sea?", + "expect": {"path": "semantic", "filters": {"region": "Arabian Sea", "has_oxygen": true}}}, + {"id": "find-bengal", "question": "Find profiles from the Bay of Bengal", + "expect": {"path": "semantic", "filters": {"region": "Bay of Bengal"}}}, + {"id": "find-chlorophyll-southern", "question": "Show me floats with chlorophyll sensors in the Southern Indian Ocean", + "expect": {"path": "semantic", "filters": {"region": "Southern Indian Ocean", "has_chlorophyll": true}}}, + {"id": "find-indonesia-january", "question": "Profiles near Indonesia in January 2026", + "expect": {"path": "semantic", "filters": {"region": "Eastern Indian Ocean", "month_num": 1, "year": 2026}}}, + {"id": "find-red-sea", "question": "Describe recent profiles from the Red Sea", + "expect": {"path": "semantic", "filters": {"region": "Red Sea & Gulf of Aden"}}}, + {"id": "find-nitrate-arabian", "question": "Find nitrate measurements in the Arabian Sea", + "expect": {"path": "semantic", "filters": {"region": "Arabian Sea", "has_nitrate": true}}}, + {"id": "find-thermocline", "question": "Show me profiles with a strong thermocline", + "expect": {"path": "semantic", "filters": {}}}, + {"id": "find-bengal-september", "question": "Profiles in the Bay of Bengal in September 2026", + "expect": {"path": "semantic", "filters": {"region": "Bay of Bengal", "month_num": 9, "year": 2026}}}, + {"id": "follow-region", "follow_up_of": "depth-avg", "question": "now only the Bay of Bengal", + "expect": {"path": "analytical", "intent": "avg_by_depth", "filters": {"region": "Bay of Bengal"}}}, + {"id": "follow-month", "follow_up_of": "depth-avg-arabian", "question": "and just in March", + "expect": {"path": "analytical", "intent": "avg_by_depth", "filters": {"region": "Arabian Sea", "month_num": 3}, + "optional_filters": ["year"]}}, + {"id": "follow-monthly-arabian", "follow_up_of": "monthly", "question": "now for the Arabian Sea", + "expect": {"path": "analytical", "intent": "temporal_trends", "filters": {"region": "Arabian Sea"}}}, + {"id": "follow-oxygen", "follow_up_of": "find-bengal", "question": "only the ones measuring oxygen", + "expect": {"path": "semantic", "filters": {"region": "Bay of Bengal", "has_oxygen": true}}} +] diff --git a/eval/runner.py b/eval/runner.py new file mode 100644 index 0000000..056c4ff --- /dev/null +++ b/eval/runner.py @@ -0,0 +1,214 @@ +""" +Score FloatChat answers against benchmark questions. + +Each case says how the question should be understood (SQL or profile search, which analysis, which filters). +A case is scored on three checks: + +- routing: the API took the expected path (and, for SQL, ran the expected analysis) +- filters: it understood exactly the expected region / month / year / sensor filters +- answer: the answer holds up — SQL returned rows and actually applies the filters it reports; every profile a search + returned matches the filters it reports +""" + +import json +import re +import statistics +import time +from collections.abc import Callable +from pathlib import Path + +RATE_LIMIT_WAIT = 65 # seconds to wait after a 429 before the single retry +Send = Callable[[dict], tuple[int, dict]] # POST /query payload -> (status code, JSON body) + + +def load_cases(path: str | Path) -> list[dict]: + cases = json.loads(Path(path).read_text(encoding="utf-8")) + seen = set() + for case in cases: + if case["id"] in seen: + raise ValueError(f"Duplicate case id {case['id']!r}") + if case.get("follow_up_of") and case["follow_up_of"] not in seen: + raise ValueError(f"{case['id']!r} follows up on {case['follow_up_of']!r}, which must come earlier") + if case["expect"]["path"] not in ("analytical", "semantic"): + raise ValueError(f"{case['id']!r} has an unknown path") + seen.add(case["id"]) + return cases + + +def _without(filters: dict | None, keys) -> dict: + return {k: v for k, v in (filters or {}).items() if k not in keys} + + +def _sql_applies(sql: str, key: str, value) -> bool: + """Does the SQL filter on this key? Templates bind parameters (:region); LLM-written SQL may inline values.""" + lowered = sql.lower() + if f":{key}" in lowered or (key.startswith("has_") and key in lowered): + return True + if isinstance(value, str): + return f"'{value.lower()}'" in lowered + if isinstance(value, int) and re.search(rf"\b{value}\b", lowered): + return ("month" if key == "month_num" else "year") in lowered + return False + + +def _profile_matches(profile: dict, filters: dict) -> bool: + return all(profile.get(key) == value for key, value in filters.items()) + + +def _check_analytical(response: dict) -> str | None: + if not response.get("sql_results"): + return "SQL returned no rows" + meta = (response.get("retrieved_metadata") or [{}])[0] + sql = meta.get("sql_query") or "" + missing = [key for key, value in (response.get("filters") or {}).items() if not _sql_applies(sql, key, value)] + return f"SQL does not apply {', '.join(missing)}" if missing else None + + +def _check_semantic(response: dict) -> str | None: + profiles = response.get("retrieved_metadata") or [] + if not profiles: + return "no profiles returned" + if any(s.get("step") == "search" and s.get("fallback_without_filters") for s in response.get("steps") or []): + return "no profile matched the filters (search was widened)" + filters = response.get("filters") or {} + wrong = sum(not _profile_matches(p, filters) for p in profiles) + return f"{wrong} of {len(profiles)} profiles do not match the filters" if wrong else None + + +def check_case(case: dict, status: int, response: dict, latency_ms: int) -> dict: + expect = case["expect"] + intents = expect.get("intent") + intents = [intents] if isinstance(intents, str) else intents + optional = expect.get("optional_filters", []) + steps = (response.get("steps") or []) if status == 200 else [] + understood = next((s for s in steps if s.get("step") == "understood"), {}) + # Routing and filters are judged on what the router decided; the answer check covers what happened next + decided = {"path": understood.get("path", response.get("query_type")), + "intent": understood.get("intent", response.get("intent")), + "filters": understood.get("filters", response.get("filters")) or {}} + result = { + "id": case["id"], + "question": case["question"], + "follow_up_of": case.get("follow_up_of"), + "expected": {"path": expect["path"], "intent": intents, "filters": expect["filters"]}, + "got": {**decided, "answered_by": response.get("query_type")} if status == 200 else None, + "status": status, + "latency_ms": latency_ms, + "router": understood.get("router"), + "llm_wrote_answer": any(s.get("step") == "answer" and s.get("llm_used") for s in steps), + "routing": False, + "filters": False, + "answer": False, + "note": None, + } + if status != 200: + result["note"] = f"HTTP {status}" if status else "request failed" + return result + if response.get("query_type") == "error": + result["note"] = "the API returned an error answer" + return result + + path_ok = decided["path"] == expect["path"] + result["routing"] = path_ok and (expect["path"] != "analytical" or not intents or decided["intent"] in intents) + result["filters"] = _without(decided["filters"], optional) == _without(expect["filters"], optional) + if response.get("query_type") != decided["path"]: + problem = "SQL failed or found nothing, so it fell back to profile search" + elif response.get("query_type") == "analytical": + problem = _check_analytical(response) + else: + problem = _check_semantic(response) + result["answer"] = problem is None + notes = [] + if not result["routing"]: + notes.append(f"routed to {decided['path']}/{decided['intent']}") + if not result["filters"]: + notes.append(f"filters {json.dumps(decided['filters'])}") + if problem: + notes.append(problem) + result["note"] = "; ".join(notes) or None + return result + + +def run_eval(cases: list[dict], send: Send, delay: float = 6.5, sleep=time.sleep, clock=time.perf_counter, + log=print) -> list[dict]: + """Ask every question in order (follow-ups get their parent's answer as history), pacing for rate limits.""" + questions = {case["id"]: case["question"] for case in cases} + answers: dict[str, dict] = {} + results = [] + for i, case in enumerate(cases): + if i: + sleep(delay) + history = [] + parent = case.get("follow_up_of") + if parent and parent in answers: + prev = answers[parent] + history = [{"question": questions[parent], "query_type": prev.get("query_type"), + "intent": prev.get("intent"), "filters": prev.get("filters") or {}}] + payload = {"query_text": case["question"], "history": history} + started = clock() + status, body = send(payload) + if status == 429: + log(f" rate limited, waiting {RATE_LIMIT_WAIT} s") + sleep(RATE_LIMIT_WAIT) + started = clock() + status, body = send(payload) + latency_ms = int((clock() - started) * 1000) + answers[case["id"]] = body if status == 200 else {} + result = check_case(case, status, body if status == 200 else {}, latency_ms) + results.append(result) + mark = "PASS" if result["routing"] and result["filters"] and result["answer"] else "FAIL" + log(f"[{i + 1}/{len(cases)}] {mark} {case['id']} ({latency_ms} ms){' - ' + result['note'] if result['note'] else ''}") + return results + + +def summarize(results: list[dict]) -> dict: + n = len(results) + + def share(key): + return round(sum(r[key] for r in results) / n, 3) if n else 0.0 + + latencies = [r["latency_ms"] for r in results if r["status"] == 200] + return { + "cases": n, + "passed": sum(r["routing"] and r["filters"] and r["answer"] for r in results), + "routing_accuracy": share("routing"), + "filter_accuracy": share("filters"), + "answer_pass_rate": share("answer"), + "median_latency_ms": int(statistics.median(latencies)) if latencies else None, + "llm_routed": sum(r["router"] == "llm" for r in results), + "llm_wrote_answer": sum(r["llm_wrote_answer"] for r in results), + "failed_requests": sum(r["status"] != 200 for r in results), + } + + +def _pct(x: float) -> str: + return f"{x * 100:.0f}%" + + +def to_markdown(summary: dict, results: list[dict], api: str, ran_at: str) -> str: + tick = {True: "✅", False: "❌"} + lines = [ + f"## FloatChat evaluation — {summary['passed']}/{summary['cases']} questions fully correct", + "", + f"Run against `{api}` on {ran_at}.", + "", + "| Metric | Score |", + "|---|---|", + f"| Routing accuracy (SQL vs search, and which analysis) | {_pct(summary['routing_accuracy'])} |", + f"| Filter accuracy (region, month, year, sensor) | {_pct(summary['filter_accuracy'])} |", + f"| Answer checks passed | {_pct(summary['answer_pass_rate'])} |", + f"| Median latency | {summary['median_latency_ms']} ms |" if summary["median_latency_ms"] is not None + else "| Median latency | n/a |", + f"| Understood by the LLM router | {summary['llm_routed']}/{summary['cases']} |", + f"| Answers written by the LLM | {summary['llm_wrote_answer']}/{summary['cases']} |", + "", + "| Case | Question | Routing | Filters | Answer | Notes |", + "|---|---|---|---|---|---|", + ] + for r in results: + question = r["question"].replace("|", "\\|") + follow = f" *(follow-up to {r['follow_up_of']})*" if r["follow_up_of"] else "" + note = (r["note"] or "").replace("|", "\\|") + lines.append(f"| `{r['id']}` | {question}{follow} | {tick[r['routing']]} | {tick[r['filters']]} | " + f"{tick[r['answer']]} | {note} |") + return "\n".join(lines) + "\n" diff --git a/readme.md b/readme.md index 2a95396..c786133 100644 --- a/readme.md +++ b/readme.md @@ -5,7 +5,8 @@ ![FloatChat overview](docs/screenshots/overview.png) **Contents:** [What FloatChat is](#-what-floatchat-is) · [How it's built](#-how-its-built) · -[Run it on your machine](#-run-it-on-your-machine) · [Using it](#-using-floatchat) · +[How well it works](#-how-well-it-works) · [Run it on your machine](#-run-it-on-your-machine) · +[Using it](#-using-floatchat) · [Limitations & roadmap](#-limitations--roadmap) --- @@ -62,19 +63,23 @@ The repo ships with **real Argo observations** from the **Indian Ocean, January - Each profile is labelled with a region: Arabian Sea, Bay of Bengal, Equatorial, Southern and Eastern Indian Ocean, Red Sea & Gulf of Aden -You can download a different period or ocean region with one command (see [Using other data](#using-other-data)). +The **live demo** keeps a rolling **last 12 months** of the same region (about 660 floats and 20,000 profiles), +refreshed every night by GitHub Actions. You can download a different period or ocean region with one command (see +[Using other data](#using-other-data)). --- ## 🏗️ How it's built ``` - ┌─────────────┐ HTTP ┌──────────────── API (FastAPI) ───────────────────────────────┐ - │ Streamlit │ ─────► │ POST /query ─► statistical? ─ yes ─► SQL agent ─► Postgres │ - │ (app.py) │ ◄───── │ └─ no ─► pgvector search (+ filters) │ - └─────────────┘ JSON │ └─► LLM (e.g. Groq) writes the answer │ - │ rate limits · LLM budget · answer cache · query log │ - └──────────────────────────────▲──────────────────────────────────┘ + ┌─────────────┐ HTTP ┌──────────────── API (FastAPI) ─────────────────────────────────────┐ + │ Streamlit │ ─────► │ POST /query, /query/stream (live steps + tokens) │ + │ (app.py) │ ◄───── │ router (LLM, keyword fallback): SQL or search? which filters? │ + └─────────────┘ JSON │ ├─ SQL: template or LLM-written SQL, repaired from DB errors ─► PG │ + / SSE │ └─ search: pgvector + filters ─► matching profiles │ + │ LLM (e.g. Groq) explains the result · every step is reported │ + │ rate limits · LLM budget · answer cache · query log │ + └──────────────────────────────▲────────────────────────────────────────┘ │ read-only role GitHub Actions (daily) ─► ERDDAP ─► pipeline ─► PostgreSQL + pgvector ``` @@ -103,9 +108,11 @@ You can download a different period or ocean region with one command (see [Using | Component | What it does | |---|---| -| `floatchat/sql_agent.py` | Decides whether a question is statistical, and which kind (by depth, by region, by depth layer, monthly trend, per float, biogeochemistry). Known kinds run hand-written SQL templates; other statistical questions get LLM-written SQL, which must pass a read-only check before it runs. | -| `floatchat/search.py` | pgvector similarity search with region, month, year and sensor filters. | -| `floatchat/answer.py` | Turns SQL rows or matching profiles into the answer, with an LLM explanation when one is available. | +| `floatchat/router.py` | Decides how to answer: SQL (and which analysis: by depth, by region, by depth layer, monthly trend, per float, biogeochemistry, or custom) or profile search, with which filters. The LLM reads free phrasing and follow-ups (*"now only the Bay of Bengal"*) and replies in JSON that is validated; keyword rules take over whenever the LLM is unavailable or its reply is unusable. | +| `floatchat/filters.py` | The only filters that ever reach SQL (region, month, year, sensor), validated and always passed as bound parameters. | +| `floatchat/sql_agent.py` | Known analyses run hand-written SQL templates with the question's filters. Other statistical questions get LLM-written SQL, which must pass a read-only check; if the database rejects it, the error goes back to the LLM to fix it (up to 2 repairs). | +| `floatchat/search.py` | pgvector similarity search with region, month, year and sensor filters (exact when filtered, so rare combinations still find their matches). | +| `floatchat/answer.py` | Turns SQL rows or matching profiles into the answer, with an LLM explanation when one is available, and records every step (what was understood, each SQL attempt, the search, who wrote the answer) so the answer can show its work. | | `floatchat/embedder.py` | The all-MiniLM-L6-v2 embedding model (ONNX). Each batch is padded only to its longest text, so a question embeds in a few milliseconds. | | `floatchat/llm.py` | A small client for any **OpenAI-compatible** chat API (Groq, OpenAI, Ollama, LM Studio, …). Without an LLM, FloatChat answers from the data alone. | | `floatchat/regions.py`, `exports.py`, `config.py`, `db/` | Region boxes and question filters; CSV/NetCDF/ASCII exports; settings; schema, roles and read queries. | @@ -114,7 +121,8 @@ You can download a different period or ocean region with one command (see [Using | Endpoint | Purpose | |---|---| -| `POST /query` | The main endpoint. It takes a question and returns the answer text, the query type (`analytical` or `semantic`), the SQL rows or matching profiles, and the context used. | +| `POST /query` | The main endpoint. It takes a question (plus up to 3 earlier turns, for follow-ups) and returns the answer text, the query type (`analytical` or `semantic`), the filters it understood, the SQL rows or matching profiles, and the steps it took. | +| `POST /query/stream` | The same answer as Server-Sent Events: `step` events as the work happens, `token` events as the answer is written, then a `result` event with the `/query` payload. | | `GET /stats` | Dataset totals, sensors, date range, last update and profiles per region. | | `GET /floats` | Each float's latest position and surface readings (the overview map). | | `POST /get_profiles` | All depth levels for the requested profiles (the profile plots). | @@ -135,6 +143,8 @@ Interactive API docs are at `http://localhost:8000/docs` while the backend is ru - a chart, or a map plus temperature/salinity/oxygen profiles - the data table and SQL - download buttons + - a **How I answered** panel: what the router understood, each SQL attempt, the search, and who wrote the text +- Follow-up questions work: the last three turns are sent along, so *"now only the Arabian Sea"* keeps the analysis. - The sidebar shows whether the database, vector index and LLM are connected. ### 6. Packaging, deployment and tests @@ -143,7 +153,8 @@ Interactive API docs are at `http://localhost:8000/docs` while the backend is ru |---|---| | `Dockerfile.api`, `Dockerfile` | The API image (with the embedding model built in) and the Streamlit image. | | `docker-compose.yml` | Runs PostgreSQL + pgvector, the API (which loads the data on first start) and the frontend. | -| `.github/workflows/` | `ci.yml` (lint, tests, container memory check), `refresh.yml` (daily data), `backfill.yml` (first load). | +| `.github/workflows/` | `ci.yml` (lint, tests, container memory check), `refresh.yml` (daily data), `backfill.yml` (first load), `eval.yml` (weekly benchmark against the live API). | +| `eval/` | 30 benchmark questions and the runner that scores the API (see [How well it works](#-how-well-it-works)). | | `DEPLOY.md` | Step-by-step free deployment: Neon, Render, GitHub Actions, cron-job.org and Groq. | | `tests/` | Unit tests, plus integration tests against a real Postgres + pgvector (`tests/integration`). | @@ -155,6 +166,7 @@ FloatChat-AI/ ├── api/ # FastAPI app: endpoints, rate limits, caches ├── floatchat/ # core: SQL agent, search, answers, embedder, LLM client, database ├── pipeline/ # ERDDAP → standard depths → descriptions/embeddings → Postgres +├── eval/ # benchmark questions, scoring runner, latest results ├── scripts/ # smoke test, container memory check ├── data/ # bundled Argo snapshot + embedding cache ├── tests/ # unit/ and integration/ @@ -166,6 +178,30 @@ FloatChat-AI/ --- +## 📏 How well it works + +`eval/questions.json` holds 30 benchmark questions covering every analysis, every region, months, years, sensors, +descriptive searches and follow-ups. Each says how it should be understood, and the runner checks three things: + +- **Routing:** SQL or profile search, and for SQL, the right analysis +- **Filters:** exactly the right region, month, year and sensor filters +- **Answer:** SQL returned rows and really applies the filters it reports; every profile a search returned matches + them + +```bash +python -m eval --api https://floatchat-ai-svjw.onrender.com # paced for the public rate limit, ~4 minutes +``` + +It writes `eval/latest.md` (the table below) and `eval/latest.json`. GitHub Actions runs it against the live API +every Monday (`eval.yml`) and shows the table in the job summary. Without an LLM the keyword router still handles the +template questions and simple follow-ups; the free-phrasing and custom-SQL questions are where the LLM earns its keep. + + +**Latest score:** see [`eval/latest.md`](eval/latest.md). + + +--- + ## 🚀 Run it on your machine ### What you need @@ -306,7 +342,8 @@ New data needs new embeddings, which takes a few minutes on a CPU. The region fi ## 🗺️ Limitations & roadmap - The bundled local data is a three-month snapshot; the deployed version keeps a rolling 12 months, refreshed daily. -- Deciding between SQL and search uses keywords; an LLM-based router would understand more phrasings. +- Without an LLM, deciding between SQL and search falls back to keywords, which miss free phrasings (see the evaluation). +- Next: a custom web app (Next.js) with a landing page that streams each answer's steps live from `/query/stream`. - Region boundaries are approximate boxes. - `streamlit_app.py` and `components/` are an experimental, feature-heavy dashboard that still uses mock data in places. They are not part of the demo (see `README_DASHBOARD.md`). diff --git a/tests/integration/test_eval_api.py b/tests/integration/test_eval_api.py new file mode 100644 index 0000000..59ef427 --- /dev/null +++ b/tests/integration/test_eval_api.py @@ -0,0 +1,26 @@ +import pytest + +from eval.__main__ import HERE +from eval.runner import load_cases, run_eval, summarize +from tests.integration.test_api import make_client + +pytestmark = pytest.mark.integration + + +def test_the_benchmark_runs_against_a_local_api(reader_engine): + # No LLM here, so this scores the keyword router: the template questions and follow-ups must still be understood + client = make_client(reader_engine, query_limits=(1000, 1000)) + + def send(payload): + response = client.post("/query", json=payload, headers={"X-Forwarded-For": "9.9.9.9"}) + return response.status_code, response.json() + + results = run_eval(load_cases(HERE / "questions.json"), send, delay=0, sleep=lambda s: None, log=lambda *_: None) + by_id = {r["id"]: r for r in results} + summary = summarize(results) + assert summary["failed_requests"] == 0 and summary["cases"] == len(results) + for case in ("depth-avg", "depth-avg-arabian", "regions", "layers", "monthly", "follow-region", "follow-month", + "follow-oxygen", "find-bengal", "find-low-oxygen"): + assert by_id[case]["routing"] and by_id[case]["filters"], (case, by_id[case]["note"]) + assert by_id["depth-avg"]["answer"] and by_id["depth-avg-arabian"]["answer"] + assert all(r["router"] == "keywords" and not r["llm_wrote_answer"] for r in results) diff --git a/tests/unit/test_eval.py b/tests/unit/test_eval.py new file mode 100644 index 0000000..99cfc40 --- /dev/null +++ b/tests/unit/test_eval.py @@ -0,0 +1,144 @@ +import json + +import pytest + +from eval.runner import RATE_LIMIT_WAIT, check_case, load_cases, run_eval, summarize, to_markdown + +DEPTH = {"id": "depth", "question": "average temperature by depth in the Arabian Sea", + "expect": {"path": "analytical", "intent": "avg_by_depth", "filters": {"region": "Arabian Sea"}}} +FIND = {"id": "find", "question": "oxygen profiles in the Bay of Bengal", + "expect": {"path": "semantic", "filters": {"region": "Bay of Bengal"}, "optional_filters": ["has_oxygen"]}} + + +def analytical(intent="avg_by_depth", filters=None, sql="SELECT ... WHERE p.region = :region", rows=1, llm=False): + filters = {"region": "Arabian Sea"} if filters is None else filters + return {"query_type": "analytical", "intent": intent, "filters": filters, + "sql_results": [{"depth": 0}] * rows, "retrieved_metadata": [{"sql_query": sql}], + "steps": [{"step": "understood", "router": "llm"}, {"step": "answer", "llm_used": llm}]} + + +def semantic(profiles, filters=None, fallback=False): + filters = {"region": "Bay of Bengal", "has_oxygen": True} if filters is None else filters + return {"query_type": "semantic", "intent": None, "filters": filters, "retrieved_metadata": profiles, + "steps": [{"step": "understood", "router": "keywords"}, + {"step": "search", "fallback_without_filters": fallback}, {"step": "answer", "llm_used": True}]} + + +def bengal(**extra): + return {"region": "Bay of Bengal", "has_oxygen": True, "month_num": 3, "year": 2026, **extra} + + +def test_a_correct_analytical_answer_passes_every_check(): + r = check_case(DEPTH, 200, analytical(llm=True), 120) + assert (r["routing"], r["filters"], r["answer"]) == (True, True, True) + assert r["note"] is None and r["router"] == "llm" and r["llm_wrote_answer"] is True + + +@pytest.mark.parametrize("response, failed, note", [ + (analytical(intent="custom"), "routing", "routed to analytical/custom"), + (semantic([bengal()], filters={"region": "Arabian Sea"}), "routing", "routed to semantic"), + (analytical(filters={}), "filters", "filters {}"), + (analytical(rows=0), "answer", "SQL returned no rows"), + (analytical(sql="SELECT avg(temperature) FROM measurements"), "answer", "SQL does not apply region"), +]) +def test_each_check_fails_on_its_own(response, failed, note): + r = check_case(DEPTH, 200, response, 10) + assert r[failed] is False and note in r["note"] + + +def test_routing_is_judged_on_the_router_decision_and_a_search_fallback_fails_the_answer(): + fell_back = semantic([bengal(region="Arabian Sea")], filters={"region": "Arabian Sea"}) + fell_back["steps"][0].update(path="analytical", intent="avg_by_depth", filters={"region": "Arabian Sea"}) + r = check_case(DEPTH, 200, fell_back, 10) + assert r["routing"] and r["filters"] and not r["answer"] and "fell back" in r["note"] + assert r["got"]["answered_by"] == "semantic" + + +def test_llm_sql_with_inlined_filter_values_counts_as_applied(): + sql = "SELECT max(temperature) FROM measurements m JOIN profiles p USING (profile_id) " \ + "WHERE p.region = 'Arabian Sea' AND EXTRACT(YEAR FROM p.profile_date) = 2026" + r = check_case(DEPTH, 200, analytical(filters={"region": "Arabian Sea", "year": 2026}, sql=sql), 10) + assert r["answer"] is True and r["filters"] is False # year wasn't expected + + +def test_a_list_of_intents_accepts_any_of_them(): + case = {**DEPTH, "expect": {**DEPTH["expect"], "intent": ["custom", "avg_by_depth"]}} + assert check_case(case, 200, analytical(intent="custom"), 10)["routing"] is True + + +def test_semantic_answers_must_only_return_matching_profiles(): + assert check_case(FIND, 200, semantic([bengal(), bengal()]), 10)["answer"] is True + wrong = check_case(FIND, 200, semantic([bengal(), bengal(region="Arabian Sea")]), 10) + assert wrong["answer"] is False and "1 of 2 profiles" in wrong["note"] + widened = check_case(FIND, 200, semantic([bengal()], fallback=True), 10) + assert widened["answer"] is False and "widened" in widened["note"] + assert check_case(FIND, 200, semantic([]), 10)["answer"] is False + + +def test_optional_filters_are_ignored_when_comparing(): + assert check_case(FIND, 200, semantic([bengal()]), 10)["filters"] is True + assert check_case(FIND, 200, semantic([bengal()], filters={"region": "Bay of Bengal"}), 10)["filters"] is True + + +def test_failed_requests_and_error_answers_fail_everything(): + for status, body, note in ((429, {}, "HTTP 429"), (0, {}, "request failed"), + (200, {"query_type": "error"}, "error answer")): + r = check_case(DEPTH, status, body, 10) + assert not (r["routing"] or r["filters"] or r["answer"]) and note in r["note"] + + +def test_follow_ups_get_their_parents_answer_as_history_and_requests_are_paced(): + follow = {"id": "follow", "follow_up_of": "depth", "question": "now only in March", + "expect": {"path": "analytical", "intent": "avg_by_depth", + "filters": {"region": "Arabian Sea", "month_num": 3}}} + sent, sleeps = [], [] + + def send(payload): + sent.append(payload) + return 200, analytical(filters={"region": "Arabian Sea", "month_num": 3} if payload["history"] else None, + sql="... :region ... :month_num") + + results = run_eval([DEPTH, follow], send, delay=6.5, sleep=sleeps.append, log=lambda *_: None) + assert sent[0]["history"] == [] + assert sent[1]["history"] == [{"question": DEPTH["question"], "query_type": "analytical", + "intent": "avg_by_depth", "filters": {"region": "Arabian Sea"}}] + assert sleeps == [6.5] and all(r["routing"] and r["filters"] and r["answer"] for r in results) + + +def test_a_rate_limited_question_is_retried_once_after_waiting(): + replies = iter([(429, {}), (200, analytical())]) + sleeps = [] + results = run_eval([DEPTH], lambda payload: next(replies), sleep=sleeps.append, log=lambda *_: None) + assert sleeps == [RATE_LIMIT_WAIT] and results[0]["answer"] is True + + +def test_summary_and_markdown(): + results = [check_case(DEPTH, 200, analytical(llm=True), 100), check_case(DEPTH, 200, analytical(rows=0), 300), + check_case(DEPTH, 429, {}, 5)] + summary = summarize(results) + assert summary == {"cases": 3, "passed": 1, "routing_accuracy": 0.667, "filter_accuracy": 0.667, + "answer_pass_rate": 0.333, "median_latency_ms": 200, "llm_routed": 2, "llm_wrote_answer": 1, + "failed_requests": 1} + markdown = to_markdown(summary, results, "http://api", "2026-11-08 10:00 UTC") + assert markdown.startswith("## FloatChat evaluation — 1/3 questions fully correct") + assert "| Routing accuracy (SQL vs search, and which analysis) | 67% |" in markdown + assert markdown.count("| `depth` |") == 3 + + +def test_load_cases_validates_ids_and_follow_up_order(tmp_path): + path = tmp_path / "cases.json" + path.write_text(json.dumps([{**DEPTH, "follow_up_of": "later"}])) + with pytest.raises(ValueError, match="must come earlier"): + load_cases(path) + path.write_text(json.dumps([DEPTH, DEPTH])) + with pytest.raises(ValueError, match="Duplicate"): + load_cases(path) + + +def test_the_shipped_benchmark_is_valid(): + from eval.__main__ import HERE + + cases = load_cases(HERE / "questions.json") + assert len(cases) >= 30 + assert {c["expect"]["path"] for c in cases} == {"analytical", "semantic"} + assert sum(bool(c.get("follow_up_of")) for c in cases) >= 3