raglab.agent#
The Composable Search Agent — roles wired by a control loop (ir_09).
raglab is the **orchestration layer on top of ir`** (the retrieval substrate).
This module is the v1 foundation: the immutable value types, the role *Protocols*
(open-closed strategy seams), and a `SingleContextAgent whose fixed control loop
is fully parametrized by injected roles. Concrete tools live at the leaves — an
ir corpus becomes one Retriever via ir.as_retriever().
The agent is multi-source by default: the loop stamps each hit’s
provenance (hit.source), and the fan-in Reranker —
rrf_reranker() — merges heterogeneous sources by rank, never by raw
score (scores from different corpora / embedders / modes are incommensurable;
ir_07/ir_08). Raw magnitudes order and dedup hits within one source, and the
loop’s pool always carries them; fused (ordinal) scores appear only at the
fan-in boundary.
The shape follows ir_09 §3/§6: a small set of named roles —
Planner / Formulator / Retriever / Evaluator / Reranker / Citer — and a loop
whose defining feature is the back-edge (evaluator → reformulate) that makes
it an agent rather than a DAG. v1 ships the loop with smart defaults (a trivial
planner + a pass-through evaluator), so the thin slice runs end-to-end with no
LLM; turning on the back-edge is just injecting an LLM Evaluator that returns
a refinement (ir_09 §8 step 3).
Progressive disclosure: make_search_agent() gives sensible defaults for
every role, so the simple path is make_search_agent(sources)("query").
Dependency direction is one-way: raglab imports ir; ir never imports
raglab. The Result type and the Retriever contract are ir’s (SSOT).
Module Attributes
A retrieved item — ir's |
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). |
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. |
A retrieved item — ir's |
|
|
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 |
|
One ReAct-style loop, sequential sub-tasks (ir_09 §7 — the cheap default). |
- class raglab.agent.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.agent.Citer(*args, **kwargs)[source]#
Bases:
ProtocolConfirm/annotate that each result supports its use (identity by default).
- class raglab.agent.Evaluator(*args, **kwargs)[source]#
Bases:
ProtocolJudge relevance + sufficiency; optionally emit a refinement (back-edge).
- class raglab.agent.Formulator(*args, **kwargs)[source]#
Bases:
ProtocolTurn a sub-task + one source into concrete low-level queries.
- class raglab.agent.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.agent.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.agent.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.agent.Planner(*args, **kwargs)[source]#
Bases:
ProtocolDecompose a query into sub-tasks and select sources for each.
- class raglab.agent.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.agent.Query(text, constraints=dict())[source]#
Bases:
objectA user intent: free text plus optional structured constraints.
- class raglab.agent.Reranker(*args, **kwargs)[source]#
Bases:
ProtocolProduce the final ordering over the (cross-source) merged results.
- raglab.agent.Result#
A retrieved item — ir’s
SearchHit(ir_09’sResult): a pointer + snippet (text) with ascoreandmetadata.
- class raglab.agent.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.agent.SubTask(goal, sources)[source]#
Bases:
objectA planner’s unit of work: a sub-goal bound to a set of registered sources.
- raglab.agent.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.agent.identity_citer(results)[source]#
No-op citer (verification needs a generated claim — that lives in srag).
- Return type:
Sequence[SearchHit]
- raglab.agent.identity_formulator(task, source)[source]#
Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).
- Return type:
- raglab.agent.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.agent.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.agent.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.agent.passthrough_evaluator(task, results)[source]#
Pass-through critic: keep everything, declare sufficient, never re-query.
- Return type:
- raglab.agent.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.agent.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.agent.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]