Compare commits
4
Commits
77fef0a499
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d541ec8d6 | ||
|
|
4e7229c92c | ||
|
|
72ebe44053 | ||
|
|
bc543459c7 |
+34
-1
@@ -84,7 +84,8 @@ tests/traces.py exporter tests (no network)
|
|||||||
stored answers, and article-by-article gathering with early exit. Focused methods
|
stored answers, and article-by-article gathering with early exit. Focused methods
|
||||||
handle stored-answer gating, query composition/search, cached fetching, skimming,
|
handle stored-answer gating, query composition/search, cached fetching, skimming,
|
||||||
and post-ingestion answer checks. Stateless module-level helpers build probe
|
and post-ingestion answer checks. Stateless module-level helpers build probe
|
||||||
seeds, rank article titles, and filter goal-relevant skim notices. Run-wide page
|
seeds and filter goal-relevant skim notices; `knowledge/ranking.py` ranks search
|
||||||
|
results. Run-wide page
|
||||||
and link caches survive calls; extraction entities, skim notices, and pending
|
and link caches survive calls; extraction entities, skim notices, and pending
|
||||||
skim leads reset per call after the proof path falls through.
|
skim leads reset per call after the proof path falls through.
|
||||||
|
|
||||||
@@ -94,6 +95,38 @@ Offline orchestration regression tests (no Wikipedia, embedder, or LLM required)
|
|||||||
.venv/bin/python knowledge/tests/answer_question.py
|
.venv/bin/python knowledge/tests/answer_question.py
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Wikipedia candidate ranking
|
||||||
|
|
||||||
|
`WikipediaClient.search` returns `WikiSearchResult` objects with `title` and
|
||||||
|
plain-text `snippet` (MediaWiki's query-specific search excerpt, not the full
|
||||||
|
introductory summary). HTML highlight tags are removed and entities decoded;
|
||||||
|
missing snippets leave the title available for ranking without an extra fetch.
|
||||||
|
|
||||||
|
All searches finish before fetching articles. Results are deduplicated by title,
|
||||||
|
retaining distinct snippets from different queries. Every unique candidate is
|
||||||
|
ranked against the **original question**, using **title + snippet**, not the
|
||||||
|
composed search queries:
|
||||||
|
|
||||||
|
- BM25 lexical relevance (k1=1.5, b=0.75) over the candidate pool, using the
|
||||||
|
existing word tokenizer and stemmer.
|
||||||
|
- Cosine similarity from the configured embedding service (`embed_model` /
|
||||||
|
`embed_url`), reusing the cached question vector and batch-embedding candidates.
|
||||||
|
- Equal-weight reciprocal rank fusion, `1/(60 + lexical_rank) +
|
||||||
|
1/(60 + semantic_rank)`. Ties share ranks; final ties retain encounter order.
|
||||||
|
|
||||||
|
There is **no query-winner priority**. `max_articles` is applied only after global
|
||||||
|
ranking. If embeddings are unavailable or malformed, the failure is logged and
|
||||||
|
ranking falls back to BM25 alone. Search events retain titles and snippets;
|
||||||
|
`rank_articles` events record the question, candidates, ranking method, BM25,
|
||||||
|
cosine, and final scores. Snippets only guide retrieval; fetched-page containment
|
||||||
|
checks still govern which facts may enter the KG.
|
||||||
|
|
||||||
|
Offline API, ranking, embedding-validation and fallback tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/python knowledge/tests/semantic_fetch.py
|
||||||
|
```
|
||||||
|
|
||||||
## Viewing a run as traces (Jaeger, 2026-10-27)
|
## Viewing a run as traces (Jaeger, 2026-10-27)
|
||||||
|
|
||||||
Every run records `events.jsonl`; `floop/traces.py` replays it as one
|
Every run records `events.jsonl`; `floop/traces.py` replays it as one
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ dead run). No API keys in code.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -36,10 +37,20 @@ def embed(texts: list[str], model: str = DEFAULT_MODEL,
|
|||||||
data = json.load(r)
|
data = json.load(r)
|
||||||
except Exception as e: # noqa: BLE001 — one honest exception type
|
except Exception as e: # noqa: BLE001 — one honest exception type
|
||||||
raise EmbedderDown(f"{url}: {e}") from e
|
raise EmbedderDown(f"{url}: {e}") from e
|
||||||
vecs = data.get("embeddings")
|
vecs = data.get("embeddings") if isinstance(data, dict) else None
|
||||||
if not vecs or len(vecs) != len(texts):
|
if not isinstance(vecs, list) or len(vecs) != len(texts):
|
||||||
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
||||||
f"{len(vecs) if vecs else 0}")
|
f"{len(vecs) if isinstance(vecs, list) else 0}")
|
||||||
|
dimension = None
|
||||||
|
for vector in vecs:
|
||||||
|
if (not isinstance(vector, list) or not vector
|
||||||
|
or any(type(x) not in (int, float) or not math.isfinite(x)
|
||||||
|
for x in vector)
|
||||||
|
or not any(vector)):
|
||||||
|
raise EmbedderDown(f"{url}: expected finite, nonzero numeric vectors")
|
||||||
|
if dimension is not None and len(vector) != dimension:
|
||||||
|
raise EmbedderDown(f"{url}: inconsistent embedding dimensions")
|
||||||
|
dimension = len(vector)
|
||||||
return vecs
|
return vecs
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+50
-34
@@ -33,11 +33,12 @@ from .skim import SkimSheet, find_quantities, skim_article
|
|||||||
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
||||||
SelectTableSignature, SkimPromoteSignature,
|
SelectTableSignature, SkimPromoteSignature,
|
||||||
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
||||||
from .embeddings import EmbedderDown, embed
|
from .embeddings import EmbedderDown, cosine, embed
|
||||||
from .queries import compose_queries, keywords, proper_nouns
|
from .queries import compose_queries, keywords, proper_nouns
|
||||||
|
from .ranking import merge_search_results, rank_articles
|
||||||
from .store import KnowledgeStore, norm_name
|
from .store import KnowledgeStore, norm_name
|
||||||
from .two_pass import claims_from, fact_from_claim
|
from .two_pass import claims_from, fact_from_claim
|
||||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
from .wiki import (WikipediaClient, WikiPage, WikiSearchResult, WikiTable, resolve_convert,
|
||||||
tables_as_chunks, format_table_frag)
|
tables_as_chunks, format_table_frag)
|
||||||
|
|
||||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||||
@@ -155,24 +156,6 @@ def _probe_seeds(kws: list[str], evidence: str) -> list[str]:
|
|||||||
return seeds
|
return seeds
|
||||||
|
|
||||||
|
|
||||||
def _rank_article_titles(per_query: list[list[str]],
|
|
||||||
terms: list[str]) -> list[str]:
|
|
||||||
"""Keep each query's winner first, then stably rank unique other titles."""
|
|
||||||
from .store import stem
|
|
||||||
title_terms = {t for w in terms if len(w) > 2
|
|
||||||
for t in (norm_name(w), stem(w))}
|
|
||||||
|
|
||||||
def relevance(title: str) -> int:
|
|
||||||
tt = norm_name(title)
|
|
||||||
return sum(1 for t in title_terms if t and t in tt)
|
|
||||||
|
|
||||||
candidates = list(dict.fromkeys(t for found in per_query for t in found))
|
|
||||||
winners = list(dict.fromkeys(found[0] for found in per_query if found))
|
|
||||||
picked = set(winners)
|
|
||||||
return winners + sorted((t for t in candidates if t not in picked),
|
|
||||||
key=relevance, reverse=True)
|
|
||||||
|
|
||||||
|
|
||||||
def _goal_skim_notice(sheet: SkimSheet, goal_terms: list[str]) -> str:
|
def _goal_skim_notice(sheet: SkimSheet, goal_terms: list[str]) -> str:
|
||||||
"""Keep goal-relevant notices and quantity signals, not unrelated prose."""
|
"""Keep goal-relevant notices and quantity signals, not unrelated prose."""
|
||||||
notice = sheet.notice()
|
notice = sheet.notice()
|
||||||
@@ -515,7 +498,7 @@ class KnowledgeExpert:
|
|||||||
if answer is not None:
|
if answer is not None:
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
ordered = self._search_articles(question, kws, ev_entities, list_mode)
|
ordered = self._search_articles(question, ev_entities, list_mode)
|
||||||
pages: list[WikiPage] = []
|
pages: list[WikiPage] = []
|
||||||
for title in ordered[: self.cfg.max_articles]:
|
for title in ordered[: self.cfg.max_articles]:
|
||||||
page = self._fetch_page(title)
|
page = self._fetch_page(title)
|
||||||
@@ -590,8 +573,8 @@ class KnowledgeExpert:
|
|||||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _search_articles(self, question: str, kws: list[str],
|
def _search_articles(self, question: str, ev_entities: list[str],
|
||||||
ev_entities: list[str], list_mode: bool) -> list[str]:
|
list_mode: bool) -> list[str]:
|
||||||
"""Compose and search all queries before globally ranking candidates."""
|
"""Compose and search all queries before globally ranking candidates."""
|
||||||
queries, entity_terms = compose_queries(
|
queries, entity_terms = compose_queries(
|
||||||
question, evidence_entities=ev_entities, list_mode=list_mode)
|
question, evidence_entities=ev_entities, list_mode=list_mode)
|
||||||
@@ -603,18 +586,49 @@ class KnowledgeExpert:
|
|||||||
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
||||||
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
||||||
think=True)
|
think=True)
|
||||||
per_query: list[list[str]] = []
|
per_query: list[list[WikiSearchResult]] = []
|
||||||
for query in queries:
|
for query in queries:
|
||||||
found = self.client.search(query, limit=self.cfg.max_search_results)
|
found = self.client.search(query, limit=self.cfg.max_search_results)
|
||||||
per_query.append(found)
|
per_query.append(found)
|
||||||
self._rec("fn.done", fn="search",
|
self._rec("fn.done", fn="search",
|
||||||
in_={"query": query, "limit": self.cfg.max_search_results},
|
in_={"query": query, "limit": self.cfg.max_search_results},
|
||||||
out_={"titles": found})
|
out_={"titles": [h.title for h in found],
|
||||||
self._log(f"wiki search ({query!r}): {found}", think=True)
|
"results": [{"title": h.title, "snippet": h.snippet}
|
||||||
ordered = _rank_article_titles(per_query, entity_terms + kws)
|
for h in found]})
|
||||||
|
self._log(f"wiki search ({query!r}): {[h.title for h in found]}", think=True)
|
||||||
|
ordered = self._rank_search_results(question, merge_search_results(per_query))
|
||||||
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
||||||
return ordered
|
return ordered
|
||||||
|
|
||||||
|
def _rank_search_results(self, question: str,
|
||||||
|
articles: list[WikiSearchResult]) -> list[str]:
|
||||||
|
"""Globally rank title+snippet candidates against the original question."""
|
||||||
|
similarities = None
|
||||||
|
if articles:
|
||||||
|
qvec = self._qvec(question)
|
||||||
|
if qvec is not None:
|
||||||
|
try:
|
||||||
|
vectors = embed([a.text for a in articles],
|
||||||
|
model=self.cfg.embed_model, url=self.cfg.embed_url)
|
||||||
|
if any(len(v) != len(qvec) for v in vectors):
|
||||||
|
raise EmbedderDown("question/article embedding dimensions differ")
|
||||||
|
similarities = [cosine(qvec, v) for v in vectors]
|
||||||
|
except EmbedderDown as e:
|
||||||
|
self._embed_ok = False
|
||||||
|
self._log(f"article ranking: embedder down ({e}); BM25-only fallback")
|
||||||
|
else:
|
||||||
|
self._log("article ranking: embeddings unavailable; BM25-only fallback",
|
||||||
|
think=True)
|
||||||
|
ranked = rank_articles(question, articles, similarities)
|
||||||
|
self._rec("fn.done", fn="rank_articles",
|
||||||
|
in_={"question": question,
|
||||||
|
"articles": [{"title": a.title, "snippet": a.snippet}
|
||||||
|
for a in articles]},
|
||||||
|
out_={"method": "bm25+cosine_rrf" if similarities is not None else "bm25",
|
||||||
|
"ranked": [{"title": r.article.title, "bm25": r.bm25,
|
||||||
|
"cosine": r.semantic, "score": r.score} for r in ranked]})
|
||||||
|
return [r.article.title for r in ranked]
|
||||||
|
|
||||||
def _fetch_page(self, title: str) -> WikiPage | None:
|
def _fetch_page(self, title: str) -> WikiPage | None:
|
||||||
"""Reuse fetched articles; log network failures and let gathering continue."""
|
"""Reuse fetched articles; log network failures and let gathering continue."""
|
||||||
if title in self._seen_pages:
|
if title in self._seen_pages:
|
||||||
@@ -1271,22 +1285,24 @@ class KnowledgeExpert:
|
|||||||
extracted = 0
|
extracted = 0
|
||||||
for chunk in capped:
|
for chunk in capped:
|
||||||
if self.cfg.extract_mode == "two_pass":
|
if self.cfg.extract_mode == "two_pass":
|
||||||
# two-pass (26/10): Pass 1 claims (short strings, coref
|
# two-pass (26/10; verbatim moved 1/11): Pass 1 claims WITH
|
||||||
# resolved), Pass 2 one typed Fact per claim — every
|
# their VERBATIM quotes (extracted while the text is in
|
||||||
# output short; the giant typed array is gone from prose.
|
# front of the model), Pass 2 one typed fact per claim —
|
||||||
|
# TYPING only, the model sees JUST the claim (FactNoQuote);
|
||||||
|
# code composes the Fact: FactNoQuote + verbatim.
|
||||||
claims = claims_from(self, entities=ent_str,
|
claims = claims_from(self, entities=ent_str,
|
||||||
heading=chunk.heading_path,
|
heading=chunk.heading_path,
|
||||||
text=chunk.text, charge_llm=charge_llm)
|
text=chunk.text, charge_llm=charge_llm)
|
||||||
self._rec("claims.done", page=page.title,
|
self._rec("claims.done", page=page.title,
|
||||||
heading=chunk.heading_path,
|
heading=chunk.heading_path,
|
||||||
out_={"n_claims": len(claims),
|
out_={"n_claims": len(claims),
|
||||||
"claims": list(claims)})
|
"claims": [c.__dict__ for c in claims]})
|
||||||
# owner ruling 26/10: completeness beats budget — every
|
# owner ruling 26/10: completeness beats budget — every
|
||||||
# unique claim gets its TYPE call (no cap, dedup only)
|
# unique claim gets its TYPE call (no cap, dedup only)
|
||||||
for claim in claims:
|
for c in claims:
|
||||||
fact = fact_from_claim(self, claim, text=chunk.text,
|
fact = fact_from_claim(self, c.claim, verbatim=c.verbatim,
|
||||||
charge_llm=charge_llm)
|
charge_llm=charge_llm)
|
||||||
self._rec("type.done", page=page.title, claim=claim[:200],
|
self._rec("type.done", page=page.title, claim=c.claim[:200],
|
||||||
out_={"fact": getattr(fact, "__dict__", None)}
|
out_={"fact": getattr(fact, "__dict__", None)}
|
||||||
if fact is not None else {"fact": None})
|
if fact is not None else {"fact": None})
|
||||||
if fact is None:
|
if fact is None:
|
||||||
|
|||||||
+52
-21
@@ -3,6 +3,10 @@
|
|||||||
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
||||||
VERBATIM spans. The containment check (checks.py) validates every span against
|
VERBATIM spans. The containment check (checks.py) validates every span against
|
||||||
the FULL document text — so chunking can never fake a quote.
|
the FULL document text — so chunking can never fake a quote.
|
||||||
|
|
||||||
|
Two-pass (two_pass.py): Pass 1 (ExtractClaims) extracts the claims WITH their
|
||||||
|
VERBATIM spans; Pass 2 (TypeClaim) types ONE claim — typing only, the model
|
||||||
|
never sees the quote; code composes Fact = FactNoQuote + verbatim (owner 1/11).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -56,6 +60,24 @@ class Fact(BaseModel):
|
|||||||
"of the sibling fact>}; empty when the text asserts no order")
|
"of the sibling fact>}; empty when the text asserts no order")
|
||||||
|
|
||||||
|
|
||||||
|
class FactNoQuote(BaseModel):
|
||||||
|
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||||
|
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
||||||
|
object: str = dspy.OutputField(desc="the fact's object / value")
|
||||||
|
start: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="when the fact begins, as stated in the claim (a year like 2018, or a full date); empty when the claim states no start")
|
||||||
|
end: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="when the fact ends, as stated in the claim; empty when ongoing/unknown")
|
||||||
|
point: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="for point-in-time facts (events): the stated date; empty otherwise")
|
||||||
|
granularity: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="precision of the stated dates: year, month, or day; empty when no dates")
|
||||||
|
|
||||||
|
|
||||||
class ExtractSignature(dspy.Signature):
|
class ExtractSignature(dspy.Signature):
|
||||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||||
extract facts about the NAMED ENTITIES: biographical facts, positions
|
extract facts about the NAMED ENTITIES: biographical facts, positions
|
||||||
@@ -72,39 +94,48 @@ class ExtractSignature(dspy.Signature):
|
|||||||
desc="the extracted facts; empty list if none")
|
desc="the extracted facts; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
|
class Claim(BaseModel):
|
||||||
|
"""One claim of Pass 1: the free-form claim PLUS the VERBATIM span
|
||||||
|
that states it. The quote is extracted HERE, in the same call that
|
||||||
|
reads the text (owner 1/11: the VERBATIM is obtained before the
|
||||||
|
typing — Pass 2 only enforces the Fact's typing)."""
|
||||||
|
claim: str = dspy.OutputField(
|
||||||
|
desc="the factual claim, coreferences resolved (entities named, "
|
||||||
|
"never pronouns)")
|
||||||
|
verbatim: str = dspy.OutputField(
|
||||||
|
desc="VERBATIM quote from the text that states the claim: the FULL "
|
||||||
|
"sentence or table row, copied exactly (at least 10 characters)")
|
||||||
|
|
||||||
|
|
||||||
class ExtractClaims(dspy.Signature):
|
class ExtractClaims(dspy.Signature):
|
||||||
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
||||||
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
||||||
and offices held, biographical facts, events, relationships,
|
and offices held, biographical facts, events, relationships,
|
||||||
quantities with units. One claim per line, plain text, no numbering.
|
quantities with units. Each claim carries the VERBATIM quote that
|
||||||
Resolve coreferences: name the entity in the claim, never a pronoun
|
states it: the FULL sentence or table row, copied exactly (at least
|
||||||
or a shorthand. Only what the text states; no inference."""
|
10 characters). Resolve coreferences: name the entity in the claim,
|
||||||
|
never a pronoun or a shorthand. Only what the text states; no
|
||||||
|
inference."""
|
||||||
entities: str = dspy.InputField(
|
entities: str = dspy.InputField(
|
||||||
desc="the named entities to extract claims about, comma separated")
|
desc="the named entities to extract claims about, comma separated")
|
||||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||||
text: str = dspy.InputField()
|
text: str = dspy.InputField()
|
||||||
claims: list[str] = dspy.OutputField(
|
claims: list[Claim] = dspy.OutputField(
|
||||||
desc="the factual claims, one string each, coreferences resolved "
|
desc="the factual claims, each with its VERBATIM quote copied "
|
||||||
"(entities named, never pronouns); empty list if none")
|
"exactly from the text; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
class TypeClaim(dspy.Signature):
|
class TypeClaim(dspy.Signature):
|
||||||
"""You are the TYPE step of a knowledge machine. Given ONE single claim
|
"""You are the TYPE step of a knowledge machine. Given ONE single claim,
|
||||||
and the TEXT it was extracted from, type the claim into the Fact
|
type the claim into the typed fact schema: subject entity, relation,
|
||||||
schema: subject entity, relation, object/value, the VERBATIM quote
|
object/value, and the temporal restrictions the claim states. All
|
||||||
copied EXACTLY from the text (the FULL sentence or table row that
|
temporal fields are optional. Only what the claim states; no
|
||||||
states the claim, at least 10 characters), and the temporal
|
inference. If the claim cannot be typed honestly, return null."""
|
||||||
restrictions the text states. All temporal fields are optional and
|
|
||||||
must be contained in the quote. Only what the claim and its quote
|
|
||||||
state; no inference. If the text does not state the claim, return
|
|
||||||
null."""
|
|
||||||
claim: str = dspy.InputField(desc="the claim to type")
|
claim: str = dspy.InputField(desc="the claim to type")
|
||||||
text: str = dspy.InputField(
|
fact: FactNoQuote | None = dspy.OutputField(
|
||||||
desc="the text the claim was extracted from — find the VERBATIM "
|
desc="the typed fact — subject, relation, object, temporal "
|
||||||
"quote here, copied exactly")
|
"restrictions, or null when the "
|
||||||
fact: Fact | None = dspy.OutputField(
|
"claim cannot be typed honestly")
|
||||||
desc="the typed Fact with its verbatim quote from the text, or "
|
|
||||||
"null when the claim cannot be typed honestly")
|
|
||||||
|
|
||||||
|
|
||||||
class AnswerFromKG(dspy.Signature):
|
class AnswerFromKG(dspy.Signature):
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Question-to-article ranking: BM25 + cosine, reciprocal rank fusion.
|
||||||
|
|
||||||
|
The candidate pool is small (all results from this call's searches), so BM25
|
||||||
|
needs no external index or dependency. Snippets guide fetching, never answers.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from .queries import WORD_RE
|
||||||
|
from .store import stem
|
||||||
|
from .wiki import WikiSearchResult
|
||||||
|
|
||||||
|
|
||||||
|
def merge_search_results(per_query: list[list[WikiSearchResult]]) -> list[WikiSearchResult]:
|
||||||
|
"""Deduplicate by title, retaining distinct query-specific snippets."""
|
||||||
|
snippets: dict[str, list[str]] = {}
|
||||||
|
for results in per_query:
|
||||||
|
for hit in results:
|
||||||
|
parts = snippets.setdefault(hit.title, [])
|
||||||
|
if hit.snippet and hit.snippet not in parts:
|
||||||
|
parts.append(hit.snippet)
|
||||||
|
return [WikiSearchResult(title, "\n".join(parts))
|
||||||
|
for title, parts in snippets.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def bm25_scores(question: str, documents: list[str]) -> list[float]:
|
||||||
|
"""Okapi BM25 (k1=1.5, b=0.75), with positive Robertson IDF.
|
||||||
|
|
||||||
|
Query terms come from the full question, never the composed searches.
|
||||||
|
Tokenization and stemming are shared with the existing lexical retrieval.
|
||||||
|
"""
|
||||||
|
counts = [Counter(stem(t) for t in WORD_RE.findall(doc.casefold()))
|
||||||
|
for doc in documents]
|
||||||
|
lengths = [sum(c.values()) for c in counts]
|
||||||
|
avg_length = sum(lengths) / len(lengths) if lengths else 0
|
||||||
|
if not avg_length:
|
||||||
|
return [0.0] * len(documents)
|
||||||
|
terms = sorted({stem(t) for t in WORD_RE.findall(question.casefold())})
|
||||||
|
df = Counter(t for c in counts for t in c)
|
||||||
|
idf = {t: math.log1p((len(counts) - df[t] + 0.5) / (df[t] + 0.5))
|
||||||
|
for t in terms}
|
||||||
|
return [sum(idf[t] * (c[t] * 2.5) /
|
||||||
|
(c[t] + 1.5 * (0.25 + 0.75 * length / avg_length))
|
||||||
|
for t in terms if c[t])
|
||||||
|
for c, length in zip(counts, lengths)]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RankedArticle:
|
||||||
|
article: WikiSearchResult
|
||||||
|
bm25: float
|
||||||
|
semantic: float | None
|
||||||
|
score: float
|
||||||
|
|
||||||
|
|
||||||
|
def rank_articles(question: str, articles: list[WikiSearchResult],
|
||||||
|
similarities: list[float] | None = None) -> list[RankedArticle]:
|
||||||
|
"""Equal-weight RRF (k=60), or BM25 alone when semantics are unavailable.
|
||||||
|
|
||||||
|
Equal scores share a rank, so lexical misses or tied cosine scores do not
|
||||||
|
introduce an arbitrary preference. Final ties preserve search encounter order.
|
||||||
|
"""
|
||||||
|
lexical = bm25_scores(question, [a.text for a in articles])
|
||||||
|
if similarities is not None:
|
||||||
|
if len(similarities) != len(articles) or not all(
|
||||||
|
math.isfinite(s) for s in similarities):
|
||||||
|
raise ValueError("one finite semantic similarity is required per article")
|
||||||
|
|
||||||
|
def reciprocal_rank(scores: list[float], value: float) -> float:
|
||||||
|
rank = 1 + sum(s > value for s in scores)
|
||||||
|
return 1.0 / (60 + rank)
|
||||||
|
|
||||||
|
ranked = []
|
||||||
|
for i, article in enumerate(articles):
|
||||||
|
semantic = similarities[i] if similarities is not None else None
|
||||||
|
score = lexical[i]
|
||||||
|
if similarities is not None:
|
||||||
|
score = reciprocal_rank(lexical, lexical[i])
|
||||||
|
score += reciprocal_rank(similarities, similarities[i])
|
||||||
|
ranked.append(RankedArticle(article, lexical[i], semantic, score))
|
||||||
|
return sorted(ranked, key=lambda a: a.score, reverse=True)
|
||||||
@@ -12,9 +12,9 @@ from unittest.mock import Mock, call, patch
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.expert import (KnowledgeConfig, KnowledgeExpert, _goal_skim_notice,
|
from knowledge.expert import (KnowledgeConfig, KnowledgeExpert, _goal_skim_notice,
|
||||||
_probe_seeds, _rank_article_titles)
|
_probe_seeds)
|
||||||
from knowledge.skim import SkimSheet
|
from knowledge.skim import SkimSheet
|
||||||
from knowledge.wiki import WikiPage, WikiTable
|
from knowledge.wiki import WikiPage, WikiSearchResult, WikiTable
|
||||||
|
|
||||||
|
|
||||||
QUESTION = "What is the flow of Po?"
|
QUESTION = "What is the flow of Po?"
|
||||||
@@ -36,11 +36,14 @@ class AnswerQuestionTests(unittest.TestCase):
|
|||||||
e = self.expert
|
e = self.expert
|
||||||
e.cfg = KnowledgeConfig()
|
e.cfg = KnowledgeConfig()
|
||||||
e.client = Mock()
|
e.client = Mock()
|
||||||
e.client.search.side_effect = [["Po"], ["Italy"]]
|
e.client.search.side_effect = [
|
||||||
|
[WikiSearchResult("Po", "Rivers flow through Italy. Po flows.")],
|
||||||
|
[WikiSearchResult("Italy")]]
|
||||||
e.client.fetch_rich.side_effect = lambda title: page(title)
|
e.client.fetch_rich.side_effect = lambda title: page(title)
|
||||||
e._checked, e._merged = 5, 3
|
e._checked, e._merged = 5, 3
|
||||||
e._prover_answer = Mock(return_value=None)
|
e._prover_answer = Mock(return_value=None)
|
||||||
e._probe = Mock(return_value=["row"])
|
e._probe = Mock(return_value=["row"])
|
||||||
|
e._qvec = Mock(return_value=None)
|
||||||
e._answer_from_rows = Mock(return_value=UNKNOWN)
|
e._answer_from_rows = Mock(return_value=UNKNOWN)
|
||||||
e._audit_ambiguity = Mock(side_effect=lambda _q, ans, _rows, _charge: ans)
|
e._audit_ambiguity = Mock(side_effect=lambda _q, ans, _rows, _charge: ans)
|
||||||
e._set_gate_hit = Mock(return_value=None)
|
e._set_gate_hit = Mock(return_value=None)
|
||||||
@@ -90,15 +93,17 @@ class AnswerQuestionTests(unittest.TestCase):
|
|||||||
e._answer_from_rows.assert_not_called()
|
e._answer_from_rows.assert_not_called()
|
||||||
e.client.search.assert_not_called()
|
e.client.search.assert_not_called()
|
||||||
|
|
||||||
def test_search_deduplicates_and_preserves_query_winners_then_relevance(self):
|
def test_search_deduplicates_and_globally_ranks_title_and_snippet(self):
|
||||||
e = self.expert
|
e = self.expert
|
||||||
e.cfg.max_articles = 5
|
e.cfg.max_articles = 5
|
||||||
e.client.search.side_effect = [
|
e.client.search.side_effect = [
|
||||||
["First", "Other", "Po flow", "Po river"],
|
[WikiSearchResult("First"), WikiSearchResult("Other"),
|
||||||
["Winner", "First", "Other"]]
|
WikiSearchResult("Po flow"), WikiSearchResult("Po river")],
|
||||||
|
[WikiSearchResult("Winner", "Po flow"), WikiSearchResult("First"),
|
||||||
|
WikiSearchResult("Other")]]
|
||||||
result = e.answer_question(QUESTION)
|
result = e.answer_question(QUESTION)
|
||||||
self.assertEqual(result["stats"]["pages"],
|
self.assertEqual(result["stats"]["pages"],
|
||||||
["First", "Winner", "Po flow", "Other", "Po river"])
|
["Po flow", "Winner", "Po river", "First", "Other"])
|
||||||
self.assertEqual(e.client.search.call_args_list, [
|
self.assertEqual(e.client.search.call_args_list, [
|
||||||
call("query one", limit=4), call("query two", limit=4)])
|
call("query one", limit=4), call("query two", limit=4)])
|
||||||
self.assertEqual(e._extract_entities, ["Po"])
|
self.assertEqual(e._extract_entities, ["Po"])
|
||||||
@@ -250,17 +255,6 @@ class PipelineHelperTests(unittest.TestCase):
|
|||||||
self.assertEqual(kws, ["flow"])
|
self.assertEqual(kws, ["flow"])
|
||||||
self.assertEqual(_probe_seeds(kws, ""), kws)
|
self.assertEqual(_probe_seeds(kws, ""), kws)
|
||||||
|
|
||||||
def test_title_ranking_handles_empty_queries_and_duplicate_winners(self):
|
|
||||||
found = [[], ["Winner", "Other", "Flow rate"], ["Winner", "Flow volume"]]
|
|
||||||
self.assertEqual(_rank_article_titles(found, ["flow"]),
|
|
||||||
["Winner", "Flow rate", "Flow volume", "Other"])
|
|
||||||
self.assertEqual(_rank_article_titles([], ["flow"]), [])
|
|
||||||
|
|
||||||
def test_title_ranking_preserves_winners_even_without_relevant_terms(self):
|
|
||||||
self.assertEqual(_rank_article_titles(
|
|
||||||
[["Loire", "Other"], ["France", "Other"]], ["France"]),
|
|
||||||
["Loire", "France", "Other"])
|
|
||||||
|
|
||||||
def test_skim_notices_include_goal_matches_and_filter_unrelated_surfaces(self):
|
def test_skim_notices_include_goal_matches_and_filter_unrelated_surfaces(self):
|
||||||
sheet = SkimSheet(title="Po", url="u", link_candidates=["River flow"])
|
sheet = SkimSheet(title="Po", url="u", link_candidates=["River flow"])
|
||||||
self.assertEqual(_goal_skim_notice(sheet, ["flow"]), sheet.notice())
|
self.assertEqual(_goal_skim_notice(sheet, ["flow"]), sheet.notice())
|
||||||
|
|||||||
@@ -0,0 +1,229 @@
|
|||||||
|
"""Offline search snippets, BM25, hybrid ranking and degradation tests.
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/semantic_fetch.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.embeddings import EmbedderDown, embed
|
||||||
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
|
from knowledge.ranking import bm25_scores, merge_search_results, rank_articles
|
||||||
|
from knowledge.wiki import WikipediaClient, WikiSearchResult
|
||||||
|
|
||||||
|
|
||||||
|
class WikipediaSearchTests(unittest.TestCase):
|
||||||
|
def test_search_requests_and_cleans_snippets(self):
|
||||||
|
client = WikipediaClient()
|
||||||
|
client._get = Mock(return_value={"query": {"search": [
|
||||||
|
{"title": "River", "snippet":
|
||||||
|
'A <span class="searchmatch">river</span> & '
|
||||||
|
"its "flow".\n More text <water>."},
|
||||||
|
{"title": "No snippet"},
|
||||||
|
]}})
|
||||||
|
self.assertEqual(client.search("river flow", limit=3), [
|
||||||
|
WikiSearchResult("River", 'A river & its "flow". More text <water>.'),
|
||||||
|
WikiSearchResult("No snippet")])
|
||||||
|
client._get.assert_called_once_with(
|
||||||
|
action="query", list="search", srsearch="river flow",
|
||||||
|
srlimit=3, srprop="snippet", srnamespace=0)
|
||||||
|
|
||||||
|
def test_empty_search(self):
|
||||||
|
client = WikipediaClient()
|
||||||
|
client._get = Mock(return_value={"query": {"search": []}})
|
||||||
|
self.assertEqual(client.search("nothing"), [])
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleRankingTests(unittest.TestCase):
|
||||||
|
def test_merge_preserves_distinct_snippets_without_duplicate_weight(self):
|
||||||
|
results = merge_search_results([
|
||||||
|
[], [WikiSearchResult("River"), WikiSearchResult("Other", "first")],
|
||||||
|
[WikiSearchResult("River", "flow"), WikiSearchResult("Other", "first"),
|
||||||
|
WikiSearchResult("River", "length"), WikiSearchResult("River", "flow")]])
|
||||||
|
self.assertEqual(results, [
|
||||||
|
WikiSearchResult("River", "flow\nlength"),
|
||||||
|
WikiSearchResult("Other", "first")])
|
||||||
|
|
||||||
|
def test_bm25_matches_formula(self):
|
||||||
|
scores = bm25_scores("river", ["river river", "stone"])
|
||||||
|
idf = math.log1p(1.5 / 1.5)
|
||||||
|
expected = idf * (2 * 2.5) / (2 + 1.5 * (0.25 + 0.75 * 2 / 1.5))
|
||||||
|
self.assertAlmostEqual(scores[0], expected)
|
||||||
|
self.assertEqual(scores[1], 0)
|
||||||
|
|
||||||
|
def test_bm25_rewards_rare_terms_and_saturates_frequency(self):
|
||||||
|
scores = bm25_scores("water discharge", [
|
||||||
|
"water water", "discharge", "water", "stone"])
|
||||||
|
self.assertGreater(scores[1], scores[0])
|
||||||
|
single = bm25_scores("river", ["river stone", "stone stone"])[0]
|
||||||
|
double = bm25_scores("river", ["river river", "stone stone"])[0]
|
||||||
|
self.assertGreater(double, single)
|
||||||
|
self.assertLess(double, 2 * single)
|
||||||
|
|
||||||
|
def test_bm25_length_normalizes_and_matches_case_stems_and_short_entities(self):
|
||||||
|
scores = bm25_scores("Po rivers", [
|
||||||
|
"PO river", "Po river " + "stone " * 100, "Outflow"])
|
||||||
|
self.assertGreater(scores[0], scores[1])
|
||||||
|
self.assertGreater(scores[1], 0)
|
||||||
|
self.assertEqual(scores[2], 0)
|
||||||
|
|
||||||
|
def test_empty_inputs_and_no_overlap(self):
|
||||||
|
self.assertEqual(bm25_scores("", ["a", ""]), [0, 0])
|
||||||
|
self.assertEqual(bm25_scores("river", ["", ""]), [0, 0])
|
||||||
|
self.assertEqual(bm25_scores("river", []), [])
|
||||||
|
self.assertEqual(rank_articles("river", []), [])
|
||||||
|
self.assertEqual(rank_articles("river", [], []), [])
|
||||||
|
|
||||||
|
def test_lexical_ranking_uses_snippet_and_question_not_title_overlap_only(self):
|
||||||
|
hits = [WikiSearchResult("River"), WikiSearchResult(
|
||||||
|
"Po", "The river discharge is the flow rate of water.")]
|
||||||
|
ranked = rank_articles("What is the river discharge?", hits)
|
||||||
|
self.assertEqual([r.article.title for r in ranked], ["Po", "River"])
|
||||||
|
self.assertIsNone(ranked[0].semantic)
|
||||||
|
self.assertEqual(ranked[0].score, ranked[0].bm25)
|
||||||
|
|
||||||
|
def test_rrf_combines_lexical_and_semantic_ranks(self):
|
||||||
|
hits = [WikiSearchResult("river river"), WikiSearchResult("river stone"),
|
||||||
|
WikiSearchResult("quartz quartz")]
|
||||||
|
lexical = rank_articles("river", hits)
|
||||||
|
hybrid = rank_articles("river", hits, [0.1, 0.9, 0.5])
|
||||||
|
self.assertEqual(lexical[0].article.title, "river river")
|
||||||
|
self.assertEqual(hybrid[0].article.title, "river stone")
|
||||||
|
self.assertAlmostEqual(hybrid[0].score, 1 / 62 + 1 / 61)
|
||||||
|
|
||||||
|
def test_semantics_can_promote_a_lexical_miss(self):
|
||||||
|
hits = [WikiSearchResult("river"), WikiSearchResult("watercourse"),
|
||||||
|
WikiSearchResult("rock"), WikiSearchResult("mineral")]
|
||||||
|
ranked = rank_articles("river", hits, [0.1, 0.99, 0.2, 0.3])
|
||||||
|
self.assertEqual(ranked[0].article.title, "watercourse")
|
||||||
|
|
||||||
|
def test_tied_lexical_scores_do_not_bias_semantic_order(self):
|
||||||
|
hits = [WikiSearchResult("A"), WikiSearchResult("B"), WikiSearchResult("C")]
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits, [0.1, 0.3, 0.9])], ["C", "B", "A"])
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits, [0.5, 0.5, 0.5])], ["A", "B", "C"])
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits)], ["A", "B", "C"])
|
||||||
|
|
||||||
|
def test_invalid_similarities_are_rejected(self):
|
||||||
|
for scores in ([], [float("nan")], [float("inf")]):
|
||||||
|
with self.subTest(scores=scores), self.assertRaises(ValueError):
|
||||||
|
rank_articles("river", [WikiSearchResult("A")], scores)
|
||||||
|
|
||||||
|
|
||||||
|
class ExpertSearchRankingTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.expert = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||||
|
e = self.expert
|
||||||
|
e.cfg = KnowledgeConfig(max_articles=1)
|
||||||
|
e._embed_ok = True
|
||||||
|
e._qvec_cache = {"river": [1.0, 0.0]}
|
||||||
|
e._log = Mock()
|
||||||
|
e._rec = Mock()
|
||||||
|
e.client = Mock()
|
||||||
|
|
||||||
|
def test_all_searches_merge_before_question_based_global_ranking(self):
|
||||||
|
e = self.expert
|
||||||
|
e.client.search.side_effect = [
|
||||||
|
[WikiSearchResult("river river"), WikiSearchResult("river stone")],
|
||||||
|
[WikiSearchResult("quartz quartz"), WikiSearchResult("river stone", "stream")]]
|
||||||
|
vectors = [[0.1, 0.99], [1.0, 0.0], [0.5, 0.86]]
|
||||||
|
with patch("knowledge.expert.compose_queries",
|
||||||
|
return_value=(["unrelated query", "another query"], ["query"])), \
|
||||||
|
patch("knowledge.expert.embed", return_value=vectors) as embedding:
|
||||||
|
ordered = e._search_articles("river", [], False)
|
||||||
|
self.assertEqual(ordered[0], "river stone")
|
||||||
|
self.assertEqual(len(ordered), 3) # max_articles applies only AFTER ranking.
|
||||||
|
embedding.assert_called_once_with(
|
||||||
|
["river river", "river stone\nstream", "quartz quartz"],
|
||||||
|
model=e.cfg.embed_model, url=e.cfg.embed_url)
|
||||||
|
e._rec.assert_any_call(
|
||||||
|
"fn.done", fn="search",
|
||||||
|
in_={"query": "another query", "limit": 4},
|
||||||
|
out_={"titles": ["quartz quartz", "river stone"],
|
||||||
|
"results": [{"title": "quartz quartz", "snippet": ""},
|
||||||
|
{"title": "river stone", "snippet": "stream"}]})
|
||||||
|
rank_event = next(c.kwargs for c in e._rec.call_args_list
|
||||||
|
if c.kwargs.get("fn") == "rank_articles")
|
||||||
|
self.assertEqual(rank_event["in_"]["question"], "river")
|
||||||
|
self.assertEqual(rank_event["out_"]["method"], "bm25+cosine_rrf")
|
||||||
|
self.assertEqual(rank_event["out_"]["ranked"][0]["title"], "river stone")
|
||||||
|
|
||||||
|
def test_question_and_documents_are_embedded_not_composed_queries(self):
|
||||||
|
e = self.expert
|
||||||
|
with patch("knowledge.expert.embed",
|
||||||
|
side_effect=[[[1.0, 0.0]], [[0.0, 1.0]]]) as embedding:
|
||||||
|
e._rank_search_results("original question", [WikiSearchResult("A", "summary")])
|
||||||
|
self.assertEqual(embedding.call_args_list[0].args, (["original question"],))
|
||||||
|
self.assertEqual(embedding.call_args_list[1].args, (["A\nsummary"],))
|
||||||
|
|
||||||
|
def test_document_embedding_failure_logs_bm25_fallback(self):
|
||||||
|
e = self.expert
|
||||||
|
hits = [WikiSearchResult("unrelated"), WikiSearchResult("river")]
|
||||||
|
with patch("knowledge.expert.embed", side_effect=EmbedderDown("offline")):
|
||||||
|
self.assertEqual(e._rank_search_results("river", hits), ["river", "unrelated"])
|
||||||
|
self.assertFalse(e._embed_ok)
|
||||||
|
e._log.assert_called_once_with(
|
||||||
|
"article ranking: embedder down (offline); BM25-only fallback")
|
||||||
|
self.assertEqual(e._rec.call_args.kwargs["out_"]["method"], "bm25")
|
||||||
|
|
||||||
|
def test_question_embedding_failure_and_already_disabled_embedder(self):
|
||||||
|
e = self.expert
|
||||||
|
with patch("knowledge.expert.embed", side_effect=EmbedderDown("offline")) as embedding:
|
||||||
|
for _ in range(2):
|
||||||
|
self.assertEqual(e._rank_search_results(
|
||||||
|
"new question", [WikiSearchResult("A")]), ["A"])
|
||||||
|
embedding.assert_called_once()
|
||||||
|
self.assertFalse(e._embed_ok)
|
||||||
|
self.assertTrue(any("BM25-only fallback" in c.args[0]
|
||||||
|
for c in e._log.call_args_list))
|
||||||
|
|
||||||
|
def test_inconsistent_question_document_dimensions_fall_back(self):
|
||||||
|
with patch("knowledge.expert.embed", return_value=[[1.0]]):
|
||||||
|
self.assertEqual(self.expert._rank_search_results(
|
||||||
|
"river", [WikiSearchResult("river")]), ["river"])
|
||||||
|
self.assertFalse(self.expert._embed_ok)
|
||||||
|
self.assertIn("dimensions differ", self.expert._log.call_args.args[0])
|
||||||
|
|
||||||
|
def test_empty_candidate_pool_does_not_call_embedder(self):
|
||||||
|
with patch("knowledge.expert.embed") as embedding:
|
||||||
|
self.assertEqual(self.expert._rank_search_results("river", []), [])
|
||||||
|
embedding.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class EmbeddingResponseTests(unittest.TestCase):
|
||||||
|
def test_invalid_embedding_responses_raise_embedder_down(self):
|
||||||
|
responses = [
|
||||||
|
[], {}, {"embeddings": []}, {"embeddings": [[1.0]]},
|
||||||
|
{"embeddings": [[1.0], [1.0, 2.0]]},
|
||||||
|
{"embeddings": [[0.0], [1.0]]},
|
||||||
|
{"embeddings": [[float("nan")], [1.0]]},
|
||||||
|
{"embeddings": [[float("inf")], [1.0]]},
|
||||||
|
{"embeddings": [["bad"], [1.0]]},
|
||||||
|
{"embeddings": [[True], [1.0]]},
|
||||||
|
{"embeddings": [[], []]},
|
||||||
|
]
|
||||||
|
for response in responses:
|
||||||
|
with self.subTest(response=response), patch(
|
||||||
|
"knowledge.embeddings.urllib.request.urlopen",
|
||||||
|
return_value=io.BytesIO(json.dumps(response).encode())):
|
||||||
|
with self.assertRaises(EmbedderDown):
|
||||||
|
embed(["question", "document"])
|
||||||
|
|
||||||
|
def test_valid_embedding_response(self):
|
||||||
|
with patch("knowledge.embeddings.urllib.request.urlopen",
|
||||||
|
return_value=io.BytesIO(b'{"embeddings":[[1,0],[0,1]]}')):
|
||||||
|
self.assertEqual(embed(["question", "document"]), [[1, 0], [0, 1]])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,29 +1,38 @@
|
|||||||
"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass EXTRACT tests (Pass 1 claims + verbatim, Pass 2 typing).
|
||||||
|
|
||||||
Law: the old single call asked a slow model for verbatim quotes + typed
|
Law: the old single call asked a slow model for verbatim quotes + typed
|
||||||
temporal fields + sibling order assertions in ONE giant JSON array — the
|
temporal fields + sibling order assertions in ONE giant JSON array — the
|
||||||
output budget that produced the 40-minute arithmetic. The two-pass split
|
output budget that produced the 40-minute arithmetic. The two-pass split
|
||||||
shortens EVERY output: Pass 1 extracts plain claims (free-form strings
|
shortens EVERY output: Pass 1 extracts the claims, each with its
|
||||||
with coreference resolved to the entity names — near-zero format tax);
|
VERBATIM quote (coreference resolved to the entity names); Pass 2 types
|
||||||
Pass 2 types ONE claim into the existing Fact schema per call.
|
ONE claim per call — TYPING only, the model sees ONLY the claim and
|
||||||
|
returns FactNoQuote; code composes the Fact: FactNoQuote + verbatim
|
||||||
|
(owner 1/11: the VERBATIM is obtained before, the TYPE model never sees
|
||||||
|
nor rewrites it).
|
||||||
|
|
||||||
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
|
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — the TYPE schema
|
||||||
assertions become IMPOSSIBLE by construction, so orders are dropped from
|
(FactNoQuote) has NO orders field at all, so sibling order assertions
|
||||||
the two-pass path (the store's fact_order keeps working for whatever
|
are impossible by construction (the store's fact_order keeps working
|
||||||
arrives as a typed Fact with orders; the two-pass facts carry none).
|
for whatever arrives as a typed Fact with orders; the two-pass facts
|
||||||
The store, the containment checks and the merge are UNTOUCHED — Pass 2
|
carry none). The store, the containment checks and the merge are
|
||||||
emits the same typed Fact as before, minus orders.
|
UNTOUCHED — the composed Fact is the same typed Fact as before, minus
|
||||||
|
orders.
|
||||||
|
|
||||||
Pinned:
|
Pinned:
|
||||||
1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the
|
1. ExtractClaims: free-form claims, coreferences RESOLVED (the claim
|
||||||
claim must name its entities, not 'he/it/the party').
|
must name its entities, not 'he/it/the party'), each carrying its
|
||||||
2. TypeClaim: one claim in -> one typed Fact out (same fields as the
|
VERBATIM quote — the quote is extracted HERE, in Pass 1.
|
||||||
legacy ExtractSignature.facts minus orders; temporal fields optional).
|
2. TypeClaim: one claim in -> one FactNoQuote out (Fact minus quote,
|
||||||
3. The pipeline wiring: _extract_two_pass returns typed Fact objects;
|
minus orders; temporal fields optional) — no text, no verbatim
|
||||||
candidates flow into _ingest_candidate exactly as before.
|
input: the TYPE model never sees the quote.
|
||||||
|
3. The pipeline wiring: the two-pass path returns composed Fact
|
||||||
|
objects; candidates flow into _ingest_candidate exactly as before.
|
||||||
4. Honest empty: no claims -> no facts, no invention.
|
4. Honest empty: no claims -> no facts, no invention.
|
||||||
5. The legacy single-pass signature STAYS (table frags use it; flipping
|
5. The legacy single-pass signature STAYS (table frags use it; flipping
|
||||||
the whole pipeline over is a later decision, config-driven).
|
the whole pipeline over is a later decision, config-driven).
|
||||||
|
6. Code COMPOSES the output Fact = FactNoQuote + verbatim (LLMs
|
||||||
|
propose, code decides) — the TYPE model never sees nor rewrites
|
||||||
|
the quote, so it cannot corrupt the span.
|
||||||
|
|
||||||
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
||||||
"""
|
"""
|
||||||
@@ -36,7 +45,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.extract import ExtractClaims, TypeClaim, Fact, ExtractSignature
|
from knowledge.extract import (Claim, ExtractClaims, ExtractSignature, Fact,
|
||||||
|
FactNoQuote, TypeClaim)
|
||||||
from knowledge.two_pass import claims_from, fact_from_claim
|
from knowledge.two_pass import claims_from, fact_from_claim
|
||||||
|
|
||||||
|
|
||||||
@@ -49,55 +59,79 @@ class Scripted:
|
|||||||
|
|
||||||
|
|
||||||
def test_extract_claims_signature():
|
def test_extract_claims_signature():
|
||||||
"""Pass 1: claims are free-form strings; coreferences resolved."""
|
"""Pass 1: claims + their VERBATIM quotes; coreferences resolved."""
|
||||||
fields = set(ExtractClaims.__fields__)
|
fields = set(ExtractClaims.__fields__)
|
||||||
assert fields == {"entities", "heading", "text", "claims"}, fields
|
assert fields == {"entities", "heading", "text", "claims"}, fields
|
||||||
|
a = ExtractClaims.model_fields["claims"].annotation
|
||||||
|
assert "Claim" in str(a), a # each claim now carries its verbatim
|
||||||
# what the model actually sees: dspy keeps desc in json_schema_extra
|
# what the model actually sees: dspy keeps desc in json_schema_extra
|
||||||
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
||||||
assert "coreference" in d.lower() or "resolved" in d.lower(), d
|
assert "verbatim" in d.lower(), d
|
||||||
print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft")
|
dv = (Claim.model_fields["verbatim"].json_schema_extra or {}).get("desc", "")
|
||||||
|
assert "verbatim" in dv.lower() and "copied exactly" in dv.lower(), dv
|
||||||
|
print("ok: ExtractClaims = claims with their VERBATIM quotes, coreferences resolved")
|
||||||
|
|
||||||
|
|
||||||
def test_type_claim_signature():
|
def test_type_claim_signature():
|
||||||
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
"""Pass 2: one claim -> one typed FactNoQuote; no verbatim, no text;
|
||||||
|
orders IMPOSSIBLE (no orders field at all)."""
|
||||||
fields = set(TypeClaim.__fields__)
|
fields = set(TypeClaim.__fields__)
|
||||||
assert fields == {"claim", "text", "fact"}, fields # text: the quote must be COPIED from it (live finding: without it, 69/70 invented quotes rejected)
|
# the model sees ONLY the claim: the VERBATIM (Pass 1's) is NOT an
|
||||||
|
# input — nothing to copy, nothing to rewrite (owner 1/11).
|
||||||
|
assert fields == {"claim", "fact"}, fields
|
||||||
f = TypeClaim.model_fields["fact"].annotation
|
f = TypeClaim.model_fields["fact"].annotation
|
||||||
assert "Fact" in str(f), f
|
assert "FactNoQuote" in str(f), f
|
||||||
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
# FactNoQuote: Fact minus quote (never shown to the TYPE model)
|
||||||
# them — untouched); the two-pass law is that TypeClaim never fills
|
# minus orders (one claim per call: no siblings to reference — the
|
||||||
# them: one claim per call means no siblings to reference.
|
# two-pass law, now enforced by the SCHEMA itself)
|
||||||
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
|
assert "quote" not in FactNoQuote.model_fields, "FactNoQuote must not carry a quote"
|
||||||
|
assert "orders" not in FactNoQuote.model_fields, "one claim per call: no siblings to reference"
|
||||||
|
# Fact KEEPS quote + orders (the legacy single-pass path and table
|
||||||
|
# frags use them — untouched)
|
||||||
|
assert "quote" in Fact.model_fields and "orders" in Fact.model_fields
|
||||||
d = TypeClaim.__doc__ or ""
|
d = TypeClaim.__doc__ or ""
|
||||||
assert "one claim" in d.lower() or "single" in d.lower(), d
|
assert "one claim" in d.lower() or "single" in d.lower(), d
|
||||||
print("ok: TypeClaim = one claim -> one Fact; orders never produced (no siblings)")
|
print("ok: TypeClaim = one claim -> FactNoQuote (typing only; no quote, no orders)")
|
||||||
|
|
||||||
|
|
||||||
def test_claims_from_runs_pass1():
|
def test_claims_from_runs_pass1():
|
||||||
e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018",
|
e = Scripted(claims=Scripted(claims=[
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"]))
|
Claim(claim="Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]))
|
||||||
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
||||||
assert out == ["Pedro Sanchez is the prime minister of Spain since 2018",
|
assert [(c.claim, c.verbatim) for c in out] == [
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"], out
|
("Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
print("ok: claims_from extracts the plain claim strings")
|
"has been the prime minister of Spain since 2018"),
|
||||||
|
("Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")], out
|
||||||
|
print("ok: claims_from extracts the claims with their verbatim quotes")
|
||||||
|
|
||||||
|
|
||||||
def test_fact_from_claim_types_one_fact():
|
def test_fact_from_claim_types_one_fact():
|
||||||
e = Scripted(typeclaim=Scripted(fact=Fact(
|
"""Pass 2 types one claim; code COMPOSES the Fact = FactNoQuote +
|
||||||
|
verbatim — the scripted FactNoQuote has no quote to invent, and the
|
||||||
|
returned Fact carries Pass 1's verbatim (LLMs propose, code
|
||||||
|
decides)."""
|
||||||
|
e = Scripted(typeclaim=Scripted(fact=FactNoQuote(
|
||||||
subject="Pedro Sanchez", relation="prime minister of",
|
subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain", quote="is a Spanish politician who has been the "
|
object="Spain",
|
||||||
"prime minister of Spain since 2018",
|
|
||||||
start="2018", end=None, point=None, granularity="year")))
|
start="2018", end=None, point=None, granularity="year")))
|
||||||
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018", text="...")
|
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
verbatim="has been the prime minister of Spain since 2018")
|
||||||
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
||||||
print("ok: fact_from_claim returns the typed Fact for one claim")
|
assert f.quote == "has been the prime minister of Spain since 2018", f.quote
|
||||||
|
assert isinstance(f, Fact), f # the store eats a real Fact
|
||||||
|
assert f.orders == [], f.orders # composed default: no siblings
|
||||||
|
print("ok: fact_from_claim composes Fact = FactNoQuote + verbatim")
|
||||||
|
|
||||||
|
|
||||||
def test_honest_empty():
|
def test_honest_empty():
|
||||||
e = Scripted(claims=Scripted(claims=[]))
|
e = Scripted(claims=Scripted(claims=[]))
|
||||||
assert claims_from(e, entities="", heading="", text="") == []
|
assert claims_from(e, entities="", heading="", text="") == []
|
||||||
e2 = Scripted(typeclaim=Scripted(fact=None))
|
e2 = Scripted(typeclaim=Scripted(fact=None))
|
||||||
assert fact_from_claim(e2, claim="", text="") is None
|
assert fact_from_claim(e2, claim="", verbatim="") is None
|
||||||
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||||
|
|
||||||
|
|
||||||
@@ -105,25 +139,32 @@ def test_claims_from_dedupes_exact_repeats():
|
|||||||
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||||
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||||
deterministic — the claim list must not be capped or filtered
|
deterministic — the claim list must not be capped or filtered
|
||||||
semantically, only made honest: no exact duplicates survive."""
|
semantically, only made honest: no exact duplicates survive. The
|
||||||
|
FIRST occurrence's verbatim is the one kept."""
|
||||||
calls = []
|
calls = []
|
||||||
|
|
||||||
class E: # minimal expert double
|
class E: # minimal expert double
|
||||||
def claims(self, entities, heading, text):
|
def claims(self, entities, heading, text):
|
||||||
calls.append((entities, heading))
|
calls.append((entities, heading))
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez is prime minister of Spain.",
|
claims = [Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
"pedro sanchez is prime minister of spain. ",
|
verbatim="prime minister of Spain"),
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
Claim(claim="pedro sanchez is prime minister of spain. ",
|
||||||
"Pedro Sanchez is prime minister of Spain.",
|
verbatim="the repeat's quote — must not survive"),
|
||||||
"from the text. I need to list factual claims"]
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
verbatim="Secretary-General of the PSOE"),
|
||||||
|
Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
|
verbatim="second repeat's quote"),
|
||||||
|
Claim(claim="from the text. I need to list factual claims",
|
||||||
|
verbatim="thinking leakage")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||||
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
assert [(c.claim, c.verbatim) for c in got] == [
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
("Pedro Sanchez is prime minister of Spain.", "prime minister of Spain"),
|
||||||
"from the text. I need to list factual claims"], got
|
("Pedro Sanchez is Secretary-General of the PSOE.", "Secretary-General of the PSOE"),
|
||||||
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
("from the text. I need to list factual claims", "thinking leakage")], got
|
||||||
|
print("ok: exact repeats deduped (case/space-insensitive); the first verbatim kept")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ mode ingests the typed facts from Pass 2 exactly as the legacy path
|
|||||||
did — same _ingest_candidate, same containment checks, same merge; the
|
did — same _ingest_candidate, same containment checks, same merge; the
|
||||||
single-pass path keeps working (control). No network: the expert's
|
single-pass path keeps working (control). No network: the expert's
|
||||||
claims/typeclaim/extract modules are scripted.
|
claims/typeclaim/extract modules are scripted.
|
||||||
|
|
||||||
|
The verbatim law (1/11): Pass 1 extracts the VERBATIM quote, Pass 2
|
||||||
|
only types — the model sees ONLY the claim and returns FactNoQuote;
|
||||||
|
code COMPOSES the Fact (FactNoQuote + verbatim), so the STORED quotes
|
||||||
|
(quotes.verbatim) must be Pass 1's spans (contained in the page text),
|
||||||
|
never the TYPE model's.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -16,7 +22,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.extract import Fact
|
from knowledge.extract import Claim, FactNoQuote
|
||||||
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
from knowledge.store import KnowledgeStore
|
from knowledge.store import KnowledgeStore
|
||||||
from knowledge.wiki import WikiPage
|
from knowledge.wiki import WikiPage
|
||||||
@@ -36,14 +42,22 @@ def make_page() -> WikiPage:
|
|||||||
|
|
||||||
|
|
||||||
class ScriptedClaims:
|
class ScriptedClaims:
|
||||||
|
"""Pass 1 double: claims WITH their verbatim quotes — spans that ARE
|
||||||
|
contained in PAGE_TEXT (the containment check runs for real)."""
|
||||||
|
|
||||||
def __call__(self, **kw):
|
def __call__(self, **kw):
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
|
claims = [Claim(claim="Pedro Sanchez has been the prime minister of Spain since 2018",
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE since 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
|
|
||||||
class ScriptedTypeClaim:
|
class ScriptedTypeClaim:
|
||||||
|
"""Pass 2 double: typing only — FactNoQuote, NO quote field at all;
|
||||||
|
code composes the Fact with Pass 1's verbatim."""
|
||||||
|
|
||||||
def __init__(self, facts):
|
def __init__(self, facts):
|
||||||
self.facts = facts
|
self.facts = facts
|
||||||
self.i = 0
|
self.i = 0
|
||||||
@@ -64,14 +78,11 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
store=store)
|
store=store)
|
||||||
e.claims = ScriptedClaims()
|
e.claims = ScriptedClaims()
|
||||||
e.typeclaim = ScriptedTypeClaim([
|
e.typeclaim = ScriptedTypeClaim([
|
||||||
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
FactNoQuote(subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain",
|
object="Spain",
|
||||||
quote="has been the prime minister of Spain since 2018",
|
|
||||||
start="2018", end=None, point=None, granularity="year"),
|
start="2018", end=None, point=None, granularity="year"),
|
||||||
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
FactNoQuote(subject="Pedro Sanchez", relation="secretary-general of",
|
||||||
object="PSOE",
|
object="PSOE",
|
||||||
quote="Secretary-General of the Spanish Socialist Workers' "
|
|
||||||
"Party (PSOE) since 2017",
|
|
||||||
start="2017", end=None, point=None, granularity="year"),
|
start="2017", end=None, point=None, granularity="year"),
|
||||||
])
|
])
|
||||||
# per-call state that answer_question initializes (the wiring test
|
# per-call state that answer_question initializes (the wiring test
|
||||||
@@ -89,7 +100,14 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
assert len(rows) == 2, rows
|
assert len(rows) == 2, rows
|
||||||
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
|
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
|
||||||
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
|
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
|
||||||
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
|
# the verbatim law end-to-end: the STORED quotes are Pass 1's verbatims
|
||||||
|
# (the TYPE model never produced a quote at all — code composed it)
|
||||||
|
quotes = {r[0] for r in store.db.execute(
|
||||||
|
"SELECT verbatim FROM quotes").fetchall()}
|
||||||
|
assert quotes == {"has been the prime minister of Spain since 2018",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' "
|
||||||
|
"Party (PSOE) since 2017"}, quotes
|
||||||
|
print("ok: two_pass ingests typed facts (Fact = FactNoQuote + verbatim, legacy checks)")
|
||||||
|
|
||||||
|
|
||||||
def test_single_pass_still_works():
|
def test_single_pass_still_works():
|
||||||
|
|||||||
+39
-23
@@ -1,52 +1,68 @@
|
|||||||
"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass extraction (Pass 1 claims + verbatim quotes, Pass 2 typing).
|
||||||
|
|
||||||
The single-pass EXTRACT asked slow local models for a giant JSON array
|
The single-pass EXTRACT asked slow local models for a giant JSON array
|
||||||
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
||||||
order assertions — the output budget behind the 40-minute arithmetic.
|
order assertions — the output budget behind the 40-minute arithmetic.
|
||||||
Two-pass shortens every output: Pass 1 lists plain claims (free-form
|
Two-pass shortens every output: Pass 1 lists the claims, each with its
|
||||||
strings, coreferences resolved — near-zero format tax); Pass 2 types
|
VERBATIM quote (extracted while the text is in front of the model);
|
||||||
ONE claim at a time into the same Fact schema the store already eats.
|
Pass 2 types ONE claim at a time — the model sees ONLY the claim and
|
||||||
|
returns FactNoQuote; code composes the Fact the store already eats:
|
||||||
|
Fact = FactNoQuote + verbatim (owner 1/11: the VERBATIM is obtained
|
||||||
|
before, the TYPE model never sees nor rewrites it).
|
||||||
|
|
||||||
Orders: NEVER produced here — one claim per call has no siblings to
|
Orders: NEVER produced here — one claim per call has no siblings to
|
||||||
reference. The legacy single-pass path (and table frags) keeps them.
|
reference, and the TYPE schema (FactNoQuote) has no orders field at
|
||||||
|
all. The legacy single-pass path (and table frags) keeps them.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .extract import Claim, Fact
|
||||||
|
|
||||||
|
|
||||||
def claims_from(expert, entities: str, heading: str, text: str,
|
def claims_from(expert, entities: str, heading: str, text: str,
|
||||||
charge_llm=None) -> list[str]:
|
charge_llm=None) -> list[Claim]:
|
||||||
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.
|
"""Pass 1: the chunk's claims, each with its VERBATIM quote — the
|
||||||
|
quote is extracted HERE, in the same call that reads the text.
|
||||||
|
|
||||||
The list is made honest by CODE only: exact repeats are dropped
|
The list is made honest by CODE only: exact repeats are dropped
|
||||||
(live finding 26/10: glm sometimes lists its whole list twice, and
|
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||||
thinking leakage leaks in as list items). Dedup is case- and
|
thinking leakage leaks in as list items). Dedup is case- and
|
||||||
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
whitespace-insensitive on the CLAIM text; the FIRST occurrence's
|
||||||
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
(claim, verbatim) is kept. NO cap, NO semantic filter: completeness
|
||||||
26/10) — every unique claim gets its TYPE call.
|
beats budget (owner ruling 26/10) — every unique claim gets its
|
||||||
|
TYPE call.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.claims(entities=entities, heading=heading, text=text)
|
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||||
seen: dict[str, str] = {}
|
seen: dict[str, Claim] = {}
|
||||||
for c in (pred.claims or []):
|
for c in (pred.claims or []):
|
||||||
c = (c or "").strip()
|
claim = (getattr(c, "claim", "") or "").strip()
|
||||||
if c:
|
verbatim = (getattr(c, "verbatim", "") or "").strip()
|
||||||
key = " ".join(c.lower().split())
|
if claim:
|
||||||
|
key = " ".join(claim.lower().split())
|
||||||
if key not in seen:
|
if key not in seen:
|
||||||
seen[key] = c
|
seen[key] = Claim(claim=claim, verbatim=verbatim)
|
||||||
return list(seen.values())
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
def fact_from_claim(expert, claim: str, text: str, charge_llm=None):
|
def fact_from_claim(expert, claim: str, verbatim: str, charge_llm=None):
|
||||||
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
||||||
|
|
||||||
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
TYPING ONLY: the model sees ONLY the claim — no text, no verbatim
|
||||||
came from) — without the text the model invents a quote and the
|
(owner 1/11: the VERBATIM is Pass 1's and the TYPE model never sees
|
||||||
containment check rejects it (live finding 26/10: 69/70 rejected).
|
nor rewrites it). Code COMPOSES the store's Fact: FactNoQuote +
|
||||||
The store's checks validate everything downstream as before. No
|
verbatim (LLMs propose, code decides) — the quote is Pass 1's span
|
||||||
orders: no siblings by construction.
|
BY CONSTRUCTION, and the store's checks validate it downstream as
|
||||||
|
before (a temporal field not contained in the quote rejects the
|
||||||
|
candidate; live finding 26/10: without grounding, 69/70 invented
|
||||||
|
quotes were rejected). No orders: no siblings by construction, and
|
||||||
|
FactNoQuote has no orders field at all.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.typeclaim(claim=claim, text=text)
|
pred = expert.typeclaim(claim=claim)
|
||||||
return getattr(pred, "fact", None)
|
nq = getattr(pred, "fact", None)
|
||||||
|
if nq is None:
|
||||||
|
return None
|
||||||
|
return Fact(**nq.model_dump(), quote=verbatim)
|
||||||
+33
-4
@@ -14,6 +14,7 @@ from __future__ import annotations
|
|||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -22,6 +23,26 @@ UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
|
|||||||
LANG = "en"
|
LANG = "en"
|
||||||
|
|
||||||
|
|
||||||
|
class _SnippetText(HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
self.parts.append(data)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class WikiSearchResult:
|
||||||
|
"""Search metadata, not evidence: snippets still need a fetched source."""
|
||||||
|
title: str
|
||||||
|
snippet: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def text(self) -> str:
|
||||||
|
return f"{self.title}\n{self.snippet}".strip()
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WikiTable:
|
class WikiTable:
|
||||||
"""One parsed wikitext table: header row + all data rows, untruncated."""
|
"""One parsed wikitext table: header row + all data rows, untruncated."""
|
||||||
@@ -331,10 +352,18 @@ class WikipediaClient:
|
|||||||
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
||||||
|
|
||||||
# ---- api surface --------------------------------------------------------
|
# ---- api surface --------------------------------------------------------
|
||||||
def search(self, query: str, limit: int = 5) -> list[str]:
|
def search(self, query: str, limit: int = 5) -> list[WikiSearchResult]:
|
||||||
"""Official search: list=search. Returns candidate article titles."""
|
"""Return titles and plain-text search snippets, without fetching pages."""
|
||||||
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
|
data = self._get(action="query", list="search", srsearch=query,
|
||||||
return [h["title"] for h in data.get("query", {}).get("search", [])]
|
srlimit=limit, srprop="snippet", srnamespace=0)
|
||||||
|
results = []
|
||||||
|
for hit in data.get("query", {}).get("search", []):
|
||||||
|
parser = _SnippetText()
|
||||||
|
parser.feed(hit.get("snippet", ""))
|
||||||
|
parser.close()
|
||||||
|
snippet = " ".join("".join(parser.parts).split())
|
||||||
|
results.append(WikiSearchResult(title=hit["title"], snippet=snippet))
|
||||||
|
return results
|
||||||
|
|
||||||
def summary(self, title: str) -> str:
|
def summary(self, title: str) -> str:
|
||||||
data = self._get(action="query", titles=title, prop="extracts",
|
data = self._get(action="query", titles=title, prop="extracts",
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ EVENTS = [
|
|||||||
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
|
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
|
||||||
"event": "claims.done", "page": "Pedro Sanchez",
|
"event": "claims.done", "page": "Pedro Sanchez",
|
||||||
"heading": "Career", "out": {"n_claims": 1,
|
"heading": "Career", "out": {"n_claims": 1,
|
||||||
"claims": ["PM of Spain since 2018"]}},
|
"claims": [{"claim": "PM of Spain since 2018",
|
||||||
|
"verbatim": "prime minister of Spain since 2018"}]}},
|
||||||
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
|
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
|
||||||
"event": "type.done", "page": "Pedro Sanchez",
|
"event": "type.done", "page": "Pedro Sanchez",
|
||||||
"claim": "PM of Spain since 2018",
|
"claim": "PM of Spain since 2018",
|
||||||
|
|||||||
Reference in New Issue
Block a user