Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/eval.yml
Original file line number Diff line number Diff line change
@@ -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
85 changes: 72 additions & 13 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand All @@ -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):
Expand All @@ -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")
Expand All @@ -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):
Expand All @@ -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})
Expand Down Expand Up @@ -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):
Expand Down
58 changes: 53 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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("""
Expand All @@ -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})
Expand Down
59 changes: 59 additions & 0 deletions docs/superpowers/plans/2026-11-08-phase2-smarter-ai.md
Original file line number Diff line number Diff line change
@@ -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 <noreply@anthropic.com>`.

## 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.
Loading
Loading