Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 31 additions & 97 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@

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).
`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
Expand All @@ -23,10 +18,9 @@ pip install raglab

## 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.
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
Expand Down Expand Up @@ -60,10 +54,7 @@ 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)`](#sources), with `ir.retrievers()` (a
lazy live view over everything ir has registered), or by hand:
`{"skills": ir.as_retriever("skills")}`.
`sources` is any `Mapping[name, Retriever]`. Build it with [`raglab.ir_sources(*names, **defaults)`](#sources), with `ir.retrievers()` (a lazy live view over everything ir has registered), or by hand: `{"skills": ir.as_retriever("skills")}`.

---

Expand All @@ -83,10 +74,7 @@ lazy live view over everything ir has registered), or by hand:
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.
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… |
|------|---------|------------------|---------------------------|
Expand All @@ -97,17 +85,15 @@ capabilities on by swapping in richer roles.
| **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.
**`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.
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

Expand All @@ -121,34 +107,18 @@ 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).
- **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**.
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.
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:
Expand All @@ -158,9 +128,7 @@ only **ranks** interact.
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`:
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)
Expand Down Expand Up @@ -192,10 +160,7 @@ def my_formulator(task, source):
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.
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.

---

Expand All @@ -214,8 +179,7 @@ Everything is exported from the top-level `raglab` namespace.
| `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`.
**Role Protocols** (the open-closed strategy seams): `Planner`, `Formulator`, `Retriever` (re-exported from `ir`), `Evaluator`, `Reranker`, `Citer`.

**Orchestrator & builders:**

Expand All @@ -225,69 +189,39 @@ Everything is exported from the top-level `raglab` namespace.
| `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`.
**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.
**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.
`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).
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.
**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.
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.
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.
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:
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.
- **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.
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.
Loading