From a5e5f57fc5fc0b54fb363cca6fd447d95269aebd Mon Sep 17 00:00:00 2001 From: Zane Date: Thu, 29 Oct 2026 22:07:47 +1300 Subject: [PATCH] Add vector retrieve() and swellsense search debug command. Stage 4 slice 1: embed the query, nearest-neighbour search with public_only, and a CLI to inspect hits without the chatbot. Co-authored-by: Cursor --- AGENTS.md | 2 + README.md | 2 + src/swellsense/cli.py | 52 +++++++++++++++ src/swellsense/retrieval/__init__.py | 5 ++ src/swellsense/retrieval/search.py | 37 +++++++++++ tests/test_cli.py | 95 ++++++++++++++++++++++++++++ tests/test_retrieval.py | 75 ++++++++++++++++++++++ 7 files changed, 268 insertions(+) create mode 100644 src/swellsense/retrieval/__init__.py create mode 100644 src/swellsense/retrieval/search.py create mode 100644 tests/test_retrieval.py diff --git a/AGENTS.md b/AGENTS.md index 6a2be76..0e40476 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,7 @@ code, with short docstrings explaining why. - `src/swellsense/extraction/`: structured extraction (boards, unit parsing) - `src/swellsense/ingest/`: source registry, fetchers, raw document storage, ingest runs - `src/swellsense/processing/`: cleaning, chunking, and the process run +- `src/swellsense/retrieval/`: vector search over stored chunks - `src/swellsense/db/`: local Postgres connection and schema - `src/swellsense/spots/`: spot profiles and the registry that loads them - `src/swellsense/tides/`: LINZ Tauranga predictions and tide state at a time @@ -77,6 +78,7 @@ code, with short docstrings explaining why. - Apply lint and format fixes: `uv run ruff check --fix && uv run ruff format` - Download sources: `uv run swellsense ingest` (or `--source ID` for one) - Process raw pages: `uv run swellsense process` (reads `data/raw/`, embeds via the configured provider, upserts into local Postgres) +- Vector search (debug): `uv run swellsense search "QUESTION"` (optional `--k N`, default 5) - Tauranga tides: `uv run swellsense tides` (or `--date YYYY-MM-DD`) - Spot forecast: `uv run swellsense forecast SPOT` (or `--hours N`, default 12) - Conditions check: `uv run swellsense check SPOT` (or `--hours N`, default 12); `uv run swellsense check --all` ranks every spot, with ties shown as ties; `--skill LEVEL` lists harder spots separately diff --git a/README.md b/README.md index 712d65b..2786206 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for ex | `uv run swellsense ingest` | Download all sources into `data/raw/` | | `uv run swellsense ingest --source wikipedia` | Download a single source | | `uv run swellsense process` | Clean, chunk and embed `data/raw/` into Postgres | +| `uv run swellsense search "what is a rip?"` | Vector search over embedded chunks (debug) | +| `uv run swellsense search "swell period" --k 10` | Return more nearest chunks | | `uv run swellsense tides` | Print today's Tauranga highs and lows | | `uv run swellsense tides --date 2026-01-15` | Print one day's Tauranga tides | | `uv run swellsense forecast mount-main-beach` | Print 12 hours of swell and wind for a spot | diff --git a/src/swellsense/cli.py b/src/swellsense/cli.py index c5e0eab..60c6734 100644 --- a/src/swellsense/cli.py +++ b/src/swellsense/cli.py @@ -7,6 +7,7 @@ rank. ``--skill`` keeps harder spots in a separate list. ``db init`` creates the local Postgres schema (pgvector, documents, chunks). ``process`` cleans, chunks and embeds raw pages into Postgres. +``search`` runs vector retrieval over stored chunks for debugging. """ import argparse @@ -33,6 +34,7 @@ from swellsense.ingest.store import load_all from swellsense.llm.embeddings import embed from swellsense.processing.run import PostgresChunkStore, ProcessReport, process +from swellsense.retrieval import retrieve from swellsense.spots.models import Spot from swellsense.spots.registry import get_spot, load_spots from swellsense.tides.linz import ( @@ -65,6 +67,23 @@ def _main(argv: list[str] | None = None) -> int: help="Clean, chunk and embed data/raw into Postgres", ) + search_parser = subparsers.add_parser( + "search", + help="Vector search over embedded chunks (debug)", + ) + search_parser.add_argument( + "query", + nargs="+", + metavar="QUESTION", + help="Natural-language question", + ) + search_parser.add_argument( + "--k", + type=int, + default=5, + help="How many chunks to return (default: 5)", + ) + tides_parser = subparsers.add_parser( "tides", help="Print Tauranga high and low waters for one day" ) @@ -126,6 +145,8 @@ def _main(argv: list[str] | None = None) -> int: return _ingest(args.source) if args.command == "process": return _process() + if args.command == "search": + return _search(" ".join(args.query), args.k) if args.command == "tides": return _tides(args.date) if args.command == "forecast": @@ -152,6 +173,37 @@ def _db_init() -> int: return 0 +def _search_preview(text: str, *, word_limit: int = 25) -> str: + words = text.split() + if len(words) <= word_limit: + return text + return " ".join(words[:word_limit]) + "..." + + +def _search(query: str, k: int) -> int: + try: + conn = connect() + try: + hits = retrieve(conn, query, k) + finally: + conn.close() + except (psycopg.Error, openai.APIError) as exc: + print(str(exc), file=sys.stderr) + return 1 + + if not hits: + print("No results.") + return 0 + + for rank, hit in enumerate(hits, start=1): + print(f"{rank}. {hit.distance:.3f}") + print(f"{hit.title} > {hit.section}") + print(hit.url) + print(_search_preview(hit.text)) + print() + return 0 + + def _process() -> int: try: docs = load_all() diff --git a/src/swellsense/retrieval/__init__.py b/src/swellsense/retrieval/__init__.py new file mode 100644 index 0000000..6e1186d --- /dev/null +++ b/src/swellsense/retrieval/__init__.py @@ -0,0 +1,5 @@ +"""Retrieval over the chunk store.""" + +from swellsense.retrieval.search import retrieve + +__all__ = ["retrieve"] diff --git a/src/swellsense/retrieval/search.py b/src/swellsense/retrieval/search.py new file mode 100644 index 0000000..153aa1e --- /dev/null +++ b/src/swellsense/retrieval/search.py @@ -0,0 +1,37 @@ +"""Vector retrieval over embedded knowledge chunks.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING + +from swellsense.db.chunks import ChunkHit, nearest +from swellsense.llm.embeddings import embed + +if TYPE_CHECKING: + import psycopg + + +def retrieve( + conn: psycopg.Connection, + query: str, + k: int = 5, + *, + embed_fn: Callable[..., list[list[float]]] = embed, + search_fn: Callable[..., list[ChunkHit]] = nearest, +) -> list[ChunkHit]: + """Return the k nearest public chunks for a natural-language query. + + Vector search only for now; keyword search, hybrid fusion and a relevance + gate arrive in later roadmap slices. + """ + if k < 1: + msg = f"k must be at least 1, got {k}" + raise ValueError(msg) + + stripped = query.strip() + if not stripped: + return [] + + vector = embed_fn([stripped], "query")[0] + return search_fn(conn, vector, k, public_only=True) diff --git a/tests/test_cli.py b/tests/test_cli.py index 36aadfd..15b73a8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8,6 +8,7 @@ import pytest from swellsense.cli import main +from swellsense.db.chunks import ChunkHit from swellsense.forecast.models import AUCKLAND, HourlyConditions, SpotForecast from swellsense.forecast.openmeteo import OPEN_METEO_ATTRIBUTION from swellsense.ingest.run import RunReport, SourceReport @@ -99,6 +100,100 @@ def fail(): assert capsys.readouterr().err.strip() == "connection refused" +def _search_hit( + *, + title: str = "Surfing", + section: str = "Rips", + url: str = "https://example.test/surfing", + text: str = "Short chunk text.", + distance: float = 0.4567, +) -> ChunkHit: + return ChunkHit( + id="doc#0", + document_id="doc", + index=0, + section=section, + text=text, + title=title, + url=url, + license="CC BY-SA 4.0", + attribution="Wiki", + usage="open", + distance=distance, + ) + + +def test_search_prints_hits_and_exits_0(capsys, monkeypatch): + long_text = " ".join(f"w{i}" for i in range(30)) + hits = [ + _search_hit(distance=0.4567, text=long_text), + _search_hit( + title="Swell", + section="Period", + url="https://example.test/swell", + text="Only five words here total", + distance=1.0, + ), + ] + + monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn()) + monkeypatch.setattr("swellsense.cli.retrieve", lambda conn, query, k: hits) + + with pytest.raises(SystemExit) as caught: + main(["search", "rip", "currents", "--k", "2"]) + + assert caught.value.code == 0 + out = capsys.readouterr().out + assert out.startswith("1. 0.457\nSurfing > Rips\nhttps://example.test/surfing\n") + preview = " ".join(f"w{i}" for i in range(25)) + "..." + assert preview in out + assert ( + "2. 1.000\n" + "Swell > Period\n" + "https://example.test/swell\n" + "Only five words here total\n" + ) in out + + +def test_search_no_results_exits_0(capsys, monkeypatch): + monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn()) + monkeypatch.setattr("swellsense.cli.retrieve", lambda conn, query, k: []) + + with pytest.raises(SystemExit) as caught: + main(["search", "nothing"]) + + assert caught.value.code == 0 + assert capsys.readouterr().out == "No results.\n" + + +def test_search_postgres_unreachable_exits_1(capsys, monkeypatch): + def fail(): + raise psycopg.OperationalError("connection refused") + + monkeypatch.setattr("swellsense.cli.connect", fail) + + with pytest.raises(SystemExit) as caught: + main(["search", "swell"]) + + assert caught.value.code == 1 + assert capsys.readouterr().err.strip() == "connection refused" + + +def test_search_ollama_unreachable_exits_1(capsys, monkeypatch): + def fail_retrieve(*args, **kwargs): + del args, kwargs + raise openai.APIConnectionError(message="connection failed", request=None) + + monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn()) + monkeypatch.setattr("swellsense.cli.retrieve", fail_retrieve) + + with pytest.raises(SystemExit) as caught: + main(["search", "swell"]) + + assert caught.value.code == 1 + assert capsys.readouterr().err.strip() == "connection failed" + + def test_process_ollama_unreachable_exits_1(capsys, monkeypatch): conn = _FakeConn() diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py new file mode 100644 index 0000000..c70e662 --- /dev/null +++ b/tests/test_retrieval.py @@ -0,0 +1,75 @@ +"""Unit tests for vector retrieval (no network, no database).""" + +from __future__ import annotations + +import pytest + +from swellsense.db.chunks import ChunkHit +from swellsense.retrieval.search import retrieve + + +def _hit(index: int, *, text: str = "body") -> ChunkHit: + return ChunkHit( + id=f"doc#{index}", + document_id="doc", + index=index, + section="Intro", + text=text, + title="Surfing", + url="https://example.test/surfing", + license="CC BY-SA 4.0", + attribution="Wiki", + usage="open", + distance=0.1 * index, + ) + + +def test_empty_or_whitespace_query_skips_embed_and_search(): + calls: list[str] = [] + + def embed_fn(texts, kind): + calls.append("embed") + return [[0.0]] + + def search_fn(conn, vector, k, public_only): + calls.append("search") + return [] + + conn = object() + assert retrieve(conn, "", embed_fn=embed_fn, search_fn=search_fn) == [] + assert retrieve(conn, " \t\n", embed_fn=embed_fn, search_fn=search_fn) == [] + assert calls == [] + + +def test_passes_query_kind_k_and_public_only(): + seen: dict[str, object] = {} + + def embed_fn(texts, kind): + seen["texts"] = texts + seen["kind"] = kind + return [[1.0, 2.0]] + + def search_fn(conn, vector, k, public_only): + seen["conn"] = conn + seen["vector"] = vector + seen["k"] = k + seen["public_only"] = public_only + return [_hit(0), _hit(1)] + + conn = object() + hits = retrieve( + conn, " rip currents ", k=3, embed_fn=embed_fn, search_fn=search_fn + ) + + assert seen["texts"] == ["rip currents"] + assert seen["kind"] == "query" + assert seen["conn"] is conn + assert seen["vector"] == [1.0, 2.0] + assert seen["k"] == 3 + assert seen["public_only"] is True + assert [h.index for h in hits] == [0, 1] + + +def test_k_zero_raises(): + with pytest.raises(ValueError, match="k must be at least 1"): + retrieve(object(), "swell", k=0)