[PR #295] [MERGED] feat(agents): add Knowledge Router — lower-cost lorebook routing agent #4551

Closed
opened 2026-10-22 04:08:39 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/295
Author: @cha1latte
Created: 4/28/2026
Status: ✅ Merged
Merged: 4/28/2026
Merged by: @SpicyMarinara

Base: main ← Head: feat/knowledge-router-agent


📝 Commits (10+)

  • 33eebee feat(agents): register knowledge-router agent type and default prompt
  • 2fa39d6 feat(agents): add knowledge-router execution function and catalog injection
  • 17dd7fc feat(generate): wire knowledge-router into the generation pipeline
  • 496f70a test(agents): add unit tests for knowledge-router helpers
  • 1d19c51 chore(scripts): add cost-model script for knowledge-router PR
  • 074b9f0 feat(client): expose lorebook source picker for the knowledge-router agent
  • d4d7c83 fix(knowledge-router): harden against prompt injection and duplicate IDs
  • 8c6a869 fix(generate): make router optional, restore regen cache, honor chat overrides
  • d46c6fe fix(client): don't persist sourceFileIds for the knowledge-router agent
  • 4f4b990 chore(scripts): replace console.log with process.stdout.write in benchmark

📊 Changes

8 files changed (+1053 additions, -54 deletions)

View changed files

📝 packages/client/src/components/agents/AgentEditor.tsx (+19 -5)
➕ packages/server/scripts/benchmark-knowledge-router.ts (+206 -0)
📝 packages/server/src/routes/generate.routes.ts (+233 -49)
📝 packages/server/src/services/agents/agent-executor.ts (+6 -0)
➕ packages/server/src/services/agents/knowledge-router.ts (+247 -0)
➕ packages/server/test/knowledge-router.test.ts (+305 -0)
📝 packages/shared/src/constants/agent-prompts.ts (+26 -0)
📝 packages/shared/src/types/agent.ts (+11 -0)

📄 Description

Part 2 of #226 — the Knowledge Router agent itself.

Summary

Adds a new built-in pre-generation agent, Knowledge Router, as a lower-cost alternative to the existing Knowledge Retrieval agent for large lorebooks.

Where Knowledge Retrieval reads the full content of every enabled entry from the source lorebooks and summarizes it (chunking when needed), the router reads a short catalog (one row per entry: id, name, keys, summary) and returns the IDs of the entries it thinks are relevant. Selected entries are then injected verbatim — no per-entry summarization pass.

Why

For large lorebooks (One Piece, Wheel of Time, etc.) the existing Knowledge Retrieval agent gets expensive — it has to summarize every enabled entry on every turn, often across multiple chunked LLM calls. The router avoids that by routing between entries instead of summarizing them.

The two agents complement each other rather than replacing one another. Power users with smaller, well-curated lorebooks may still prefer Retrieval for its summarization quality; users with large lorebooks get a cheaper option.

How it works (short version)

  1. Route layer loads enabled entries from the agent's source lorebooks. constant: true entries are skipped (they already inject unconditionally via the standard activation pipeline — routing them would duplicate work).
  2. The router builds a catalog row per candidate entry: <entry id="..." name="..." keys="...">summary</entry>.
  3. The catalog summary uses the entry's description field (added in #227) when non-empty, otherwise falls back to the first ~60 tokens of the entry's content. This keeps the router useful out of the box on existing lorebooks while letting power users tune precision via descriptions.
  4. The agent LLM returns { "entryIds": [...] }.
  5. Selected entries are looked up and injected verbatim into the prompt as <knowledge_router> (or ## Knowledge Router under markdown wrap), parallel to how <knowledge_retrieval> is injected.

The router runs in parallel with Knowledge Retrieval and the standard pre-gen agent pipeline via the same Promise.all gate — so enabling both adds at most the slower of the two latencies, not their sum.

Architecture (commit-by-commit)

Feature commits:

Commit Layer
33eebee Shared — register agent type + default prompt
2fa39d6 Server agents — executeKnowledgeRouter + <entry_catalog> injection in agent-executor
17dd7fc Server routes — wire into generate pipeline (loader, runner promise, prompt injection, regen filter)
496f70a Tests — unit tests for the pure helpers + empty-entries early-return
1d19c51 Cost-model script for the PR description (see below)
074b9f0 Client — extend the existing Knowledge Sources picker to also show for Router (file uploads stay Retrieval-only)

Review-feedback commits (CodeRabbit passes 1 & 2):

Commit What
d4d7c83 knowledge-router: escape all catalog fields, dedupe IDs, logger.error
8c6a869 generate: router try/catch, regen-cache rehydration fix, entryStateOverrides
d46c6fe client: don't persist sourceFileIds for knowledge-router agent
4f4b990 benchmark script: process.stdout.write instead of console.log
372b82b knowledge-router: trim whitespace from parsed entry IDs
cea6e1f generate: KR try/catch parity + ephemeral projection + correct regen replay

Cost model

Modeled (not benchmarked) input/output tokens for both agents at three lorebook sizes. The script (packages/server/scripts/benchmark-knowledge-router.ts) uses the real buildCatalog helper to measure actual catalog sizes, then estimates LLM costs analytically. All assumptions documented at the top of the file so reviewers can challenge or re-run with their own numbers.

Default-assumption results (~50% description coverage, 800-char avg entry content):

Entries Knowledge Retrieval Knowledge Router Router vs KR (input)
20 4,750 in / 300 out (1 call) 1,465 in / 40 out (1 call) 30.8%
100 23,150 in / 1,200 out (4 calls) 5,775 in / 200 out (1 call) 24.9%
500 114,550 in / 5,400 out (18 calls) 27,763 in / 1,000 out (1 call) 24.2%

The 500-entry case is the killer — KR makes 18 sequential LLM calls, Router makes 1.

Known limitations

  • Router quality scales with description quality. With 0% description coverage, every catalog row is a content snippet — accuracy drops on entries whose first ~60 tokens aren't representative. The hybrid fallback keeps the agent functional out of the box, but the encouraged path is for users to write tight descriptions on their important entries.
  • Catalog capped at 400 entries. Larger lorebooks are truncated (order-preserving) with a warning log to prevent context-window blowups. The router still works on the truncated set; a future enhancement could rank or paginate before truncating, but real-world lorebooks rarely approach this scale.
  • No "both agents enabled" warning UI yet. If a user enables both Knowledge Retrieval and Knowledge Router on the same lorebook, both will fire and inject — the model handles it fine but it's redundant work. Warning + a description-coverage badge are planned for the next PR in this set.
  • Inconsistency: Knowledge Retrieval's loader does not honor chatMeta.entryStateOverrides. The router's loader does (added in this PR after CodeRabbit feedback) — KR's existing loader has the same gap and should be brought in line in a follow-up. Not addressed here to keep this PR's scope tight. (Note: KR's parallel-promise rejection bug was incidentally fixed in cea6e1f since the try/catch pattern was trivial to apply to both.)

Test plan

Manual smoke tests performed on a fresh dev install (pnpm dev), Roleplay chat, 5-entry test lorebook ("Bingus Bongus studios") with mixed description coverage (3/5 with description, 2/5 with blank description to exercise the content fallback):

  • Router fires on a fresh send. Console: [Agent] ✓ Knowledge Router (knowledge-router) — 10.1s with verbatim entry text.
  • Router selected the right 2 of 5 entries for the test prompt ("tell me about the studio's mascot and where the team works") — both with blank descriptions, picked via content fallback.
  • Selected entries appear in the chat response (mascot/Beans + Greenhouse details verbatim).
  • Router does NOT re-fire on regen — only one [Agent] ✓ Knowledge Router line across original + regen.
  • constant: true entries are filtered before reaching the router. Flipped Beans to Constant; router's text payload no longer contained ### Beans the Salamander. Beans content still appeared in the response (via the standard activation pipeline).
  • Both Knowledge Router and Knowledge Retrieval enabled simultaneously — both fire in parallel, total wall-clock bounded by the slower one (~12s, not ~22s). Both outputs reach the prompt without collision.
  • pnpm check passes locally.
  • 19/19 unit tests pass (packages/server/test/knowledge-router.test.ts).

Summary by CodeRabbit

  • New Features

    • Added Knowledge Router agent to select relevant lorebook entries during generation
    • Agent Editor: configure Knowledge Router and choose knowledge sources (router shows router-specific help; uploaded files remain retrieval-only)
    • Generation pipeline: Knowledge Router runs alongside retrieval to enrich prompts and improves regeneration so cached injections are replayed in the correct position
  • Bug Fixes

    • Saving agent settings no longer preserves stale uploaded-file IDs when switching to Router

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/295 **Author:** [@cha1latte](https://github.com/cha1latte) **Created:** 4/28/2026 **Status:** ✅ Merged **Merged:** 4/28/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `main` ← **Head:** `feat/knowledge-router-agent` --- ### 📝 Commits (10+) - [`33eebee`](https://github.com/Pasta-Devs/Marinara-Engine/commit/33eebee0fa50951de118634f4e8bac8e1fd89ff2) feat(agents): register knowledge-router agent type and default prompt - [`2fa39d6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2fa39d6f774d907b04ce27874edb3c92277185b9) feat(agents): add knowledge-router execution function and catalog injection - [`17dd7fc`](https://github.com/Pasta-Devs/Marinara-Engine/commit/17dd7fc3f30184f8e81b61cbdf33ea7cb31f9fba) feat(generate): wire knowledge-router into the generation pipeline - [`496f70a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/496f70ae02b405e6eafb0fda3f6cadaa00d08137) test(agents): add unit tests for knowledge-router helpers - [`1d19c51`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1d19c515d6d1372ba797c4308188330bd02eafa4) chore(scripts): add cost-model script for knowledge-router PR - [`074b9f0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/074b9f079b8b3a1de59eaec6f9f1b7f2743f3323) feat(client): expose lorebook source picker for the knowledge-router agent - [`d4d7c83`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d4d7c83113b5b6e987442274daeca30b00538fac) fix(knowledge-router): harden against prompt injection and duplicate IDs - [`8c6a869`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8c6a86999e3d1e6c3b6c0e64148ef1abad4f5371) fix(generate): make router optional, restore regen cache, honor chat overrides - [`d46c6fe`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d46c6fec0c06fb86df069bb641dc0540c40d1ebc) fix(client): don't persist sourceFileIds for the knowledge-router agent - [`4f4b990`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4f4b990b68b7055b6f391931099d23532a44d70d) chore(scripts): replace console.log with process.stdout.write in benchmark ### 📊 Changes **8 files changed** (+1053 additions, -54 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/agents/AgentEditor.tsx` (+19 -5) ➕ `packages/server/scripts/benchmark-knowledge-router.ts` (+206 -0) 📝 `packages/server/src/routes/generate.routes.ts` (+233 -49) 📝 `packages/server/src/services/agents/agent-executor.ts` (+6 -0) ➕ `packages/server/src/services/agents/knowledge-router.ts` (+247 -0) ➕ `packages/server/test/knowledge-router.test.ts` (+305 -0) 📝 `packages/shared/src/constants/agent-prompts.ts` (+26 -0) 📝 `packages/shared/src/types/agent.ts` (+11 -0) </details> ### 📄 Description Part 2 of #226 — the Knowledge Router agent itself. ## Summary Adds a new built-in pre-generation agent, **Knowledge Router**, as a lower-cost alternative to the existing Knowledge Retrieval agent for large lorebooks. Where Knowledge Retrieval reads the *full content* of every enabled entry from the source lorebooks and summarizes it (chunking when needed), the router reads a *short catalog* (one row per entry: id, name, keys, summary) and returns the IDs of the entries it thinks are relevant. Selected entries are then injected verbatim — no per-entry summarization pass. ## Why For large lorebooks (One Piece, Wheel of Time, etc.) the existing Knowledge Retrieval agent gets expensive — it has to summarize every enabled entry on every turn, often across multiple chunked LLM calls. The router avoids that by routing *between* entries instead of summarizing them. The two agents complement each other rather than replacing one another. Power users with smaller, well-curated lorebooks may still prefer Retrieval for its summarization quality; users with large lorebooks get a cheaper option. ## How it works (short version) 1. Route layer loads enabled entries from the agent's source lorebooks. `constant: true` entries are skipped (they already inject unconditionally via the standard activation pipeline — routing them would duplicate work). 2. The router builds a catalog row per candidate entry: `<entry id="..." name="..." keys="...">summary</entry>`. 3. The catalog `summary` uses the entry's `description` field (added in #227) when non-empty, otherwise falls back to the first ~60 tokens of the entry's content. This keeps the router useful out of the box on existing lorebooks while letting power users tune precision via descriptions. 4. The agent LLM returns `{ "entryIds": [...] }`. 5. Selected entries are looked up and injected verbatim into the prompt as `<knowledge_router>` (or `## Knowledge Router` under markdown wrap), parallel to how `<knowledge_retrieval>` is injected. The router runs in parallel with Knowledge Retrieval and the standard pre-gen agent pipeline via the same `Promise.all` gate — so enabling both adds at most the slower of the two latencies, not their sum. ## Architecture (commit-by-commit) **Feature commits:** | Commit | Layer | |---|---| | `33eebee` | Shared — register agent type + default prompt | | `2fa39d6` | Server agents — `executeKnowledgeRouter` + `<entry_catalog>` injection in agent-executor | | `17dd7fc` | Server routes — wire into generate pipeline (loader, runner promise, prompt injection, regen filter) | | `496f70a` | Tests — unit tests for the pure helpers + empty-entries early-return | | `1d19c51` | Cost-model script for the PR description (see below) | | `074b9f0` | Client — extend the existing Knowledge Sources picker to also show for Router (file uploads stay Retrieval-only) | **Review-feedback commits (CodeRabbit passes 1 & 2):** | Commit | What | |---|---| | `d4d7c83` | knowledge-router: escape all catalog fields, dedupe IDs, logger.error | | `8c6a869` | generate: router try/catch, regen-cache rehydration fix, entryStateOverrides | | `d46c6fe` | client: don't persist sourceFileIds for knowledge-router agent | | `4f4b990` | benchmark script: process.stdout.write instead of console.log | | `372b82b` | knowledge-router: trim whitespace from parsed entry IDs | | `cea6e1f` | generate: KR try/catch parity + ephemeral projection + correct regen replay | ## Cost model Modeled (not benchmarked) input/output tokens for both agents at three lorebook sizes. The script (`packages/server/scripts/benchmark-knowledge-router.ts`) uses the real `buildCatalog` helper to measure actual catalog sizes, then estimates LLM costs analytically. All assumptions documented at the top of the file so reviewers can challenge or re-run with their own numbers. Default-assumption results (~50% description coverage, 800-char avg entry content): | Entries | Knowledge Retrieval | Knowledge Router | Router vs KR (input) | |---|---|---|---| | 20 | 4,750 in / 300 out (1 call) | 1,465 in / 40 out (1 call) | **30.8%** | | 100 | 23,150 in / 1,200 out (4 calls) | 5,775 in / 200 out (1 call) | **24.9%** | | 500 | 114,550 in / 5,400 out (18 calls) | 27,763 in / 1,000 out (1 call) | **24.2%** | The 500-entry case is the killer — KR makes 18 sequential LLM calls, Router makes 1. ## Known limitations - **Router quality scales with description quality.** With 0% description coverage, every catalog row is a content snippet — accuracy drops on entries whose first ~60 tokens aren't representative. The hybrid fallback keeps the agent functional out of the box, but the encouraged path is for users to write tight descriptions on their important entries. - **Catalog capped at 400 entries.** Larger lorebooks are truncated (order-preserving) with a warning log to prevent context-window blowups. The router still works on the truncated set; a future enhancement could rank or paginate before truncating, but real-world lorebooks rarely approach this scale. - **No "both agents enabled" warning UI yet.** If a user enables both Knowledge Retrieval and Knowledge Router on the same lorebook, both will fire and inject — the model handles it fine but it's redundant work. Warning + a description-coverage badge are planned for the next PR in this set. - **Inconsistency: Knowledge Retrieval's loader does not honor `chatMeta.entryStateOverrides`.** The router's loader does (added in this PR after CodeRabbit feedback) — KR's existing loader has the same gap and should be brought in line in a follow-up. Not addressed here to keep this PR's scope tight. (Note: KR's parallel-promise rejection bug *was* incidentally fixed in `cea6e1f` since the try/catch pattern was trivial to apply to both.) ## Test plan Manual smoke tests performed on a fresh dev install (`pnpm dev`), Roleplay chat, 5-entry test lorebook ("Bingus Bongus studios") with mixed description coverage (3/5 with description, 2/5 with blank description to exercise the content fallback): - [x] Router fires on a fresh send. Console: `[Agent] ✓ Knowledge Router (knowledge-router) — 10.1s` with verbatim entry text. - [x] Router selected the right 2 of 5 entries for the test prompt ("tell me about the studio's mascot and where the team works") — both with blank descriptions, picked via content fallback. - [x] Selected entries appear in the chat response (mascot/Beans + Greenhouse details verbatim). - [x] Router does NOT re-fire on regen — only one `[Agent] ✓ Knowledge Router` line across original + regen. - [x] `constant: true` entries are filtered before reaching the router. Flipped Beans to Constant; router's text payload no longer contained `### Beans the Salamander`. Beans content still appeared in the response (via the standard activation pipeline). - [x] Both Knowledge Router and Knowledge Retrieval enabled simultaneously — both fire in parallel, total wall-clock bounded by the slower one (~12s, not ~22s). Both outputs reach the prompt without collision. - [x] `pnpm check` passes locally. - [x] 19/19 unit tests pass (`packages/server/test/knowledge-router.test.ts`). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added Knowledge Router agent to select relevant lorebook entries during generation * Agent Editor: configure Knowledge Router and choose knowledge sources (router shows router-specific help; uploaded files remain retrieval-only) * Generation pipeline: Knowledge Router runs alongside retrieval to enrich prompts and improves regeneration so cached injections are replayed in the correct position * **Bug Fixes** * Saving agent settings no longer preserves stale uploaded-file IDs when switching to Router <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:08:39 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#4551
No description provided.