From 45f4d204725b7cd036d63dfeea388261dc4249f4 Mon Sep 17 00:00:00 2001 From: Ravi Mula Date: Mon, 16 Nov 2026 13:07:49 +0530 Subject: [PATCH] feat: expose search profiles and the search workbench --- docs/openapi-search.yaml | 2 +- pipeline/search/query_expansion.py | 23 +++++- ui/src/views/SearchWorkbenchView.jsx | 116 ++++++++++++++++++++++++--- 3 files changed, 125 insertions(+), 16 deletions(-) diff --git a/docs/openapi-search.yaml b/docs/openapi-search.yaml index 5115ef8..0430a78 100644 --- a/docs/openapi-search.yaml +++ b/docs/openapi-search.yaml @@ -6,7 +6,7 @@ info: This is a hand-written companion spec (the running FastAPI app declares these routes with untyped `dict` payloads, so no schema is generated at `/openapi.json` for them) — reverse-engineered from `pipeline/api/`, - `pipeline/models.py`, and `pipeline/vector_store/qdrant_store.py`. + `pipeline/documents/models.py`, and `pipeline/vector_store/qdrant_store.py`. Not the full API surface — only `/search` (vector/hybrid semantic search) and `/chunks/search` (keyword search across chunk records). diff --git a/pipeline/search/query_expansion.py b/pipeline/search/query_expansion.py index 335af3d..474ad90 100644 --- a/pipeline/search/query_expansion.py +++ b/pipeline/search/query_expansion.py @@ -1,5 +1,24 @@ -"""Normalize search queries before ranking.""" +"""Literal search expansions supplied by a deployment.""" + +import json +import os def expand_query(query: str, profile: str) -> str: - return query.strip() + text = query.strip() + if not text or not profile or profile == "none": + return text + profiles = json.loads(os.environ.get("QUERY_EXPANSION_RULES", "{}")) + if not isinstance(profiles, dict): + raise ValueError("QUERY_EXPANSION_RULES must be an object of named profiles") + rules = profiles.get(profile, {}) + if not isinstance(rules, dict) or len(rules) > 128: + raise ValueError("A query expansion profile must map at most 128 phrases to text") + lower = text.casefold() + additions = [] + for phrase, expansion in rules.items(): + if not phrase.strip() or not isinstance(expansion, str) or len(expansion) > 256: + raise ValueError("Query expansion phrases must have bounded text") + if phrase.casefold() in lower: + additions.append(expansion.strip()) + return " ".join([text, *dict.fromkeys(additions)])[:4096] diff --git a/ui/src/views/SearchWorkbenchView.jsx b/ui/src/views/SearchWorkbenchView.jsx index 1015bf8..56aa536 100644 --- a/ui/src/views/SearchWorkbenchView.jsx +++ b/ui/src/views/SearchWorkbenchView.jsx @@ -1,4 +1,5 @@ import React, { useEffect, useState } from 'react' +import { Link } from 'react-router-dom' import { ChevronDown, ChevronUp, Code, RotateCcw, Search as SearchIcon, Sliders, AlertCircle } from 'lucide-react' import { Badge } from '../components/ui/badge' import { Button } from '../components/ui/button' @@ -29,6 +30,8 @@ const EXAMPLE_QUERIES = [ export default function SearchWorkbenchView() { const [query, setQuery] = useState('') const [results, setResults] = useState([]) + const [schemeChoices, setSchemeChoices] = useState([]) + const [resultQuery, setResultQuery] = useState('') const [showAdvanced, setShowAdvanced] = useState(false) const [showCandidates, setShowCandidates] = useState(false) const [settings, setSettings] = useState(DEFAULT_SEARCH_SETTINGS) @@ -36,6 +39,13 @@ export default function SearchWorkbenchView() { const [searching, setSearching] = useState(false) const [searchError, setSearchError] = useState(null) const [candidates, setCandidates] = useState([]) + const [collections, setCollections] = useState([]) + const [language, setLanguage] = useState('') + const [strictLanguage, setStrictLanguage] = useState(false) + const [subjectId, setSubjectId] = useState('') + const [areaScheme, setAreaScheme] = useState('') + const [areaCode, setAreaCode] = useState('') + const [season, setSeason] = useState('') useEffect(() => { fetchSettings() @@ -43,18 +53,31 @@ export default function SearchWorkbenchView() { async function fetchSettings() { try { - const data = await fetchJson('/settings/search') - setSettings(data) + const [data, available] = await Promise.all([ + fetchJson('/settings/search'), fetchJson('/search/collections'), + ]) + setCollections(available) + setSettings({ ...data, indexName: available.some(({ name }) => name === data.indexName) + ? data.indexName : available[0]?.name || data.indexName }) } catch (settingsError) { setSearchError(settingsError.message) } } - async function handleSearch(overrideQuery) { + async function handleSearch(overrideQuery, schemeWorkflowId) { // Example-query chips pass the text directly: setQuery is async, so reading // state here would search the previous value. const effectiveQuery = typeof overrideQuery === 'string' ? overrideQuery : query if (!effectiveQuery.trim()) return + if (Boolean(areaScheme.trim()) !== Boolean(areaCode.trim())) { + setSearchError('Enter both a location code system and a location code.') + return + } + const applicability = { + ...(subjectId.trim() && { agriculture_subject_ids: [subjectId.trim()] }), + ...(areaCode.trim() && { coverage_areas: [{ codeScheme: areaScheme.trim(), areaCode: areaCode.trim() }] }), + ...(season.trim() && { seasons: [season.trim()] }), + } try { setSearching(true) setSearchError(null) @@ -63,6 +86,7 @@ export default function SearchWorkbenchView() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: effectiveQuery, + ...(schemeWorkflowId && { document_workflow_id: schemeWorkflowId }), index_name: settings.indexName, search_mode: settings.searchMethod, top_k: settings.limit, @@ -77,10 +101,14 @@ export default function SearchWorkbenchView() { query_expansion_profile: settings.queryExpansionProfile, rerank_mode: settings.rerankMode, hybrid_rrf_k: settings.hybridRrfK, + ...(language.trim() && { language: language.trim(), strict_language: strictLanguage }), + ...(Object.keys(applicability).length > 0 && { applicability }), include_raw_hits: true, }) }) setResults(data.hits || []) + setSchemeChoices(data.scheme_choices || []) + setResultQuery(effectiveQuery) setCandidates(data.raw_hits || data.candidates || []) setSearched(true) } catch (err) { @@ -91,7 +119,13 @@ export default function SearchWorkbenchView() { } function handleReset() { - setSettings(DEFAULT_SEARCH_SETTINGS) + setSettings({ ...DEFAULT_SEARCH_SETTINGS, indexName: collections[0]?.name || DEFAULT_SEARCH_SETTINGS.indexName }) + setLanguage('') + setStrictLanguage(false) + setSubjectId('') + setAreaScheme('') + setAreaCode('') + setSeason('') } function update(key, value) { @@ -123,6 +157,7 @@ export default function SearchWorkbenchView() { setQuery(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleSearch()} @@ -134,6 +169,43 @@ export default function SearchWorkbenchView() { +
+ {collections.length > 0 && ( + + )} + + + + + +
+ {language.trim() && } +
+ ))} +
+ + )} + {searched && !searching && (
@@ -291,9 +374,16 @@ export default function SearchWorkbenchView() {
{Number(result._score || 0).toFixed(2)} - {getSearchResultTitle(result)} + {result.workflow_id ? ( + + {getSearchResultTitle(result)} + + ) : {getSearchResultTitle(result)}}
+ {result.text_language && {result.text_language}{result.language_fallback ? ' · source fallback' : ''}} Chunk {result.chunk_num} · Pages {result.page_start}–{result.page_end} @@ -367,7 +457,7 @@ export default function SearchWorkbenchView() {

Search the pipeline index

- Results come from reviewed, ingested chunks — not the raw source files. + Search passages and open the source revision to inspect the evidence.