feat(search): add calibrated retrieval and LangChain knowledge tool
Add exact and semantic evidence admission, measured calibration, bounded tool execution, and independent held-out evaluation preparation with regression coverage and operator guides. Real-provider quality gates remain pending. Validation: 1300 provider-free tests passed; 3 Windows symlink skips. PostgreSQL acceptance not rerun because TEST_DATABASE_URL is unset.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"""Lexical comparisons only: faithful evidence and embedding inputs stay unchanged."""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
TRANSLATE_FROM = "۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩كيى"
|
||||
TRANSLATE_TO = "01234567890123456789کیی"
|
||||
TRANSLATION = str.maketrans(TRANSLATE_FROM, TRANSLATE_TO)
|
||||
LEXICAL_POLICY = "nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
|
||||
# Python split() and PostgreSQL locale whitespace classes differ for NBSP.
|
||||
# Bind the complete Unicode whitespace set used by Python str.split().
|
||||
WHITESPACE = "\t\n\v\f\r\x1c\x1d\x1e\x1f\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"
|
||||
SQL_LEXICAL_PARAMS = dict(lexical_from=TRANSLATE_FROM + WHITESPACE,
|
||||
lexical_to=TRANSLATE_TO + " " * len(WHITESPACE))
|
||||
SQL_LEXICAL_TEXT = (
|
||||
"regexp_replace(lower(translate(normalize(c.text, NFC), "
|
||||
":lexical_from, :lexical_to)), ' +', ' ', 'g')"
|
||||
)
|
||||
_TOKEN = re.compile(r"(?<![\w./-])[\w]+(?:[./-][\w]+)*(?![\w/-]|\.(?=[\w./-]))")
|
||||
_ARTICLE = re.compile(r"(?<!\w)(?:ماده|تبصره|article|clause)\s+[0-9]+(?:[./-][0-9]+)*(?![\w/-]|\.(?=[\w./-]))")
|
||||
_DATE = re.compile(r"(?:[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}|[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4})\Z")
|
||||
|
||||
|
||||
def lexical_text(value):
|
||||
return " ".join(unicodedata.normalize("NFC", value).translate(TRANSLATION).lower().split())
|
||||
|
||||
|
||||
def exact_patterns(query, context=None):
|
||||
value = lexical_text(query + ("\n" + context if context else ""))
|
||||
keys = {match.group() for match in _ARTICLE.finditer(value)}
|
||||
for match in _TOKEN.finditer(value):
|
||||
token = match.group()
|
||||
# Dates or mixed letter/digit codes, never an isolated quantity.
|
||||
if _DATE.fullmatch(token) or (any(c.isalpha() for c in token)
|
||||
and any(c.isdigit() for c in token)):
|
||||
keys.add(token)
|
||||
# Query/context are already bounded to 4000 characters. No key is silently
|
||||
# dropped, and regex syntax comes solely from these validated tokens.
|
||||
return tuple("(^|[^[:alnum:]_./-])" +
|
||||
re.sub(r"([.\\+*?\[\]^$(){}|])", r"\\\1", key) +
|
||||
"($|[^[:alnum:]_./-]|\\.(?![[:alnum:]_./-]))" for key in sorted(keys))
|
||||
Reference in New Issue
Block a user