PHPackages                             twdnhfr/laravel-bes-rag - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. twdnhfr/laravel-bes-rag

ActiveLibrary[Search &amp; Filtering](/categories/search)

twdnhfr/laravel-bes-rag
=======================

A deep RAG search orchestrator for Laravel, based on Bidirectional Evolutionary Search (BES): backward goal decomposition, evolving evidence trails and cited, auditable answers.

v0.2.1(1mo ago)55[1 PRs](https://github.com/twdnhfr/laravel-bes-rag/pulls)MITPHPPHP ^8.3CI passing

Since Jun 10Pushed 1w agoCompare

[ Source](https://github.com/twdnhfr/laravel-bes-rag)[ Packagist](https://packagist.org/packages/twdnhfr/laravel-bes-rag)[ Docs](https://github.com/twdnhfr/laravel-bes-rag)[ GitHub Sponsors](https://github.com/twdnhfr)[ RSS](/packages/twdnhfr-laravel-bes-rag/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (3)Dependencies (26)Versions (5)Used By (0)

laravel-bes-rag
===============

[](#laravel-bes-rag)

[![laravel-bes-rag — Deep RAG for Laravel powered by Bidirectional Evolutionary Search](art/header.webp)](art/header.webp)

**A deep RAG search orchestrator for Laravel**, based on [Bidirectional Evolutionary Search (BES)](https://arxiv.org/abs/2605.28814): instead of `question → top-k → answer`, hard multi-hop questions are decomposed into checkable sub-goals, multiple *evidence trails* are evolved against them, and the final answer is synthesized strictly from cited evidence — with a full audit trail of every query, chunk and score.

Built on the [Laravel AI SDK](https://github.com/laravel/ai) (`laravel/ai`) as the provider-agnostic engine for text generation, structured output and embeddings.

```
Question
  → backward decomposition: checkable sub-goals with declarative verifiers
  → forward search: seed multiple retrieval/answer trails
  → scoring: evidence coverage, groundedness, citation support, contradictions
  → evolution: expand / combine / delete / translocate / crossover
  → final answer: best grounded terminal trail, synthesized from its evidence only

```

> **When to use this:** BES-RAG is a *deep research mode* for hard, multi-hop questions where plain top-k RAG fails. It costs a multiple of a single RAG call (budgeted and capped, but real). Don't route every query through it.

Installation
------------

[](#installation)

```
composer require twdnhfr/laravel-bes-rag

php artisan vendor:publish --tag="bes-rag-migrations"
php artisan migrate

php artisan vendor:publish --tag="bes-rag-config"   # optional
```

Quick start
-----------

[](#quick-start)

The only contract you must provide is the `Retriever` — the adapter to your vector store or search index:

```
use Twdnhfr\BesRag\Contracts\Retriever;
use Twdnhfr\BesRag\Data\RetrievalQuery;
use Twdnhfr\BesRag\Data\RetrievedChunk;

class PgVectorRetriever implements Retriever
{
    public function retrieve(RetrievalQuery $query, int $topK = 5): array
    {
        // query your store, return RetrievedChunk[]
    }
}
```

Then run a deep search:

```
use Twdnhfr\BesRag\Facades\BesRag;

$result = BesRag::make()
    ->retriever(new PgVectorRetriever)
    ->budget(30)
    ->maxDepth(3)
    ->answer('Who founded the company that produces the Model S?');

$result->answer();         // cited answer: "... [doc_42/chunk_3]"
$result->citations();      // [['document_id' => 'doc_42', 'chunk_id' => 'chunk_3'], ...]
$result->evidenceTrail();  // the full winning trail for auditing
$result->scores();         // raw / backward / effective + per-goal coverage
```

Multi-tenant stores scope retrieval per run via `->retrievalContext([...])` — the array is persisted with the run (so queue workers see it) and arrives at your retriever as `RetrievalQuery->filters`:

```
BesRag::make()->retrievalContext(['brain_id' => $brain->id])->dispatch($question);
```

### Async via queue pipeline

[](#async-via-queue-pipeline)

```
// Bind the retriever so queue workers can rebuild the engine:
$this->app->bind(\Twdnhfr\BesRag\Contracts\Retriever::class, PgVectorRetriever::class);

$result = BesRag::make()->dispatch($question);   // returns immediately
$result->id();                                   // poll later:
BesRag::result($id)->finished();
```

The pipeline runs `StartRun → SeedCandidates → SearchStep (self-redispatching) → FinalizeAnswer`. Payloads carry only the run id; all artifacts live in the database.

### HTTP API (opt-in)

[](#http-api-opt-in)

Set `BES_RAG_ROUTES_ENABLED=true` (add your own auth middleware via `bes-rag.routes.middleware`):

MethodRoutePurposePOST`/bes-rag/deep-answer`start a run (`{question, sync?, budget?}`)GET`/bes-rag/runs/{run}`status + answerGET`/bes-rag/runs/{run}/debug`goal tree, all candidates, scores, stepsGET`/bes-rag/runs/{run}/stream`SSE progress eventsHow it works
------------

[](#how-it-works)

### Backward decomposition

[](#backward-decomposition)

The question is decomposed (via LLM structured output) into atomic sub-goals with **declarative verifiers** — never LLM-generated code:

Verifier typeChecks`semantic_query_coverage`a trail query/chunk is semantically close to the goal (embeddings)`evidence_presence`≥ N evidence chunks with source metadata`citation_support`answer claims are backed by cited chunks (LLM judge)`entity_match`required entities/dates literally appear in evidence`contradiction_check`no evidence strongly contradicts the answer (LLM judge)`dependency_satisfied`gating on `depends_on` goalsRegister your own via `->verifier('my_type', new MyVerifier)`.

### Forward search &amp; evolution

[](#forward-search--evolution)

A candidate is an `EvidenceTrail` (queries → retrieved chunks → selected evidence → synthesis notes → answer draft), not just an answer. Parents are selected by Boltzmann sampling over effective scores (temperature annealed across the budget); pair operators pick complementary parents. Default operator mix (configurable):

```
expand 70% · combine 10% · translocate 7.5% · crossover 7.5% · delete 5%

```

`crossover` cuts along goal boundaries, never blindly by step index — source context stays intact.

### Scoring

[](#scoring)

```
raw_score      = weighted(groundedness, citation support, evidence quality,
                          contradiction absence, source diversity)
backward_score = recursive goal-tree score (alpha-blend of self + children)
effective      = bucket_interpolation(raw, backward)   ← default

```

The bucket policy makes the *hard* signal dominate: a trail that merely "looks topically right" to the goal tree can never outrank a meaningfully better-grounded trail. Backward score only breaks ties within a raw-score bucket. (`score_policy: weighted` gives the simple linear blend.)

### Cost control

[](#cost-control)

Two independent caps stop a run deterministically: the **step budget** (`budget`) and the **LLM call cap** (`max_llm_calls`) — one search step can trigger several LLM calls, so the step budget alone doesn't bound cost. The LLM judge (groundedness/citations/contradictions) is one memoized structured call per scored trail. Embeddings are cached in-process and optionally in a Laravel cache store.

> **Thresholds are embedder-relative.** `thresholds.semantic_coverage: 0.72` is calibrated for MiniLM-class embeddings. Recalibrate against a small eval set when you switch embedding models.

Testing your integration
------------------------

[](#testing-your-integration)

The package ships deterministic fakes (no HTTP):

```
use Twdnhfr\BesRag\Testing\FakeLlm;
use Twdnhfr\BesRag\Testing\FakeEmbedder;
use Twdnhfr\BesRag\Retrieval\ArrayRetriever;

$llm = (new FakeLlm)
    ->onStructured(fn ($instructions, $prompt) => [...])
    ->onText(fn () => 'Answer with citation [doc/c1].');

$result = BesRag::make()
    ->retriever(new ArrayRetriever([...chunks...]))
    ->llm($llm)
    ->embedder(new FakeEmbedder)
    ->answer('...');
```

Configuration
-------------

[](#configuration)

See [`config/bes-rag.php`](config/bes-rag.php) — provider/models per purpose (decompose/expand/verify/synthesize/embeddings), budgets, operator mix, scoring weights, thresholds, queue and routes. Everything is also overridable per run through the fluent builder.

What this deliberately does not do
----------------------------------

[](#what-this-deliberately-does-not-do)

- **No dynamic code eval.** The original BES inference code verifies goals with Python `eval`; this package uses registered, declarative verifiers only.
- **No blind step concatenation.** Evolution operators cut along goal boundaries to preserve source context.
- **No backward-score dominance.** Groundedness and citation support always outrank topical coverage.

Credits &amp; paper
-------------------

[](#credits--paper)

Independent Laravel implementation of the search method from:

> Xu, Qi, Su, Ye, Lakkaraju, Kakade, Du — *Self-Improving Language Models with Bidirectional Evolutionary Search* ([arXiv:2605.28814](https://arxiv.org/abs/2605.28814), [project page](https://guoweixu.com/bes/), [code](https://github.com/Embodied-Minds-Lab/BES))

No shared code or affiliation; the multi-hop adaptation follows the paper's appendix.

License
-------

[](#license)

MIT — see [LICENSE.md](LICENSE.md).

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance94

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

46d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13796752?v=4)[Tobi](/maintainers/twdnhfr)[@twdnhfr](https://github.com/twdnhfr)

---

Top Contributors

[![twdnhfr](https://avatars.githubusercontent.com/u/13796752?v=4)](https://github.com/twdnhfr "twdnhfr (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

searchlaravelaillmragretrievalbesdeep-research

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/twdnhfr-laravel-bes-rag/health.svg)

```
[![Health](https://phpackages.com/badges/twdnhfr-laravel-bes-rag/health.svg)](https://phpackages.com/packages/twdnhfr-laravel-bes-rag)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M48](/packages/spatie-laravel-pdf)[spatie/laravel-site-search

A site search engine

309137.1k](/packages/spatie-laravel-site-search)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.8k](/packages/rawilk-profile-filament-plugin)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

45955.7k](/packages/harris21-laravel-fuse)[elegantly/laravel-translator

All on one translations management for Laravel

6333.1k](/packages/elegantly-laravel-translator)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24957.5k](/packages/vormkracht10-laravel-mails)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
