> built 2026-11-23 07:55 UTC from 11b7e34 (main) · raglab 0.2.13. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# raglab

The **agentic-search / RAG orchestration layer on top of [`ir`](https://github.com/i2mint/ir)** (the retrieval substrate).

`raglab` turns a retrieval substrate into a **Composable Search Agent**: a small set of injected **roles** — Planner, Formulator, Retriever, Evaluator, Reranker, Citer — wired by a control loop. The loop’s defining feature is the **back-edge** (*evaluator → reformulate*): when results aren’t good enough, the agent rewrites the query and searches again. That back-edge is what makes it an *agent* rather than a fixed pipeline (DAG).

```bash
pip install raglab
```

> **Fresh start (v0.2.0+).** This repo took over the `raglab` PyPI name. The
> earlier backend (PyPI 0.0.x–0.1.x) was renamed and now lives at
> [addaix/raglab_bak](https://github.com/addaix/raglab_bak) (PyPI:
> [`raglab_bak`](https://pypi.org/project/raglab_bak/)). The API below is the new
> agent layer.

---

## Quick start

The default agent runs **fully offline** — no LLM, no network. Point it at one or more `ir` corpora and call it like a function; you get back ranked [`ir.SearchHit`](https://github.com/i2mint/ir)s.

<!-- wads-docs: skip needs registered ir corpora and an LLM key -->
```python
import ir
import raglab

# Register named 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")  # -> list[ir.SearchHit], ranked
```

A self-contained, runnable example (build a tiny corpus, search it):

```python
import ir
from ir.store import CorpusStore
import raglab

docs = {
    "deploy": "deploy the app to the server with systemd units",
    "embed": "embed text with a model and cache the vectors",
    "search": "vector similarity search with metadata filters",
}
corpus = ir.build(
    ir.CorpusSource.from_mapping(docs, name="t", strategy=ir.WholeText()),
    store=CorpusStore.memory(),
    embedder="light",  # numpy-only, no model download
)

agent = raglab.make_search_agent({"t": ir.as_retriever(corpus, k=3)})
results = agent("deploy the app to the server")
results[0].artifact_id  # -> "deploy"
```

`sources` is any `Mapping[name, Retriever]`. Build it with [`raglab.ir_sources(*names, **defaults)`](), with `ir.retrievers()` (a lazy live view over everything ir has registered), or by hand: `{"skills": ir.as_retriever("skills")}`.

---

## The mental model

```default
           ┌─────────── back-edge (re-query when insufficient) ──────────┐
           ▼                                                             │
  Query → Planner → [SubTask] → Formulator → [LowLevelQuery] → Retriever(s)
                                                                   │
                                          accumulated hits ◄───────┘
                                                   │
                                            Evaluator ──► Judgement(relevant, sufficient, refinement)
                                                   │              └─ refinement ⟲ back-edge
                                          (sufficient / budget hit)
                                                   ▼
                                       Reranker (fan-in) → Citer → ranked results
```

The **loop is fixed**; every *decision* in it is an injected **role** (a plain callable satisfying a `Protocol`). v1 ships every role with a sensible default, so the simple path — `make_search_agent(sources)("query")` — just works. You turn capabilities on by swapping in richer roles.

| Role           | Decides                                   | Default (no-LLM)                                 | Inject an LLM version to…                           |
|----------------|-------------------------------------------|--------------------------------------------------|-----------------------------------------------------|
| **Planner**    | decompose query → sub-tasks, pick sources | `single_subtask_planner` (one task, all sources) | split a query into parallel sub-goals               |
| **Formulator** | sub-task → concrete search queries        | `identity_formulator` (verbatim)                 | rewrite / expand / HyDE (`make_llm_formulator`)     |
| **Retriever**  | run one query against one source          | *injected at the leaf* (`ir.as_retriever`)       | add web / SQL / graph backends                      |
| **Evaluator**  | relevance + sufficiency + **back-edge**   | `passthrough_evaluator` (keep all, stop)         | judge sufficiency & re-query (`make_llm_evaluator`) |
| **Reranker**   | final cross-source ordering (fan-in)      | `rrf_reranker` (rank fusion)                     | weight sources, change fusion                       |
| **Citer**      | confirm each result supports its use      | `identity_citer` (no-op)                         | *(generation/verification lives in `srag`)*         |

**`Budget`** bounds the loop (`max_rounds`, `max_sources_per_task`, `max_results_per_task`) — the safety net under the (harder) sufficiency decision.

---

## Turning on query understanding and the back-edge

Inject the two LLM roles to upgrade the offline slice into a real agent. Both build their model lazily on [`oa`](https://github.com/thorwhalen/oa) **only when invoked**, so `import raglab` stays offline.

<!-- wads-docs: skip needs registered ir corpora and an LLM key -->
```python
import raglab

agent = raglab.make_search_agent(
    sources,
    formulator=raglab.make_llm_formulator(),  # rewrite/expand the query (HyDE)
    evaluator=raglab.make_llm_evaluator(),  # sufficiency + the back-edge
)
results = agent("how do I deploy the app")
```

How the Evaluator splits the decision (a load-bearing boundary):

- **Relevance is `ir`’s.** Each round the accumulated hits pass through `ir.select` (default strategy `"conservative"` — distractor-robust); the committed subset becomes `Judgement.relevant`. LLM relevance scoring is known-fragile, so the LLM stays out of it.
- **Sufficiency is the LLM’s.** Informed by ir’s model-free `Selection.sufficient` hint, the judge decides whether the committed subset actually satisfies the goal. If not, it emits an improved query — a `refinement` `SubTask` over the same sources. **That refinement is the back-edge.**

Both builders accept an injectable double (`formulate=` / `judge=`) for deterministic tests, and both **fail safe**: a formulator error falls back to the raw query (never makes retrieval worse); a judge error returns no refinement (the loop’s break condition — a failing judge can never spin forever).

---

## Multi-source search and the fan-in reranker

The agent is **multi-source by default**. The loop stamps each hit’s provenance (`hit.source`), and the default fan-in reranker, `rrf_reranker`, merges heterogeneous sources **by rank, never by raw score**.

This matters because scores from different corpora / embedders / retrieval modes are *incommensurable* — a cosine score (~0–1) and a BM25 score (~0–50) cannot be compared directly. Reciprocal Rank Fusion (RRF) sidesteps this: within one source raw scores order and dedup that source’s hits (one scale, sound); across sources only **ranks** interact.

```python
# Two sources on different score scales:
#   rrf_reranker (default): interleaves both sources' rank-1 hits first.
#   score_reranker (opt-in): a raw-score sort — only sound when every source
#                            shares one scale (same embedder + mode).
agent = raglab.make_search_agent(sources, reranker=raglab.score_reranker)
```

Colliding `artifact_id`s from different sources stay distinct (identity is `(source, artifact_id)`). Each fused hit keeps its pre-fusion magnitude in `metadata["source_score"]`. For per-source trust weights or a custom `rrf_k`:

```python
reranker = raglab.make_rrf_reranker(weights={"skills": 2.0, "web": 0.5}, rrf_k=60)
agent = raglab.make_search_agent(sources, reranker=reranker)
```

---

## Customizing roles

Every role is just a callable matching a `Protocol`, so you can inject your own:

```python
from raglab import SubTask, LowLevelQuery, Judgement, make_search_agent


def my_planner(query, sources):
    # split into two sub-goals over all sources
    return [
        SubTask(goal=g, sources=tuple(sources))
        for g in (query.text, query.text + " examples")
    ]


def my_formulator(task, source):
    return [LowLevelQuery(source=source, query=task.goal, params={"k": 10})]


agent = make_search_agent(sources, planner=my_planner, formulator=my_formulator)
```

A **custom Retriever** is any `callable(query, **params) -> Sequence[ir.SearchHit]`. It must return `ir.SearchHit` instances (the `Result` alias) — the loop stamps provenance on its output, so duck-typed hit objects raise at the tagging step. ir-backed retrievers self-attribute their corpus name.

---

## API at a glance

Everything is exported from the top-level `raglab` namespace.

**Value types** (frozen dataclasses, plain data):

| Type            | Fields                                                              |
|-----------------|---------------------------------------------------------------------|
| `Query`         | `text`, `constraints`                                               |
| `SubTask`       | `goal`, `sources: tuple[str, ...]`                                  |
| `LowLevelQuery` | `source`, `query`, `params` (per-call retriever overrides)          |
| `Judgement`     | `relevant`, `sufficient`, `refinement: SubTask | None`              |
| `Budget`        | `max_rounds=3`, `max_sources_per_task=4`, `max_results_per_task=50` |
| `Result`        | alias for `ir.SearchHit`                                            |

**Role Protocols** (the open-closed strategy seams): `Planner`, `Formulator`, `Retriever` (re-exported from `ir`), `Evaluator`, `Reranker`, `Citer`.

**Orchestrator & builders:**

| Name                                                                                     | What it does                                                            |
|------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|
| `make_search_agent(sources, *, planner, formulator, evaluator, reranker, citer, budget)` | Build a `SingleContextAgent` with smart defaults for every role.        |
| `SingleContextAgent`                                                                     | The orchestrator dataclass: one ReAct-style loop, sequential sub-tasks. |
| <a name="sources"></a>`ir_sources(*names, **search_defaults)`                            | A `{name: Retriever}` registry backed by named ir corpora.              |

**Default roles (the no-LLM thin slice):** `single_subtask_planner`, `identity_formulator`, `passthrough_evaluator`, `score_reranker`, `rrf_reranker`, `make_rrf_reranker(*, rrf_k, weights, identity)`, `identity_citer`.

**LLM roles:** `make_llm_formulator(*, formulate=None, params=None, **make_kwargs)`, `make_llm_evaluator(*, judge=None, select_strategy="conservative", select_kwargs=None, prerank=None, prompt=EVALUATION_PROMPT, ...)`, and the default `EVALUATION_PROMPT` string.

---

## Architecture & boundaries

`raglab` **owns the agent**: the value types, the role Protocols, the control loop with the back-edge, the budget governor, the source registry, and the cross-source fan-in.

It **consumes from `ir`** (and does not reimplement): `ir.as_retriever` (corpus → Retriever), `ir.retrievers()` (the live registry view), `ir.make_llm_formulator` (the query rewriter), `ir.select` + its `Selection.sufficient` signal (relevance

+ the sufficiency hint), and `ir.fuse_hits` (RRF). The `Result` type and the `Retriever` contract are **ir’s** (single source of truth).

**Dependency direction is one-way:** `raglab` imports `ir` (and `oa` for the LLM roles, lazily); **`ir` never imports `raglab`.** Keeping `oa` opt-in is what lets `import raglab` stay offline.

What lives **elsewhere:** answer synthesis / generation and the Citer/Verifier (which needs a *generated claim* to verify) belong in the RAG/generation layer (`srag`), not the search agent. raglab’s deliverable is **pointers + extractions**, not an essay.

Where it sits in the ecosystem: **`raglab` → `ir` → {`ef`, `vd`}** — `ir` is the retrieval substrate, `ef` owns embedders/segmenters, `vd` is the vector-store facade.

---

## Status & roadmap

Shipped at **0.2.4**: the `SingleContextAgent` control loop with the back-edge, all six role Protocols, the no-LLM defaults, the LLM Formulator + Evaluator, and the RRF cross-source fan-in reranker. The roles, value types, and loop are stable; richer strategies are added behind the same contracts.

The living roadmap is **[issue #2](https://github.com/addaix/raglab/issues/2)** (Composable Search Agent on ir, the *ir_09* reference design). Not yet built:

- **Budget governor refinements** — the per-task results cap currently truncates in arrival order rather than by rank ([#5](https://github.com/addaix/raglab/issues/5)); termination as a separately injected policy is planned.
- **PurposeStore** — persistent, purpose-indexed memory overlay ([#6](https://github.com/addaix/raglab/issues/6)). There is no cross-run memory today.
- **`MultiAgentAgent`** — one subagent per sub-task/source (breadth-first, ~15× cost); promotion swaps only the orchestrator, keeping role contracts identical.

---

## House style

Functional over OOP; SOLID when OOP; facades, SSOT, dependency injection; progressive disclosure; keyword-only args beyond the third positional; `collections.abc` + frozen `dataclass`es; `Protocol`s for the role seams. Tests are hermetic (fake retrievers, injected LLM doubles) with a few end-to-end checks over a real `ir` corpus using the light, numpy-only embedder.

<p class="epythet-aggregates">This documentation as a single file: <a href="raglab.md">raglab.md</a> (Markdown, for agents).</p>


# _autosummary/raglab.agent.html.md

# 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`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker) —
[`rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.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()`](_autosummary/raglab.agent.html.md#raglab.agent.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

| [`Result`](_autosummary/raglab.agent.html.md#raglab.agent.Result)   | A retrieved item — ir's `SearchHit` (ir_09's `Result`): a *pointer + snippet* (`text`) with a `score` and `metadata`.   |
|-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|

### Functions

| [`rank_fair_cap`](_autosummary/raglab.agent.html.md#raglab.agent.rank_fair_cap)(results, limit)                     | Keep at most `limit` hits, taking the best of each source in turn (the default).                                    |
|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| [`arrival_order_cap`](_autosummary/raglab.agent.html.md#raglab.agent.arrival_order_cap)(results, limit)                 | Keep the first `limit` hits in arrival order (source order x query order).                                          |
| [`make_search_agent`](_autosummary/raglab.agent.html.md#raglab.agent.make_search_agent)(sources, \*[, planner, ...])    | Build a [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent) over *sources* with smart defaults.     |
| [`ir_sources`](_autosummary/raglab.agent.html.md#raglab.agent.ir_sources)(\*names, \*\*search_defaults)          | A source registry `{name: Retriever}` backed by named `ir` corpora.                                                 |
| [`single_subtask_planner`](_autosummary/raglab.agent.html.md#raglab.agent.single_subtask_planner)(query, sources)            | Trivial planner: one sub-task over *all* registered sources, no decomposition.                                      |
| [`identity_formulator`](_autosummary/raglab.agent.html.md#raglab.agent.identity_formulator)(task, source)                 | Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).                                          |
| [`passthrough_evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.passthrough_evaluator)(task, results)              | Pass-through critic: keep everything, declare sufficient, never re-query.                                           |
| [`score_reranker`](_autosummary/raglab.agent.html.md#raglab.agent.score_reranker)(results)                           | Magnitude merge: one surface per artifact, ordered by descending raw score.                                         |
| [`rrf_reranker`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_reranker)(results)                             | Cross-source merge (the default fan-in): fuse by rank, never by raw score.                                          |
| [`make_rrf_reranker`](_autosummary/raglab.agent.html.md#raglab.agent.make_rrf_reranker)(\*[, rrf_k, weights, identity]) | A parametrized [`rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_reranker) (per-source trust weights, `rrf_k`). |
| [`identity_citer`](_autosummary/raglab.agent.html.md#raglab.agent.identity_citer)(results)                           | No-op citer (verification needs a generated claim — that lives in srag).                                            |

### Classes

| [`Query`](_autosummary/raglab.agent.html.md#raglab.agent.Query)(text[, constraints])                      | A user intent: free text plus optional structured constraints.                                                        |
|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask)(goal, sources)                          | A planner's unit of work: a sub-goal bound to a set of registered sources.                                            |
| [`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)(source, query[, params])          | One concrete query against one source.                                                                                |
| [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement)(relevant, sufficient[, ...])          | An evaluator's verdict over a round's results.                                                                        |
| [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)(level, is_about, is_supported, ...) | A graded verdict on one candidate (raglab#8): a level, three axes, the evidence.                                      |
| [`Result`](_autosummary/raglab.agent.html.md#raglab.agent.Result)                                          | A retrieved item — ir's `SearchHit` (ir_09's `Result`): a *pointer + snippet* (`text`) with a `score` and `metadata`. |
| [`Planner`](_autosummary/raglab.agent.html.md#raglab.agent.Planner)(\*args, \*\*kwargs)                     | Decompose a query into sub-tasks and select sources for each.                                                         |
| [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator)(\*args, \*\*kwargs)                  | Turn a sub-task + one source into concrete low-level queries.                                                         |
| [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)(\*args, \*\*kwargs)                   | Judge relevance + sufficiency; optionally emit a refinement (back-edge).                                              |
| [`Reranker`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker)(\*args, \*\*kwargs)                    | Produce the final ordering over the (cross-source) merged results.                                                    |
| [`Citer`](_autosummary/raglab.agent.html.md#raglab.agent.Citer)(\*args, \*\*kwargs)                       | Confirm/annotate that each result supports its use (identity by default).                                             |
| [`Budget`](_autosummary/raglab.agent.html.md#raglab.agent.Budget)([max_rounds, max_sources_per_task, ...]) | Loop bounds: the safety net under the (harder) sufficiency decision.                                                  |
| [`PoolCap`](_autosummary/raglab.agent.html.md#raglab.agent.PoolCap)(\*args, \*\*kwargs)                     | Bound the pool the evaluator sees to at most `limit` results.                                                         |
| [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent)(sources[, planner, ...])     | 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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Loop bounds: the safety net under the (harder) sufficiency decision.

### *class* raglab.agent.Citer(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Confirm/annotate that each result supports its use (identity by default).

### *class* raglab.agent.Evaluator(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Judge relevance + sufficiency; optionally emit a refinement (back-edge).

### *class* raglab.agent.Formulator(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Turn 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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A graded verdict on one candidate (raglab#8): a level, three axes, the evidence.

`level` is 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) and `is_useful`
(ISUSE). `evidence_quote` is a verbatim span of the candidate’s content
backing the level; `facet` names the sub-goal it was judged against.

### *class* raglab.agent.Judgement(relevant, sufficient, refinement=None, graded=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

An evaluator’s verdict over a round’s results.

`relevant` is the kept subset; `sufficient` says whether to stop; a
non-`None` `refinement` is the **back-edge** — the next sub-task to
re-query with. The pass-through default returns `sufficient=True` and no
refinement (no loop). `graded` is optional and additive: a graded
evaluator maps each judged `artifact_id` to its [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel);
binary evaluators leave it empty.

### *class* raglab.agent.LowLevelQuery(source, query, params=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One concrete query against one source.

`query` is the text handed to the source’s `Retriever`; `params`
are per-call retriever overrides (e.g. `mode` / `filter` / `k` for an
ir corpus). A formulator turns a [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) into these.

### *class* raglab.agent.Planner(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Decompose a query into sub-tasks and select sources for each.

### *class* raglab.agent.PoolCap(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Bound the pool the evaluator sees to at most `limit` results.

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())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A user intent: free text plus optional structured constraints.

### *class* raglab.agent.Reranker(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Produce the final ordering over the (cross-source) merged results.

### raglab.agent.Result

A retrieved item — ir’s `SearchHit` (ir_09’s `Result`):
a *pointer + snippet* (`text`) with a `score` and `metadata`.

### *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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One 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.refinement` in `_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`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

#### evaluator(results)

Pass-through critic: keep everything, declare sufficient, never re-query.

* **Return type:**
  [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement)

#### formulator(source)

Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)]

#### planner(sources)

Trivial planner: one sub-task over *all* registered sources, no decomposition.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask)]

#### pool_cap(limit)

Keep at most `limit` hits, 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, as
`ir.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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

#### reranker()

Cross-source merge (the default fan-in): fuse by rank, never by raw score.

Groups the accumulated pool by `hit.source` and delegates the merge to
`ir.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
colliding `artifact_id`s 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 exactly [`score_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.score_reranker)’s ordering; fused,
rank-derived scores only appear when there is genuinely something to fuse.
Each fused hit keeps its pre-fusion magnitude as
`metadata["source_score"]`. For per-source weights, another `rrf_k`,
or opt-in cross-source duplicate merging, use [`make_rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.make_rrf_reranker).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### *class* raglab.agent.SubTask(goal, sources)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A planner’s unit of work: a sub-goal bound to a set of registered sources.

### raglab.agent.arrival_order_cap(results, limit)

Keep the first `limit` hits 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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

### raglab.agent.identity_citer(results)

No-op citer (verification needs a generated claim — that lives in srag).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.agent.identity_formulator(task, source)

Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)]

### raglab.agent.ir_sources(\*names, \*\*search_defaults)

A source registry `{name: Retriever}` backed by named `ir` corpora.

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), use `ir.retrievers()` instead —
the agent accepts either, or any `Mapping[name, Retriever]`.
`search_defaults` (e.g. `mode="hybrid"`) apply to every source.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]]]

### raglab.agent.make_rrf_reranker(, rrf_k=60, weights=None, identity=None)

A parametrized [`rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_reranker) (per-source trust weights, `rrf_k`).

* **Parameters:**
  * **rrf_k** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – the RRF rank constant (standard default 60).
  * **weights** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – optional per-source trust dial, by source name (default 1.0
    each) — biases the merge without ever comparing raw scores.
  * **identity** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`SearchHit`], [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`None`](https://docs.python.org/3/builtins/constants.html#None)]) – opt-in cross-source duplicate detection (e.g. `"pointer"`)
    — see `ir.retrieve.Identity`. Default: never merge across
    sources.
* **Return type:**
  [`Reranker`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker)

### 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)

Build a [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent) over *sources* with smart defaults.

`sources` is a `Mapping[name, Retriever]` — e.g.
`{"skills": ir.as_retriever("skills")}`, [`ir_sources()`](_autosummary/raglab.agent.html.md#raglab.agent.ir_sources), or the lazy
`ir.retrievers()` view. Every role defaults to its no-LLM thin-slice
implementation, so `make_search_agent(sources)("query")` just works;
inject an LLM `formulator` / `evaluator` to turn on rewriting and the
back-edge. Pass a `run_log` (any callable taking a [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord), e.g.
`list.append`) to record what each round decided, and a `memory` (e.g. a
[`raglab.memory.PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore)) to journal what runs keep and reuse it.

A custom `Retriever` must return `ir.SearchHit` instances (the
`Result` alias): the loop stamps provenance (`hit.source`) on its
output, so duck-typed hit objects raise at the tagging step.

* **Return type:**
  [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent)

### raglab.agent.passthrough_evaluator(task, results)

Pass-through critic: keep everything, declare sufficient, never re-query.

* **Return type:**
  [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement)

### raglab.agent.rank_fair_cap(results, limit)

Keep at most `limit` hits, 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, as
`ir.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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

### raglab.agent.rrf_reranker(results)

Cross-source merge (the default fan-in): fuse by rank, never by raw score.

Groups the accumulated pool by `hit.source` and delegates the merge to
`ir.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
colliding `artifact_id`s 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 exactly [`score_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.score_reranker)’s ordering; fused,
rank-derived scores only appear when there is genuinely something to fuse.
Each fused hit keeps its pre-fusion magnitude as
`metadata["source_score"]`. For per-source weights, another `rrf_k`,
or opt-in cross-source duplicate merging, use [`make_rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.make_rrf_reranker).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.agent.score_reranker(results)

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()`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_reranker), which never compares raw scores across sources.

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.agent.single_subtask_planner(query, sources)

Trivial planner: one sub-task over *all* registered sources, no decomposition.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask)]


# _autosummary/raglab.bench.html.md

# raglab.bench

Cross-run benchmark: the instrument for purpose-indexed memory (raglab#15, item 4).

The follow-ups of the memory design (CONSOLIDATE, SUPERSEDE, purpose transfer, DECAY)
are each gated on an *observed* trigger. This module is what observes: it replays a
workload of purposes through an agent twice, once cold (no memory) and once warm (with
a [`PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore)), counting the source calls of each, and reports

* `sweeps_cold` / `sweeps_warm`: retriever calls without and with memory (what
  memory saves),
* `recall`: the share of the cold run’s hits the warm run also returned (what memory
  costs in answer quality: `1.0` means nothing was lost),
* `extractions`: units kept per purpose after the warm run (the CONSOLIDATE
  trigger is “this exceeds a threshold”).

Cold and warm calls interleave on the same sources, purpose by purpose, so a source
that changes over time shows as lost recall: that is the SUPERSEDE trigger, but so is
plain non-determinism (an approximate index, a live API). Run the benchmark on a
deterministic snapshot to read `recall` as what memory alone lost.

Hermetic and offline: pass any sources; nothing here calls an LLM:

```default
report = cross_run_benchmark(sources, ["invoices 2023", "2023 invoices"])
report.sweeps_saved, report.recall
```

### Functions

| [`cross_run_benchmark`](_autosummary/raglab.bench.html.md#raglab.bench.cross_run_benchmark)(sources, workload, \*[, ...])   | Replay `workload` (purposes, in order, repeats and paraphrases welcome) cold and warm, and report what memory saved and what it lost.   |
|------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------|
| [`extraction_counts`](_autosummary/raglab.bench.html.md#raglab.bench.extraction_counts)(store)                            | `{purpose: number of units kept}` (each purpose under its own statement).                                                               |
| [`loop_vs_single_benchmark`](_autosummary/raglab.bench.html.md#raglab.bench.loop_vs_single_benchmark)(sources, questions, \*)    | Run each question through the agent loop and through a single discover; compare.                                                        |

### Classes

| [`CrossRunReport`](_autosummary/raglab.bench.html.md#raglab.bench.CrossRunReport)(rows[, extractions])           | Totals over a workload, with the per-purpose `rows` and `extractions`.       |
|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`LoopVsSingleReport`](_autosummary/raglab.bench.html.md#raglab.bench.LoopVsSingleReport)(rows)                      | Totals over the questions, with the per-question `rows`.                     |
| [`PurposeRow`](_autosummary/raglab.bench.html.md#raglab.bench.PurposeRow)(purpose, sweeps_cold, ...)         | One purpose of the workload: its source calls cold and warm, and its recall. |
| [`QuestionRow`](_autosummary/raglab.bench.html.md#raglab.bench.QuestionRow)(question, calls_loop, ...[, ...]) | One question: source calls and hits of the loop and of a single discover.    |

### *class* raglab.bench.CrossRunReport(rows, extractions=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Totals over a workload, with the per-purpose `rows` and `extractions`.

#### *property* recall *: [float](https://docs.python.org/3/builtins/functions.html#float)*

Mean, over purposes, of the share of cold hits the warm run also returned.

#### *property* sweeps_saved *: [float](https://docs.python.org/3/builtins/functions.html#float)*

Share of the cold source calls the warm run did not make.

### *class* raglab.bench.LoopVsSingleReport(rows)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Totals over the questions, with the per-question `rows`.

#### *property* extra_calls *: [float](https://docs.python.org/3/builtins/functions.html#float)*

no extra).

* **Type:**
  Source calls the loop makes per call of a single discover (`1.0`

#### *property* single_recall_of_loop *: [float](https://docs.python.org/3/builtins/functions.html#float)*

Mean share of the loop’s hits a single discover also returned.

### *class* raglab.bench.PurposeRow(purpose, sweeps_cold, sweeps_warm, recall)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One purpose of the workload: its source calls cold and warm, and its recall.

### *class* raglab.bench.QuestionRow(question, calls_loop, calls_single, hits_loop, hits_single, single_recall_of_loop, recall_loop=None, recall_single=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One question: source calls and hits of the loop and of a single discover.

#### recall_loop *: [float](https://docs.python.org/3/builtins/functions.html#float) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

share of the relevant ids each variant returned (else `None`)

* **Type:**
  with `relevant`

#### single_recall_of_loop *: [float](https://docs.python.org/3/builtins/functions.html#float)*

the loop added nothing)

* **Type:**
  share of the loop’s hits that a single discover also returned (1.0

### raglab.bench.cross_run_benchmark(sources, workload, \*, agent_factory=<function make_search_agent>, memory_factory=<class 'raglab.memory.PurposeStore'>, \*\*agent_kwargs)

Replay `workload` (purposes, in order, repeats and paraphrases welcome) cold
and warm, and report what memory saved and what it lost.

`agent_factory(sources, memory=..., **agent_kwargs)` builds the agent (default
[`make_search_agent()`](_autosummary/raglab.agent.html.md#raglab.agent.make_search_agent)); the cold agent gets `memory=None`.
The warm agent shares one `memory_factory()` store across the whole workload.

* **Return type:**
  [`CrossRunReport`](_autosummary/raglab.bench.html.md#raglab.bench.CrossRunReport)

### raglab.bench.extraction_counts(store)

`{purpose: number of units kept}` (each purpose under its own statement).

```pycon
>>> from raglab.memory import ExtractionUnit
>>> s = PurposeStore()
>>> s["q"] = [ExtractionUnit("q", {"artifact_id": "a"}, 0.0)]
>>> extraction_counts(s)
{'q': 1}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### raglab.bench.loop_vs_single_benchmark(sources, questions, \*, relevant=None, agent_factory=<function make_search_agent>, single_budget=None, \*\*loop_kwargs)

Run each question through the agent loop and through a single discover; compare.

The *single* run is the same agent with `single_budget` (default one round, one
pass over the sources) and none of `loop_kwargs`: no LLM roles, so no rewriting
and no back-edge. The *loop* run gets `loop_kwargs` (`formulator`, `evaluator`,
`planner`, `budget`…). Both count their retriever calls. `relevant` maps a
question to the artifact ids that answer it, and adds recall against that ground
truth; without it the report says how much of the loop’s answer a single discover
already had, and what the loop costs in extra source calls. Offline when the roles
are: pass fakes, or live sources for a real measurement.

* **Return type:**
  [`LoopVsSingleReport`](_autosummary/raglab.bench.html.md#raglab.bench.LoopVsSingleReport)


# _autosummary/raglab.html.md

# 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):

```default
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: `raglab` imports `ir`; `ir` never imports `raglab`.

> 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

| [`rank_fair_cap`](_autosummary/raglab.html.md#raglab.rank_fair_cap)(results, limit)                     | Keep at most `limit` hits, taking the best of each source in turn (the default).                                                 |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| [`arrival_order_cap`](_autosummary/raglab.html.md#raglab.arrival_order_cap)(results, limit)                 | Keep the first `limit` hits in arrival order (source order x query order).                                                       |
| [`make_search_agent`](_autosummary/raglab.html.md#raglab.make_search_agent)(sources, \*[, planner, ...])    | Build a [`SingleContextAgent`](_autosummary/raglab.html.md#raglab.SingleContextAgent) over *sources* with smart defaults.                  |
| [`ir_sources`](_autosummary/raglab.html.md#raglab.ir_sources)(\*names, \*\*search_defaults)          | A source registry `{name: Retriever}` backed by named `ir` corpora.                                                              |
| [`single_subtask_planner`](_autosummary/raglab.html.md#raglab.single_subtask_planner)(query, sources)            | Trivial planner: one sub-task over *all* registered sources, no decomposition.                                                   |
| [`identity_formulator`](_autosummary/raglab.html.md#raglab.identity_formulator)(task, source)                 | Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).                                                       |
| [`passthrough_evaluator`](_autosummary/raglab.html.md#raglab.passthrough_evaluator)(task, results)              | Pass-through critic: keep everything, declare sufficient, never re-query.                                                        |
| [`score_reranker`](_autosummary/raglab.html.md#raglab.score_reranker)(results)                           | Magnitude merge: one surface per artifact, ordered by descending raw score.                                                      |
| [`rrf_reranker`](_autosummary/raglab.html.md#raglab.rrf_reranker)(results)                             | Cross-source merge (the default fan-in): fuse by rank, never by raw score.                                                       |
| [`make_rrf_reranker`](_autosummary/raglab.html.md#raglab.make_rrf_reranker)(\*[, rrf_k, weights, identity]) | A parametrized [`rrf_reranker()`](_autosummary/raglab.html.md#raglab.rrf_reranker) (per-source trust weights, `rrf_k`).              |
| [`identity_citer`](_autosummary/raglab.html.md#raglab.identity_citer)(results)                           | No-op citer (verification needs a generated claim — that lives in srag).                                                         |
| [`make_llm_formulator`](_autosummary/raglab.html.md#raglab.make_llm_formulator)(\*[, formulate, params])      | An LLM-backed raglab [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator).                        |
| [`make_llm_evaluator`](_autosummary/raglab.html.md#raglab.make_llm_evaluator)(\*[, judge, ...])              | An LLM-backed raglab [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) (turns on the back-edge). |
| [`apply_gates`](_autosummary/raglab.html.md#raglab.apply_gates)(proposed, content, \*[, levels, ...]) | The level a judge's proposal is allowed, after calibration and the gates.                                                        |
| [`make_graded_rubric_evaluator`](_autosummary/raglab.html.md#raglab.make_graded_rubric_evaluator)(\*[, levels, ...])   | An [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) that grades every candidate on a rubric.    |

### Classes

| [`Query`](_autosummary/raglab.html.md#raglab.Query)(text[, constraints])                       | A user intent: free text plus optional structured constraints.                                                    |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|
| [`SubTask`](_autosummary/raglab.html.md#raglab.SubTask)(goal, sources)                           | A planner's unit of work: a sub-goal bound to a set of registered sources.                                        |
| [`LowLevelQuery`](_autosummary/raglab.html.md#raglab.LowLevelQuery)(source, query[, params])           | One concrete query against one source.                                                                            |
| [`Judgement`](_autosummary/raglab.html.md#raglab.Judgement)(relevant, sufficient[, ...])           | An evaluator's verdict over a round's results.                                                                    |
| [`GradedLabel`](_autosummary/raglab.html.md#raglab.GradedLabel)(level, is_about, is_supported, ...)  | A graded verdict on one candidate (raglab#8): a level, three axes, the evidence.                                  |
| [`Result`](_autosummary/raglab.html.md#raglab.Result)                                           |                                                                                                                   |
| [`Planner`](_autosummary/raglab.html.md#raglab.Planner)(\*args, \*\*kwargs)                      | Decompose a query into sub-tasks and select sources for each.                                                     |
| [`Formulator`](_autosummary/raglab.html.md#raglab.Formulator)(\*args, \*\*kwargs)                   | Turn a sub-task + one source into concrete low-level queries.                                                     |
| [`Evaluator`](_autosummary/raglab.html.md#raglab.Evaluator)(\*args, \*\*kwargs)                    | Judge relevance + sufficiency; optionally emit a refinement (back-edge).                                          |
| [`Reranker`](_autosummary/raglab.html.md#raglab.Reranker)(\*args, \*\*kwargs)                     | Produce the final ordering over the (cross-source) merged results.                                                |
| [`Citer`](_autosummary/raglab.html.md#raglab.Citer)(\*args, \*\*kwargs)                        | Confirm/annotate that each result supports its use (identity by default).                                         |
| [`Budget`](_autosummary/raglab.html.md#raglab.Budget)([max_rounds, max_sources_per_task, ...])  | Loop bounds: the safety net under the (harder) sufficiency decision.                                              |
| [`PoolCap`](_autosummary/raglab.html.md#raglab.PoolCap)(\*args, \*\*kwargs)                      | Bound the pool the evaluator sees to at most `limit` results.                                                     |
| [`Memory`](_autosummary/raglab.html.md#raglab.Memory)(\*args, \*\*kwargs)                       | Cross-run memory: recall hits for a purpose; take [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) s. |
| [`PurposeStore`](_autosummary/raglab.html.md#raglab.PurposeStore)([backend, embedder, ...])           | `MutableMapping[purpose, list[ExtractionUnit]]` over an injected `backend`.                                       |
| [`ExtractionUnit`](_autosummary/raglab.html.md#raglab.ExtractionUnit)(purpose, hit, recorded_at[, ...]) | One piece of evidence a run committed to, for one purpose.                                                        |
| [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord)(purpose, round, goal, sources, ...)  | What one round of the loop decided: the run-log's unit (raglab#6).                                                |
| [`RunLog`](_autosummary/raglab.html.md#raglab.RunLog)(\*args, \*\*kwargs)                       | A sink for the loop's [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) s, one call per round.         |
| [`SingleContextAgent`](_autosummary/raglab.html.md#raglab.SingleContextAgent)(sources[, planner, ...])      | 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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Loop bounds: the safety net under the (harder) sufficiency decision.

### *class* raglab.Citer(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Confirm/annotate that each result supports its use (identity by default).

### *class* raglab.Evaluator(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Judge relevance + sufficiency; optionally emit a refinement (back-edge).

### *class* raglab.ExtractionUnit(purpose, hit, recorded_at, importance=1.0, confidence=None, level='raw', supersedes=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One piece of evidence a run committed to, for one purpose.

`hit` is the `SearchHit.to_dict()` of the kept hit: provenance
(`source`, `artifact_id`) and its raw magnitude, never a fused score.
`level` is the consolidation level (`"raw"` until CONSOLIDATE exists);
`supersedes` names the artifact id a later unit replaces (for SUPERSEDE).

#### *classmethod* from_dict(d)

Inverse of [`to_dict()`](_autosummary/raglab.html.md#raglab.ExtractionUnit.to_dict).

* **Return type:**
  [`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)

#### *property* identity *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]*

ir’s identity of the artifact this points at.

* **Type:**
  `(source, artifact_id)`

#### to_dict()

JSON-clean form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### to_result()

The `SearchHit` this unit was made from.

* **Return type:**
  `SearchHit`

### *class* raglab.Formulator(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Turn a sub-task + one source into concrete low-level queries.

### *class* raglab.GradedLabel(level, is_about, is_supported, is_useful, evidence_quote='', facet=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A graded verdict on one candidate (raglab#8): a level, three axes, the evidence.

`level` is 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) and `is_useful`
(ISUSE). `evidence_quote` is a verbatim span of the candidate’s content
backing the level; `facet` names the sub-goal it was judged against.

### *class* raglab.Judgement(relevant, sufficient, refinement=None, graded=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

An evaluator’s verdict over a round’s results.

`relevant` is the kept subset; `sufficient` says whether to stop; a
non-`None` `refinement` is the **back-edge** — the next sub-task to
re-query with. The pass-through default returns `sufficient=True` and no
refinement (no loop). `graded` is optional and additive: a graded
evaluator maps each judged `artifact_id` to its [`GradedLabel`](_autosummary/raglab.html.md#raglab.GradedLabel);
binary evaluators leave it empty.

### *class* raglab.LowLevelQuery(source, query, params=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One concrete query against one source.

`query` is the text handed to the source’s `Retriever`; `params`
are per-call retriever overrides (e.g. `mode` / `filter` / `k` for an
ir corpus). A formulator turns a [`SubTask`](_autosummary/raglab.html.md#raglab.SubTask) into these.

### *class* raglab.Memory(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Cross-run memory: recall hits for a purpose; take [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) s.

Opt-in (`SingleContextAgent.memory` defaults to `None`). Before sweeping a
sub-task, the agent offers the recalled hits to the evaluator; if they are
sufficient, it does not sweep. [`raglab.memory.PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore) is one.

### *class* raglab.Planner(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Decompose a query into sub-tasks and select sources for each.

### *class* raglab.PoolCap(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Bound the pool the evaluator sees to at most `limit` results.

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>)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

`MutableMapping[purpose, list[ExtractionUnit]]` over an injected `backend`.

`backend` maps `purpose_id()` to a JSON-clean record
`{"purpose", "embedding", "units"}`: any `MutableMapping` (a dict, a dol
store of JSON files, …). `store[purpose]` recalls from every *related*
purpose (the same one, or one whose embedding is at least `min_relevance`
cosine-similar); `store[purpose] = units` replaces that purpose’s units.
Calling the store with a [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) journals 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)

The units of every purpose related to `purpose`, ranked by `read_strategy`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)]

#### recall_hits(purpose)

[`recall()`](_autosummary/raglab.html.md#raglab.PurposeStore.recall) as `SearchHit` s, ready to seed the agent’s pool.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

#### write(purpose, units)

Merge `units` into `purpose`’s, with the `write_strategy`.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### write_strategy(new)

ADD new artifacts; UPDATE (replace with the newer unit) those already kept.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)]

### *class* raglab.Query(text, constraints=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A user intent: free text plus optional structured constraints.

### *class* raglab.Reranker(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Produce 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())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What 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. `purpose` is the sub-task’s original goal; `goal` is what this
round actually searched (a refinement, from round 1 on). `committed` holds the
hits the evaluator kept, with their **raw** per-source magnitudes: the pool never
carries fused scores, so neither does the record. Round `-1` is the recall
round of an agent with a `memory`: its pool was recalled, not swept.

#### to_dict()

JSON-clean form: hits via `SearchHit.to_dict`, labels as plain dicts.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### *class* raglab.RunLog(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

A sink for the loop’s [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) s, one call per round.

Opt-in (the agent’s `run_log` defaults to `None`: nothing is recorded).
`list.append` is 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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One 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.refinement` in `_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`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

#### evaluator(results)

Pass-through critic: keep everything, declare sufficient, never re-query.

* **Return type:**
  [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement)

#### formulator(source)

Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)]

#### planner(sources)

Trivial planner: one sub-task over *all* registered sources, no decomposition.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask)]

#### pool_cap(limit)

Keep at most `limit` hits, 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, as
`ir.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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

#### reranker()

Cross-source merge (the default fan-in): fuse by rank, never by raw score.

Groups the accumulated pool by `hit.source` and delegates the merge to
`ir.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
colliding `artifact_id`s 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 exactly [`score_reranker()`](_autosummary/raglab.html.md#raglab.score_reranker)’s ordering; fused,
rank-derived scores only appear when there is genuinely something to fuse.
Each fused hit keeps its pre-fusion magnitude as
`metadata["source_score"]`. For per-source weights, another `rrf_k`,
or opt-in cross-source duplicate merging, use [`make_rrf_reranker()`](_autosummary/raglab.html.md#raglab.make_rrf_reranker).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### *class* raglab.SubTask(goal, sources)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A 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)

The level a judge’s proposal is allowed, after calibration and the gates.

The quote must be at least `min_quote_chars` long and found in `content`,
ignoring case and runs of whitespace (judges re-case and re-wrap what they
copy). `calibration_offset` is in levels, rounded half up, so a shift is
the same at every level.

```pycon
>>> 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:**
  [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)

### raglab.arrival_order_cap(results, limit)

Keep the first `limit` hits 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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

### raglab.identity_citer(results)

No-op citer (verification needs a generated claim — that lives in srag).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.identity_formulator(task, source)

Identity formulator: the sub-goal verbatim as one query (no rewrite/HyDE).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)]

### raglab.ir_sources(\*names, \*\*search_defaults)

A source registry `{name: Retriever}` backed by named `ir` corpora.

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), use `ir.retrievers()` instead —
the agent accepts either, or any `Mapping[name, Retriever]`.
`search_defaults` (e.g. `mode="hybrid"`) apply to every source.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]]]

### 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)

An [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) that grades every candidate on a rubric.

* **Parameters:**
  * **levels** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – the ordered levels, best first.
  * **rubric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – what each level means, shown to the judge.
  * **judge** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – an injectable graded judge (a test double, or your own router);
    built lazily on `oa` when omitted.
  * **disclose_level** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – what the judge reads — each candidate’s
    content through `ir.disclose()` at that level (`store=` /
    `loader=` go in `disclose_kwargs`); a candidate with nothing to
    load is judged on its snippet.
  * **disclose_kwargs** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – what the judge reads — each candidate’s
    content through `ir.disclose()` at that level (`store=` /
    `loader=` go in `disclose_kwargs`); a candidate with nothing to
    load is judged on its snippet.
  * **require_evidence_quote** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.html.md#raglab.apply_gates).
  * **unsupported_cap** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.html.md#raglab.apply_gates).
  * **calibration_offset** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.html.md#raglab.apply_gates).
* **Return type:**
  [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

:param : min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.html.md#raglab.apply_gates).
:type relevant_level: [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)
:param relevant_level: the lowest level kept in `Judgement.relevant`.
:type refine: [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)]], [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) | [`None`](https://docs.python.org/3/builtins/constants.html#None)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)
:param refine: the back-edge policy `(task, graded) -> SubTask | None`; by

> default none, so the loop stops after one round.
* **Parameters:**
  **rng** ([`Random`](https://docs.python.org/3/library/random.html#random.Random) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the source of the per-call level order (seed it for reproducible
  prompts).
* **Return type:**
  [*Evaluator*](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

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.graded` is keyed by `artifact_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)

An LLM-backed raglab [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.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 the `Judgement.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-free `sufficient` hint via abstention) and decides
whether the goal is satisfied. When it is not, the judge’s improved query
becomes a `refinement` [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) over the same sources
— the **back-edge**.

* **Parameters:**
  * **judge** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`bool`](https://docs.python.org/3/builtins/functions.html#bool), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)] | [`str`](https://docs.python.org/3/builtins/stdtypes.html#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 on `oa`.
  * **select_strategy** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – ir selection strategy for the relevance decision
    (default `"conservative"` — distractor-robust).
  * **select_kwargs** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – extra args forwarded to `ir.select()`
    (e.g. `max_k`, `rel`). `min_score` is allowed only while the
    round’s pool keeps raw scores (single-source, or
    `prerank=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`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the per-round merge that puts the accumulated pool best-first
    (and deduped) before `ir.select`. Defaults to
    [`rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_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. Inject [`score_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.score_reranker) for
    sources known to share one score scale.
  * **max_result_chars** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – per-result text truncation in the judge prompt.
* **Return type:**
  [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

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)

An LLM-backed raglab [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.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 a
[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery) against `source`.

* **Parameters:**
  * **formulate** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]]) – an injectable ir-style formulator (a test double, or one you
    built). When omitted it is built once via
    `ir.make_llm_formulator()` (`**make_kwargs` are forwarded —
    e.g. `n`, `prompt`, `rewriter`); that call is offline (`oa` is
    imported lazily only when the formulator is *invoked*), so
    `import raglab` stays offline.
  * **params** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – per-call retriever overrides (e.g. `{"mode": "hybrid", "k": 5}`)
    attached to every emitted [`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery).
* **Return type:**
  [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator)

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)

A parametrized [`rrf_reranker()`](_autosummary/raglab.html.md#raglab.rrf_reranker) (per-source trust weights, `rrf_k`).

* **Parameters:**
  * **rrf_k** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – the RRF rank constant (standard default 60).
  * **weights** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – optional per-source trust dial, by source name (default 1.0
    each) — biases the merge without ever comparing raw scores.
  * **identity** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`SearchHit`], [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`None`](https://docs.python.org/3/builtins/constants.html#None)]) – opt-in cross-source duplicate detection (e.g. `"pointer"`)
    — see `ir.retrieve.Identity`. Default: never merge across
    sources.
* **Return type:**
  [`Reranker`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker)

### 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)

Build a [`SingleContextAgent`](_autosummary/raglab.html.md#raglab.SingleContextAgent) over *sources* with smart defaults.

`sources` is a `Mapping[name, Retriever]` — e.g.
`{"skills": ir.as_retriever("skills")}`, [`ir_sources()`](_autosummary/raglab.html.md#raglab.ir_sources), or the lazy
`ir.retrievers()` view. Every role defaults to its no-LLM thin-slice
implementation, so `make_search_agent(sources)("query")` just works;
inject an LLM `formulator` / `evaluator` to turn on rewriting and the
back-edge. Pass a `run_log` (any callable taking a [`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord), e.g.
`list.append`) to record what each round decided, and a `memory` (e.g. a
[`raglab.memory.PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore)) to journal what runs keep and reuse it.

A custom `Retriever` must return `ir.SearchHit` instances (the
`Result` alias): the loop stamps provenance (`hit.source`) on its
output, so duck-typed hit objects raise at the tagging step.

* **Return type:**
  [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent)

### raglab.passthrough_evaluator(task, results)

Pass-through critic: keep everything, declare sufficient, never re-query.

* **Return type:**
  [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement)

### raglab.rank_fair_cap(results, limit)

Keep at most `limit` hits, 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, as
`ir.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`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

### raglab.rrf_reranker(results)

Cross-source merge (the default fan-in): fuse by rank, never by raw score.

Groups the accumulated pool by `hit.source` and delegates the merge to
`ir.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
colliding `artifact_id`s 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 exactly [`score_reranker()`](_autosummary/raglab.html.md#raglab.score_reranker)’s ordering; fused,
rank-derived scores only appear when there is genuinely something to fuse.
Each fused hit keeps its pre-fusion magnitude as
`metadata["source_score"]`. For per-source weights, another `rrf_k`,
or opt-in cross-source duplicate merging, use [`make_rrf_reranker()`](_autosummary/raglab.html.md#raglab.make_rrf_reranker).

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.score_reranker(results)

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()`](_autosummary/raglab.html.md#raglab.rrf_reranker), which never compares raw scores across sources.

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`SearchHit`]

### raglab.single_subtask_planner(query, sources)

Trivial planner: one sub-task over *all* registered sources, no decomposition.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask)]

### Modules

| [`agent`](_autosummary/raglab.agent.html.md#module-raglab.agent)     | The Composable Search Agent — roles wired by a control loop (ir_09).                      |
|--------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
| [`bench`](_autosummary/raglab.bench.html.md#module-raglab.bench)     | Cross-run benchmark: the instrument for purpose-indexed memory (raglab#15, item 4).       |
| [`judging`](_autosummary/raglab.judging.html.md#module-raglab.judging) | Graded rubric judging — every candidate gets a level, three axes and evidence (raglab#8). |
| [`llm`](_autosummary/raglab.llm.html.md#module-raglab.llm)         | LLM-backed roles — the Formulator and Evaluator (ir_09 §8 steps 1 & 3).                   |
| [`memory`](_autosummary/raglab.memory.html.md#module-raglab.memory)   | Purpose-indexed memory: what past runs found, kept per purpose (raglab#6, stage 0).       |
| [`recipes`](_autosummary/raglab.recipes.html.md#module-raglab.recipes) | Recipes: whole workflows composed from raglab's roles, ready to call.                     |


# _autosummary/raglab.judging.html.md

# raglab.judging

Graded rubric judging — every candidate gets a level, three axes and evidence (raglab#8).

A binary relevant/not cannot say “mentions the word but is not about it”. The
evaluator built by [`make_graded_rubric_evaluator()`](_autosummary/raglab.judging.html.md#raglab.judging.make_graded_rubric_evaluator) asks an injected judge,
for **each** candidate in the round’s pool, for the three Self-RAG axes
(`is_about`, `is_supported`, `is_useful`), a level on an ordered scale and
a verbatim `evidence_quote` from the candidate’s disclosed content. The judge
proposes; deterministic gates here dispose:

- a level above `unsupported_cap` needs `is_supported` — topical vocabulary
  without supporting content is capped (the direct fix for on-word distractors);
- with `require_evidence_quote`, it also needs a quote found verbatim in the
  content the judge was shown (whitespace-insensitive);
- `calibration_offset` (levels, learned from a gold slice) shifts every level
  down (positive: the judge over-grades) or up;
- the level options are shown in a fresh random order on every call, against
  position bias.

The result is a [`Judgement`](_autosummary/raglab.agent.html.md#raglab.agent.Judgement) whose additive `graded` map
carries every label, whose `relevant` keeps the candidates at or above
`relevant_level`, and whose back-edge comes from an injected `refine` policy
(none by default: the loop stops). As in [`raglab.llm`](_autosummary/raglab.llm.html.md#module-raglab.llm), the default judge is
built lazily on `oa`, so `import raglab` stays offline, and a judge that
fails on a candidate leaves it ungraded rather than guessing.

### Module Attributes

| [`DEFAULT_LEVELS`](_autosummary/raglab.judging.html.md#raglab.judging.DEFAULT_LEVELS)         | Ordered levels, best first.                                                 |
|-------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`DEFAULT_TOPICAL_RUBRIC`](_autosummary/raglab.judging.html.md#raglab.judging.DEFAULT_TOPICAL_RUBRIC) | What the default levels mean, for a "is this package about TOPIC" question. |
| [`GRADING_PROMPT`](_autosummary/raglab.judging.html.md#raglab.judging.GRADING_PROMPT)         | The judge's prompt; `{levels}` is shown in a fresh random order each call.  |

### Functions

| [`make_graded_rubric_evaluator`](_autosummary/raglab.judging.html.md#raglab.judging.make_graded_rubric_evaluator)(\*[, levels, ...])   | An [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) that grades every candidate on a rubric.   |
|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| [`apply_gates`](_autosummary/raglab.judging.html.md#raglab.judging.apply_gates)(proposed, content, \*[, levels, ...]) | The level a judge's proposal is allowed, after calibration and the gates.                                                       |

### raglab.judging.DEFAULT_LEVELS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), ...]* *= ('core', 'strong', 'uses-tools', 'tangential', 'none')*

Ordered levels, best first.

### raglab.judging.DEFAULT_TOPICAL_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"*

What the default levels mean, for a “is this package about TOPIC” question.

### raglab.judging.GRADING_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'*

The judge’s prompt; `{levels}` is shown in a fresh random order each call.

### raglab.judging.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)

The level a judge’s proposal is allowed, after calibration and the gates.

The quote must be at least `min_quote_chars` long and found in `content`,
ignoring case and runs of whitespace (judges re-case and re-wrap what they
copy). `calibration_offset` is in levels, rounded half up, so a shift is
the same at every level.

```pycon
>>> 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:**
  [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)

### raglab.judging.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)

An [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) that grades every candidate on a rubric.

* **Parameters:**
  * **levels** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – the ordered levels, best first.
  * **rubric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – what each level means, shown to the judge.
  * **judge** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – an injectable graded judge (a test double, or your own router);
    built lazily on `oa` when omitted.
  * **disclose_level** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – what the judge reads — each candidate’s
    content through `ir.disclose()` at that level (`store=` /
    `loader=` go in `disclose_kwargs`); a candidate with nothing to
    load is judged on its snippet.
  * **disclose_kwargs** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – what the judge reads — each candidate’s
    content through `ir.disclose()` at that level (`store=` /
    `loader=` go in `disclose_kwargs`); a candidate with nothing to
    load is judged on its snippet.
  * **require_evidence_quote** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.judging.html.md#raglab.judging.apply_gates).
  * **unsupported_cap** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.judging.html.md#raglab.judging.apply_gates).
  * **calibration_offset** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.judging.html.md#raglab.judging.apply_gates).
* **Return type:**
  [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

:param : min_quote_chars: the gates, see [`apply_gates()`](_autosummary/raglab.judging.html.md#raglab.judging.apply_gates).
:type relevant_level: [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)
:param relevant_level: the lowest level kept in `Judgement.relevant`.
:type refine: [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)]], [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) | [`None`](https://docs.python.org/3/builtins/constants.html#None)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)
:param refine: the back-edge policy `(task, graded) -> SubTask | None`; by

> default none, so the loop stops after one round.
* **Parameters:**
  **rng** ([`Random`](https://docs.python.org/3/library/random.html#random.Random) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the source of the per-call level order (seed it for reproducible
  prompts).
* **Return type:**
  [*Evaluator*](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

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.graded` is keyed by `artifact_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.


# _autosummary/raglab.llm.html.md

# raglab.llm

LLM-backed roles — the Formulator and Evaluator (ir_09 §8 steps 1 & 3).

`raglab`’s no-LLM thin slice ([`raglab.agent`](_autosummary/raglab.agent.html.md#module-raglab.agent)) runs offline: an identity
formulator and a pass-through evaluator. This module supplies the two LLM roles
that turn that slice into a real agent — query understanding and the back-edge:

- [`make_llm_formulator()`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_formulator) — query rewrite / expand / HyDE. A thin adapter
  over ir’s `ir.make_llm_formulator()` (the `formulate=` seam, ir_09 §3):
  ir owns the lazy-`oa` rewriter and the identity fallback; raglab only
  adapts the shape `str -> str | [str]` to the role contract
  `(SubTask, source) -> [LowLevelQuery]`.
- [`make_llm_evaluator()`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_evaluator) — sufficiency + refinement. `ir.select` owns the
  *relevance* decision (the calibrated committed subset, ir_09 §3); the LLM owns
  *sufficiency* — informed by ir’s model-free `ir.Selection.sufficient`
  hint, it judges whether the committed subset actually satisfies the goal and,
  when it does not, emits a `refinement` SubTask. That refinement is the
  **back-edge** that makes the loop an agent rather than a DAG.

Two load-bearing boundaries (ir ↔ raglab), guarded here:

1. A Formulator returns **queries, never SubTasks** — decomposition is the
   Planner’s job. [`make_llm_formulator()`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_formulator) only ever yields
   [`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery)s.
2. The **back-edge lives in raglab**, never in ir: ir derives a `sufficient`
   *signal* from its own selection; raglab’s Evaluator is what reads it, decides,
   and re-queries.

Both builders mirror `ir.select.make_llm_selector()`: an injectable callable
(a test double, or your own router), built lazily on `oa` only when omitted
(so `import raglab` stays offline), with a **safe fallback** — a formulator must
never make retrieval worse than the raw query, and an evaluator must never
fabricate an endless loop (on any failure it returns no refinement, which is the
loop’s break condition).

### Module Attributes

| [`EVALUATION_PROMPT`](_autosummary/raglab.llm.html.md#raglab.llm.EVALUATION_PROMPT)   | Default prompt for [`make_llm_evaluator()`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_evaluator) — judge sufficiency, else emit a single improved query (the refinement that drives the back-edge).   |
|----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### Functions

| [`make_llm_formulator`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_formulator)(\*[, formulate, params])   | An LLM-backed raglab [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator).                        |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| [`make_llm_evaluator`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_evaluator)(\*[, judge, ...])           | An LLM-backed raglab [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator) (turns on the back-edge). |

### raglab.llm.EVALUATION_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'*

Default prompt for [`make_llm_evaluator()`](_autosummary/raglab.llm.html.md#raglab.llm.make_llm_evaluator) — judge sufficiency, else emit a
single improved query (the refinement that drives the back-edge).

### raglab.llm.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)

An LLM-backed raglab [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.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 the `Judgement.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-free `sufficient` hint via abstention) and decides
whether the goal is satisfied. When it is not, the judge’s improved query
becomes a `refinement` [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) over the same sources
— the **back-edge**.

* **Parameters:**
  * **judge** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`bool`](https://docs.python.org/3/builtins/functions.html#bool), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)] | [`str`](https://docs.python.org/3/builtins/stdtypes.html#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 on `oa`.
  * **select_strategy** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – ir selection strategy for the relevance decision
    (default `"conservative"` — distractor-robust).
  * **select_kwargs** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – extra args forwarded to `ir.select()`
    (e.g. `max_k`, `rel`). `min_score` is allowed only while the
    round’s pool keeps raw scores (single-source, or
    `prerank=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`](_autosummary/raglab.agent.html.md#raglab.agent.Reranker) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the per-round merge that puts the accumulated pool best-first
    (and deduped) before `ir.select`. Defaults to
    [`rrf_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.rrf_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. Inject [`score_reranker()`](_autosummary/raglab.agent.html.md#raglab.agent.score_reranker) for
    sources known to share one score scale.
  * **max_result_chars** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – per-result text truncation in the judge prompt.
* **Return type:**
  [`Evaluator`](_autosummary/raglab.agent.html.md#raglab.agent.Evaluator)

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.llm.make_llm_formulator(, formulate=None, params=None, \*\*make_kwargs)

An LLM-backed raglab [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.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 a
[`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery) against `source`.

* **Parameters:**
  * **formulate** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]]) – an injectable ir-style formulator (a test double, or one you
    built). When omitted it is built once via
    `ir.make_llm_formulator()` (`**make_kwargs` are forwarded —
    e.g. `n`, `prompt`, `rewriter`); that call is offline (`oa` is
    imported lazily only when the formulator is *invoked*), so
    `import raglab` stays offline.
  * **params** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – per-call retriever overrides (e.g. `{"mode": "hybrid", "k": 5}`)
    attached to every emitted [`LowLevelQuery`](_autosummary/raglab.agent.html.md#raglab.agent.LowLevelQuery).
* **Return type:**
  [`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator)

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.


# _autosummary/raglab.memory.html.md

# raglab.memory

Purpose-indexed memory: what past runs found, kept per purpose (raglab#6, stage 0).

The retrieval index is purpose-free by design; the search agent is the one layer that
sees *purpose* (the sub-task goal, the refinement chain, the evaluator’s verdicts).
Without memory, everything a run learned dies when it returns. A [`PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore)
keeps the precipitate: the hits each run committed to, as [`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit) s
keyed by purpose, carrying their provenance (`(source, artifact_id)` plus the whole
`SearchHit.to_dict()`, raw magnitudes only).

It is a [`RunLog`](_autosummary/raglab.html.md#raglab.RunLog) sink (writes come from the run-log’s
[`RoundRecord`](_autosummary/raglab.html.md#raglab.RoundRecord) s, the one shared record shape) and a
[`Memory`](_autosummary/raglab.html.md#raglab.Memory) the agent reads from before sweeping:

```default
store = PurposeStore()
agent = make_search_agent(sources, memory=store)
agent("invoices from 2023")  # sweeps, journals what it kept
agent("invoices from 2023")  # recalls those hits; sweeps only if not sufficient
```

Progressive disclosure: `store[purpose]` is the related-purpose read. With no
`embedder` only the same purpose (normalized text) is related; inject one
(`str -> vector`, e.g. a vd/ir embedder) and similar purposes share their findings.

The four verbs of the design (report 14) are injected strategies; stage 0 ships two
(`write_strategy`: ADD, or UPDATE an artifact already kept; `read_strategy`:
relevance x importance x recency). CONSOLIDATE and DECAY are follow-ups, gated on
observed need.

### Functions

| [`json_clean`](_autosummary/raglab.memory.html.md#raglab.memory.json_clean)(obj)                          | `obj` as plain JSON types (numpy values via `tolist`, the rest via `str`).                                         |
|-------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
| [`make_relevance_recency_reader`](_autosummary/raglab.memory.html.md#raglab.memory.make_relevance_recency_reader)(\*[, ...]) | A [`ReadStrategy`](_autosummary/raglab.memory.html.md#raglab.memory.ReadStrategy) scoring `relevance**alpha * importance * recency`. |
| [`normalize_purpose`](_autosummary/raglab.memory.html.md#raglab.memory.normalize_purpose)(statement)             | The canonical text of a purpose: case-folded, whitespace collapsed.                                                |
| [`purpose_id`](_autosummary/raglab.memory.html.md#raglab.memory.purpose_id)(statement)                    | Content-hash id of a purpose (of its [`normalize_purpose()`](_autosummary/raglab.memory.html.md#raglab.memory.normalize_purpose) text).   |
| `relevance_recency_reader`(candidates, \*, now)                                           |                                                                                                                    |
| [`upsert_write`](_autosummary/raglab.memory.html.md#raglab.memory.upsert_write)(existing, new)              | ADD new artifacts; UPDATE (replace with the newer unit) those already kept.                                        |

### Classes

| [`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)(purpose, hit, recorded_at[, ...])   | One piece of evidence a run committed to, for one purpose.                       |
|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`PurposeStore`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore)([backend, embedder, ...])             | `MutableMapping[purpose, list[ExtractionUnit]]` over an injected `backend`.      |
| [`ReadStrategy`](_autosummary/raglab.memory.html.md#raglab.memory.ReadStrategy)(\*args, \*\*kwargs)                   | Rank `(relevance, unit)` candidates (from related purposes) into what to recall. |
| [`WriteStrategy`](_autosummary/raglab.memory.html.md#raglab.memory.WriteStrategy)(\*args, \*\*kwargs)                  | Merge `new` units into a purpose's `existing` ones (ADD/UPDATE/SUPERSEDE/NOOP).  |

### *class* raglab.memory.ExtractionUnit(purpose, hit, recorded_at, importance=1.0, confidence=None, level='raw', supersedes=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One piece of evidence a run committed to, for one purpose.

`hit` is the `SearchHit.to_dict()` of the kept hit: provenance
(`source`, `artifact_id`) and its raw magnitude, never a fused score.
`level` is the consolidation level (`"raw"` until CONSOLIDATE exists);
`supersedes` names the artifact id a later unit replaces (for SUPERSEDE).

#### *classmethod* from_dict(d)

Inverse of [`to_dict()`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit.to_dict).

* **Return type:**
  [`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)

#### *property* identity *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]*

ir’s identity of the artifact this points at.

* **Type:**
  `(source, artifact_id)`

#### to_dict()

JSON-clean form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### to_result()

The `SearchHit` this unit was made from.

* **Return type:**
  `SearchHit`

### *class* raglab.memory.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>)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

`MutableMapping[purpose, list[ExtractionUnit]]` over an injected `backend`.

`backend` maps [`purpose_id()`](_autosummary/raglab.memory.html.md#raglab.memory.purpose_id) to a JSON-clean record
`{"purpose", "embedding", "units"}`: any `MutableMapping` (a dict, a dol
store of JSON files, …). `store[purpose]` recalls from every *related*
purpose (the same one, or one whose embedding is at least `min_relevance`
cosine-similar); `store[purpose] = units` replaces that purpose’s units.
Calling the store with a `RoundRecord` journals 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)

The units of every purpose related to `purpose`, ranked by `read_strategy`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)]

#### recall_hits(purpose)

[`recall()`](_autosummary/raglab.memory.html.md#raglab.memory.PurposeStore.recall) as `SearchHit` s, ready to seed the agent’s pool.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SearchHit`]

#### write(purpose, units)

Merge `units` into `purpose`’s, with the `write_strategy`.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### write_strategy(new)

ADD new artifacts; UPDATE (replace with the newer unit) those already kept.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)]

### *class* raglab.memory.ReadStrategy(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Rank `(relevance, unit)` candidates (from related purposes) into what to recall.

### *class* raglab.memory.WriteStrategy(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Merge `new` units into a purpose’s `existing` ones (ADD/UPDATE/SUPERSEDE/NOOP).

### raglab.memory.json_clean(obj)

`obj` as plain JSON types (numpy values via `tolist`, the rest via `str`).

```pycon
>>> json_clean({"p": (1, 2), "x": {1}})
{'p': [1, 2], 'x': '{1}'}
```

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### raglab.memory.make_relevance_recency_reader(, half_life=2592000.0, alpha=1.0)

A [`ReadStrategy`](_autosummary/raglab.memory.html.md#raglab.memory.ReadStrategy) scoring `relevance**alpha * importance * recency`.

`recency` halves every `half_life` seconds. Each artifact is recalled once,
at its best score, best first.

* **Return type:**
  [`ReadStrategy`](_autosummary/raglab.memory.html.md#raglab.memory.ReadStrategy)

### raglab.memory.normalize_purpose(statement)

The canonical text of a purpose: case-folded, whitespace collapsed.

```pycon
>>> normalize_purpose("  Invoices   from 2023 ")
'invoices from 2023'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### raglab.memory.purpose_id(statement)

Content-hash id of a purpose (of its [`normalize_purpose()`](_autosummary/raglab.memory.html.md#raglab.memory.normalize_purpose) text).

```pycon
>>> purpose_id("Invoices from 2023") == purpose_id("invoices  from 2023")
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### raglab.memory.upsert_write(existing, new)

ADD new artifacts; UPDATE (replace with the newer unit) those already kept.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`ExtractionUnit`](_autosummary/raglab.memory.html.md#raglab.memory.ExtractionUnit)]


# _autosummary/raglab.recipes.corpus_labeling.html.md

# raglab.recipes.corpus_labeling

Label a corpus against a topic, facet by facet, with a graded judge (raglab#8, part B).

[`label_corpus()`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.label_corpus) composes existing pieces and adds no orchestrator:

- a planner that emits one [`SubTask`](_autosummary/raglab.agent.html.md#raglab.agent.SubTask) per **facet** of the
  topic, for broad recall;
- a formulator (identity by default; [`raglab.make_llm_formulator()`](_autosummary/raglab.html.md#raglab.make_llm_formulator) for
  query expansion);
- the graded rubric evaluator ([`raglab.make_graded_rubric_evaluator()`](_autosummary/raglab.html.md#raglab.make_graded_rubric_evaluator)),
  which judges **every** retrieved candidate on its disclosed content;
- a **coverage** check per facet (enough candidates at `coverage_level`),
  which, when a facet looks thin and a `reformulate` policy is given, emits a
  refinement sub-task: the back-edge of [`SingleContextAgent`](_autosummary/raglab.agent.html.md#raglab.agent.SingleContextAgent).

The deliverable is a frozen [`CorpusLabeling`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.CorpusLabeling): each judged artifact’s best
[`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel) (its `facet` set) and each facet’s coverage.
Nothing here touches `ir`; the corpus is read through a retriever
(`ir.as_retriever()` by default).

### Functions

| [`label_corpus`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.label_corpus)(corpus, \*, facets[, retriever, ...])   | Label `corpus` for each of `facets` with a graded judge; see the module.   |
|-------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------|

### Classes

| [`CorpusLabeling`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.CorpusLabeling)([labels, coverage, levels])   | The graded labels of a corpus for one topic, and each facet's coverage.                     |
|-----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| [`FacetCoverage`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.FacetCoverage)(facet, judged, covered, ...)   | How well one facet was covered: candidates judged, those at the coverage level, rounds run. |

### *class* raglab.recipes.corpus_labeling.CorpusLabeling(labels=dict(), coverage=dict(), levels=('core', 'strong', 'uses-tools', 'tangential', 'none'))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The graded labels of a corpus for one topic, and each facet’s coverage.

#### at_least(level)

The artifact ids labelled `level` or better, on the levels they were labelled on.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* raglab.recipes.corpus_labeling.FacetCoverage(facet, judged, covered, rounds, sufficient)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

How well one facet was covered: candidates judged, those at the coverage level, rounds run.

### raglab.recipes.corpus_labeling.label_corpus(corpus, \*, facets, retriever=None, formulator=<function identity_formulator>, judge=None, reformulate=None, levels=('core', 'strong', 'uses-tools', 'tangential', 'none'), coverage_level='strong', min_covered=1, budget=None, k=50, \*\*evaluator_kwargs)

Label `corpus` for each of `facets` with a graded judge; see the module.

* **Parameters:**
  * **corpus** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – an `ir` corpus or corpus name, read through
    `ir.as_retriever(corpus, k=k)` unless `retriever` is given.
  * **facets** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – the topic’s facets, as `{name: goal}` or names (a name is its
    own goal). One sub-task each.
  * **retriever** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), list[SearchHit]]]) – inject a `Retriever` instead (a test
    double, a federated source); `corpus` is then not read.
  * **formulator** ([`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator)) – the Formulator role (identity, or
    [`raglab.make_llm_formulator()`](_autosummary/raglab.html.md#raglab.make_llm_formulator)).
  * **judge** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the graded judge (built lazily on `oa` when omitted).
  * **reformulate** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)]], str | None] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – gap-driven reformulation; when a facet has fewer than
    `min_covered` labels at `coverage_level` it gets a new query, which
    becomes the facet’s next sub-task. `None` (default): one round each.
  * **budget** ([`Budget`](_autosummary/raglab.agent.html.md#raglab.agent.Budget) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the loop bounds (`max_rounds` caps the reformulations).
  * **\*\*evaluator_kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – forwarded to
    [`make_graded_rubric_evaluator()`](_autosummary/raglab.judging.html.md#raglab.judging.make_graded_rubric_evaluator) (`rubric`,
    `calibration_offset`, `disclose_kwargs`, `rng`, …).
* **Return type:**
  [`CorpusLabeling`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.CorpusLabeling)


# _autosummary/raglab.recipes.html.md

# raglab.recipes

Recipes: whole workflows composed from raglab’s roles, ready to call.

### Functions

| [`label_corpus`](_autosummary/raglab.recipes.html.md#raglab.recipes.label_corpus)(corpus, \*, facets[, retriever, ...])   | Label `corpus` for each of `facets` with a graded judge; see the module.   |
|-------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------|

### Classes

| [`CorpusLabeling`](_autosummary/raglab.recipes.html.md#raglab.recipes.CorpusLabeling)([labels, coverage, levels])   | The graded labels of a corpus for one topic, and each facet's coverage.                     |
|-----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| [`FacetCoverage`](_autosummary/raglab.recipes.html.md#raglab.recipes.FacetCoverage)(facet, judged, covered, ...)   | How well one facet was covered: candidates judged, those at the coverage level, rounds run. |

### *class* raglab.recipes.CorpusLabeling(labels=dict(), coverage=dict(), levels=('core', 'strong', 'uses-tools', 'tangential', 'none'))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The graded labels of a corpus for one topic, and each facet’s coverage.

#### at_least(level)

The artifact ids labelled `level` or better, on the levels they were labelled on.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* raglab.recipes.FacetCoverage(facet, judged, covered, rounds, sufficient)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

How well one facet was covered: candidates judged, those at the coverage level, rounds run.

### raglab.recipes.label_corpus(corpus, \*, facets, retriever=None, formulator=<function identity_formulator>, judge=None, reformulate=None, levels=('core', 'strong', 'uses-tools', 'tangential', 'none'), coverage_level='strong', min_covered=1, budget=None, k=50, \*\*evaluator_kwargs)

Label `corpus` for each of `facets` with a graded judge; see the module.

* **Parameters:**
  * **corpus** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – an `ir` corpus or corpus name, read through
    `ir.as_retriever(corpus, k=k)` unless `retriever` is given.
  * **facets** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – the topic’s facets, as `{name: goal}` or names (a name is its
    own goal). One sub-task each.
  * **retriever** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), list[SearchHit]]]) – inject a `Retriever` instead (a test
    double, a federated source); `corpus` is then not read.
  * **formulator** ([`Formulator`](_autosummary/raglab.agent.html.md#raglab.agent.Formulator)) – the Formulator role (identity, or
    [`raglab.make_llm_formulator()`](_autosummary/raglab.html.md#raglab.make_llm_formulator)).
  * **judge** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the graded judge (built lazily on `oa` when omitted).
  * **reformulate** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`GradedLabel`](_autosummary/raglab.agent.html.md#raglab.agent.GradedLabel)]], str | None] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – gap-driven reformulation; when a facet has fewer than
    `min_covered` labels at `coverage_level` it gets a new query, which
    becomes the facet’s next sub-task. `None` (default): one round each.
  * **budget** ([`Budget`](_autosummary/raglab.agent.html.md#raglab.agent.Budget) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the loop bounds (`max_rounds` caps the reformulations).
  * **\*\*evaluator_kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – forwarded to
    [`make_graded_rubric_evaluator()`](_autosummary/raglab.judging.html.md#raglab.judging.make_graded_rubric_evaluator) (`rubric`,
    `calibration_offset`, `disclose_kwargs`, `rng`, …).
* **Return type:**
  [`CorpusLabeling`](_autosummary/raglab.recipes.corpus_labeling.html.md#raglab.recipes.corpus_labeling.CorpusLabeling)

### Modules

| [`corpus_labeling`](_autosummary/raglab.recipes.corpus_labeling.html.md#module-raglab.recipes.corpus_labeling)   | Label a corpus against a topic, facet by facet, with a graded judge (raglab#8, part B).   |
|----------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-23 07:55 UTC** from commit <a href="https://github.com/addaix/raglab/commit/11b7e3444e639f490fdb8002593418c9f79a18b6"><code>11b7e34</code></a> on branch <code>main</code>, for **raglab 0.2.13** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                      |
|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/raglab/commit/11b7e3444e639f490fdb8002593418c9f79a18b6"><code>11b7e3444e639f490fdb8002593418c9f79a18b6</code></a> |
| Branch              | <code>main</code>                                                                                                                                    |
| Tags at this commit | none                                                                                                                                                 |
| Working tree        | clean                                                                                                                                                |
| Remote              | <code>https://github.com/addaix/raglab</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/raglab</code>                                                                 |
| Run          | <a href="https://github.com/addaix/raglab/actions/runs/45134504971">45134504971</a>        |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>11b7e3444e639f490fdb8002593418c9f79a18b6</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.24  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>pydata_sphinx_theme</code>) |
| accent        | <code>#006688</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/raglab/0.2.13/">0.2.13</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/addaix/raglab && cd raglab
git checkout 11b7e3444e639f490fdb8002593418c9f79a18b6
pip install "epythet==0.2.24"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`raglab` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Instruction files

Files agents read before working in this repository.

- [`.claude/CLAUDE.md`](https://github.com/addaix/raglab/tree/HEAD/.claude/CLAUDE.md): read by Claude Code

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/raglab/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`raglab.md`](https://addaix.github.io/raglab/raglab.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/raglab/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`raglab`](_autosummary/raglab.html.md#module-raglab)   | `raglab` — the agentic-search / RAG orchestration layer on top of `ir`.   |
|-------------------------------------------------------------------------|---------------------------------------------------------------------------|


