raglab#
raglab — the agentic-search / RAG orchestration layer on top of ir.
raglab turns a retrieval substrate into a Composable Search Agent (the ir_09
architecture): a small set of injected roles — Planner, Formulator,
Retriever, Evaluator, Reranker, Citer — wired by a control loop whose back-edge
(evaluator → reformulate) is what makes it an agent rather than a DAG. Concrete
tools live at the leaves: an ir corpus becomes one Retriever via
ir.as_retriever.
Quick start (the no-LLM thin slice — runs offline):
import ir
import raglab
# register ir corpora as the agent's sources, then search across them:
sources = raglab.ir_sources("skills", "reports", mode="hybrid")
agent = raglab.make_search_agent(sources)
results = agent("how do I deploy the app") # ranked ir.SearchHits
Inject an LLM formulator (query rewrite/HyDE) and evaluator (sufficiency
refinement) to turn on query understanding and the back-edge. Dependency direction is one-way:
raglabimportsir;irnever importsraglab.
> Fresh start (v0.2.0+). This repo took over the raglab PyPI name; the older
> backend now lives at raglab_bak. Development is just beginning.
Functions
|
Keep at most |
|
Keep the first |
|
Build a |
|
A source registry |
|
Trivial planner: one sub-task over all registered sources, no decomposition. |
|
Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE). |
|
Pass-through critic: keep everything, declare sufficient, never re-query. |
|
Magnitude merge: one surface per artifact, ordered by descending raw score. |
|
Cross-source merge (the default fan-in): fuse by rank, never by raw score. |
|
A parametrized |
|
No-op citer (verification needs a generated claim — that lives in srag). |
|
An LLM-backed raglab |
|
An LLM-backed raglab |
|
The level a judge's proposal is allowed, after calibration and the gates. |
|
An |
Classes
|
A user intent: free text plus optional structured constraints. |
|
A planner's unit of work: a sub-goal bound to a set of registered sources. |
|
One concrete query against one source. |
|
An evaluator's verdict over a round's results. |
|
A graded verdict on one candidate (raglab#8): a level, three axes, the evidence. |
|
Decompose a query into sub-tasks and select sources for each. |
|
Turn a sub-task + one source into concrete low-level queries. |
|
Judge relevance + sufficiency; optionally emit a refinement (back-edge). |
|
Produce the final ordering over the (cross-source) merged results. |
|
Confirm/annotate that each result supports its use (identity by default). |
|
Loop bounds: the safety net under the (harder) sufficiency decision. |
|
Bound the pool the evaluator sees to at most |
|
Cross-run memory: recall hits for a purpose; take |
|
|
|
One piece of evidence a run committed to, for one purpose. |
|
What one round of the loop decided: the run-log's unit (raglab#6). |
|
A sink for the loop's |
|
One ReAct-style loop, sequential sub-tasks (ir_09 §7 — the cheap default). |
- class raglab.Budget(max_rounds=3, max_sources_per_task=4, max_results_per_task=50)[source]#
Bases:
objectLoop bounds: the safety net under the (harder) sufficiency decision.
- class raglab.Citer(*args, **kwargs)[source]#
Bases:
ProtocolConfirm/annotate that each result supports its use (identity by default).
- class raglab.Evaluator(*args, **kwargs)[source]#
Bases:
ProtocolJudge relevance + sufficiency; optionally emit a refinement (back-edge).
- class raglab.ExtractionUnit(purpose, hit, recorded_at, importance=1.0, confidence=None, level='raw', supersedes=None)[source]#
Bases:
objectOne piece of evidence a run committed to, for one purpose.
hitis theSearchHit.to_dict()of the kept hit: provenance (source,artifact_id) and its raw magnitude, never a fused score.levelis the consolidation level ("raw"until CONSOLIDATE exists);supersedesnames the artifact id a later unit replaces (for SUPERSEDE).
- class raglab.Formulator(*args, **kwargs)[source]#
Bases:
ProtocolTurn a sub-task + one source into concrete low-level queries.
- class raglab.GradedLabel(level, is_about, is_supported, is_useful, evidence_quote='', facet=None)[source]#
Bases:
objectA graded verdict on one candidate (raglab#8): a level, three axes, the evidence.
levelis one of the evaluator’s ordered levels (best first). The axes are Self-RAG’s:is_about(topical, ISREL),is_supported(the content actually establishes it, not a lexical mention: ISSUP) andis_useful(ISUSE).evidence_quoteis a verbatim span of the candidate’s content backing the level;facetnames the sub-goal it was judged against.
- class raglab.Judgement(relevant, sufficient, refinement=None, graded=dict())[source]#
Bases:
objectAn evaluator’s verdict over a round’s results.
relevantis the kept subset;sufficientsays whether to stop; a non-Nonerefinementis the back-edge — the next sub-task to re-query with. The pass-through default returnssufficient=Trueand no refinement (no loop).gradedis optional and additive: a graded evaluator maps each judgedartifact_idto itsGradedLabel; binary evaluators leave it empty.
- class raglab.LowLevelQuery(source, query, params=dict())[source]#
Bases:
objectOne concrete query against one source.
queryis the text handed to the source’sRetriever;paramsare per-call retriever overrides (e.g.mode/filter/kfor an ir corpus). A formulator turns aSubTaskinto these.
- class raglab.Memory(*args, **kwargs)[source]#
Bases:
ProtocolCross-run memory: recall hits for a purpose; take
RoundRecords.Opt-in (
SingleContextAgent.memorydefaults toNone). Before sweeping a sub-task, the agent offers the recalled hits to the evaluator; if they are sufficient, it does not sweep.raglab.memory.PurposeStoreis one.
- class raglab.Planner(*args, **kwargs)[source]#
Bases:
ProtocolDecompose a query into sub-tasks and select sources for each.
- class raglab.PoolCap(*args, **kwargs)[source]#
Bases:
ProtocolBound the pool the evaluator sees to at most
limitresults.A governor decision (which hits survive the budget), injected like every other role so a strategy can be swapped without touching the loop. It must return hits unchanged — never re-scored — because the pool keeps raw per-source magnitudes until the fan-in reranker.
- class raglab.PurposeStore(backend=dict(), embedder=None, write_strategy=<function upsert_write>, read_strategy=<function make_relevance_recency_reader.<locals>.read>, min_relevance=0.8, clock=<built-in function time>)[source]#
Bases:
MutableMappingMutableMapping[purpose, list[ExtractionUnit]]over an injectedbackend.backendmapspurpose_id()to a JSON-clean record{"purpose", "embedding", "units"}: anyMutableMapping(a dict, a dol store of JSON files, …).store[purpose]recalls from every related purpose (the same one, or one whose embedding is at leastmin_relevancecosine-similar);store[purpose] = unitsreplaces that purpose’s units. Calling the store with aRoundRecordjournals what the round kept.- clock()#
time() -> floating-point number
Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
- recall(purpose)[source]#
The units of every purpose related to
purpose, ranked byread_strategy.- Return type:
- recall_hits(purpose)[source]#
recall()asSearchHits, ready to seed the agent’s pool.- Return type:
list[SearchHit]
- write_strategy(new)#
ADD new artifacts; UPDATE (replace with the newer unit) those already kept.
- Return type:
- class raglab.Query(text, constraints=dict())[source]#
Bases:
objectA user intent: free text plus optional structured constraints.
- class raglab.Reranker(*args, **kwargs)[source]#
Bases:
ProtocolProduce the final ordering over the (cross-source) merged results.
- raglab.Result#
alias of
SearchHit
- class raglab.RoundRecord(purpose, round, goal, sources, sufficient, refinement, committed, graded=dict())[source]#
Bases:
objectWhat one round of the loop decided: the run-log’s unit (raglab#6).
Written at the evaluator’s judgement point, it is the single record shape that per-run observability (the run-log) and cross-run memory (a purpose store) both consume.
purposeis the sub-task’s original goal;goalis what this round actually searched (a refinement, from round 1 on).committedholds the hits the evaluator kept, with their raw per-source magnitudes: the pool never carries fused scores, so neither does the record. Round-1is the recall round of an agent with amemory: its pool was recalled, not swept.
- class raglab.RunLog(*args, **kwargs)[source]#
Bases:
ProtocolA sink for the loop’s
RoundRecords, one call per round.Opt-in (the agent’s
run_logdefaults toNone: nothing is recorded).list.appendis one:log = []; make_search_agent(sources, run_log=log.append).
- class raglab.SingleContextAgent(sources, planner=<function single_subtask_planner>, formulator=<function identity_formulator>, evaluator=<function passthrough_evaluator>, reranker=<function rrf_reranker>, citer=<function identity_citer>, budget=Budget(), pool_cap=<function rank_fair_cap>, run_log=None, memory=None)[source]#
Bases:
objectOne ReAct-style loop, sequential sub-tasks (ir_09 §7 — the cheap default).
The loop is fixed; every decision is an injected role. Promotion to a multi-agent orchestrator (ir_09 §7) swaps this class while keeping the same role contracts. The back-edge is the single line
current = judged.refinementin_run_task()— that is what makes this an agent.- citer()#
No-op citer (verification needs a generated claim — that lives in srag).
- Return type:
Sequence[SearchHit]
- evaluator(results)#
Pass-through critic: keep everything, declare sufficient, never re-query.
- Return type:
- formulator(source)#
Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).
- Return type:
- planner(sources)#
Trivial planner: one sub-task over all registered sources, no decomposition.
- pool_cap(limit)#
Keep at most
limithits, taking the best of each source in turn (the default).Groups the pool by
hit.source(in first-arrival order; untagged hits are one group), collapses each group to one hit per artifact (its best surface, asir.base.best_per_artifact()does), orders the group best-first by its own raw score – sound, since one source is one score scale – and deals hits round-robin across the groups. So a late source’s strong hits are never cut before the evaluator sees them, a duplicate never takes a slot, and no score ever crosses a source boundary or is rewritten (unlike pre-ranking with the RRF reranker, whose fused ordinal scores must never re-enter the pool). The output is in that dealt order whatever the pool’s size. A missing or NaN score sorts last in its source.- Return type:
list[SearchHit]
- reranker()#
Cross-source merge (the default fan-in): fuse by rank, never by raw score.
Groups the accumulated pool by
hit.sourceand delegates the merge toir.fuse_hits()(ir is the SSOT for hit operations): within each source raw scores order and dedup that source’s hits — one scale, sound — and across sources only ranks interact (Reciprocal Rank Fusion), so heterogeneous embedders / modes can never mis-order the merge, and collidingartifact_ids from different sources stay distinct results (identity is(source, artifact_id)).A single-source pool (or an untagged one — hits with no
source) keeps its raw scores and exactlyscore_reranker()’s ordering; fused, rank-derived scores only appear when there is genuinely something to fuse. Each fused hit keeps its pre-fusion magnitude asmetadata["source_score"]. For per-source weights, anotherrrf_k, or opt-in cross-source duplicate merging, usemake_rrf_reranker().- Return type:
Sequence[SearchHit]
- class raglab.SubTask(goal, sources)[source]#
Bases:
objectA planner’s unit of work: a sub-goal bound to a set of registered sources.
- raglab.apply_gates(proposed, content, *, levels=('core', 'strong', 'uses-tools', 'tangential', 'none'), unsupported_cap='tangential', require_evidence_quote=True, calibration_offset=None, min_quote_chars=8)[source]#
The level a judge’s proposal is allowed, after calibration and the gates.
The quote must be at least
min_quote_charslong and found incontent, ignoring case and runs of whitespace (judges re-case and re-wrap what they copy).calibration_offsetis in levels, rounded half up, so a shift is the same at every level.>>> label = GradedLabel('core', True, False, True, 'a DAG of tasks') >>> apply_gates(label, 'Runs a DAG of tasks asynchronously.').level 'tangential' >>> ok = GradedLabel('core', True, True, True, 'graph library') >>> apply_gates(ok, 'A graph library.').level, apply_gates(ok, 'Nothing here.').level ('core', 'tangential') >>> apply_gates(ok, 'A graph library.', calibration_offset=1.4).level 'strong'
- Return type:
- raglab.arrival_order_cap(results, limit)[source]#
Keep the first
limithits in arrival order (source order x query order).The pre-governor behaviour: a late source’s strong hits can be cut before the evaluator sees them. Kept as an explicit opt-in (
pool_cap=arrival_order_cap).- Return type:
list[SearchHit]
- raglab.identity_citer(results)[source]#
No-op citer (verification needs a generated claim — that lives in srag).
- Return type:
Sequence[SearchHit]
- raglab.identity_formulator(task, source)[source]#
Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).
- Return type:
- raglab.ir_sources(*names, **search_defaults)[source]#
A source registry
{name: Retriever}backed by namedircorpora.Each name is bound to
ir.as_retriever(name, **search_defaults), opened eagerly. For the lazy live view over everything registered (a corpus opens only when its key is first used), useir.retrievers()instead — the agent accepts either, or anyMapping[name, Retriever].search_defaults(e.g.mode="hybrid") apply to every source.
- raglab.make_graded_rubric_evaluator(*, levels=('core', 'strong', 'uses-tools', 'tangential', 'none'), rubric="- core: the candidate's main purpose IS the topic.\n- strong: a substantial, central part of the candidate is about the topic.\n- uses-tools: the candidate builds on tools or libraries of the topic (its dependencies or imports establish it) without being about it.\n- tangential: the topic is mentioned, or its vocabulary appears, but the content does not establish it.\n- none: unrelated.\n", judge=None, disclose_level='body', disclose_kwargs=None, require_evidence_quote=True, unsupported_cap='tangential', calibration_offset=None, min_quote_chars=8, relevant_level='uses-tools', refine=None, rng=None, prompt='Goal: {goal}\n\nRubric (levels, in no particular order):\n{levels}\n\nDefinitions:\n{rubric}\n\nCandidate {artifact_id}:\n---\n{content}\n---\n\nAnswer with one JSON object and nothing else, with keys:\n"is_about" (bool: is the candidate topically about the goal?),\n"is_supported" (bool: does its content - code, dependencies, imports, full text - actually establish it, beyond a mention of the words?),\n"is_useful" (bool: would it help someone pursuing the goal?),\n"evidence_quote" (a short span copied VERBATIM from the candidate\'s content that supports your level),\n"level" (one of the rubric\'s levels).\n', max_content_chars=4000, **prompt_function_kwargs)[source]#
An
Evaluatorthat grades every candidate on a rubric.- Parameters:
rubric (
str) – what each level means, shown to the judge.judge (
Callable[...,Mapping[str,Any] |str] |None) – an injectable graded judge (a test double, or your own router); built lazily onoawhen omitted.disclose_level (
str) – what the judge reads — each candidate’s content throughir.disclose()at that level (store=/loader=go indisclose_kwargs); a candidate with nothing to load is judged on its snippet.disclose_kwargs (
Mapping[str,Any] |None) – what the judge reads — each candidate’s content throughir.disclose()at that level (store=/loader=go indisclose_kwargs); a candidate with nothing to load is judged on its snippet.require_evidence_quote (
bool) – min_quote_chars: the gates, seeapply_gates().unsupported_cap (
str) – min_quote_chars: the gates, seeapply_gates().calibration_offset (
float|None) – min_quote_chars: the gates, seeapply_gates().
- Return type:
:param : min_quote_chars: the gates, see
apply_gates(). :type relevant_level:str:param relevant_level: the lowest level kept inJudgement.relevant. :type refine:Callable[[SubTask,Mapping[str,GradedLabel]],SubTask|None] |None:param refine: the back-edge policy(task, graded) -> SubTask | None; bydefault none, so the loop stops after one round.
- Parameters:
rng (
Random|None) – the source of the per-call level order (seed it for reproducible prompts).- Return type:
Every candidate is judged once per goal: one judge call per (source, artifact) the first time it appears in a pool for that goal, its label remembered for later rounds, so a kept hit is not re-judged (nor lost to a later failing call).
Judgement.gradedis keyed byartifact_id; an id found in several sources carries its best label. A reply that does not parse leaves the candidate ungraded (logged); when every judge call of a round raises, the first error is re-raised rather than returning an empty, “sufficient” round. This evaluator is for labelling a pool, not for cheap filtering.
- raglab.make_llm_evaluator(*, judge=None, select_strategy='conservative', select_kwargs=None, prerank=None, prompt='A search agent is pursuing this goal:\n\n{goal}\n\nA calibrated selector reviewed the retrieved candidates and committed to the\nresults below (it abstained if this list is empty):\n\n{results}\n\nDecide whether these results are SUFFICIENT to satisfy the goal.\n- If they are, reply with exactly: SUFFICIENT\n- If they are not, reply with: INSUFFICIENT\n then, on the next line, a single improved search query that would retrieve what\n is still missing. Keep it a terse search phrase — no prose, no numbering.\n', max_result_chars=500, **prompt_function_kwargs)[source]#
An LLM-backed raglab
Evaluator(turns on the back-edge).Relevance is ir’s: each round the accumulated results are passed through
ir.select()and the committed subset becomes theJudgement.relevant(so the LLM stays in its lane — LLM relevance is known-fragile, ir_01 §3). Sufficiency is the LLM’s: it reads the committed subset (informed by ir’s model-freesufficienthint via abstention) and decides whether the goal is satisfied. When it is not, the judge’s improved query becomes arefinementSubTaskover the same sources — the back-edge.- Parameters:
judge (
Optional[Callable[...,tuple[bool,str|None] |str]]) – an injectable(goal, results) -> (sufficient, refinement)callable (a test double, or your own router); a raw text reply is also accepted and parsed. When omitted it is built lazily onoa.select_strategy (
str) – ir selection strategy for the relevance decision (default"conservative"— distractor-robust).select_kwargs (
Mapping[str,Any] |None) – extra args forwarded toir.select()(e.g.max_k,rel).min_scoreis allowed only while the round’s pool keeps raw scores (single-source, orprerank=score_reranker): an absolute floor is per-(corpus, mode, embedder), so a round whose pool was rank-fused across sources raises rather than silently mass-abstaining on ordinal RRF scores.prerank (
Reranker|None) – the per-round merge that puts the accumulated pool best-first (and deduped) beforeir.select. Defaults torrf_reranker()— a round’s pool can already mix sources (a SubTask spans several), so the same rank-based, scale-safe merge as the fan-in applies; single-source rounds keep raw scores. Injectscore_reranker()for sources known to share one score scale.max_result_chars (
int) – per-result text truncation in the judge prompt.
- Return type:
Safe fallback: any judge error returns
refinement=None— the control loop’s break condition — so a failing judge can never fabricate an endless loop. Sufficiency without a refinement query is likewise treated as a stop.
- raglab.make_llm_formulator(*, formulate=None, params=None, **make_kwargs)[source]#
An LLM-backed raglab
Formulator.Adapts an ir-style query formulator (
str -> str | [str]) to the role contract(SubTask, source) -> [LowLevelQuery]: the sub-goal text is rewritten / expanded into one or more search queries, each wrapped as aLowLevelQueryagainstsource.- Parameters:
formulate (
Optional[Callable[[str],str|Sequence[str]]]) – an injectable ir-style formulator (a test double, or one you built). When omitted it is built once viair.make_llm_formulator()(**make_kwargsare forwarded — e.g.n,prompt,rewriter); that call is offline (oais imported lazily only when the formulator is invoked), soimport raglabstays offline.params (
Mapping[str,Any] |None) – per-call retriever overrides (e.g.{"mode": "hybrid", "k": 5}) attached to every emittedLowLevelQuery.
- Return type:
The boundary: this returns queries, never SubTasks. ir’s formulator already falls back to identity on any failure, so the emitted list is never empty — a formulator must never make retrieval worse than the raw sub-goal.
- raglab.make_rrf_reranker(*, rrf_k=60, weights=None, identity=None)[source]#
A parametrized
rrf_reranker()(per-source trust weights,rrf_k).- Parameters:
rrf_k (
int) – the RRF rank constant (standard default 60).weights (
Mapping[str,float] |None) – optional per-source trust dial, by source name (default 1.0 each) — biases the merge without ever comparing raw scores.identity (
Union[Callable[[SearchHit],Any],str,None]) – opt-in cross-source duplicate detection (e.g."pointer") — seeir.retrieve.Identity. Default: never merge across sources.
- Return type:
- raglab.make_search_agent(sources, *, planner=None, formulator=None, evaluator=None, reranker=None, citer=None, budget=None, pool_cap=None, run_log=None, memory=None)[source]#
Build a
SingleContextAgentover sources with smart defaults.sourcesis aMapping[name, Retriever]— e.g.{"skills": ir.as_retriever("skills")},ir_sources(), or the lazyir.retrievers()view. Every role defaults to its no-LLM thin-slice implementation, somake_search_agent(sources)("query")just works; inject an LLMformulator/evaluatorto turn on rewriting and the back-edge. Pass arun_log(any callable taking aRoundRecord, e.g.list.append) to record what each round decided, and amemory(e.g. araglab.memory.PurposeStore) to journal what runs keep and reuse it.A custom
Retrievermust returnir.SearchHitinstances (theResultalias): the loop stamps provenance (hit.source) on its output, so duck-typed hit objects raise at the tagging step.- Return type:
- raglab.passthrough_evaluator(task, results)[source]#
Pass-through critic: keep everything, declare sufficient, never re-query.
- Return type:
- raglab.rank_fair_cap(results, limit)[source]#
Keep at most
limithits, taking the best of each source in turn (the default).Groups the pool by
hit.source(in first-arrival order; untagged hits are one group), collapses each group to one hit per artifact (its best surface, asir.base.best_per_artifact()does), orders the group best-first by its own raw score – sound, since one source is one score scale – and deals hits round-robin across the groups. So a late source’s strong hits are never cut before the evaluator sees them, a duplicate never takes a slot, and no score ever crosses a source boundary or is rewritten (unlike pre-ranking with the RRF reranker, whose fused ordinal scores must never re-enter the pool). The output is in that dealt order whatever the pool’s size. A missing or NaN score sorts last in its source.- Return type:
list[SearchHit]
- raglab.rrf_reranker(results)[source]#
Cross-source merge (the default fan-in): fuse by rank, never by raw score.
Groups the accumulated pool by
hit.sourceand delegates the merge toir.fuse_hits()(ir is the SSOT for hit operations): within each source raw scores order and dedup that source’s hits — one scale, sound — and across sources only ranks interact (Reciprocal Rank Fusion), so heterogeneous embedders / modes can never mis-order the merge, and collidingartifact_ids from different sources stay distinct results (identity is(source, artifact_id)).A single-source pool (or an untagged one — hits with no
source) keeps its raw scores and exactlyscore_reranker()’s ordering; fused, rank-derived scores only appear when there is genuinely something to fuse. Each fused hit keeps its pre-fusion magnitude asmetadata["source_score"]. For per-source weights, anotherrrf_k, or opt-in cross-source duplicate merging, usemake_rrf_reranker().- Return type:
Sequence[SearchHit]
- raglab.score_reranker(results)[source]#
Magnitude merge: one surface per artifact, ordered by descending raw score.
Delegates to
ir.base.best_per_artifact()(ir is the SSOT for hit operations): an artifact retrieved by several queries / rounds — common once the back-edge re-queries — survives once, at its highest score. Identity is(source, artifact_id), so two sources’ same-id artifacts never collapse.A plain score sort compares raw scores across sources, which is only sound when every source shares one score scale (same embedder + mode) — it is the explicit homogeneous-sources opt-in. The default fan-in is
rrf_reranker(), which never compares raw scores across sources.- Return type:
Sequence[SearchHit]
- raglab.single_subtask_planner(query, sources)[source]#
Trivial planner: one sub-task over all registered sources, no decomposition.
Modules
The Composable Search Agent — roles wired by a control loop (ir_09). |
|
Cross-run benchmark: the instrument for purpose-indexed memory (raglab#15, item 4). |
|
Graded rubric judging — every candidate gets a level, three axes and evidence (raglab#8). |
|
LLM-backed roles — the Formulator and Evaluator (ir_09 §8 steps 1 & 3). |
|
Purpose-indexed memory: what past runs found, kept per purpose (raglab#6, stage 0). |
|
Recipes: whole workflows composed from raglab's roles, ready to call. |